/** * @param \Nette\DI\Container $dic * @throws MemberAccessException * @internal */ public function injectComponentFactories(Nette\DI\Container $dic) { if (!$this instanceof Nette\Application\UI\PresenterComponent && !$this instanceof Nette\Application\UI\Component) { throw new MemberAccessException('Trait ' . __TRAIT__ . ' can be used only in descendants of PresenterComponent.'); } $this->autowireComponentFactoriesLocator = $dic; $storage = $dic->hasService('autowired.cacheStorage') ? $dic->getService('autowired.cacheStorage') : $dic->getByType('Nette\\Caching\\IStorage'); $cache = new Nette\Caching\Cache($storage, 'Kdyby.Autowired.AutowireComponentFactories'); if ($cache->load($presenterClass = get_class($this)) !== NULL) { return; } $ignore = class_parents('Nette\\Application\\UI\\Presenter') + ['ui' => 'Nette\\Application\\UI\\Presenter']; $rc = new ClassType($this); foreach ($rc->getMethods() as $method) { if (in_array($method->getDeclaringClass()->getName(), $ignore, TRUE) || !Strings::startsWith($method->getName(), 'createComponent')) { continue; } foreach ($method->getParameters() as $parameter) { if (!($class = $parameter->getClassName())) { // has object type hint continue; } if (!$this->findByTypeForFactory($class) && !$parameter->allowsNull()) { throw new MissingServiceException("No service of type {$class} found. Make sure the type hint in {$method} is written correctly and service of this type is registered."); } } } $files = array_map(function ($class) { return ClassType::from($class)->getFileName(); }, array_diff(array_values(class_parents($presenterClass) + ['me' => $presenterClass]), $ignore)); $files[] = ClassType::from($this->autowireComponentFactoriesLocator)->getFileName(); $cache->save($presenterClass, TRUE, [$cache::FILES => $files]); }
private function setupServices() { $builder = $this->getContainerBuilder(); $config = $this->validateConfig($this->defaults); $gopay = $builder->getDefinition($this->prefix('gopay')); $services = ['payment' => PaymentService::class, 'recurrentPayment' => RecurrentPaymentService::class, 'preAuthorizedPayment' => PreAuthorizedPaymentService::class]; foreach ($services as $serviceName => $serviceClass) { $def = $builder->addDefinition($this->prefix("service.{$serviceName}"))->setClass($serviceClass, [$gopay]); if (is_bool($config['payments']['changeChannel'])) { $def->addSetup('allowChangeChannel', [$config['payments']['changeChannel']]); } if (isset($config['payments']['channels'])) { $constants = ClassType::from(Gopay::class); foreach ($config['payments']['channels'] as $code => $channel) { $constChannel = 'METHOD_' . strtoupper($code); if ($constants->hasConstant($constChannel)) { $code = $constants->getConstant($constChannel); } if (is_array($channel)) { $channel['code'] = $code; $def->addSetup('addChannel', $channel); } else { if (is_scalar($channel)) { $def->addSetup('addChannel', [$code, $channel]); } } } } } }
/** * @param $class */ public function getSchema($class) { if (!isset($this->_annotationSchema[$class])) { $schema = array(); $ref = ClassType::from($class); if ($ref->hasAnnotation('secured')) { foreach ($ref->getMethods() as $method) { $name = $method->getName(); if (substr($name, 0, 6) !== 'action' && substr($name, 0, 6) !== 'handle') { continue; } if ($method->hasAnnotation('secured')) { $secured = $method->getAnnotation('secured'); $name = $method->getName(); $schema[$name] = array(); $schema[$name]['resource'] = $this->getSchemaOfResource($method, $secured); $schema[$name]['privilege'] = $this->getSchemaOfPrivilege($method, $secured); $schema[$name]['roles'] = $this->getSchemaOfRoles($method, $secured); $schema[$name]['users'] = $this->getSchemaOfUsers($method, $secured); } } } $this->_annotationSchema[$class] = $schema; } return $this->_annotationSchema[$class]; }
public static function build($className) { $reflection = \Nette\Reflection\ClassType::from($className); $annotations = $reflection->getAnnotations(); $ret = array('entityClass' => $className); foreach ($annotations as $key => $value) { if ($key == "Entity") { $entity = $value[0]; if (isset($entity->repositoryClass)) { $ret['repositoryClass'] = (string) $entity->repositoryClass; } elseif (isset($entity->validatorClass)) { $ret['validatorClass'] = (string) $entity->validatorClass; } } elseif ($key == "Table") { $table = $value[0]; $ret['table'] = (string) $table->name; $ret['mainIndex'] = isset($table->mainIndex) ? (string) $table->mainIndex : NULL; $ret['topicIndex'] = isset($table->topicIndex) ? (string) $table->topicIndex : NULL; } elseif ($key == "Column") { foreach ($value as $column) { $name = $column->name; unset($column->name); $ret['columns'][$name] = (array) $column; } } elseif (in_array($key, array("AssociationHasOne", "AssociationHasMany"))) { foreach ($value as $association) { $name = $association->name; unset($association->name); $ret['associations'][$name] = (array) $association; } } } return $ret; }
public function testSignalAllow() { $this->presenter->setSignalMock("test2"); $this->presenter->checkRequirements(ClassType::from(__NAMESPACE__ . '\BackendPresenter\PresenterMock')); $this->assertFalse($this->presenter->isAllowedMock('handleTest1')); $this->assertTrue($this->presenter->isAllowedMock('handleTest2')); }
public function __construct($type) { if (strpos($type, '*') !== FALSE) { $this->pattern = str_replace('\\*', '.*', preg_quote($type)); } else { $this->type = Nette\Reflection\ClassType::from($type)->getName(); } }
/** * Sets a variable in this session section. * @param string name * @param mixed value * @return void */ public function __set($name, $value) { $this->start(); $this->data[$name] = $value; if (is_object($value)) { $this->meta[$name]['V'] = Nette\Reflection\ClassType::from($value)->getAnnotation('serializationVersion'); } }
public function loadConfiguration() { $builder = $this->getContainerBuilder(); $latte = $builder->hasDefinition('nette.latteFactory') ? $builder->getDefinition('nette.latteFactory') : $builder->getDefinition('nette.latte'); $latte->addSetup('Lohini\\Latte\\Macros\\CoreMacros::install(?->getCompiler())', ['@self']); foreach (\Nette\Reflection\ClassType::from('Lohini\\Latte\\Filters')->getMethods() as $method) { $latte->addSetup('addFilter', [$method->name, ['Lohini\\Latte\\Filters', $method->name]]); } }
public function __construct(Nette\DI\ServiceDefinition $def, $serviceId) { $this->serviceDefinition = $def; if (empty($def->class)) { throw new Kdyby\Aop\InvalidArgumentException("Given service definition has unresolved class, please specify service type explicitly."); } $this->originalType = Nette\Reflection\ClassType::from($def->class); $this->serviceId = $serviceId; }
/** * Registers adapter for given file extension. * @param string file extension * @param string class name (IConfigAdapter) * @return void */ public static function registerExtension($extension, $class) { if (!class_exists($class)) { throw new Nette\InvalidArgumentException("Class '{$class}' was not found."); } if (!Nette\Reflection\ClassType::from($class)->implementsInterface('Nette\\Config\\IAdapter')) { throw new Nette\InvalidArgumentException("Configuration adapter '{$class}' is not Nette\\Config\\IAdapter implementor."); } self::$extensions[strtolower($extension)] = $class; }
public function beforeCompile() { $builder = $this->getContainerBuilder(); $mapping = $builder->getDefinition('movi.entityMapping'); foreach (array_keys($builder->findByTag(self::REPOSITORY_TAG)) as $repository) { $reflection = ClassType::from($builder->getDefinition($repository)->class); $class = $reflection->newInstanceWithoutConstructor(); $mapping->addSetup('registerEntities', array($class->getEntities())); } }
public function getTests() { $tests = []; foreach (ClassType::from($this)->getMethods(Method::IS_PUBLIC) as $method) { $name = $method->getShortName(); if (preg_match(static::METHOD_PATTERN, $name)) { $tests[] = $name; } } return $tests; }
/** * Získá všechny hodnoty z entity, které mají anotaci @column a nemají anotaci @id. * @return array */ public function getValues() { $reflector = \Nette\Reflection\ClassType::from($this); $values = array(); foreach ($reflector->getProperties() as $property) { if ($property->hasAnnotation("column") && !$property->hasAnnotation("id")) { $name = $property->getName(); $values[$this->normalizeColumnName($name)] = $this->{$name}; } } return $values; }
public function preFlush(PreFlushEventArgs $args) { $em = $args->getEntityManager(); $uow = $em->getUnitOfWork(); foreach ($uow->getScheduledEntityInsertions() as $entity) { $reflection = Nette\Reflection\ClassType::from($entity); if ($reflection->hasProperty("priority")) { $repository = $em->getRepository($reflection->getName()); $result = $repository->createQueryBuilder("p")->select("MAX(p.priority)")->getQuery()->execute(); $entity->priority = ($result ? (int) $result[0][1] : 0) + 1; } } }
/** * @param $entity * @param callable $modifier * @return \Kdyby\Doctrine\QueryBuilder */ private function createBaseQuery($entity, $modifier) { $reflection = ClassType::from($entity); if (!$reflection->hasProperty('priority')) { throw new InvalidArgumentException('Entity has not property $priority'); } $qb = $this->entityManager->getRepository($reflection->getName())->createQueryBuilder("e")->select(); if ($modifier !== NULL) { $modifier($qb); } $qb->setMaxResults(1); return $qb; }
/** * @param string * @return array */ protected static function getAllClassTypes($class) { $rc = Reflection\ClassType::from($class); $classTypes = array_merge(array($class), class_parents($class), class_implements($class)); if (PHP_VERSION_ID >= 50400) { do { $classTypes = array_merge($classTypes, $rc->getTraitNames()); } while ($rc = $rc->getParentClass()); } return array_map(function ($val) { return ltrim(strtolower($val), '\\'); }, $classTypes); }
/** * @param Container * @param string * @return Service */ public function __construct(Container $container, $entityClass) { if (!class_exists($entityClass)) { throw new \Nette\InvalidArgumentException("Entity '$entityClass' does not exist"); } elseif (!\Nette\Reflection\ClassType::from($entityClass)->implementsInterface('Nella\Models\IEntity')) { throw new \Nette\InvalidArgumentException( "Entity '$entityClass' does not valid entity (must implements Nella\\Models\\IEntity)" ); } $this->container = $container; $this->entityClass = $entityClass; }
protected function loadProperties(&$fileDependencies) { $classTree = [$current = $this->reflection->name]; while (($current = get_parent_class($current)) !== false) { $classTree[] = $current; } foreach (array_reverse($classTree) as $class) { $reflection = ClassType::from($class); $fileDependencies[] = $reflection->getFileName(); $this->currentReflection = $reflection; $this->parseAnnotations($reflection); } }
private function initDatabase($fileName = null) { $reflection = \Nette\Reflection\ClassType::from(get_class($this)); $dir = dirname($reflection->getFileName()); $fileName = $fileName ? $fileName : $dir . '/init.sql'; $initSql = file_get_contents($fileName); $queries = explode(';', $initSql); foreach ($queries as $query) { if (empty($query)) { continue; } $this->database->query(trim($query)); } }
protected function loadProperties(&$fileDependencies) { $classTree = [$current = $this->reflection->name]; while (($current = get_parent_class($current)) !== FALSE) { if (strpos($current, 'Fragment') !== FALSE) { break; } $classTree[] = $current; } foreach (array_reverse($classTree) as $class) { $reflection = ClassType::from($class); $fileDependencies[] = $reflection->getFileName(); $this->parseAnnotations($reflection); } }
/** * @return Latte\Token */ private function findCurrentToken() { static $positionRef, $tokensRef; if (!property_exists('Nette\\Latte\\Token', 'empty')) { return NULL; } if (empty($positionRef)) { $compilerRef = ClassType::from($this->getCompiler()); $positionRef = $compilerRef->getProperty('position'); $positionRef->setAccessible(TRUE); $tokensRef = $compilerRef->getProperty('tokens'); $tokensRef->setAccessible(TRUE); } $tokens = $tokensRef->getValue($this->getCompiler()); return $tokens[$positionRef->getValue($this->getCompiler())]; }
/** * @param string * @param \Doctrine\ORM\Mapping\ClassMetadataInfo */ public function loadMetadataForClass($className, \Doctrine\ORM\Mapping\ClassMetadataInfo $metadata) { parent::loadMetadataForClass($className, $metadata); if ($metadata instanceof \Nella\Doctrine\Mapping\ClassMetadata) { $class = \Nette\Reflection\ClassType::from($className); if ($class->hasAnnotation('service')) { $service = $class->getAnnotation('service'); if (!isset($service['class'])) { throw new \Doctrine\ORM\Mapping\MappingException("Missing service class."); } $metadata->setServiceClass($service['class']); } } }
/** * Registers repositories from annotations */ private function registerAnnotations() { $ref = Nette\Reflection\ClassType::from($this); $annotations = $ref->getAnnotations(); if (isset($annotations['property-read'])) { $c = get_called_class(); $namespace = substr($c, 0, strrpos($c, '\\')); foreach ($annotations['property-read'] as $value) { if (preg_match('#^([\\\\\\w]+Repository)\\s+\\$(\\w+)$#', $value, $m)) { $class = '\\' . Reflection\AnnotationsParser::expandClassName($m[1], $ref); $this->register($m[2], $class); $this->aliases[$m[2]] = $class; } } } }
/** * Adds new services from list of definitions. Expands %param% and @service values. * Format: * serviceName => array( * class => 'ClassName' or factory => 'Factory::create' * arguments => array(...) * methods => array( * array(methodName, array(...)) * ... * ) * tags => array(...) * ) */ public function addDefinitions(IContainer $container, array $definitions) { foreach ($definitions as $name => $definition) { if (!is_array($definition)) { $definition = array('class' => $definition); } $arguments = isset($definition['arguments']) ? $definition['arguments'] : array(); $expander = function (&$val) use($container) { $val = $val[0] === '@' ? $container->getService(substr($val, 1)) : $container->expand($val); }; if (isset($definition['class'])) { $class = $definition['class']; $methods = isset($definition['methods']) ? $definition['methods'] : array(); $factory = function ($container) use($class, $arguments, $methods, $expander) { $class = $container->expand($class); if ($arguments) { array_walk_recursive($arguments, $expander); $service = Nette\Reflection\ClassType::from($class)->newInstanceArgs($arguments); } else { $service = new $class(); } array_walk_recursive($methods, $expander); foreach ($methods as $method) { call_user_func_array(array($service, $method[0]), isset($method[1]) ? $method[1] : array()); } return $service; }; } elseif (isset($definition['factory'])) { array_unshift($arguments, $definition['factory']); $factory = function ($container) use($arguments, $expander) { array_walk_recursive($arguments, $expander); $factory = $arguments[0]; $arguments[0] = $container; return call_user_func_array($factory, $arguments); }; } else { throw new Nette\InvalidStateException("The definition of service '{$name}' is missing factory method."); } if (isset($definition['tags'])) { $tags = (array) $definition['tags']; array_walk_recursive($tags, $expander); } else { $tags = NULL; } $container->addService($name, $factory, $tags); } }
public function __construct(Container $container) { $this->container = $container; $listeners = $this->container->findByType('\\Phoenix\\Events\\IEventListener'); foreach ($listeners as $class) { $reflection = ClassType::from($container->getService($class)); foreach ($reflection->getMethods() as $method) { if ($method->hasAnnotation(self::ANNOTATION_EVENT_LISTENER)) { $event = (string) $method->getAnnotation(self::ANNOTATION_EVENT_LISTENER); if (!isset($this->eventListeners[$event])) { $this->eventListeners[$event] = []; } $this->eventListeners[$event][] = new EventListenerWrapper($container->getService($class), $method); } } } }
/** * Puts data into the cache * * @param string The cache id. * @param string The cache entry/data. * @param int The lifetime. If != false, sets a specific lifetime for this cache entry (null => infinite lifeTime). * @return boolean TRUE if the entry was successfully stored in the cache, FALSE otherwise. */ protected function doSave($id, $data, $lifeTime = FALSE) { $files = array(); if ($data instanceof ClassMetadata) { $ref = ClassType::from($data->name); $files[] = $ref->getFileName(); foreach ($data->parentClasses as $class) { $ref = ClassType::from($class); $files[] = $ref->getFileName(); } } if ($lifeTime != 0) { $this->storage->save($id, $data, array(NCache::EXPIRE => time() + $lifeTime, NCache::TAGS => array(static::CACHE_TAG), NCache::FILES => $files)); } else { $this->storage->save($id, $data, array(NCache::TAGS => array(static::CACHE_TAG), NCache::FILES => $files)); } return TRUE; }
/** * Puts data into the cache * * @param string The cache id. * @param string The cache entry/data. * @param int The lifetime. If != false, sets a specific lifetime for this cache entry (null => infinite lifeTime). * @return boolean TRUE if the entry was successfully stored in the cache, FALSE otherwise. */ protected function doSave($id, $data, $lifeTime = false) { $files = array(); if ($data instanceof \Doctrine\ORM\Mapping\ClassMetadata) { $ref = \Nette\Reflection\ClassType::from($data->name); $files[] = $ref->getFileName(); foreach ($data->parentClasses as $class) { $ref = \Nette\Reflection\ClassType::from($class); $files[] = $ref->getFileName(); } } if ($lifeTime != 0) { $this->storage->save($id, $data, array(\Nette\Caching\Cache::EXPIRE => time() + $lifeTime, \Nette\Caching\Cache::TAGS => array(static::CACHE_TAG), \Nette\Caching\Cache::FILES => $files)); } else { $this->storage->save($id, $data, array(\Nette\Caching\Cache::TAGS => array(static::CACHE_TAG), \Nette\Caching\Cache::FILES => $files)); } return TRUE; }
/** * Invoke filter * * @param string $code * @param \Lohini\WebLoader\WebLoader $loader * @param string $file * @return string */ public function __invoke($code, \Lohini\WebLoader\WebLoader $loader, $file = NULL) { if ($file === NULL || !in_array(\Nette\Utils\Strings::lower(pathinfo($file, PATHINFO_EXTENSION)), [\PHPSass\File::SASS, \PHPSass\File::SCSS])) { return $code; } $so = ['style' => \PHPSass\Renderers\Renderer::STYLE_COMPRESSED, 'syntax' => pathinfo($file, PATHINFO_EXTENSION), 'load_paths' => [dirname($file)]]; if (class_exists('PHPSass\\Extensions\\Compass')) { $so['functions'] = \PHPSass\Extensions\Compass::getFunctions('Compass'); $so['extensions'] = ['Compass']; $so['load_paths'][] = dirname(\Nette\Reflection\ClassType::from('PHPSass\\Extensions\\Compass')->getFileName()); } if (!\Nette\Environment::isProduction()) { $so['debug'] = TRUE; $so['debug_info'] = TRUE; $so['style'] = \PHPSass\Renderers\Renderer::STYLE_NESTED; } $filter = new \PHPSass\Parser($so); return $filter->toCss($file, TRUE); }
/** * {@inheritdoc} */ protected function _doSave($id, $data, $lifeTime = 0) { $files = array(); if ($data instanceof \Doctrine\ORM\Mapping\ClassMetadata) { $ref = \Nette\Reflection\ClassType::from($data->name); $files[] = $ref->getFileName(); foreach ($data->parentClasses as $class) { $ref = \Nette\Reflection\ClassType::from($class); $files[] = $ref->getFileName(); } } if ($lifeTime != 0) { $this->data->save($id, $data, array('expire' => time() + $lifeTime, 'tags' => array("doctrine"), 'files' => $files)); } else { $this->data->save($id, $data, array('tags' => array("doctrine"), 'files' => $files)); } return TRUE; }
/** * @param $id * @param $data * @param int $lifeTime * @return bool */ protected function doSave($id, $data, $lifeTime = 0) { if ($this->debug !== TRUE) { return $this->doSaveDependingOnFiles($id, $data, array(), $lifeTime); } $files = array(); if ($data instanceof Doctrine\ORM\Mapping\ClassMetadata) { $files[] = ClassType::from($data->name)->getFileName(); foreach ($data->parentClasses as $class) { $files[] = ClassType::from($class)->getFileName(); } } if (!empty($data)) { if (is_array($data) && reset($data) instanceof Doctrine\ORM\Mapping\Annotation || $data instanceof Doctrine\ORM\Mapping\Annotation) { if (($m = Strings::match($id, '~^\\[(?P<class>[^@$]+)(?:\\$(?P<prop>[^@$]+))?\\@\\[Annot\\]~i')) && class_exists($m['class'])) { $files[] = ClassType::from($m['class'])->getFileName(); } } } return $this->doSaveDependingOnFiles($id, $data, $files, $lifeTime); }