/** * @param \Symfony\Component\DependencyInjection\ContainerBuilder $container * @param \Doctrine\Common\Annotations\AnnotationReader $annotationReader * @param \FSi\Bundle\AdminBundle\Finder\AdminClassFinder $adminClassFinder */ function it_registers_annotated_admin_classes_as_services($container, $annotationReader, $adminClassFinder) { $container->getParameter('kernel.bundles')->willReturn(array('FSi\\Bundle\\AdminBundle\\spec\\fixtures\\MyBundle', 'FSi\\Bundle\\AdminBundle\\FSiAdminBundle', 'Symfony\\Bundle\\FrameworkBundle\\FrameworkBundle')); $baseDir = __DIR__ . '/../../../../../..'; $adminClassFinder->findClasses(array(realpath($baseDir . '/spec/fixtures/Admin'), realpath($baseDir . '/Admin')))->willReturn(array('FSi\\Bundle\\AdminBundle\\spec\\fixtures\\Admin\\SimpleAdminElement', 'FSi\\Bundle\\AdminBundle\\spec\\fixtures\\Admin\\CRUDElement')); $annotationReader->getClassAnnotation(Argument::allOf(Argument::type('ReflectionClass'), Argument::which('getName', 'FSi\\Bundle\\AdminBundle\\spec\\fixtures\\Admin\\CRUDElement')), 'FSi\\Bundle\\AdminBundle\\Annotation\\Element')->willReturn(null); $annotationReader->getClassAnnotation(Argument::allOf(Argument::type('ReflectionClass'), Argument::which('getName', 'FSi\\Bundle\\AdminBundle\\spec\\fixtures\\Admin\\SimpleAdminElement')), 'FSi\\Bundle\\AdminBundle\\Annotation\\Element')->willReturn(new Element(array())); $container->addResource(Argument::allOf(Argument::type('Symfony\\Component\\Config\\Resource\\DirectoryResource'), Argument::which('getResource', realpath($baseDir . '/spec/fixtures/Admin')), Argument::which('getPattern', '/\\.php$/')))->shouldBeCalled(); $container->addResource(Argument::allOf(Argument::type('Symfony\\Component\\Config\\Resource\\DirectoryResource'), Argument::which('getResource', realpath($baseDir . '/Admin')), Argument::which('getPattern', '/\\.php$/')))->shouldBeCalled(); $container->addDefinitions(Argument::that(function ($definitions) { if (count($definitions) !== 1) { return false; } /** @var \Symfony\Component\DependencyInjection\Definition $definition */ $definition = $definitions[0]; if ($definition->getClass() !== 'FSi\\Bundle\\AdminBundle\\spec\\fixtures\\Admin\\SimpleAdminElement') { return false; } if (!$definition->hasTag('admin.element')) { return false; } return true; }))->shouldBeCalled(); $this->process($container); }
public function persist($entity) { $reflection = new \ReflectionClass($entity); $originURI = $entity->getOrigin(); if (!$originURI) { throw new \Exception("Cannot persist entity, because origin URI is not defined"); } $sparql = ''; $annotationReader = new AnnotationReader(); $iri = $annotationReader->getClassAnnotation($reflection, 'Soil\\DiscoverBundle\\Annotation\\Iri'); if ($iri) { $iri = $iri->value; $sparql .= "<{$originURI}> rdf:type {$iri} . " . PHP_EOL; } $props = $reflection->getProperties(); foreach ($props as $prop) { $matchAnnotation = $annotationReader->getPropertyAnnotation($prop, 'Soil\\DiscoverBundle\\Annotation\\Iri'); if ($matchAnnotation && $matchAnnotation->persist) { $match = $matchAnnotation->value; $prop->setAccessible(true); $value = $prop->getValue($entity); $sparql .= "<{$originURI}> {$match} <{$value}> . " . PHP_EOL; } } if ($sparql) { $this->logger->addInfo('Persisting: '); $this->logger->addInfo($sparql); $num = $this->endpoint->insert($sparql); $this->logger->addInfo('Return: ' . print_r($num, true)); return $num; } else { return null; } }
public function setUp() { $config = new Configuration(); $config->setProxyDir(__DIR__ . '/Proxies'); $config->setProxyNamespace('Proxies'); $reader = new AnnotationReader(); $reader->setDefaultAnnotationNamespace('Doctrine\\ODM\\MongoDB\\Mapping\\'); $config->setMetadataDriverImpl(new AnnotationDriver($reader, __DIR__ . '/Documents')); $this->dm = DocumentManager::create(new Mongo(), $config); $currencies = array('USD' => 1, 'EURO' => 1.7, 'JPN' => 0.0125); foreach ($currencies as $name => &$multiplier) { $multiplier = new Currency($name, $multiplier); $this->dm->persist($multiplier); } $product = new ConfigurableProduct('T-Shirt'); $product->addOption(new Option('small', new Money(12.99, $currencies['USD']), new StockItem('T-shirt Size S', new Money(9.99, $currencies['USD']), 15))); $product->addOption(new Option('medium', new Money(14.99, $currencies['USD']), new StockItem('T-shirt Size M', new Money(11.99, $currencies['USD']), 15))); $product->addOption(new Option('large', new Money(17.99, $currencies['USD']), new StockItem('T-shirt Size L', new Money(13.99, $currencies['USD']), 15))); $this->dm->persist($product); $this->dm->flush(); foreach ($currencies as $currency) { $this->dm->detach($currency); } $this->dm->detach($product); unset($currencies, $product); }
public function loadMetadataForClass($className) { $metadata = new ClassMetadata($className); $reflectionClass = new \ReflectionClass($className); $reflectionProperties = $reflectionClass->getProperties(); foreach ($reflectionProperties as $reflectionProperty) { $name = $reflectionProperty->getName(); $pMetadata = new PropertyMetadata($name); $annotations = $this->reader->getPropertyAnnotations($reflectionProperty); foreach ($annotations as $annotation) { if ($annotation instanceof Annotations\Expose) { $pMetadata->setExpose((bool) $annotation->value); } elseif ($annotation instanceof Annotations\Type) { $pMetadata->setType((string) $annotation->value); } elseif ($annotation instanceof Annotations\Groups) { $pMetadata->setGroups($annotation->value); } elseif ($annotation instanceof Annotations\SerializedName) { $pMetadata->setSerializedName((string) $annotation->value); } elseif ($annotation instanceof Annotations\SinceVersion) { $pMetadata->setSinceVersion((string) $annotation->value); } elseif ($annotation instanceof Annotations\UntilVersion) { $pMetadata->setUntilVersion((string) $annotation->value); } } $metadata->addPropertyMetadata($pMetadata); } return $metadata; }
public function testParseAnnotationDocblocks() { $class = new \ReflectionClass(__NAMESPACE__ . '\\DCOM55Annotation'); $reader = new AnnotationReader(); $annots = $reader->getClassAnnotations($class); $this->assertEquals(0, count($annots)); }
/** * @Pdf() */ public function testPdfAnnotationIsCorrectlyCreatedByReader() { $reader = new AnnotationReader(); $method = new \ReflectionMethod($this, 'testPdfAnnotationIsCorrectlyCreatedByReader'); $pdf = $reader->getMethodAnnotation($method, 'Ps\\PdfBundle\\Annotation\\Pdf'); $this->assertNotNull($pdf); }
/** * {@inheritdoc} */ public function guessType($class, $property) { $metadata = $this->getClassMetadata($class); if (!$metadata->hasAssociation($property)) { return null; } $multiple = $metadata->isCollectionValuedAssociation($property); $annotationReader = new AnnotationReader(); $associationMapping = $metadata->getAssociationMapping($property); $associationMetadata = $this->getClassMetadata($associationMapping['targetEntity']); if (null === $annotationReader->getClassAnnotation($associationMetadata->getReflectionClass(), static::TREE_ANNOTATION)) { return null; } $levelProperty = null; $parentProperty = null; foreach ($associationMetadata->getReflectionProperties() as $property) { if ($annotationReader->getPropertyAnnotation($property, static::TREE_LEVEL_ANNOTATION)) { $levelProperty = $property->getName(); } if ($annotationReader->getPropertyAnnotation($property, static::TREE_PARENT_ANNOTATION)) { $parentProperty = $property->getName(); } } if (null === $levelProperty || null === $parentProperty) { return null; } return new TypeGuess('tree_choice', ['class' => $associationMapping['targetEntity'], 'multiple' => $multiple, 'level_property' => $levelProperty, 'parent_property' => $parentProperty], Guess::VERY_HIGH_CONFIDENCE); }
/** * {@inheritdoc} */ protected function execute(InputInterface $input, OutputInterface $output) { $reader = new AnnotationReader(); /** @var ManagerRegistry $doctrine */ $doctrine = $this->getContainer()->get('doctrine'); $em = $doctrine->getManager(); $cmf = $em->getMetadataFactory(); $existing = []; $created = []; /** @var ClassMetadata $metadata */ foreach ($cmf->getAllMetadata() as $metadata) { $refl = $metadata->getReflectionClass(); if ($refl === null) { $refl = new \ReflectionClass($metadata->getName()); } if ($reader->getClassAnnotation($refl, 'Padam87\\AttributeBundle\\Annotation\\Entity') != null) { $schema = $em->getRepository('Padam87AttributeBundle:Schema')->findOneBy(['className' => $metadata->getName()]); if ($schema === null) { $schema = new Schema(); $schema->setClassName($metadata->getName()); $em->persist($schema); $em->flush($schema); $created[] = $metadata->getName(); } else { $existing[] = $metadata->getName(); } } } $table = new Table($output); $table->addRow(['Created:', implode(PHP_EOL, $created)]); $table->addRow(new TableSeparator()); $table->addRow(['Existing:', implode(PHP_EOL, $existing)]); $table->render(); }
/** * @param string $className * @return Datagrid */ public function create($className) { /** @var \Doctrine\ORM\EntityManager $entityManager */ $entityManager = $this->getServiceLocator()->get('Doctrine\\ORM\\EntityManager'); $metadata = $entityManager->getClassMetadata($className); $reflection = $metadata->getReflectionClass(); $datagridSpec = new ArrayObject(array('className' => $className, 'primaryKey' => $metadata->getSingleIdentifierFieldName(), 'name' => array('singular' => '', 'plural' => ''), 'defaultSort' => null, 'headerColumns' => array(), 'searchColumns' => array(), 'suggestColumns' => array())); $reader = new AnnotationReader(); foreach ($reader->getClassAnnotations($reflection) as $annotation) { $params = compact('datagridSpec', 'annotation'); $this->getEventManager()->trigger('discoverTitle', $this, $params); } foreach ($reflection->getProperties() as $property) { foreach ($reader->getPropertyAnnotations($property) as $annotation) { $params = compact('datagridSpec', 'annotation', 'property'); $this->getEventManager()->trigger('configureColumn', $this, $params); } } foreach ($reflection->getMethods() as $method) { foreach ($reader->getMethodAnnotations($method) as $annotation) { $params = compact('datagridSpec', 'annotation', 'method'); $this->getEventManager()->trigger('configureColumn', $this, $params); } } $this->datagrids[$className] = new Datagrid($entityManager, $datagridSpec->getArrayCopy()); return $this->datagrids[$className]; }
public function __construct($consumerWorker, ConnectionFactory $connectionFactory) { $this->connectionFactory = $connectionFactory; $className = get_class($consumerWorker); $reflectionClass = new \ReflectionClass($className); $reader = new AnnotationReader(); $methods = $reflectionClass->getMethods(); foreach ($methods as $method) { $methodAnnotations = $reader->getMethodAnnotations($method); foreach ($methodAnnotations as $annotation) { if ($annotation instanceof Annotation\Consumer) { $parameters = $method->getParameters(); $taskClassName = false; if (!empty($parameters)) { $taskClass = $parameters[0]->getClass(); $isMessage = $taskClass->implementsInterface('IvixLabs\\RabbitmqBundle\\Message\\MessageInterface'); if (!$isMessage) { throw new \InvalidArgumentException('Task must implmenet IvixLabs\\RabbitmqBundle\\Message\\MessageInterface'); } $taskClassName = $taskClass->getName(); } $key = $annotation->connectionName . '_' . $annotation->channelName . '_' . $annotation->exchangeName . '_' . $annotation->routingKey; if (!isset($this->taskClasses[$key])) { $this->taskClasses[$key] = []; } $this->taskClasses[$key][] = [$taskClassName, $method->getClosure($consumerWorker), $annotation]; } } } }
/** * {@inheritdoc} */ public function generate(ReflectionClass $originalClass, ClassGenerator $classGenerator) { CanProxyAssertion::assertClassCanBeProxied($originalClass); $classGenerator->setExtendedClass($originalClass->getName()); $additionalInterfaces = ['OpenClassrooms\\ServiceProxy\\ServiceProxyInterface']; $additionalProperties['proxy_realSubject'] = new PropertyGenerator('proxy_realSubject', null, PropertyGenerator::FLAG_PRIVATE); $additionalMethods['setProxy_realSubject'] = new MethodGenerator('setProxy_realSubject', [['name' => 'realSubject']], MethodGenerator::FLAG_PUBLIC, '$this->proxy_realSubject = $realSubject;'); $methods = $originalClass->getMethods(\ReflectionMethod::IS_PUBLIC); foreach ($methods as $method) { $preSource = ''; $postSource = ''; $exceptionSource = ''; $methodAnnotations = $this->annotationReader->getMethodAnnotations($method); foreach ($methodAnnotations as $methodAnnotation) { if ($methodAnnotation instanceof Cache) { $this->addCacheAnnotation($classGenerator); $additionalInterfaces['cache'] = 'OpenClassrooms\\ServiceProxy\\ServiceProxyCacheInterface'; $response = $this->cacheStrategy->execute($this->serviceProxyStrategyRequestBuilder->create()->withAnnotation($methodAnnotation)->withClass($originalClass)->withMethod($method)->build()); foreach ($response->getMethods() as $methodToAdd) { $additionalMethods[$methodToAdd->getName()] = $methodToAdd; } foreach ($response->getProperties() as $propertyToAdd) { $additionalProperties[$propertyToAdd->getName()] = $propertyToAdd; } $preSource .= $response->getPreSource(); $postSource .= $response->getPostSource(); $exceptionSource .= $response->getExceptionSource(); } } $classGenerator->addMethodFromGenerator($this->generateProxyMethod($method, $preSource, $postSource, $exceptionSource)); } $classGenerator->setImplementedInterfaces($additionalInterfaces); $classGenerator->addProperties($additionalProperties); $classGenerator->addMethods($additionalMethods); }
/** * Parse a controller class. * * @param string $class * @return array */ public function parseController($class) { $reflectionClass = new ReflectionClass($class); $classAnnotations = $this->reader->getClassAnnotations($reflectionClass); $controllerMetadata = []; $middleware = []; // find entity parameters and plugins foreach ($classAnnotations as $annotation) { // controller attributes if ($annotation instanceof \ProAI\Annotations\Annotations\Controller) { $prefix = $annotation->prefix; $middleware = $this->addMiddleware($middleware, $annotation->middleware); } if ($annotation instanceof \ProAI\Annotations\Annotations\Middleware) { $middleware = $this->addMiddleware($middleware, $annotation->value); } // resource controller if ($annotation instanceof \ProAI\Annotations\Annotations\Resource) { $resourceMethods = ['index', 'create', 'store', 'show', 'edit', 'update', 'destroy']; if (!empty($annotation->only)) { $resourceMethods = array_intersect($resourceMethods, $annotation->only); } elseif (!empty($annotation->except)) { $resourceMethods = array_diff($resourceMethods, $annotation->except); } $resource = ['name' => $annotation->value, 'methods' => $resourceMethods]; } } // find routes foreach ($reflectionClass->getMethods() as $reflectionMethod) { $name = $reflectionMethod->getName(); $methodAnnotations = $this->reader->getMethodAnnotations($reflectionMethod); $routeMetadata = []; // controller method is resource route if (!empty($resource) && in_array($name, $resource['methods'])) { $routeMetadata = ['uri' => $resource['name'] . $this->getResourcePath($name), 'controller' => $class, 'controllerMethod' => $name, 'httpMethod' => $this->getResourceHttpMethod($name), 'as' => $resource['name'] . '.' . $name, 'middleware' => '']; } // controller method is route if ($route = $this->hasHttpMethodAnnotation($name, $methodAnnotations)) { $routeMetadata = ['uri' => $route['uri'], 'controller' => $class, 'controllerMethod' => $name, 'httpMethod' => $route['httpMethod'], 'as' => $route['as'], 'middleware' => $route['middleware']]; } // add more route options to route metadata if (!empty($routeMetadata)) { if (!empty($middleware)) { $routeMetadata['middleware'] = $middleware; } // add other method annotations foreach ($methodAnnotations as $annotation) { if ($annotation instanceof \ProAI\Annotations\Annotations\Middleware) { $middleware = $this->addMiddleware($middleware, $routeMetadata['middleware']); } } // add global prefix and middleware if (!empty($prefix)) { $routeMetadata['uri'] = $prefix . '/' . $routeMetadata['uri']; } $controllerMetadata[$name] = $routeMetadata; } } return $controllerMetadata; }
/** * @param ReflectionProperty $property * @return PropertyMetadata */ private function loadPropertyMetadata(ReflectionProperty $property) { $propertyMetadata = new PropertyMetadata($property->getDeclaringClass()->getName(), $property->getName()); foreach ($this->reader->getPropertyAnnotations($property) as $propertyAnnotation) { if ($propertyAnnotation instanceof Type) { $propertyMetadata->type = $propertyAnnotation->name; } if ($propertyAnnotation instanceof ReferenceOne) { $propertyMetadata->reference = PropertyMetadata::REFERENCE_ONE; $propertyMetadata->target = $propertyAnnotation->target; } if ($propertyAnnotation instanceof ReferenceMany) { $propertyMetadata->reference = PropertyMetadata::REFERENCE_MANY; $propertyMetadata->target = $propertyAnnotation->target; } if ($propertyAnnotation instanceof ReferenceKey) { $propertyMetadata->reference = PropertyMetadata::REFERENCE_KEY; $propertyMetadata->target = $propertyAnnotation->target; if ($propertyAnnotation->value instanceof Type) { $propertyMetadata->value = ['type' => 'type', 'name' => $propertyAnnotation->value->name]; } } if ($propertyAnnotation instanceof EmbedOne) { $propertyMetadata->embed = PropertyMetadata::EMBED_ONE; $propertyMetadata->target = $propertyAnnotation->target; $propertyMetadata->mapping = $propertyAnnotation->mapping; } if ($propertyAnnotation instanceof EmbedMany) { $propertyMetadata->embed = PropertyMetadata::EMBED_MANY; $propertyMetadata->target = $propertyAnnotation->target; $propertyMetadata->mapping = $propertyAnnotation->mapping; } } return $propertyMetadata; }
public function setBriefProperty($object, $name, $value, $expectedClass = null) { $reflection = new \ReflectionClass($object); if (!$reflection->hasProperty($name)) { return false; } $property = $reflection->getProperty($name); $property->setAccessible(true); if ($value instanceof Resource) { $value = $value->getUri(); $annotation = $this->annotationReader->getPropertyAnnotation($property, 'Soil\\CommentsDigestBundle\\Annotation\\Entity'); if ($annotation) { $expectedClass = $annotation->value ?: true; var_dump($expectedClass); try { $entity = $this->resolver->getEntityForURI($value, $expectedClass); } catch (\Exception $e) { $entity = null; echo "Problem with discovering" . PHP_EOL; echo $e->getMessage() . PHP_EOL; var_dump($value, $expectedClass); echo PHP_EOL; //FIXME: Add logging } if ($entity) { $value = $entity; } } } elseif ($value instanceof Literal) { $value = $value->getValue(); } $property->setValue($object, $value); }
public function setUp() { $config = new Configuration(); $config->setProxyDir(__DIR__ . '/../../../../Proxies'); $config->setProxyNamespace('Proxies'); $config->setHydratorDir(__DIR__ . '/../../../../Hydrators'); $config->setHydratorNamespace('Hydrators'); $config->setDefaultDB('doctrine_odm_tests'); /* $config->setLoggerCallable(function(array $log) { print_r($log); }); $config->setMetadataCacheImpl(new ApcCache()); */ $reader = new AnnotationReader(); $reader->setDefaultAnnotationNamespace('Doctrine\ODM\MongoDB\Mapping\\'); $this->annotationDriver = new AnnotationDriver($reader, __DIR__ . '/../../../../Documents'); $config->setMetadataDriverImpl($this->annotationDriver); $conn = new Connection(null, array(), $config); $this->dm = DocumentManager::create($conn, $config); $this->uow = $this->dm->getUnitOfWork(); }
/** * (non-PHPdoc) * @see Gedmo\Mapping.Driver::readExtendedMetadata() */ public function readExtendedMetadata(ClassMetadataInfo $meta, array &$config) { require_once __DIR__ . '/../Annotations.php'; $reader = new AnnotationReader(); $reader->setAnnotationNamespaceAlias('Gedmo\\Timestampable\\Mapping\\', 'gedmo'); $class = $meta->getReflectionClass(); // property annotations foreach ($class->getProperties() as $property) { if ($meta->isMappedSuperclass && !$property->isPrivate() || $meta->isInheritedField($property->name) || $meta->isInheritedAssociation($property->name)) { continue; } if ($timestampable = $reader->getPropertyAnnotation($property, self::ANNOTATION_TIMESTAMPABLE)) { $field = $property->getName(); if (!$meta->hasField($field)) { throw MappingException::fieldMustBeMapped($field, $meta->name); } if (!$this->_isValidField($meta, $field)) { throw MappingException::notValidFieldType($field, $meta->name); } if (!in_array($timestampable->on, array('update', 'create', 'change'))) { throw MappingException::triggerTypeInvalid($field, $meta->name); } if ($timestampable->on == 'change') { if (!isset($timestampable->field) || !isset($timestampable->value)) { throw MappingException::parametersMissing($field, $meta->name); } $field = array('field' => $field, 'trackedField' => $timestampable->field, 'value' => $timestampable->value); } // properties are unique and mapper checks that, no risk here $config[$timestampable->on][] = $field; } } }
/** * @covers \Weasel\JsonMarshaller\Config\DoctrineAnnotations\JsonAnySetter */ public function testBasicClassAnnotations() { AnnotationRegistry::registerFile(__DIR__ . '/../../../../../lib/Weasel/JsonMarshaller/Config/DoctrineAnnotations/JsonAnySetter.php'); $annotationReader = new AnnotationReader(); $got = $annotationReader->getMethodAnnotations(new \ReflectionMethod(__NAMESPACE__ . '\\JsonAnySetterTestVictim', 'basic')); $this->assertEquals(array(new JsonAnySetter()), $got); }
/** * {@inheritdoc} */ protected function execute(InputInterface $input, OutputInterface $output) { $model = $input->getArgument('model'); $seeds = $input->getArgument('seeds'); $io = new SymfonyStyle($input, $output); if (!class_exists($model)) { $io->error(array('The model you specified does not exist.', 'You can create a model with the "model:create" command.')); return 1; } $this->dm = $this->createDocumentManager($input->getOption('server')); $faker = Faker\Factory::create(); AnnotationRegistry::registerAutoloadNamespace('Hive\\Annotations', dirname(__FILE__) . '/../../'); $reflectionClass = new \ReflectionClass($model); $properties = $reflectionClass->getProperties(\ReflectionProperty::IS_PUBLIC); $reader = new AnnotationReader(); for ($i = 0; $i < $seeds; $i++) { $instance = new $model(); foreach ($properties as $property) { $name = $property->getName(); $seed = $reader->getPropertyAnnotation($property, 'Hive\\Annotations\\Seed'); if ($seed !== null) { $fake = $seed->fake; if (class_exists($fake)) { $instance->{$name} = $this->createFakeReference($fake); } else { $instance->{$name} = $faker->{$seed->fake}; } } } $this->dm->persist($instance); } $this->dm->flush(); $io->success(array("Created {$seeds} seeds for {$model}")); }
protected function execute(InputInterface $input, OutputInterface $output) { // get repository $entityClass = $input->getArgument('entityClass'); $repository = $this->getHelper('em')->getEntityManager()->getRepository($entityClass); $reflClass = new ReflectionClass($entityClass); $reader = new AnnotationReader(); $annotation = $reader->getClassAnnotation($reflClass, '\\Keratine\\Lucene\\Mapping\\Annotation\\Indexable'); if (!$annotation) { $output->writeln(sprintf('<error>%s must define the "%s" annotation.</error>', $entityClass, '\\Keratine\\Lucene\\Mapping\\Annotation\\Indexable')); return; } $indexManager = new IndexManager($this->getHelper('zendsearch')->getIndices()[$annotation->index]); // delete all indexed documents $numDocs = $indexManager->numDocs(); for ($id = 0; $id < $numDocs; $id++) { $indexManager->delete($id); } // index each entity foreach ($repository->findAll() as $entity) { $indexManager->index($entity); } // optimize index $indexManager->optimize(); // get number of indexed documents $numDocs = $indexManager->numDocs(); $output->writeln(sprintf('<info>%d document(s) indexed</info>', $numDocs)); }
public function onSerializerPreDeserialize(PreDeserializeEvent $e) { $className = $e->getType(); $className = $className['name']; /** Handle ArrayCollection or array JMS type. */ if ($className == "ArrayCollection" || $className == "array") { $className = $e->getType(); $className = $className['params'][0]['name']; } $classMetadata = $e->getContext()->getMetadataFactory()->getMetadataForClass($className); /** @var PropertyMetadata $propertyMetadata */ foreach ($classMetadata->propertyMetadata as $propertyMetadata) { if ($propertyMetadata->reflection === null) { continue; } /** @var JoinColumn $joinColumnAnnotation */ $joinColumnAnnotation = $this->reader->getPropertyAnnotation($propertyMetadata->reflection, 'Doctrine\\ORM\\Mapping\\JoinColumn'); if ($joinColumnAnnotation !== null) { if (array_key_exists($joinColumnAnnotation->name, $e->getData())) { $idValue = $e->getData(); $idValue = $idValue[$joinColumnAnnotation->name]; if ($idValue !== null) { $e->setData($e->getData() + array($propertyMetadata->name => array('id' => $idValue))); } else { $e->setData($e->getData() + array($propertyMetadata->name => null)); } } } } }
public function setUp() { if (version_compare(\Doctrine\Common\Version::VERSION, '2.1.0RC4-DEV', '>=')) { $this->markTestSkipped('Doctrine common is 2.1.0RC4-DEV version, skipping.'); } else { if (version_compare(\Doctrine\Common\Version::VERSION, '2.1.0-BETA3-DEV', '>=')) { $reader = new AnnotationReader(); $reader->setDefaultAnnotationNamespace('Doctrine\\ORM\\Mapping\\'); $reader->setIgnoreNotImportedAnnotations(true); $reader->setAnnotationNamespaceAlias('Gedmo\\Mapping\\Annotation\\', 'gedmo'); $reader->setEnableParsePhpImports(false); $reader->setAutoloadAnnotations(true); $reader = new CachedReader(new \Doctrine\Common\Annotations\IndexedReader($reader), new ArrayCache()); } else { $reader = new AnnotationReader(); $reader->setAutoloadAnnotations(true); $reader->setAnnotationNamespaceAlias('Gedmo\\Mapping\\Annotation\\', 'gedmo'); $reader->setDefaultAnnotationNamespace('Doctrine\\ORM\\Mapping\\'); } } $config = new \Doctrine\ORM\Configuration(); $config->setProxyDir(TESTS_TEMP_DIR); $config->setProxyNamespace('Gedmo\\Mapping\\Proxy'); $config->setMetadataDriverImpl(new AnnotationDriver($reader)); $conn = array('driver' => 'pdo_sqlite', 'memory' => true); //$config->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger()); $evm = new \Doctrine\Common\EventManager(); $this->timestampable = new \Gedmo\Timestampable\TimestampableListener(); $evm->addEventSubscriber($this->timestampable); $this->em = \Doctrine\ORM\EntityManager::create($conn, $config, $evm); $schemaTool = new \Doctrine\ORM\Tools\SchemaTool($this->em); $schemaTool->dropSchema(array()); $schemaTool->createSchema(array($this->em->getClassMetadata(self::ARTICLE))); }
public function getContentFiles($object) { $reflectedClass = new \ReflectionClass($object); $reader = new AnnotationReader(); $annotations = $reader->getClassAnnotations($reflectedClass); $isContentFiledClass = false; foreach ($annotations as $annotation) { if ($annotation instanceof ContentFiled) { $isContentFiledClass = true; } } if (!$isContentFiledClass) { throw new \InvalidArgumentException('Only @ContentFiled annotated classes are supported!'); } $contentFiles = []; foreach ($reflectedClass->getProperties() as $property) { foreach ($reader->getPropertyAnnotations($property) as $annotation) { if ($annotation instanceof ContentFileAnnotation) { $mappingType = $object->{$annotation->mappingTypeMethod}(); $contentFiles = array_merge($contentFiles, $this->contentFileManager->findFilesByMappingType($mappingType)); } } } return $contentFiles; }
public function readExtendedMetadata($meta, array &$config) { // load our available annotations require_once __DIR__ . '/../Annotations.php'; $reader = new AnnotationReader(); // set annotation namespace and alias //$reader->setAnnotationNamespaceAlias('Gedmo\Mapping\Mock\Extension\Encoder\Mapping\\', 'ext'); $class = $meta->getReflectionClass(); // check only property annotations foreach ($class->getProperties() as $property) { // skip inherited properties if ($meta->isMappedSuperclass && !$property->isPrivate() || $meta->isInheritedField($property->name) || isset($meta->associationMappings[$property->name]['inherited'])) { continue; } // now lets check if property has our annotation if ($encode = $reader->getPropertyAnnotation($property, 'Gedmo\\Mapping\\Mock\\Extension\\Encoder\\Mapping\\Encode')) { $field = $property->getName(); // check if field is mapped if (!$meta->hasField($field)) { throw new \Exception("Field is not mapped as object property"); } // allow encoding only strings if (!in_array($encode->type, array('sha1', 'md5'))) { throw new \Exception("Invalid encoding type supplied"); } // validate encoding type $mapping = $meta->getFieldMapping($field); if ($mapping['type'] != 'string') { throw new \Exception("Only strings can be encoded"); } // store the metadata $config['encode'][$field] = array('type' => $encode->type, 'secret' => $encode->secret); } } }
protected function getTemplateDataForModel($model) { $data = ['name' => Helper::get()->shortName($model), 'slug' => Helper::get()->slugify($model), 'properties' => []]; $reflectionClass = new \ReflectionClass($model); $properties = $reflectionClass->getProperties(\ReflectionProperty::IS_PUBLIC); $reader = new AnnotationReader(); foreach ($properties as $property) { $name = $property->getName(); $type = null; $targetEntity = null; $mappedBySlug = null; $propertyDefinition = ['name' => $name]; if (($fieldAnnotation = $reader->getPropertyAnnotation($property, 'Doctrine\\ODM\\MongoDB\\Mapping\\Annotations\\Field')) !== null) { $type = $fieldAnnotation->type; } elseif (($referenceOneAnnotation = $reader->getPropertyAnnotation($property, 'Doctrine\\ODM\\MongoDB\\Mapping\\Annotations\\ReferenceOne')) !== null) { $name .= '.id'; $type = 'reference'; $targetEntity = Helper::get()->shortName($referenceOneAnnotation->targetDocument); } elseif (($referenceManyAnnotation = $reader->getPropertyAnnotation($property, 'Doctrine\\ODM\\MongoDB\\Mapping\\Annotations\\ReferenceMany')) !== null) { $type = 'referenced_list'; $targetEntity = Helper::get()->shortName($referenceManyAnnotation->targetDocument); $mappedBySlug = Helper::get()->slugify($referenceManyAnnotation->mappedBy, false); } elseif ($reader->getPropertyAnnotation($property, 'Doctrine\\ODM\\MongoDB\\Mapping\\Annotations\\Id') === null) { continue; } $propertyDefinition['name'] = $name; $propertyDefinition['type'] = $type; if ($targetEntity) { $propertyDefinition[$type] = ['targetEntity' => $targetEntity, 'targetEntitySlug' => Helper::get()->slugify($targetEntity), 'mappedBySlug' => $mappedBySlug]; } $data['properties'][] = $propertyDefinition; } return $data; }
public function testAnnotationReader() { $reader = new AnnotationReader(); $method = new \ReflectionMethod('FOS\\RestBundle\\Tests\\Fixtures\\Controller\\ParamsAnnotatedController', 'getArticlesAction'); $params = $reader->getMethodAnnotations($method); // Param 1 (query) $this->assertEquals('page', $params[0]->name); $this->assertEquals('\\d+', $params[0]->requirements); $this->assertEquals('1', $params[0]->default); $this->assertEquals('Page of the overview.', $params[0]->description); $this->assertFalse($params[0]->map); $this->assertFalse($params[0]->strict); // Param 2 (request) $this->assertEquals('byauthor', $params[1]->name); $this->assertEquals('[a-z]+', $params[1]->requirements); $this->assertEquals('by author', $params[1]->description); $this->assertEquals(['search'], $params[1]->incompatibles); $this->assertFalse($params[1]->map); $this->assertTrue($params[1]->strict); // Param 3 (query) $this->assertEquals('filters', $params[2]->name); $this->assertTrue($params[2]->map); $this->assertEquals(new NotNull(), $params[2]->requirements); // Param 4 (file) $this->assertEquals('avatar', $params[3]->name); $this->assertEquals(['mimeTypes' => 'application/json'], $params[3]->requirements); $this->assertTrue($params[3]->image); $this->assertTrue($params[3]->strict); // Param 5 (file) $this->assertEquals('foo', $params[4]->name); $this->assertEquals(new NotNull(), $params[4]->requirements); $this->assertFalse($params[4]->image); $this->assertFalse($params[4]->strict); }
/** * Entity Indexer * @param string|EntityClass $entityClassName * * @throws InvalidAnnotationException Invalid annotations used */ public function __construct($entityClassName) { $this->entityClass = new \ReflectionClass($entityClassName); if (!$this->entityClass->isSubclassOf("\\SweetORM\\Entity")) { throw new \UnexpectedValueException("The className for getTable should be a class that is extending the SweetORM Entity class"); // @codeCoverageIgnore } $this->entity = new EntityStructure(); $this->entity->name = $this->entityClass->getName(); // Reader $reader = new AnnotationReader(); $this->classAnnotations = $reader->getClassAnnotations($this->entityClass); $this->entityAnnotation = $reader->getClassAnnotation($this->entityClass, EntityClass::class); // Validate Entity annotation if ($this->entityAnnotation === null || !$this->entityAnnotation instanceof EntityClass) { throw new InvalidAnnotationException("Entity '" . $this->entityClass->getName() . "' should use Annotations to use it! Please look at the documentation for help."); // @codeCoverageIgnore } // Run all the indexers foreach (self::$indexers as $indexerClass) { $indexerFullClass = "\\SweetORM\\Structure\\Indexer\\" . $indexerClass; /** @var Indexer $instance */ $instance = new $indexerFullClass($this->entityClass, $reader); $instance->indexEntity($this->entity); } }
/** * Loads the metadata for the specified class into the provided container. * * @param string $className * @param ClassMetadata $metadata */ public function loadMetadataForClass($className, ClassMetadata $metadata) { $class = $metadata->getReflectionClass(); if (!$class) { // this happens when running annotation driver in combination with // static reflection services. This is not the nicest fix $class = new \ReflectionClass($metadata->name); } $entityAnnot = $this->reader->getClassAnnotation($class, 'Doctrine\\KeyValueStore\\Mapping\\Annotations\\Entity'); if (!$entityAnnot) { throw new \InvalidArgumentException($metadata->name . ' is not a valid key-value-store entity.'); } $metadata->storageName = $entityAnnot->storageName; // Evaluate annotations on properties/fields foreach ($class->getProperties() as $property) { $idAnnot = $this->reader->getPropertyAnnotation($property, 'Doctrine\\KeyValueStore\\Mapping\\Annotations\\Id'); $transientAnnot = $this->reader->getPropertyAnnotation($property, 'Doctrine\\KeyValueStore\\Mapping\\Annotations\\Transient'); if ($idAnnot) { $metadata->mapIdentifier($property->getName()); } elseif ($transientAnnot) { $metadata->skipTransientField($property->getName()); } else { $metadata->mapField(['fieldName' => $property->getName()]); } } }
/** * @param \ReflectionClass $class * * @return \Metadata\ClassMetadata */ public function loadMetadataForClass(\ReflectionClass $class) { $classMetadata = new ClassMetadata($class->getName()); foreach ($class->getMethods(\ReflectionMethod::IS_PUBLIC) as $reflectionMethod) { if (false === strpos($reflectionMethod->getName(), 'Action')) { continue; } if ($reflectionMethod->isAbstract()) { continue; } $methodMetadata = new ActionMetadata($class->getName(), $reflectionMethod->getName()); $annotations = $this->reader->getMethodAnnotations($reflectionMethod); foreach ($annotations as $annotation) { if ($annotation instanceof \BackBee\Rest\Controller\Annotations\QueryParam) { $data = array('name' => $annotation->name, 'key' => $annotation->key ? $annotation->key : $annotation->name, 'default' => $annotation->default, 'description' => $annotation->description, 'requirements' => $annotation->requirements); $methodMetadata->queryParams[] = $data; } elseif ($annotation instanceof \BackBee\Rest\Controller\Annotations\RequestParam) { $data = array('name' => $annotation->name, 'key' => $annotation->key ? $annotation->key : $annotation->name, 'default' => $annotation->default, 'description' => $annotation->description, 'requirements' => $annotation->requirements); $methodMetadata->requestParams[] = $data; } elseif ($annotation instanceof \BackBee\Rest\Controller\Annotations\Pagination) { $methodMetadata->default_start = $annotation->default_start; $methodMetadata->default_count = $annotation->default_count; $methodMetadata->max_count = $annotation->max_count; $methodMetadata->min_count = $annotation->min_count; } elseif ($annotation instanceof \BackBee\Rest\Controller\Annotations\ParamConverter) { $methodMetadata->param_converter_bag[] = $annotation; } elseif ($annotation instanceof \BackBee\Rest\Controller\Annotations\Security) { $methodMetadata->security[] = $annotation; } } $classMetadata->addMethodMetadata($methodMetadata); } return $classMetadata; }
protected function getProperties($object) { $reflClass = new \ReflectionClass($object); $codeAnnotation = $this->annotationReader->getClassAnnotation($reflClass, Segment::class); if (!$codeAnnotation) { throw new AnnotationMissing(sprintf("Missing @Segment annotation for class %", $reflClass->getName())); } $properties = [$codeAnnotation->value]; foreach ($reflClass->getProperties() as $propRefl) { $propRefl->setAccessible(true); /** @var SegmentPiece $isSegmentPiece */ $isSegmentPiece = $this->annotationReader->getPropertyAnnotation($propRefl, SegmentPiece::class); if ($isSegmentPiece) { if (!$isSegmentPiece->parts) { $properties[$isSegmentPiece->position] = $propRefl->getValue($object); } else { $parts = $isSegmentPiece->parts; $value = $propRefl->getValue($object); $valuePieces = []; foreach ($parts as $key => $part) { if (is_integer($key)) { $partName = $part; } else { $partName = $key; } $valuePieces[] = isset($value[$partName]) ? $value[$partName] : null; } $properties[$isSegmentPiece->position] = $this->weedOutEmpty($valuePieces); } } } $properties = $this->weedOutEmpty($properties); return $properties; }
/** * buildMetaData * * build the columns and other metadata for this class */ protected function buildMetaData() { $columnArray = array(); $className = $this->getClassName($this->tableConfig); $refl = new \ReflectionClass($className); $properties = $refl->getProperties(); foreach ($properties as $property) { $column = $this->reader->getPropertyAnnotation($property, $this->columnNs); if (!empty($column)) { if (!isset($column->source)) { throw new InvalidArgumentException('DataTables requires a "source" attribute be provided for a column'); } if (!isset($column->name)) { throw new InvalidArgumentException('DataTables requires a "name" attribute be provided for a column'); } // check for default $default = $this->reader->getPropertyAnnotation($property, $this->defaultSortNs); if (!empty($default)) { $column->defaultSort = true; } // check for formatting $format = $this->reader->getPropertyAnnotation($property, $this->formatNs); if (!empty($format)) { if (!isset($format->dataFields)) { throw new InvalidArgumentException('DataTables requires a "dataFields" attribute be provided for a column formatter'); } $column->format = $format; } $this->columns[] = $column; $columnArray[$column->source] = $column->name; } } $this->table->setColumns($columnArray); $this->table->setMetaData(array('table' => $this->tableConfig, 'columns' => $this->columns)); }