_id
stringlengths 2
7
| title
stringlengths 3
151
| partition
stringclasses 3
values | text
stringlengths 83
13k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q262100 | Dispatcher.invokeAction | test | private function invokeAction($object, $method, array $arguments)
{
$methodInfo = $this->reflectionFactory->getMethod(
get_class($object), $method
);
$parameters = $methodInfo->getParameters();
$values = array();
$total = count($parameters);
for ($i = 0; $i < $total; $i++) {
$parameter = array_shift($parameters);
$name = $parameter->getName();
if (isset($arguments[$name])) {
$values[] = $arguments[$name];
} else if ($parameter->isOptional()) {
$values[] = $parameter->getDefaultValue();
} else {
$ctl = get_class($object);
throw new MvcException(
"Missing required argument: $name for action $ctl:$method"
);
}
}
return $methodInfo->invokeArgs($object, $values);
} | php | {
"resource": ""
} |
q262101 | TcpPeer.hasActivity | test | public function hasActivity()
{
if (!$this->isConnected()) {
return false;
}
$read = array($this->socket);
$write = null;
$ex = null;
$result = socket_select($read, $write, $ex, 0, 0);
if ($result === false) {
throw new TcpException(
'Error selecting from socket: '
. socket_strerror(socket_last_error($this->socket))
);
}
return !empty($read);
} | php | {
"resource": ""
} |
q262102 | ContainerImpl.getBeanDefinition | test | public function getBeanDefinition($name)
{
if (isset($this->_beanAliases[$name])) {
$name = $this->_beanAliases[$name];
}
if (isset($this->_beanDefs[$name])) {
return $this->_beanDefs[$name];
}
$beanDefinition = null;
if ($this->_beanDefCache !== null) {
$beanDefinition = $this->_beanDefCache->fetch($name, $result);
}
if ($beanDefinition) {
$this->_beanDefs[$name] = $beanDefinition;
return $beanDefinition;
}
foreach ($this->_beanDefinitionProviders as $provider) {
$beanDefinition = $provider->getBeanDefinition($name);
if ($beanDefinition) {
$beanDefinition->setClass($this->_searchAndReplaceProperties(
$beanDefinition->getClass()
));
break;
}
}
if (!$beanDefinition) {
throw new BeanFactoryException('Unknown bean: ' . $name);
}
$beanDefinition = $this->_lifecycleManager->afterDefinition($beanDefinition);
$this->_beanDefs[$name] = $beanDefinition;
$this->_beanDefCache->store($name, $beanDefinition);
foreach ($beanDefinition->getAliases() as $alias) {
$this->_beanAliases[$alias] = $name;
}
return $beanDefinition;
} | php | {
"resource": ""
} |
q262103 | ContainerImpl._searchAndReplaceProperties | test | private function _searchAndReplaceProperties($value)
{
if (is_string($value)) {
foreach ($this->_properties as $k => $v) {
if (strpos($value, $k) !== false) {
if (is_string($v)) {
$value = str_replace($k, $v, $value);
} else {
$value = $v;
// Assigned value is not a string, so we cant use
// strpos anymore on it (i.e: cant continue replacing)
break;
}
}
}
}
return $value;
} | php | {
"resource": ""
} |
q262104 | ContainerImpl._getConstructorValuesForDefinition | test | private function _getConstructorValuesForDefinition($definition)
{
$args = array();
foreach ($definition->getArguments() as $argument) {
$value = $this->_getValueFromDefinition($argument);
if ($argument->hasName()) {
$name = $argument->getName();
$args[$name] = $value;
} else {
$args[] = $value;
}
}
return $args;
} | php | {
"resource": ""
} |
q262105 | ContainerImpl._instantiateByConstructor | test | private function _instantiateByConstructor(BeanDefinition $definition)
{
$class = $definition->getClass();
if ($definition->hasProxyClass()) {
$class = $definition->getProxyClassName();
}
$rClass = $this->_reflectionFactory->getClass($class);
$factoryMethod = $rClass->getConstructor();
if ($factoryMethod !== null) {
$args = $this->_sortArgsWithNames($definition, $factoryMethod);
if (empty($args)) {
return $rClass->newInstanceArgs();
} else {
return $rClass->newInstanceArgs($args);
}
} else {
return $rClass->newInstanceArgs();
}
} | php | {
"resource": ""
} |
q262106 | ContainerImpl._instantiateByFactoryClass | test | private function _instantiateByFactoryClass(BeanDefinition $definition)
{
$class = $definition->getClass();
$rClass = $this->_reflectionFactory->getClass($class);
$factoryMethodName = $definition->getFactoryMethod();
$factoryMethod = $rClass->getMethod($factoryMethodName);
$args = $this->_sortArgsWithNames($definition, $factoryMethod);
return forward_static_call_array(array($class, $factoryMethodName), $args);
} | php | {
"resource": ""
} |
q262107 | ContainerImpl._instantiateByFactoryBean | test | private function _instantiateByFactoryBean(BeanDefinition $definition)
{
$factoryBean = $this->getBean($definition->getFactoryBean());
$refObject = new \ReflectionObject($factoryBean);
$factoryMethod = $refObject->getMethod($definition->getFactoryMethod());
$args = $this->_sortArgsWithNames($definition, $factoryMethod);
return $factoryMethod->invokeArgs($factoryBean, $args);
} | php | {
"resource": ""
} |
q262108 | ContainerImpl._instantiate | test | private function _instantiate(BeanDefinition $definition)
{
if ($definition->isCreatedByConstructor()) {
return $this->_instantiateByConstructor($definition);
} else if ($definition->isCreatedWithFactoryBean()) {
return $this->_instantiateByFactoryBean($definition);
} else {
return $this->_instantiateByFactoryClass($definition);
}
} | php | {
"resource": ""
} |
q262109 | ContainerImpl._createBeanDependencies | test | private function _createBeanDependencies(BeanDefinition $definition)
{
foreach ($definition->getDependsOn() as $depBean) {
$this->getBean(trim($depBean));
}
} | php | {
"resource": ""
} |
q262110 | ContainerImpl._applyAspect | test | private function _applyAspect(
$targetClass, AspectDefinition $aspectDefinition, IDispatcher $dispatcher
) {
$rClass = $this->_reflectionFactory->getClass($targetClass);
$aspect = $this->getBean($aspectDefinition->getBeanName());
foreach ($aspectDefinition->getPointcuts() as $pointcutName) {
$pointcut = $this->_aspectManager->getPointcut($pointcutName);
if ($pointcut === false) {
throw new BeanFactoryException('Could not find pointcut: ' . $pointcutName);
}
$expression = $pointcut->getExpression();
foreach ($rClass->getMethods() as $method) {
$methodName = $method->getName();
if (preg_match('/' . $expression . '/', $methodName) === 0) {
continue;
}
if (
$aspectDefinition->getType() == AspectDefinition::ASPECT_METHOD
) {
$dispatcher->addMethodInterceptor($methodName, $aspect, $pointcut->getMethod());
} else {
$dispatcher->addExceptionInterceptor($methodName, $aspect, $pointcut->getMethod());
}
}
}
} | php | {
"resource": ""
} |
q262111 | ContainerImpl._applySpecificAspects | test | private function _applySpecificAspects(BeanDefinition $definition, IDispatcher $dispatcher)
{
if ($definition->hasAspects()) {
foreach ($definition->getAspects() as $aspect) {
$this->_applyAspect($definition->getClass(), $aspect, $dispatcher);
}
}
} | php | {
"resource": ""
} |
q262112 | ContainerImpl._applyGlobalAspects | test | private function _applyGlobalAspects(BeanDefinition $definition, IDispatcher $dispatcher)
{
$class = $definition->getClass();
$rClass = $this->_reflectionFactory->getClass($class);
foreach ($this->_aspectManager->getAspects() as $aspect) {
$expression = $aspect->getExpression();
if (preg_match('/' . $expression . '/', $class) === 0) {
$parentClass = $rClass->getParentClass();
while($parentClass !== false) {
if (preg_match('/' . $expression . '/', $parentClass->getName()) > 0) {
$this->_applyAspect($class, $aspect, $dispatcher);
}
$parentClass = $parentClass->getParentClass();
}
} else {
$this->_applyAspect($class, $aspect, $dispatcher);
}
}
} | php | {
"resource": ""
} |
q262113 | ContainerImpl._applyAspects | test | private function _applyAspects(BeanDefinition $definition)
{
$class = $definition->getClass();
$dispatcher = clone $this->_dispatcherTemplate;
$this->_applySpecificAspects($definition, $dispatcher);
$this->_applyGlobalAspects($definition, $dispatcher);
if ($dispatcher->hasMethodsIntercepted()) {
$definition->setProxyClassName(
$this->_proxyFactory->create($class, $dispatcher)
);
}
} | php | {
"resource": ""
} |
q262114 | ContainerImpl._createBean | test | private function _createBean(BeanDefinition $definition)
{
$name = $definition->getName();
if (isset($this->_definitionsInProcess[$name])) {
throw new BeanFactoryException(
"Cyclic dependency found for: $name"
);
}
$this->_definitionsInProcess[$name] = '';
$this->_lifecycleManager->beforeCreate($definition);
$this->_createBeanDependencies($definition);
$this->_applyAspects($definition);
$bean = $this->_instantiate($definition);
if (!is_object($bean)) {
unset($this->_definitionsInProcess[$name]);
throw new BeanFactoryException(
'Could not instantiate ' . $definition->getName()
);
}
$this->_assemble($bean, $definition);
$this->_setupInitAndShutdown($bean, $definition);
$this->_lifecycleManager->afterCreate($bean, $definition);
unset($this->_definitionsInProcess[$name]);
return $bean;
} | php | {
"resource": ""
} |
q262115 | ContainerImpl._setupInitAndShutdown | test | private function _setupInitAndShutdown($bean, BeanDefinition $definition)
{
if ($definition->hasInitMethod()) {
$initMethod = $definition->getInitMethod();
$bean->$initMethod();
}
if ($definition->hasDestroyMethod()) {
$destroyMethod = $definition->getDestroyMethod();
$this->registerShutdownMethod($bean, $destroyMethod);
}
} | php | {
"resource": ""
} |
q262116 | ContainerImpl._nonSetterMethodInject | test | private function _nonSetterMethodInject($bean, $name, $value)
{
$rClass = $this->_reflectionFactory->getClass(get_class($bean));
if ($rClass->hasMethod($name)) {
$bean->$name($value);
return true;
}
return false;
} | php | {
"resource": ""
} |
q262117 | ContainerImpl._propertyInject | test | private function _propertyInject($bean, $name, $value)
{
$rClass = $this->_reflectionFactory->getClass(get_class($bean));
if ($rClass->hasProperty($name)) {
$rProperty = $rClass->getProperty($name);
if (!$rProperty->isPublic()) {
$rProperty->setAccessible(true);
}
$rProperty->setValue($bean, $value);
return true;
}
return false;
} | php | {
"resource": ""
} |
q262118 | ContainerImpl.getBean | test | public function getBean($name)
{
$ret = false;
$beanDefinition = $this->getBeanDefinition($name);
$beanName = $name . '.bean';
if ($beanDefinition->isAbstract()) {
throw new BeanFactoryException(
"Cant instantiate abstract bean: $name"
);
}
if ($beanDefinition->isPrototype()) {
$ret = $this->_createBean($beanDefinition);
} else if ($beanDefinition->isSingleton()) {
if (isset($this->_beans[$beanName])) {
$ret = $this->_beans[$beanName];
} else {
$ret = $this->_beanCache->fetch($beanName, $result);
if (!$ret) {
$ret = $this->_createBean($beanDefinition);
}
$this->_beans[$beanName] = $ret;
}
}
return $ret;
} | php | {
"resource": ""
} |
q262119 | ContainerImpl.getInstance | test | public static function getInstance(array $properties = array())
{
if (self::$_containerInstance === false) {
// Init cache subsystems.
if (isset($properties['ding']['cache'])) {
CacheLocator::configure($properties['ding']['cache']);
}
if (isset($properties['ding']['log4php.properties'])) {
\Logger::configure($properties['ding']['log4php.properties']);
}
self::$_containerInstance = new ContainerImpl($properties['ding']['factory']);
}
return self::$_containerInstance;
} | php | {
"resource": ""
} |
q262120 | ContainerImpl.fillAware | test | public function fillAware(BeanDefinition $def, $bean)
{
$class = get_class($bean);
$rClass = $this->_reflectionFactory->getClass($class);
if ($rClass->implementsInterface('Ding\Reflection\IReflectionFactoryAware')) {
$bean->setReflectionFactory($this->_reflectionFactory);
}
if ($rClass->implementsInterface('Ding\Bean\IBeanNameAware')) {
$bean->setBeanName($def->getName());
}
if ($rClass->implementsInterface('Ding\Logger\ILoggerAware')) {
$bean->setLogger(\Logger::getLogger($class));
}
if ($rClass->implementsInterface('Ding\Container\IContainerAware')) {
$bean->setContainer($this);
}
if ($rClass->implementsInterface('Ding\Resource\IResourceLoaderAware')) {
$bean->setResourceLoader($this);
}
if ($rClass->implementsInterface('Ding\Aspect\IAspectManagerAware')) {
$bean->setAspectManager($this->_aspectManager);
}
if ($rClass->implementsInterface('Ding\Bean\IBeanDefinitionProvider')) {
$this->registerBeanDefinitionProvider($bean);
}
if ($rClass->implementsInterface('Ding\Bean\Lifecycle\IAfterConfigListener')) {
$this->_lifecycleManager->addAfterConfigListener($bean);
}
if ($rClass->implementsInterface('Ding\Bean\Lifecycle\IAfterDefinitionListener')) {
$this->_lifecycleManager->addAfterDefinitionListener($bean);
}
if ($rClass->implementsInterface('Ding\Bean\Lifecycle\IBeforeCreateListener')) {
$this->_lifecycleManager->addBeforeCreateListener($bean);
}
if ($rClass->implementsInterface('Ding\Bean\Lifecycle\IAfterCreateListener')) {
$this->_lifecycleManager->addAfterCreateListener($bean);
}
if ($rClass->implementsInterface('Ding\Bean\Lifecycle\IBeforeAssembleListener')) {
$this->_lifecycleManager->addBeforeAssembleListener($bean);
}
if ($rClass->implementsInterface('Ding\Bean\Lifecycle\IAfterAssembleListener')) {
$this->_lifecycleManager->addAfterAssembleListener($bean);
}
if ($rClass->implementsInterface('Ding\Aspect\IAspectProvider')) {
$this->_aspectManager->registerAspectProvider($bean);
}
if ($rClass->implementsInterface('Ding\Aspect\IPointcutProvider')) {
$this->_aspectManager->registerPointcutProvider($bean);
}
} | php | {
"resource": ""
} |
q262121 | ContainerImpl.signalHandler | test | public function signalHandler($signo)
{
$msg = "Caught Signal: $signo";
$this->_logger->warn($msg);
$this->eventDispatch('dingSignal', $signo);
} | php | {
"resource": ""
} |
q262122 | Autoloader.load | test | public static function load($class)
{
$classFile = str_replace('\\', DIRECTORY_SEPARATOR, $class) . '.php';
$file = stream_resolve_include_path($classFile);
if ($file && file_exists($file)) {
require_once $file;
return true;
}
return false;
} | php | {
"resource": ""
} |
q262123 | BeanDefinition.makeChildBean | test | public function makeChildBean($childName)
{
$bean = serialize($this);
$bean = unserialize($bean);
$bean->setName($childName);
$bean->clearAliases();
$bean->makeConcrete();
return $bean;
} | php | {
"resource": ""
} |
q262124 | ReflectionFactory._populateClassesPerAnnotations | test | private function _populateClassesPerAnnotations($class, Collection $annotations)
{
foreach ($annotations->getAll() as $name => $annotation) {
$cacheKey = $name . '.classbyannotations';
if (!isset($this->_classesAnnotated[$name])) {
$this->_classesAnnotated[$name] = array();
}
$this->_classesAnnotated[$name][$class] = $class;
$this->_cache->store($cacheKey, $this->_classesAnnotated);
}
} | php | {
"resource": ""
} |
q262125 | Xml._loadXml | test | private function _loadXml($filename)
{
$xmls = array();
libxml_use_internal_errors(true);
if (is_array($filename)) {
foreach ($filename as $file) {
$result = $this->_loadXml($file);
if ($result !== false) {
foreach ($result as $name => $xml) {
$xmls[$name] = $xml;
}
}
}
return $xmls;
}
$contents = false;
foreach ($this->_directories as $directory) {
$fullname = $directory . DIRECTORY_SEPARATOR . $filename;
if (!file_exists($fullname)) {
continue;
}
$contents = @file_get_contents($fullname);
}
if ($contents === false) {
throw new BeanFactoryException($filename . ' not found in ' . print_r($this->_directories, true));
}
$ret = simplexml_load_string($contents);
if ($ret === false) {
return $ret;
}
$xmls[$filename] = $ret;
foreach ($ret->xpath("//import") as $imported) {
$filename = (string)$imported->attributes()->resource;
foreach ($this->_loadXml($filename) as $name => $xml) {
$xmls[$name] = $xml;
}
}
return $xmls;
} | php | {
"resource": ""
} |
q262126 | Xml._load | test | private function _load()
{
if ($this->_simpleXml !== false) {
return;
}
$this->_simpleXml = $this->_loadXml($this->_filename);
if (empty($this->_simpleXml)) {
throw new BeanFactoryException(
'Could not parse: ' . $this->_filename
. ': ' . $this->_getXmlErrors()
);
}
} | php | {
"resource": ""
} |
q262127 | TcpServerHelper.close | test | public function close()
{
$this->_open = false;
$this->_peers = array();
$this->_peersSockets = array();
$this->_peersLastDataReceived = array();
$this->_handler->close();
socket_close($this->_socket);
$this->_socket = false;
} | php | {
"resource": ""
} |
q262128 | TcpServerHelper.open | test | public function open()
{
$this->_open = false;
$this->_handler->beforeOpen();
$this->_socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if ($this->_socket === false) {
throw new TcpException(
'Error opening socket: ' . socket_strerror(socket_last_error())
);
}
if ($this->_reuse) {
socket_set_option ($this->_socket, SOL_SOCKET, SO_REUSEADDR, 1);
}
if (!@socket_bind($this->_socket, $this->_address, $this->_port)) {
$error = socket_strerror(socket_last_error($this->_socket));
socket_close($this->_socket);
$this->_socket = false;
throw new TcpException('Error binding socket: ' . $error);
}
socket_set_nonblock($this->_socket);
$this->_handler->beforeListen();
if (!socket_listen($this->_socket, $this->_backlog)) {
$error = socket_strerror(socket_last_error($this->_socket));
socket_close($this->_socket);
$this->_socket = false;
throw new TcpException('Error listening socket: ' . $error);
}
$this->_open = true;
} | php | {
"resource": ""
} |
q262129 | TcpServerHelper._freePeer | test | private function _freePeer(\Ding\Helpers\Tcp\TcpPeer $peer)
{
$peerName = $peer->getName();
unset($this->_peers[$peerName]);
unset($this->_peersSockets[$peerName]);
unset($this->_peersLastDataReceived[$peerName]);
} | php | {
"resource": ""
} |
q262130 | Proxy.createClass | test | protected function createClass($newName, array $proxyMethods, \ReflectionClass $class)
{
$src = $this->proxyTemplate;
$src = str_replace('NEW_NAME', $newName, $src);
$src = str_replace('CLASS_NAME', $class->getName(), $src);
$methods = array();
foreach ($proxyMethods as $method) {
if ($class->hasMethod($method)) {
$methods[] = $this->createMethod($class->getMethod($method));
}
}
$src = str_replace('METHODS', implode("\n", $methods), $src);
return $src;
} | php | {
"resource": ""
} |
q262131 | Proxy.createParameter | test | protected function createParameter(\ReflectionParameter $parameter)
{
$parameterSrc = '';
$paramClass = $parameter->getClass();
if ($parameter->isArray()) {
$parameterSrc .= 'array ';
} else if ($paramClass) {
$parameterSrc .= $paramClass->getName() . ' ';
}
if ($parameter->isPassedByReference()) {
$parameterSrc .= ' &';
}
$parameterSrc .= '$' . $parameter->getName();
if ($parameter->isOptional()) {
$parameterSrc .= '=';
if ($parameter->getDefaultValue() === null) {
$parameterSrc .= 'null';
} else if ($parameter->getDefaultValue() === false) {
$parameterSrc .= 'false';
} else if ($parameter->getDefaultValue() === true) {
$parameterSrc .= 'true';
} else if (is_array($parameter->getDefaultValue())) {
$parameterSrc .= 'array()';
} else {
$parameterSrc .= "'" . $parameter->getDefaultValue() . "'";
}
}
return $parameterSrc;
} | php | {
"resource": ""
} |
q262132 | Proxy.createMethod | test | protected function createMethod(\ReflectionMethod $method)
{
$visibility = '';
$additional = '';
$name = $method->getName();
if ($method->isPublic()) {
$visibility = ' public';
} else if ($method->isProtected()) {
$visibility = ' protected';
} else if ($method->isPrivate()) {
// useless really. $visibility = ' private';
return '';
}
if ($method->isStatic()) {
// useless really. $additional .= ' static ';
return '';
}
//if ($method->isAbstract()) {
// useless really. $$additional .= ' abstract ';
//return '';
//}
if ($method->isConstructor()) {
$name = '__construct';
} else if ($method->isDestructor()) {
$name = '__destruct';
}
$args = array();
foreach ($method->getParameters() as $parameter) {
$args[] = $this->createParameter($parameter);
}
$src = $this->methodTemplate;
$src = str_replace('VISIBILITY', $visibility, $src);
$src = str_replace('ADDITIONAL', $additional, $src);
$src = str_replace('METHOD_NAME', $name, $src);
$src = str_replace('METHOD_ARGS', implode(',', $args), $src);
$src = str_replace(
'CLASS_NAME', $method->getDeclaringClass()->getName(), $src
);
return $src;
} | php | {
"resource": ""
} |
q262133 | Proxy.create | test | public function create($class, IDispatcher $dispatcher)
{
$subject = $this->reflectionFactory->getClass($class);
$proxyClassName = 'Proxy' . str_replace('\\', '', $subject->getName());
$cacheKey = $proxyClassName . '.proxy';
$result = false;
$src = $this->cache->fetch($cacheKey, $result);
if (!$result) {
$src = $this->createClass(
$proxyClassName, $dispatcher->getMethodsIntercepted(), $subject
);
$this->cache->store($cacheKey, $src);
}
eval($src);
$proxyClassName::setDispatcher($dispatcher);
$proxyClassName::setReflectionFactory($this->reflectionFactory);
return $proxyClassName;
} | php | {
"resource": ""
} |
q262134 | Yaml._loadYaml | test | private function _loadYaml($filename)
{
$yamls = array();
if (is_array($filename)) {
foreach ($filename as $file) {
foreach ($this->_loadYaml($file) as $name => $yaml) {
$yamls[$name] = $yaml;
}
}
return $yamls;
}
$contents = false;
foreach ($this->_directories as $directory) {
$fullname = $directory . DIRECTORY_SEPARATOR . $filename;
if (!file_exists($fullname)) {
continue;
}
$contents = @file_get_contents($fullname);
}
if ($contents === false) {
throw new BeanFactoryException($filename . ' not found in ' . print_r($this->_directories, true));
}
$ret = @yaml_parse($contents);
if ($ret === false) {
return $ret;
}
$yamls[$filename] = $ret;
if (isset($ret['import'])) {
foreach ($ret['import'] as $imported) {
foreach ($this->_loadYaml($imported) as $name => $yaml) {
$yamls[$name] = $yaml;
}
}
}
return $yamls;
} | php | {
"resource": ""
} |
q262135 | Yaml._load | test | private function _load()
{
if ($this->_yamlFiles !== false) {
return;
}
$this->_yamlFiles = $this->_loadYaml($this->_filename);
if (empty($this->_yamlFiles)) {
throw new BeanFactoryException('Could not parse: ' . $this->_filename);
}
} | php | {
"resource": ""
} |
q262136 | PamiHelper._load | test | private function _load()
{
$options = array(
'host' => $this->_host,
'port' => $this->_port,
'username' => $this->_user,
'secret' => $this->_pass,
'connect_timeout' => $this->_connect_timeout,
'read_timeout' => $this->_read_timeout
);
$this->_ami = new ClientImpl($options);
$this->_init = true;
} | php | {
"resource": ""
} |
q262137 | PamiHelper.open | test | public function open()
{
if (!$this->_init) {
$this->_load();
}
$this->_ami->registerEventListener($this);
$this->_ami->open();
} | php | {
"resource": ""
} |
q262138 | CacheLocator._returnCacheFromImpl | test | private static function _returnCacheFromImpl($options)
{
switch ($options['impl'])
{
case 'file':
return FileCacheImpl::getInstance($options);
case 'apc':
return ApcCacheImpl::getInstance($options);
case 'dummy':
return DummyCacheImpl::getInstance($options);
case 'zend':
return ZendCacheImpl::getInstance($options['zend']);
case 'memcached':
return MemcachedCacheImpl::getInstance($options['memcached']);
default:
throw new CacheException('Invalid cache impl requested');
}
} | php | {
"resource": ""
} |
q262139 | BeanLifecycleManager.afterDefinition | test | public function afterDefinition(BeanDefinition $bean)
{
$return = $bean;
foreach ($this->_lifecyclers[BeanLifecycle::AfterDefinition] as $lifecycleListener) {
$return = $lifecycleListener->afterDefinition($return);
}
return $return;
} | php | {
"resource": ""
} |
q262140 | BeanLifecycleManager.beforeCreate | test | public function beforeCreate(BeanDefinition $beanDefinition)
{
foreach ($this->_lifecyclers[BeanLifecycle::BeforeCreate] as $lifecycleListener) {
$lifecycleListener->beforeCreate($beanDefinition);
}
} | php | {
"resource": ""
} |
q262141 | BeanLifecycleManager.afterCreate | test | public function afterCreate($bean, BeanDefinition $beanDefinition)
{
foreach ($this->_lifecyclers[BeanLifecycle::AfterCreate] as $lifecycleListener) {
$lifecycleListener->afterCreate($bean, $beanDefinition);
}
} | php | {
"resource": ""
} |
q262142 | BeanLifecycleManager.beforeAssemble | test | public function beforeAssemble($bean, BeanDefinition $beanDefinition)
{
foreach ($this->_lifecyclers[BeanLifecycle::BeforeAssemble] as $lifecycleListener) {
$lifecycleListener->beforeAssemble($bean, $beanDefinition);
}
} | php | {
"resource": ""
} |
q262143 | BeanLifecycleManager.afterAssemble | test | public function afterAssemble($bean, BeanDefinition $beanDefinition)
{
foreach ($this->_lifecyclers[BeanLifecycle::AfterAssemble] as $lifecycleListener) {
$lifecycleListener->afterAssemble($bean, $beanDefinition);
}
} | php | {
"resource": ""
} |
q262144 | SyslogHelper.open | test | public function open()
{
openlog($this->_ident, intval($this->_options), intval($this->_facility));
} | php | {
"resource": ""
} |
q262145 | DispatcherImpl.getInterceptors | test | public function getInterceptors($method)
{
if (!isset($this->_methodsIntercepted[$method])) {
return false;
}
return $this->_methodsIntercepted[$method];
} | php | {
"resource": ""
} |
q262146 | DispatcherImpl.getExceptionInterceptors | test | public function getExceptionInterceptors($method)
{
if (!isset($this->_methodsExceptionIntercepted[$method])) {
return false;
}
return $this->_methodsExceptionIntercepted[$method];
} | php | {
"resource": ""
} |
q262147 | DispatcherImpl._callInterceptors | test | private function _callInterceptors(
MethodInvocation $invocation, array $interceptors
) {
$total = count($interceptors) - 1;
$invocationChain = $invocation;
for ($i = $total; $i >= 0; $i--) {
$newInvocation = new MethodInvocation(
get_class($interceptors[$i]->getInterceptor()),
$interceptors[$i]->getInterceptorMethod(),
array($invocationChain),
$interceptors[$i]->getInterceptor(),
$this->reflectionFactory,
$invocation
);
$invocationChain = $newInvocation;
}
return $invocationChain->proceed();
} | php | {
"resource": ""
} |
q262148 | DispatcherImpl.invokeException | test | public function invokeException(MethodInvocation $invocation)
{
$interceptors = $this->getExceptionInterceptors($method = $invocation->getMethod());
if ($interceptors != false && !empty($interceptors)) {
return $this->_callInterceptors($invocation, $interceptors);
}
throw $invocation->getException();
} | php | {
"resource": ""
} |
q262149 | DispatcherImpl.invoke | test | public function invoke(MethodInvocation $invocation)
{
$interceptors = $this->getInterceptors($invocation->getMethod());
if ($interceptors != false) {
return $this->_callInterceptors($invocation, $interceptors);
}
return $invocation->proceed();
} | php | {
"resource": ""
} |
q262150 | TcpClientHelper.close | test | public function close()
{
$this->_connected = false;
$this->_handler->disconnect();
socket_close($this->_socket);
$this->_socket = false;
} | php | {
"resource": ""
} |
q262151 | TcpClientHelper.read | test | public function read(&$buffer, $length, $peek = false)
{
$length = socket_recv($this->_socket, $buffer, $length, $peek ? MSG_PEEK : 0);
return $length;
} | php | {
"resource": ""
} |
q262152 | TcpClientHelper.open | test | public function open($address = false, $port = false)
{
$this->_connected = false;
$this->_socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if ($this->_socket === false) {
throw new TcpException(
'Error opening socket: ' . socket_strerror(socket_last_error())
);
}
if ($this->_reuse) {
socket_set_option ($this->_socket, SOL_SOCKET, SO_REUSEADDR, 1);
}
if ($address !== false) {
if (!@socket_bind($this->_socket, $address, $port)) {
throw new TcpException(
'Error binding socket: ' . socket_strerror(socket_last_error())
);
}
}
if ($this->_cTo > 0) {
socket_set_nonblock($this->_socket);
$timer = 0;
} else {
socket_set_block($this->_socket);
$timer = -1;
}
$result = false;
$this->_handler->beforeConnect();
for(; $timer < $this->_cTo; $timer++)
{
$result = @socket_connect(
$this->_socket, $this->_address, intval($this->_port)
);
if ($result === true) {
break;
}
$error = socket_last_error();
if ($error != SOCKET_EINPROGRESS && $error != SOCKET_EALREADY) {
socket_close($this->_socket);
$error = socket_strerror($error);
$this->_socket = false;
throw new TcpException('Could not connect: ' . $error);
}
// Use the select() as a sleep.
$read = array($this->_socket);
$write = null;
$ex = null;
$result = @socket_select($read, $write, $ex, 0, 650);
}
if (!$result) {
$this->_handler->connectTimeout();
socket_close($this->_socket);
$this->_socket = false;
return;
}
socket_set_nonblock($this->_socket);
$this->_lastDataReadTime = $this->getMicrotime();
$this->_connected = true;
$this->_handler->connect();
register_tick_function(array($this, 'process'));
} | php | {
"resource": ""
} |
q262153 | ModelAndView.add | test | public function add(array $objects)
{
foreach ($objects as $name => $value) {
$this->_objects[$name] = $value;
}
} | php | {
"resource": ""
} |
q262154 | WhoopsEditorServiceProvider.buildUri | test | protected function buildUri(string $uri, string $filePath, int $line): string
{
$uri = str_replace('%file', $filePath, $uri);
$uri = str_replace('%line', $line, $uri);
return $uri;
} | php | {
"resource": ""
} |
q262155 | WhoopsEditorServiceProvider.overwriteAppConfig | test | protected function overwriteAppConfig()
{
$this->config = $this->app->make('config');
$editor = $this->resolveEditor();
$editorConfig = $this->config->get('whoops-editor.editors.' . $editor);
if (!$editorConfig) {
$this->overwriteAppEditor($editor);
return;
}
$this->overwriteAppEditor(function ($filePath, $line) use ($editorConfig) {
$filePath = $this->resolveFilePath($filePath);
if (is_string($editorConfig)) {
return $this->buildUri($editorConfig, $filePath, $line);
}
$editorConfig['url'] = $this->buildUri($editorConfig['url'], $filePath, $line);
return $editorConfig;
});
} | php | {
"resource": ""
} |
q262156 | WhoopsEditorServiceProvider.resolveFilePath | test | protected function resolveFilePath(string $filePath): string
{
$localPath = $this->config->get('whoops-editor.local-projects-path');
$homesteadPath = $this->config->get('whoops-editor.homestead-projects-path');
if (!$localPath || !$homesteadPath) {
return $filePath;
}
$local = rtrim($localPath, '/');
$homestead = rtrim($homesteadPath, '/');
return str_replace("{$homestead}/", "{$local}/", $filePath);
} | php | {
"resource": ""
} |
q262157 | Page.publishedDropDownList | test | public static function publishedDropDownList()
{
$formatter = Yii::$app->formatter;
return [
false => $formatter->asBoolean(false),
true => $formatter->asBoolean(true),
];
} | php | {
"resource": ""
} |
q262158 | DefaultController.findModel | test | protected function findModel($alias)
{
$model = Page::find()->where([
'alias' => $alias,
'published' => true,
])->one();
if ($model !== null) {
return $model;
}
throw new NotFoundHttpException(Module::t('PAGE_NOT_FOUND'));
} | php | {
"resource": ""
} |
q262159 | Link.build | test | public static function build($name, $url, $isInternal, $isNewtab)
{
$link = new static;
$link->title = $name;
$link->url = $url;
$link->is_internal = (bool) $isInternal;
$link->is_newtab = (bool) $isNewtab;
return $link;
} | php | {
"resource": ""
} |
q262160 | ManagerController.actionUpdate | test | public function actionUpdate($id = null)
{
if ($id === null) {
$model = new Page();
$model->display_title = true;
} else {
$model = $this->findModel($id);
}
if ($model->load(Yii::$app->request->post()) && $model->save()) {
Yii::$app->session->setFlash('success', Module::t('SAVE_SUCCESS'));
return $this->redirect(['update', 'id' => $model->id]);
}
$module = Yii::$app->getModule('pages');
return $this->render($id === null ? 'create' : 'update', [
'model' => $model,
'module' => $module,
]);
} | php | {
"resource": ""
} |
q262161 | DatePicker.registerTranslations | test | private function registerTranslations()
{
Yii::$app->i18n->translations['datepicker'] = [
'class' => 'yii\i18n\PhpMessageSource',
'sourceLanguage' => 'en-US',
'basePath' => __DIR__ . DIRECTORY_SEPARATOR . 'messages',
'forceTranslation' => true,
];
$this->clientOptions['tooltips'] = [
'today' => Yii::t('datepicker', 'Go to today'),
'clear' => Yii::t('datepicker', 'Clear selection'),
'close' => Yii::t('datepicker', 'Close the picker'),
'selectMonth' => Yii::t('datepicker', 'Select Month'),
'prevMonth' => Yii::t('datepicker', 'Previous Month'),
'nextMonth' => Yii::t('datepicker', 'Next Month'),
'selectYear' => Yii::t('datepicker', 'Select Year'),
'prevYear' => Yii::t('datepicker', 'Previous Year'),
'nextYear' => Yii::t('datepicker', 'Next Year'),
'selectDecade' => Yii::t('datepicker', 'Select Decade'),
'prevDecade' => Yii::t('datepicker', 'Previous Decade'),
'nextDecade' => Yii::t('datepicker', 'Next Decade'),
'prevCentury' => Yii::t('datepicker', 'Previous Century'),
'nextCentury' => Yii::t('datepicker', 'Next Century'),
'pickHour' => Yii::t('datepicker', 'Pick Hour'),
'incrementHour' => Yii::t('datepicker', 'Increment Hour'),
'decrementHour' => Yii::t('datepicker', 'Decrement Hour'),
'pickMinute' => Yii::t('datepicker', 'Pick Minute'),
'incrementMinute' => Yii::t('datepicker', 'Increment Minute'),
'decrementMinute' => Yii::t('datepicker', 'Decrement Minute'),
'pickSecond' => Yii::t('datepicker', 'Pick Second'),
'incrementSecond' => Yii::t('datepicker', 'Increment Second'),
'decrementSecond' => Yii::t('datepicker', 'Decrement Second'),
'togglePeriod' => Yii::t('datepicker', 'Toggle Period'),
'selectTime' => Yii::t('datepicker', 'Select Time'),
];
} | php | {
"resource": ""
} |
q262162 | DatePicker.registerClientScript | test | public function registerClientScript()
{
$js = [];
$view = $this->getView();
DatePickerAsset::register($view);
$id = $this->options['id'];
$selector = ";jQuery('#$id')";
if ($this->addon) {
$selector .= ".parent()";
}
$this->hashPluginOptions($view);
$js[] = "$selector." . self::PLUGIN_NAME . "({$this->_hashVar});";
if (!empty($this->dropdownItems)) {
$js[] = "$selector.find('.dropdown-menu a').on('click', function (e) { e.preventDefault(); jQuery('#$id').val(jQuery(this).data('value')); });";
}
if ($this->showDecades === false) {
$js[] = "$selector.on('dp.show dp.update', function () { $(this).find('.datepicker-years .picker-switch').removeAttr('title').css('cursor', 'default').css('background', 'inherit').on('click', function (e) { e.stopPropagation(); }); });";
}
if (!empty($this->clientEvents)) {
foreach ($this->clientEvents as $event => $handler) {
$js[] = "$selector.on('$event', $handler);";
}
}
$view->registerJs(implode("\n", $js) . "\n");
} | php | {
"resource": ""
} |
q262163 | EditUserVoter.vote | test | public function vote(TokenInterface $token, $object, array $attributes)
{
$user = $token->getUser();
foreach ($attributes as $attribute) {
if (!$this->supportsAttribute($attribute)) {
continue;
}
if ($this->hasRole($token, 'ROLE_ADMIN')) {
return VoterInterface::ACCESS_GRANTED;
}
if ($attribute == 'EDIT_USER') {
$user2 = $object;
return $this->usersHaveSameId($user, $user2) ? VoterInterface::ACCESS_GRANTED : VoterInterface::ACCESS_DENIED;
}
if ($attribute == 'EDIT_USER_ID') {
$id = $object;
return $this->hasUserId($user, $id) ? VoterInterface::ACCESS_GRANTED : VoterInterface::ACCESS_DENIED;
}
}
return VoterInterface::ACCESS_ABSTAIN;
} | php | {
"resource": ""
} |
q262164 | Mailer.getFromEmail | test | protected function getFromEmail()
{
if (!$this->fromAddress) {
return null;
}
if ($this->fromName) {
return array($this->fromAddress => $this->fromName);
}
return $this->fromAddress;
} | php | {
"resource": ""
} |
q262165 | UserManager.loadUserByUsername | test | public function loadUserByUsername($username)
{
if (strpos($username, '@') !== false) {
$user = $this->findOneBy(array($this->getUserColumns('email') => $username));
if (!$user) {
throw new UsernameNotFoundException(sprintf('Email "%s" does not exist.', $username));
}
return $user;
}
$user = $this->findOneBy(array($this->getUserColumns('username') => $username));
if (!$user) {
throw new UsernameNotFoundException(sprintf('Username "%s" does not exist.', $username));
}
return $user;
} | php | {
"resource": ""
} |
q262166 | UserManager.hydrateUser | test | protected function hydrateUser(array $data)
{
// Test for new columns added in v2.0.
// If they're missing, throw an exception and explain that migration is needed.
foreach (array(
$this->getUserColumns('username'),
$this->getUserColumns('isEnabled'),
$this->getUserColumns('confirmationToken'),
$this->getUserColumns('timePasswordResetRequested')
) as $col) {
if (!array_key_exists($col, $data)) {
throw new \RuntimeException('Internal error: database schema appears out of date. See https://github.com/jasongrimes/silex-simpleuser/blob/master/sql/MIGRATION.md');
}
}
$userClass = $this->getUserClass();
/** @var User $user */
$user = new $userClass($data['email']);
$user->setId($data['id']);
$user->setPassword($data['password']);
$user->setSalt($data['salt']);
$user->setName($data['name']);
if ($roles = explode(',', $data['roles'])) {
$user->setRoles($roles);
}
$user->setTimeCreated($data['time_created']);
$user->setUsername($data['username']);
$user->setEnabled($data['isEnabled']);
$user->setConfirmationToken($data['confirmationToken']);
$user->setTimePasswordResetRequested($data['timePasswordResetRequested']);
if (!empty($data['customFields'])) {
$user->setCustomFields($data['customFields']);
}
return $user;
} | php | {
"resource": ""
} |
q262167 | UserManager.createUser | test | public function createUser($email, $plainPassword, $name = null, $roles = array())
{
$userClass = $this->getUserClass();
$user = new $userClass($email);
if (!empty($plainPassword)) {
$this->setUserPassword($user, $plainPassword);
}
if ($name !== null) {
$user->setName($name);
}
if (!empty($roles)) {
$user->setRoles($roles);
}
return $user;
} | php | {
"resource": ""
} |
q262168 | UserManager.setUserPassword | test | public function setUserPassword(User $user, $password)
{
$user->setPassword($this->encodeUserPassword($user, $password));
} | php | {
"resource": ""
} |
q262169 | UserManager.checkUserPassword | test | public function checkUserPassword(User $user, $password)
{
return $user->getPassword() === $this->encodeUserPassword($user, $password);
} | php | {
"resource": ""
} |
q262170 | UserManager.isLoggedIn | test | function isLoggedIn()
{
$token = $this->app['security']->getToken();
if (null === $token) {
return false;
}
return $this->app['security']->isGranted('IS_AUTHENTICATED_REMEMBERED');
} | php | {
"resource": ""
} |
q262171 | UserManager.findOneBy | test | public function findOneBy(array $criteria)
{
$users = $this->findBy($criteria);
if (empty($users)) {
return null;
}
return reset($users);
} | php | {
"resource": ""
} |
q262172 | UserManager.findBy | test | public function findBy(array $criteria = array(), array $options = array())
{
// Check the identity map first.
if (array_key_exists($this->getUserColumns('id'), $criteria)
&& array_key_exists($criteria[$this->getUserColumns('id')], $this->identityMap)) {
return array($this->identityMap[$criteria[$this->getUserColumns('id')]]);
}
list ($common_sql, $params) = $this->createCommonFindSql($criteria);
$sql = 'SELECT * ' . $common_sql;
if (array_key_exists('order_by', $options)) {
list ($order_by, $order_dir) = is_array($options['order_by']) ? $options['order_by'] : array($options['order_by']);
$sql .= 'ORDER BY ' . $this->conn->quoteIdentifier($order_by) . ' ' . ($order_dir == 'DESC' ? 'DESC' : 'ASC') . ' ';
}
if (array_key_exists('limit', $options)) {
list ($offset, $limit) = is_array($options['limit']) ? $options['limit'] : array(0, $options['limit']);
$sql .= ' LIMIT ' . (int) $limit . ' ' .' OFFSET ' . (int) $offset ;
}
$data = $this->conn->fetchAll($sql, $params);
$users = array();
foreach ($data as $userData) {
if (array_key_exists($userData[$this->getUserColumns('id')], $this->identityMap)) {
$user = $this->identityMap[$userData[$this->getUserColumns('id')]];
} else {
$userData['customFields'] = $this->getUserCustomFields($userData[$this->getUserColumns('id')]);
$user = $this->hydrateUser($userData);
$this->identityMap[$user->getId()] = $user;
}
$users[] = $user;
}
return $users;
} | php | {
"resource": ""
} |
q262173 | UserManager.createCommonFindSql | test | protected function createCommonFindSql(array $criteria = array())
{
$params = array();
$sql = 'FROM ' . $this->conn->quoteIdentifier($this->userTableName). ' ';
// JOIN on custom fields, if needed.
if (array_key_exists('customFields', $criteria)) {
$i = 0;
foreach ($criteria['customFields'] as $attribute => $value) {
$i++;
$alias = 'custom' . $i;
$sql .= 'JOIN ' . $this->conn->quoteIdentifier($this->userCustomFieldsTableName). ' ' . $alias . ' ';
$sql .= 'ON ' . $this->conn->quoteIdentifier($this->userTableName). '.' . $this->getUserColumns('id') . ' = ' . $alias . '.'. $this->getUserColumns('user_id').' ';
$sql .= 'AND ' . $alias . '.'.$this->getUserColumns('attribute').' = :attribute' . $i . ' ';
$sql .= 'AND ' . $alias . '.'.$this->getUserColumns('value').' = :value' . $i . ' ';
$params['attribute' . $i] = $attribute;
$params['value' . $i] = $value;
}
}
$first_crit = true;
foreach ($criteria as $key => $val) {
if ($key == 'customFields') {
continue;
} else {
$sql .= ($first_crit ? 'WHERE' : 'AND') . ' ' . $key . ' = :' . $key . ' ';
$params[$key] = $val;
}
$first_crit = false;
}
return array ($sql, $params);
} | php | {
"resource": ""
} |
q262174 | UserManager.findCount | test | public function findCount(array $criteria = array())
{
list ($common_sql, $params) = $this->createCommonFindSql($criteria);
$sql = 'SELECT COUNT(*) ' . $common_sql;
return $this->conn->fetchColumn($sql, $params) ?: 0;
} | php | {
"resource": ""
} |
q262175 | UserManager.insert | test | public function insert(User $user)
{
$this->dispatcher->dispatch(UserEvents::BEFORE_INSERT, new UserEvent($user));
$sql = 'INSERT INTO ' . $this->conn->quoteIdentifier($this->userTableName) . '
('.$this->getUserColumns('email').', '.$this->getUserColumns('password').', '.$this->getUserColumns('salt').', '.$this->getUserColumns('name').
', '.$this->getUserColumns('roles').', '.$this->getUserColumns('time_created').', '.$this->getUserColumns('username').', '.$this->getUserColumns('isEnabled').
', '.$this->getUserColumns('confirmationToken').', '.$this->getUserColumns('timePasswordResetRequested').')
VALUES (:email, :password, :salt, :name, :roles, :timeCreated, :username, :isEnabled, :confirmationToken, :timePasswordResetRequested) ';
$params = array(
'email' => $user->getEmail(),
'password' => $user->getPassword(),
'salt' => $user->getSalt(),
'name' => $user->getName(),
'roles' => implode(',', $user->getRoles()),
'timeCreated' => $user->getTimeCreated(),
'username' => $user->getRealUsername(),
'isEnabled' => $user->isEnabled(),
'confirmationToken' => $user->getConfirmationToken(),
'timePasswordResetRequested' => $user->getTimePasswordResetRequested(),
);
$this->conn->executeUpdate($sql, $params);
$user->setId($this->conn->lastInsertId());
$this->saveUserCustomFields($user);
$this->identityMap[$user->getId()] = $user;
$this->dispatcher->dispatch(UserEvents::AFTER_INSERT, new UserEvent($user));
} | php | {
"resource": ""
} |
q262176 | UserManager.update | test | public function update(User $user)
{
$this->dispatcher->dispatch(UserEvents::BEFORE_UPDATE, new UserEvent($user));
$sql = 'UPDATE ' . $this->conn->quoteIdentifier($this->userTableName). '
SET '.$this->getUserColumns('email').' = :email
, '.$this->getUserColumns('password').' = :password
, '.$this->getUserColumns('salt').' = :salt
, '.$this->getUserColumns('name').' = :name
, '.$this->getUserColumns('roles').' = :roles
, '.$this->getUserColumns('time_created').' = :timeCreated
, '.$this->getUserColumns('username').' = :username
, '.$this->getUserColumns('isEnabled').' = :isEnabled
, '.$this->getUserColumns('confirmationToken').' = :confirmationToken
, '.$this->getUserColumns('timePasswordResetRequested').' = :timePasswordResetRequested
WHERE '.$this->getUserColumns('id').' = :id';
$params = array(
'email' => $user->getEmail(),
'password' => $user->getPassword(),
'salt' => $user->getSalt(),
'name' => $user->getName(),
'roles' => implode(',', $user->getRoles()),
'timeCreated' => $user->getTimeCreated(),
'username' => $user->getRealUsername(),
'isEnabled' => $user->isEnabled(),
'confirmationToken' => $user->getConfirmationToken(),
'timePasswordResetRequested' => $user->getTimePasswordResetRequested(),
'id' => $user->getId(),
);
$this->conn->executeUpdate($sql, $params);
$this->saveUserCustomFields($user);
$this->dispatcher->dispatch(UserEvents::AFTER_UPDATE, new UserEvent($user));
} | php | {
"resource": ""
} |
q262177 | UserManager.delete | test | public function delete(User $user)
{
$this->dispatcher->dispatch(UserEvents::BEFORE_DELETE, new UserEvent($user));
$this->clearIdentityMap($user);
$this->conn->executeUpdate('DELETE FROM ' . $this->conn->quoteIdentifier($this->userTableName). ' WHERE '.$this->getUserColumns('id').' = ?', array($user->getId()));
$this->conn->executeUpdate('DELETE FROM ' . $this->conn->quoteIdentifier($this->userCustomFieldsTableName). ' WHERE '.$this->getUserColumns('user_id').' = ?', array($user->getId()));
$this->dispatcher->dispatch(UserEvents::AFTER_DELETE, new UserEvent($user));
} | php | {
"resource": ""
} |
q262178 | UserManager.validate | test | public function validate(User $user)
{
$errors = $user->validate();
// Ensure email address is unique.
$duplicates = $this->findBy(array($this->getUserColumns('email') => $user->getEmail()));
if (!empty($duplicates)) {
foreach ($duplicates as $dup) {
if ($user->getId() && $dup->getId() == $user->getId()) {
continue;
}
$errors['email'] = 'An account with that email address already exists.';
}
}
// Ensure username is unique.
$duplicates = $this->findBy(array($this->getUserColumns('username') => $user->getRealUsername()));
if (!empty($duplicates)) {
foreach ($duplicates as $dup) {
if ($user->getId() && $dup->getId() == $user->getId()) {
continue;
}
$errors['username'] = 'An account with that username already exists.';
}
}
// If username is required, ensure it is set.
if ($this->isUsernameRequired && !$user->getRealUsername()) {
$errors['username'] = 'Username is required.';
}
return $errors;
} | php | {
"resource": ""
} |
q262179 | UserManager.clearIdentityMap | test | public function clearIdentityMap($user = null)
{
if ($user === null) {
$this->identityMap = array();
} else if ($user instanceof User && array_key_exists($user->getId(), $this->identityMap)) {
unset($this->identityMap[$user->getId()]);
} else if (is_numeric($user) && array_key_exists($user, $this->identityMap)) {
unset($this->identityMap[$user]);
}
} | php | {
"resource": ""
} |
q262180 | UserManager.loginAsUser | test | public function loginAsUser(User $user)
{
if (null !== ($current_token = $this->app['security']->getToken())) {
$providerKey = method_exists($current_token, 'getProviderKey') ? $current_token->getProviderKey() : $current_token->getKey();
$token = new UsernamePasswordToken($user, null, $providerKey);
$this->app['security']->setToken($token);
$this->app['user'] = $user;
}
} | php | {
"resource": ""
} |
q262181 | ProcessPool.init | test | private function init($force = false)
{
if (!function_exists('pcntl_signal') || ($this->initialized && !$force)) {
return;
}
$this->initialized = true;
pcntl_signal(SIGCHLD, array($this, 'signalHandler'));
} | php | {
"resource": ""
} |
q262182 | ProcessPool.reaper | test | public function reaper($pid = null, $status = null)
{
if ($pid === null) {
$pid = pcntl_waitpid(-1, $status, WNOHANG);
}
while ($pid > 0) {
if (isset($this->workers[$pid])) {
// @todo does the socket really need to be closed?
//@socket_close($this->workers[$pid]['socket']);
unset($this->workers[$pid]);
} else {
// the child died before the parent could initialize the $worker
// queue. So we track it temporarily so we can handle it in
// self::create().
$this->caught[$pid] = $status;
}
$pid = pcntl_waitpid(-1, $status, WNOHANG);
}
} | php | {
"resource": ""
} |
q262183 | ProcessPool.wait | test | public function wait($timeout = null)
{
$x = null; // trash var needed for socket_select
$startTime = microtime(true);
while (true) {
$this->apply(); // maintain worker queue
// check each child socket pair for a new result
$read = array_map(function($w){ return $w['socket']; }, $this->workers);
// it's possible for no workers/sockets to be present due to REAPING
if (!empty($read)) {
$ok = @socket_select($read, $x, $x, $timeout);
if ($ok !== false and $ok > 0) {
return $read;
}
}
// timed out?
if ($timeout and microtime(true) - $startTime > $timeout) {
return null;
}
// no sense in waiting if we have no workers and no more pending
if (empty($this->workers) and empty($this->pending)) {
return null;
}
}
} | php | {
"resource": ""
} |
q262184 | ProcessPool.get | test | public function get($timeout = null, $nullOnTimeout = false)
{
$startTime = microtime(true);
while ($this->getPending()) {
// return the next result
if ($this->hasResult()) {
return $this->getResult();
}
// wait for the next result
$ready = $this->wait($timeout);
if (is_array($ready)) {
foreach ($ready as $socket) {
$res = self::socket_fetch($socket);
if ($res !== null) {
$this->results[] = $res;
$this->count++;
}
}
if ($this->hasResult()) {
return $this->getResult();
}
}
// timed out?
if ($timeout and microtime(true) - $startTime > $timeout) {
if ($nullOnTimeout) {
return null;
}
throw new ProcessPoolException("Timeout");
}
}
} | php | {
"resource": ""
} |
q262185 | ProcessPool.getAll | test | public function getAll($timeout = null, $nullOnTimeout = false)
{
$results = array();
$startTime = microtime(true);
while ($this->getPending()) {
try {
$res = $this->get($timeout);
if ($res !== null) {
$results[] = $res;
}
} catch (ProcessPoolException $e) {
// timed out
}
// timed out?
if ($timeout and microtime(true) - $startTime > $timeout) {
if ($nullOnTimeout) {
return null;
}
throw new ProcessPoolException("Timeout");
}
}
return $results;
} | php | {
"resource": ""
} |
q262186 | ProcessPool.apply | test | public function apply($func = null)
{
// add new function to pending queue
if ($func !== null) {
if ($func instanceof \Closure or $func instanceof ProcessInterface or is_callable($func)) {
$this->pending[] = func_get_args();
} else {
throw new \UnexpectedValueException("Parameter 1 in ProcessPool#apply must be a Closure or callable");
}
}
// start a new worker if our current worker queue is low
if (!empty($this->pending) and count($this->workers) < $this->max) {
call_user_func_array(array($this, 'create'), array_shift($this->pending));
}
return $this;
} | php | {
"resource": ""
} |
q262187 | ProcessPool.getPending | test | public function getPending($pendingOnly = false)
{
if ($pendingOnly) {
return count($this->pending);
}
return count($this->pending) + count($this->workers) + count($this->results);
} | php | {
"resource": ""
} |
q262188 | ProcessPool.socket_send | test | public static function socket_send($socket, $data)
{
$serialized = serialize($data);
$hdr = pack('N', strlen($serialized)); // 4 byte length
$buffer = $hdr . $serialized;
$total = strlen($buffer);
while (true) {
$sent = socket_write($socket, $buffer);
if ($sent === false) {
// @todo handle error?
//$error = socket_strerror(socket_last_error());
break;
}
if ($sent >= $total) {
break;
}
$total -= $sent;
$buffer = substr($buffer, $sent);
}
} | php | {
"resource": ""
} |
q262189 | ProcessPool.socket_fetch | test | public static function socket_fetch($socket)
{
// read 4 byte length first
$hdr = '';
do {
$read = socket_read($socket, 4 - strlen($hdr));
if ($read === false or $read === '') {
return null;
}
$hdr .= $read;
} while (strlen($hdr) < 4);
list($len) = array_values(unpack("N", $hdr));
// read the full buffer
$buffer = '';
do {
$read = socket_read($socket, $len - strlen($buffer));
if ($read === false or $read == '') {
return null;
}
$buffer .= $read;
} while (strlen($buffer) < $len);
$data = unserialize($buffer);
return $data;
} | php | {
"resource": ""
} |
q262190 | MigrateV1ToV2.sqlDownData | test | public function sqlDownData()
{
// Map columns to custom fields.
$colmap = array();
foreach ($this->fieldmap as $field => $col) {
$colmap[$col] = $field;
}
// Test that the v2 columns actually exist.
$existingCols = $this->conn->getSchemaManager()->listTableColumns($this->usersTable);
$existingColnames = array_map(function($col) { return $col->getName(); }, $existingCols);
foreach ($this->fieldmap as $col) {
if (!in_array($col, $existingColnames)) {
throw new \RuntimeException('Cannot migrate down because current schema is not v2. (Missing column "' . $this->usersTable . '.' . $col . '").');
}
}
// Get user columns to revert back to custom fields.
$userData = $this->conn->fetchAll('SELECT id AS user_id, ' . implode(', ', $this->fieldmap) . ' FROM ' . $this->conn->quoteIdentifier($this->usersTable));
$queries = array();
foreach ($userData as $row) {
foreach ($this->fieldmap as $col) {
if ($row[$col] !== null) {
$queries[] = 'INSERT INTO ' . $this->conn->quoteIdentifier($this->userCustomFieldsTable)
. ' (user_id, attribute, value) VALUES'
. ' (' . $this->conn->quote($row['user_id'], Type::INTEGER)
. ', ' . $this->conn->quote($colmap[$col], Type::STRING)
. ', ' . $this->conn->quote($row[$col], Type::STRING)
. ')';
}
}
}
return $queries;
} | php | {
"resource": ""
} |
q262191 | UserController.registerAction | test | public function registerAction(Application $app, Request $request)
{
if ($request->isMethod('POST')) {
try {
$user = $this->createUserFromRequest($request);
if ($error = $this->userManager->validatePasswordStrength($user, $request->request->get('password'))) {
throw new InvalidArgumentException($error);
}
if ($this->isEmailConfirmationRequired) {
$user->setEnabled(false);
$user->setConfirmationToken($app['user.tokenGenerator']->generateToken());
}
$this->userManager->insert($user);
if ($this->isEmailConfirmationRequired) {
// Send email confirmation.
$app['user.mailer']->sendConfirmationMessage($user);
// Render the "go check your email" page.
return $app['twig']->render($this->getTemplate('register-confirmation-sent'), array(
'layout_template' => $this->getTemplate('layout'),
'email' => $user->getEmail(),
));
} else {
// Log the user in to the new account.
$this->userManager->loginAsUser($user);
$app['session']->getFlashBag()->set('alert', 'Account created.');
// Redirect to user's new profile page.
return $app->redirect($app['url_generator']->generate('user.view', array('id' => $user->getId())));
}
} catch (InvalidArgumentException $e) {
$error = $e->getMessage();
}
}
return $app['twig']->render($this->getTemplate('register'), array(
'layout_template' => $this->getTemplate('layout'),
'error' => isset($error) ? $error : null,
'name' => $request->request->get('name'),
'email' => $request->request->get('email'),
'username' => $request->request->get('username'),
'isUsernameRequired' => $this->isUsernameRequired,
));
} | php | {
"resource": ""
} |
q262192 | UserController.confirmEmailAction | test | public function confirmEmailAction(Application $app, Request $request, $token)
{
$user = $this->userManager->findOneBy(array('confirmationToken' => $token));
if (!$user) {
$app['session']->getFlashBag()->set('alert', 'Sorry, your email confirmation link has expired.');
return $app->redirect($app['url_generator']->generate('user.login'));
}
$user->setConfirmationToken(null);
$user->setEnabled(true);
$this->userManager->update($user);
$this->userManager->loginAsUser($user);
$app['session']->getFlashBag()->set('alert', 'Thank you! Your account has been activated.');
return $app->redirect($app['url_generator']->generate('user.view', array('id' => $user->getId())));
} | php | {
"resource": ""
} |
q262193 | UserController.loginAction | test | public function loginAction(Application $app, Request $request)
{
$authException = $app['user.last_auth_exception']($request);
if ($authException instanceof DisabledException) {
// This exception is thrown if (!$user->isEnabled())
// Warning: Be careful not to disclose any user information besides the email address at this point.
// The Security system throws this exception before actually checking if the password was valid.
$user = $this->userManager->refreshUser($authException->getUser());
return $app['twig']->render($this->getTemplate('login-confirmation-needed'), array(
'layout_template' => $this->getTemplate('layout'),
'email' => $user->getEmail(),
'fromAddress' => $app['user.mailer']->getFromAddress(),
'resendUrl' => $app['url_generator']->generate('user.resend-confirmation'),
));
}
return $app['twig']->render($this->getTemplate('login'), array(
'layout_template' => $this->getTemplate('layout'),
'error' => $authException ? $authException->getMessageKey() : null,
'last_username' => $app['session']->get('_security.last_username'),
'allowRememberMe' => isset($app['security.remember_me.response_listener']),
'allowPasswordReset' => $this->isPasswordResetEnabled(),
));
} | php | {
"resource": ""
} |
q262194 | UserController.resendConfirmationAction | test | public function resendConfirmationAction(Application $app, Request $request)
{
$email = $request->request->get('email');
$user = $this->userManager->findOneBy(array('email' => $email));
if (!$user) {
throw new NotFoundHttpException('No user account was found with that email address.');
}
if (!$user->getConfirmationToken()) {
$user->setConfirmationToken($app['user.tokenGenerator']->generateToken());
$this->userManager->update($user);
}
$app['user.mailer']->sendConfirmationMessage($user);
// Render the "go check your email" page.
return $app['twig']->render($this->getTemplate('register-confirmation-sent'), array(
'layout_template' => $this->getTemplate('layout'),
'email' => $user->getEmail(),
));
} | php | {
"resource": ""
} |
q262195 | UserController.viewAction | test | public function viewAction(Application $app, Request $request, $id)
{
$user = $this->userManager->getUser($id);
if (!$user) {
throw new NotFoundHttpException('No user was found with that ID.');
}
if (!$user->isEnabled() && !$app['security']->isGranted('ROLE_ADMIN')) {
throw new NotFoundHttpException('That user is disabled (pending email confirmation).');
}
return $app['twig']->render($this->getTemplate('view'), array(
'layout_template' => $this->getTemplate('layout'),
'user' => $user,
'imageUrl' => $this->getGravatarUrl($user->getEmail()),
));
} | php | {
"resource": ""
} |
q262196 | UserController.editAction | test | public function editAction(Application $app, Request $request, $id)
{
$errors = array();
$user = $this->userManager->getUser($id);
if (!$user) {
throw new NotFoundHttpException('No user was found with that ID.');
}
$customFields = $this->editCustomFields ?: array();
if ($request->isMethod('POST')) {
$user->setName($request->request->get('name'));
$user->setEmail($request->request->get('email'));
if ($request->request->has('username')) {
$user->setUsername($request->request->get('username'));
}
if ($request->request->get('password')) {
if ($request->request->get('password') != $request->request->get('confirm_password')) {
$errors['password'] = 'Passwords don\'t match.';
} else if ($error = $this->userManager->validatePasswordStrength($user, $request->request->get('password'))) {
$errors['password'] = $error;
} else {
$this->userManager->setUserPassword($user, $request->request->get('password'));
}
}
if ($app['security']->isGranted('ROLE_ADMIN') && $request->request->has('roles')) {
$user->setRoles($request->request->get('roles'));
}
foreach (array_keys($customFields) as $customField) {
if ($request->request->has($customField)) {
$user->setCustomField($customField, $request->request->get($customField));
}
}
$errors += $this->userManager->validate($user);
if (empty($errors)) {
$this->userManager->update($user);
$msg = 'Saved account information.' . ($request->request->get('password') ? ' Changed password.' : '');
$app['session']->getFlashBag()->set('alert', $msg);
}
}
return $app['twig']->render($this->getTemplate('edit'), array(
'layout_template' => $this->getTemplate('layout'),
'error' => implode("\n", $errors),
'user' => $user,
'available_roles' => array('ROLE_USER', 'ROLE_ADMIN'),
'image_url' => $this->getGravatarUrl($user->getEmail()),
'customFields' => $customFields,
'isUsernameRequired' => $this->isUsernameRequired,
));
} | php | {
"resource": ""
} |
q262197 | User.validate | test | public function validate()
{
$errors = array();
if (!$this->getEmail()) {
$errors['email'] = 'Email address is required.';
} else if (!strpos($this->getEmail(), '@')) {
// Basic email format sanity check. Real validation comes from sending them an email with a link they have to click.
$errors['email'] = 'Email address appears to be invalid.';
} else if (strlen($this->getEmail()) > 100) {
$errors['email'] = 'Email address can\'t be longer than 100 characters.';
}
if (!$this->getPassword()) {
$errors['password'] = 'Password is required.';
} else if (strlen($this->getPassword()) > 255) {
$errors['password'] = 'Password can\'t be longer than 255 characters.';
}
if (strlen($this->getName()) > 100) {
$errors['name'] = 'Name can\'t be longer than 100 characters.';
}
// Username can't contain "@",
// because that's how we distinguish between email and username when signing in.
// (It's possible to sign in by providing either one.)
if ($this->getRealUsername() && strpos($this->getRealUsername(), '@') !== false) {
$errors['username'] = 'Username cannot contain the "@" symbol.';
}
return $errors;
} | php | {
"resource": ""
} |
q262198 | UserServiceProvider.connect | test | public function connect(Application $app)
{
if (!$app['resolver'] instanceof ServiceControllerResolver) {
// using RuntimeException crashes PHP?!
throw new \LogicException('You must enable the ServiceController service provider to be able to use these routes.');
}
/** @var ControllerCollection $controllers */
$controllers = $app['controllers_factory'];
$controllers->get('/', 'user.controller:viewSelfAction')
->bind('user')
->before(function(Request $request) use ($app) {
// Require login. This should never actually cause access to be denied,
// but it causes a login form to be rendered if the viewer is not logged in.
if (!$app['user']) {
throw new AccessDeniedException();
}
});
$controllers->get('/{id}', 'user.controller:viewAction')
->bind('user.view')
->assert('id', '\d+');
$controllers->method('GET|POST')->match('/{id}/edit', 'user.controller:editAction')
->bind('user.edit')
->before(function(Request $request) use ($app) {
if (!$app['security']->isGranted('EDIT_USER_ID', $request->get('id'))) {
throw new AccessDeniedException();
}
});
$controllers->get('/list', 'user.controller:listAction')
->bind('user.list');
$controllers->method('GET|POST')->match('/register', 'user.controller:registerAction')
->bind('user.register');
$controllers->get('/confirm-email/{token}', 'user.controller:confirmEmailAction')
->bind('user.confirm-email');
$controllers->post('/resend-confirmation', 'user.controller:resendConfirmationAction')
->bind('user.resend-confirmation');
$controllers->get('/login', 'user.controller:loginAction')
->bind('user.login');
$controllers->method('GET|POST')->match('/forgot-password', 'user.controller:forgotPasswordAction')
->bind('user.forgot-password');
$controllers->get('/reset-password/{token}', 'user.controller:resetPasswordAction')
->bind('user.reset-password');
// login_check and logout are dummy routes so we can use the names.
// The security provider should intercept these, so no controller is needed.
$controllers->method('GET|POST')->match('/login_check', function() {})
->bind('user.login_check');
$controllers->get('/logout', function() {})
->bind('user.logout');
return $controllers;
} | php | {
"resource": ""
} |
q262199 | FormattedResponder.priorities | test | protected function priorities()
{
$priorities = [];
foreach ($this as $formatter => $quality) {
foreach ($formatter::accepts() as $type) {
$priorities[$type] = $formatter;
}
}
return $priorities;
} | php | {
"resource": ""
} |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.