protected function _loadDriver() { $cache = new \Doctrine\Common\Cache\ArrayCache(); $reader = new \Doctrine\Common\Annotations\AnnotationReader($cache); $reader->setDefaultAnnotationNamespace('Doctrine\\ORM\\Mapping\\'); return new \Doctrine\ORM\Mapping\Driver\AnnotationDriver($reader); }
/** * @return Doctrine\Common\Annotations\AnnotationReader */ public function createServiceAnnotations__reflectionReader() { $service = new Doctrine\Common\Annotations\AnnotationReader(); $service->addGlobalIgnoredName('persistent'); $service->addGlobalIgnoredName('serializationVersion'); return $service; }
public function testParseAnnotationDocblocks() { $class = new \ReflectionClass(__NAMESPACE__ . '\\DCOM55Annotation'); $reader = new \Doctrine\Common\Annotations\AnnotationReader(); $annots = $reader->getClassAnnotations($class); $this->assertEquals(0, count($annots)); }
/** * @param array $paths * @return \Doctrine\Common\Annotations\AnnotationReader */ protected function createAnnotationDriver($paths = array(), $alias = null) { if (version_compare(\Doctrine\Common\Version::VERSION, '3.0.0', '>=')) { $reader = new \Doctrine\Common\Annotations\CachedReader(new \Doctrine\Common\Annotations\AnnotationReader(), new ArrayCache()); } else { if (version_compare(\Doctrine\Common\Version::VERSION, '2.1.0-BETA3-DEV', '>=')) { $reader = new \Doctrine\Common\Annotations\AnnotationReader(); $reader->setIgnoreNotImportedAnnotations(true); $reader->setEnableParsePhpImports(false); if ($alias) { $reader->setAnnotationNamespaceAlias('Doctrine\\ORM\\Mapping\\', $alias); } else { $reader->setDefaultAnnotationNamespace('Doctrine\\ORM\\Mapping\\'); } $reader = new \Doctrine\Common\Annotations\CachedReader(new \Doctrine\Common\Annotations\IndexedReader($reader), new ArrayCache()); } else { $reader = new \Doctrine\Common\Annotations\AnnotationReader(); if ($alias) { $reader->setAnnotationNamespaceAlias('Doctrine\\ORM\\Mapping\\', $alias); } else { $reader->setDefaultAnnotationNamespace('Doctrine\\ORM\\Mapping\\'); } } } return new \Doctrine\ORM\Mapping\Driver\AnnotationDriver($reader, (array) $paths); }
public function createDocumentManager(array $paths = null) { $reader = new \Doctrine\Common\Annotations\AnnotationReader(); $reader->addGlobalIgnoredName('group'); if (empty($paths)) { $paths = array(__DIR__ . "/../../Models"); } $metaDriver = new AnnotationDriver($reader, $paths); $factoryclass = isset($GLOBALS['DOCTRINE_PHPCR_FACTORY']) ? $GLOBALS['DOCTRINE_PHPCR_FACTORY'] : '\\Jackalope\\RepositoryFactoryJackrabbit'; if ($factoryclass === '\\Jackalope\\RepositoryFactoryDoctrineDBAL') { $params = array(); foreach ($GLOBALS as $key => $value) { if (0 === strpos($key, 'jackalope.doctrine.dbal.')) { $params[substr($key, strlen('jackalope.doctrine.dbal.'))] = $value; } } if (isset($params['username'])) { $params['user'] = $params['username']; } $GLOBALS['jackalope.doctrine_dbal_connection'] = \Doctrine\DBAL\DriverManager::getConnection($params); } $parameters = array_intersect_key($GLOBALS, $factoryclass::getConfigurationKeys()); // factory will return null if it gets unknown parameters $repository = $factoryclass::getRepository($parameters); $this->assertNotNull($repository, 'There is an issue with your parameters: ' . var_export(array_keys($parameters), true)); $workspace = isset($GLOBALS['DOCTRINE_PHPCR_WORKSPACE']) ? $GLOBALS['DOCTRINE_PHPCR_WORKSPACE'] : 'tests'; $user = isset($GLOBALS['DOCTRINE_PHPCR_USER']) ? $GLOBALS['DOCTRINE_PHPCR_USER'] : ''; $pass = isset($GLOBALS['DOCTRINE_PHPCR_PASS']) ? $GLOBALS['DOCTRINE_PHPCR_PASS'] : ''; $credentials = new \PHPCR\SimpleCredentials($user, $pass); $session = $repository->login($credentials, $workspace); $this->sessions[] = $session; $config = new \Doctrine\ODM\PHPCR\Configuration(); $config->setMetadataDriverImpl($metaDriver); return DocumentManager::create($session, $config); }
public function __construct() { // load database configuration from CodeIgniter require_once APPPATH . 'config/database.php'; // Set up class loading. You could use different autoloaders, provided by your favorite framework, // if you want to. require_once APPPATH . 'libraries/Doctrine/Common/ClassLoader.php'; $doctrineClassLoader = new ClassLoader('Doctrine', APPPATH . 'libraries'); $doctrineClassLoader->register(); $entitiesClassLoader = new ClassLoader('models', rtrim(APPPATH, '/')); $entitiesClassLoader->register(); $proxiesClassLoader = new ClassLoader('Proxies', APPPATH . 'models/proxies'); $proxiesClassLoader->register(); // Set up caches $config = new Configuration(); $cache = new ArrayCache(); $config->setMetadataCacheImpl($cache); $config->setQueryCacheImpl($cache); // Set up driver $Doctrine_AnnotationReader = new \Doctrine\Common\Annotations\AnnotationReader($cache); $Doctrine_AnnotationReader->setDefaultAnnotationNamespace('Doctrine\\ORM\\Mapping\\'); $driver = new \Doctrine\ORM\Mapping\Driver\AnnotationDriver($Doctrine_AnnotationReader, APPPATH . 'models'); $config->setMetadataDriverImpl($driver); // Proxy configuration $config->setProxyDir(APPPATH . '/models/proxies'); $config->setProxyNamespace('Proxies'); // Set up logger //$logger = new EchoSqlLogger; //$config->setSqlLogger($logger); $config->setAutoGenerateProxyClasses(TRUE); // Database connection information $connectionOptions = array('driver' => 'pdo_mysql', 'user' => $db['default']['username'], 'password' => $db['default']['password'], 'host' => $db['default']['hostname'], 'dbname' => $db['default']['database']); // Create EntityManager $this->em = EntityManager::create($connectionOptions, $config); }
public function __construct() { $class = $this; $this->container = new \Slim\Container(); $this->container['cache'] = function () { return new \Slim\HttpCache\CacheProvider(); }; $this->app = new \Slim\App($this->container); $this->app->add(new \Slim\HttpCache\Cache('public', 86400)); $this->app->group('/api', function () use($class) { foreach (get_class_methods($class) as $mthod) { if ($mthod !== '__construct') { $reflection = new ReflectionObject($class); $reflectionMethod = $reflection->getMethod($mthod); $reader = new \Doctrine\Common\Annotations\AnnotationReader(); $annotations = $reader->getMethodAnnotations($reflectionMethod); if (!empty($annotations[0])) { $contentType = $annotations[0]->produces; $this->map([$annotations[0]->method], $annotations[0]->value, function ($request, $response, $args) use($class, $reflectionMethod, $contentType) { $newResponse = $response->withHeader('Content-type', $contentType); $reflectionMethod->invoke($class, $request, $newResponse); $resWithLastMod = $this->cache->withLastModified($newResponse, time() - 3600); return $resWithLastMod; }); } } } }); $this->app->run(); }
/** * @param array $paths * @return \Doctrine\ORM\Mapping\Driver\AnnotationDriver */ protected function createAnnotationDriver($paths = array(), $alias = null) { if (version_compare(\Doctrine\Common\Version::VERSION, '3.0.0', '>=')) { $reader = new \Doctrine\Common\Annotations\CachedReader(new \Doctrine\Common\Annotations\AnnotationReader(), new ArrayCache()); } else { if (version_compare(\Doctrine\Common\Version::VERSION, '2.2.0-DEV', '>=')) { // Register the ORM Annotations in the AnnotationRegistry $reader = new \Doctrine\Common\Annotations\SimpleAnnotationReader(); $reader->addNamespace('Doctrine\\ORM\\Mapping'); $reader = new \Doctrine\Common\Annotations\CachedReader($reader, new ArrayCache()); } else { if (version_compare(\Doctrine\Common\Version::VERSION, '2.1.0-BETA3-DEV', '>=')) { $reader = new \Doctrine\Common\Annotations\AnnotationReader(); $reader->setIgnoreNotImportedAnnotations(true); $reader->setEnableParsePhpImports(false); if ($alias) { $reader->setAnnotationNamespaceAlias('Doctrine\\ORM\\Mapping\\', $alias); } else { $reader->setDefaultAnnotationNamespace('Doctrine\\ORM\\Mapping\\'); } $reader = new \Doctrine\Common\Annotations\CachedReader(new \Doctrine\Common\Annotations\IndexedReader($reader), new ArrayCache()); } else { $reader = new \Doctrine\Common\Annotations\AnnotationReader(); if ($alias) { $reader->setAnnotationNamespaceAlias('Doctrine\\ORM\\Mapping\\', $alias); } else { $reader->setDefaultAnnotationNamespace('Doctrine\\ORM\\Mapping\\'); } } } } \Doctrine\Common\Annotations\AnnotationRegistry::registerFile(__DIR__ . "/../../../lib/Doctrine/ORM/Mapping/Driver/DoctrineAnnotations.php"); return new \Doctrine\ORM\Mapping\Driver\AnnotationDriver($reader, (array) $paths); }
public function testIssue() { $reader = new \Doctrine\Common\Annotations\AnnotationReader(); $result = $reader->getClassAnnotations(new \ReflectionClass(__NAMESPACE__ . "\\MappedClass")); foreach ($result as $annot) { $classAnnotations[get_class($annot)] = $annot; } $this->assertTrue(!isset($classAnnotations['']), 'Class "xxx" is not a valid entity or mapped super class.'); }
/** * @group DDC-706 */ public function testIsTransient() { $reader = new \Doctrine\Common\Annotations\AnnotationReader(new \Doctrine\Common\Cache\ArrayCache()); $reader->setDefaultAnnotationNamespace('Doctrine\\ORM\\Mapping\\'); $chain = new DriverChain(); $chain->addDriver(new \Doctrine\ORM\Mapping\Driver\AnnotationDriver($reader, array()), 'Doctrine\\Tests\\Models\\CMS'); $this->assertTrue($chain->isTransient('stdClass'), "stdClass isTransient"); $this->assertFalse($chain->isTransient('Doctrine\\Tests\\Models\\CMS\\CmsUser'), "CmsUser is not Transient"); }
public function initialize($parameters = array()) { parent::initialize($parameters); $schema = $this->getParameter('schema'); $connectionName = $this->getParameter('name'); $connectionOptions = $this->getParameter('options'); $plugins = (array) $this->getParameter('plugins'); $config = new \Doctrine\ORM\Configuration(); $config->setMetadataCacheImpl(new \Doctrine\Common\Cache\ArrayCache()); $configuration = sfProjectConfiguration::getActive(); $paths = array(); if ($schema) { $paths[] = $schema; } $paths[] = realpath(__DIR__ . '/../config/doctrine'); $paths[] = realpath(sfConfig::get('sf_config_dir') . '/doctrine'); $enabledPlugins = $configuration->getPlugins(); foreach ($configuration->getAllPluginPaths() as $plugin => $path) { if (!in_array($plugin, $enabledPlugins) || !in_array($plugin, $plugins)) { continue; } $paths[] = $path . '/config/doctrine'; } $paths = array_unique($paths); $config->setMetadataDriverImpl(new YamlDriver($paths)); $config->setProxyDir(sfConfig::get('sf_lib_dir') . '/Proxies'); $config->setProxyNamespace('Proxies'); $configuration = sfProjectConfiguration::getActive(); if (sfConfig::get('sf_debug')) { $config->setSqlLogger(new sfDoctrineSqlLogger($configuration->getEventDispatcher())); } $method = sprintf('configureDoctrineConnection%s', $connectionName); $methodExists = method_exists($configuration, $method); if (method_exists($configuration, 'configureDoctrineConnection') && !$methodExists) { $configuration->configureDoctrineConnection($config); } else { if ($methodExists) { $configuration->{$method}($config); } } $this->em = \Doctrine\ORM\EntityManager::create($connectionOptions, $config); if (method_exists($configuration, 'configureEntityManager')) { $configuration->configureEntityManager($this->em); } ActiveEntity::setEntityManager($this->em); // ODM MongoDB $config = new Doctrine\ODM\MongoDB\Configuration(); $config->setProxyDir(sfConfig::get('sf_lib_dir') . '/Proxies'); $config->setProxyNamespace('Proxies'); $reader = new Doctrine\Common\Annotations\AnnotationReader(); $reader->setDefaultAnnotationNamespace('Doctrine\\ODM\\MongoDB\\Mapping\\'); $config->setMetadataDriverImpl(new Doctrine\ODM\MongoDB\Mapping\Driver\AnnotationDriver($reader, sfConfig::get('sf_lib_dir') . DIRECTORY_SEPARATOR . 'Documents')); $this->dm = Doctrine\ODM\MongoDB\DocumentManager::create(new \Doctrine\ODM\MongoDB\Mongo(), $config); }
/** * @expectedException \Exception * @expectedExceptionMessage Class "xxx" is not a valid entity or mapped super class. */ public function testIssue() { $reader = new \Doctrine\Common\Annotations\AnnotationReader(); $result = $reader->getClassAnnotations(new \ReflectionClass(__NAMESPACE__ . "\\MappedClass")); foreach ($result as $annot) { $classAnnotations[get_class($annot)] = $annot; } // Evaluate Entity annotation if (!isset($classAnnotations['Doctrine\\Tests\\Common\\Annotations\\Ticket\\Doctrine\\ORM\\Mapping\\Entity'])) { throw new \Exception('Class "xxx" is not a valid entity or mapped super class.'); } }
/** * EntityManager mock object together with * annotation mapping driver and pdo_sqlite * database in memory * * @return EntityManager */ protected function getMockSqliteEntityManager() { $conn = array('driver' => 'pdo_sqlite', 'memory' => true); $config = $this->getMock('Doctrine\\ORM\\Configuration'); $config->expects($this->once())->method('getProxyDir')->will($this->returnValue(sys_get_temp_dir())); $config->expects($this->once())->method('getProxyNamespace')->will($this->returnValue('Proxy')); $config->expects($this->once())->method('getAutoGenerateProxyClasses')->will($this->returnValue(true)); $reader = new \Doctrine\Common\Annotations\AnnotationReader(); $reader->setDefaultAnnotationNamespace('Doctrine\\ORM\\Mapping\\'); $mappingDriver = new \Doctrine\ORM\Mapping\Driver\AnnotationDriver($reader); $config->expects($this->any())->method('getMetadataDriverImpl')->will($this->returnValue($mappingDriver)); $em = EntityManager::create($conn, $config); return $em; }
/** * @param LoadClassMetadataEventArgs $eventArgs */ public function loadClassMetadata(LoadClassMetadataEventArgs $eventArgs) { $reader = new \Doctrine\Common\Annotations\AnnotationReader(); $meta = $eventArgs->getClassMetadata(); foreach ($meta->getReflectionClass()->getProperties() as $property) { if ($meta->isMappedSuperclass && !$property->isPrivate() || $meta->isInheritedField($property->name) || isset($meta->associationMappings[$property->name]['inherited'])) { continue; } /** @var $annotation \Snowcap\ImBundle\Doctrine\Mapping\Mogrify */ if ($annotation = $reader->getPropertyAnnotation($property, 'Snowcap\\ImBundle\\Doctrine\\Mapping\\Mogrify')) { $field = $property->getName(); $this->config[$meta->getTableName()]['fields'][$field] = array('property' => $property, 'params' => $annotation->params); } } }
public function testHasGetMetadata_NamespaceSeperatorIsNotNormalized() { require_once __DIR__ . "/../../Models/Global/GlobalNamespaceModel.php"; $reader = new \Doctrine\Common\Annotations\AnnotationReader(new \Doctrine\Common\Cache\ArrayCache()); $reader->setDefaultAnnotationNamespace('Doctrine\\ORM\\Mapping\\'); $metadataDriver = new \Doctrine\ORM\Mapping\Driver\AnnotationDriver($reader); $metadataDriver->addPaths(array(__DIR__ . '/../../Models/Global/')); $entityManager = $this->_createEntityManager($metadataDriver); $mf = $entityManager->getMetadataFactory(); $m1 = $mf->getMetadataFor("DoctrineGlobal_Article"); $h1 = $mf->hasMetadataFor("DoctrineGlobal_Article"); $h2 = $mf->hasMetadataFor("\\DoctrineGlobal_Article"); $m2 = $mf->getMetadataFor("\\DoctrineGlobal_Article"); $this->assertNotSame($m1, $m2); $this->assertFalse($h2); $this->assertTrue($h1); }
function __construct() { $reader = new \Doctrine\Common\Annotations\AnnotationReader(); $className = get_class($this); $reflect = new ReflectionClass($className); $props = $reflect->getProperties(); foreach ($props as $p) { $anno = $reader->getPropertyAnnotations($p); if (array_key_exists('inject', $anno)) { $classToMake = $anno['inject']->class; $class = new $classToMake(); $propName = $p->name; if ($this->{$propName} == null) { $this->{$propName} = $class; } } } }
/** * @param \ReflectionClass $class * @return FormMetadata */ private function getClassFormFields(\ReflectionClass $class) { $metadata = new FormMetadata(); $reader = new \Doctrine\Common\Annotations\AnnotationReader(); /** @var \ReflectionProperty[] $properties */ $properties = $class->getProperties(); foreach ($properties as $property) { $field = $reader->getPropertyAnnotation($property, 'Corleonis\\FormMetadataBundle\\Configuration\\Field'); $fieldGroup = $reader->getPropertyAnnotation($property, 'Corleonis\\FormMetadataBundle\\Configuration\\FieldGroup'); $formType = $reader->getPropertyAnnotation($property, 'Corleonis\\FormMetadataBundle\\Configuration\\FormType'); $fieldEntity = $reader->getPropertyAnnotation($property, 'Corleonis\\FormMetadataBundle\\Configuration\\FieldEntity'); // prepare the option fields for our field if ($field && $field->value) { $preparer = FieldOptionPreparerFactory::get($field->value); if ($preparer) { $preparer->prepare($field); } } if (!empty($fieldGroup) && !empty($field)) { if (empty($field->name)) { $field->name = $property->getName(); } $metadata->addGroup($fieldGroup, $field); } elseif (!empty($field)) { if (empty($field->name)) { $field->name = $property->getName(); } $metadata->addField($field); } if (!empty($formType)) { if (empty($field->name)) { $formType->name = $property->getName(); } $metadata->addFormType($formType); } if (!empty($fieldEntity)) { if (empty($field->name)) { $fieldEntity->name = $property->getName(); } $metadata->addFieldEntity($fieldEntity); } } return $metadata; }
/** * Read the entity and create an associated metadata * @param $entity * @return null|FormMetadata */ public function getMetadata($entity) { $metadata = new FormMetadata(); $reader = new \Doctrine\Common\Annotations\AnnotationReader(); $reflectionClass = new \ReflectionClass(get_class($entity)); while (is_object($reflectionClass)) { $properties = $reflectionClass->getProperties(); foreach ($properties as $property) { $field = $reader->getPropertyAnnotation($property, 'FlintLabs\\Bundle\\FormMetadataBundle\\Configuration\\Field'); if (!empty($field)) { if (empty($field->name)) { $field->name = $property->getName(); } $metadata->addField($field); } } $reflectionClass = $reflectionClass->getParentClass(); } return $metadata; }
public function describeClass($class) { $return_array = null; if (self::$_cache_directory) { $filename = self::getCacheDirectory() . str_replace("\\", '_', $class) . '_description.cache.php'; if (file_exists($filename)) { $return_array = unserialize(file_get_contents($filename)); } } if ($return_array === null) { $reflection_class = new \ReflectionClass($class); $reader = new \Doctrine\Common\Annotations\AnnotationReader(new \Doctrine\Common\Cache\ArrayCache()); $reader->setEnableParsePhpImports(true); $reader->setDefaultAnnotationNamespace('RedpillLinpro\\GamineBundle\\Annotations\\'); $return_array = array(); foreach ($reflection_class->getProperties() as $property) { $is_id = false; $annotations = $reader->getPropertyAnnotations($property); foreach ($annotations as $annotation) { if (!method_exists($annotation, 'getKey')) { continue; } switch ($annotation->getKey()) { case 'id': $return_array['primary_key']['property'] = $property->name; $return_array['primary_key']['key'] = $property->name; $is_id = true; break; } $return_array['properties'][$property->name][$annotation->getKey()] = (array) $annotation; } if ($is_id && isset($return_array['properties'][$property->name]['column']['name'])) { $return_array['primary_key']['key'] = $return_array['properties'][$property->name]['column']['name']; } } if (self::$_cache_directory) { file_put_contents($filename, serialize($return_array)); } } return $return_array; }
public function getMetadata($className) { $reflClass = new \ReflectionClass($className); $reader = new \Doctrine\Common\Annotations\AnnotationReader(); $metadata = new ElementMetadata(); $metadata->class = $className; foreach ($reflClass->getProperties() as $reflProp) { $annot = $reader->getPropertyAnnotation($reflProp, 'Broda\\Component\\Rest\\Annotation\\Client\\Identifier'); if (null !== $annot) { $metadata->identifier = $reflProp->getName(); break; // o resto dos campos são ignorados } } if (!$metadata->identifier) { if (!$reflClass->hasProperty('id')) { throw new \RuntimeException(sprintf('A classe %s precisa de um identifier ' . '(ou "id" ou uma propriedade com a anotação @Identifier)', $className)); } $metadata->identifier = 'id'; } return $metadata; }
protected function getDoctrine_Odm_Mongodb_Metadata_AnnotationReaderService() { if (isset($this->shared['doctrine.odm.mongodb.metadata.annotation_reader'])) { return $this->shared['doctrine.odm.mongodb.metadata.annotation_reader']; } $instance = new Doctrine\Common\Annotations\AnnotationReader($this->getDoctrine_Odm_Mongodb_Cache_ArrayService()); $this->shared['doctrine.odm.mongodb.metadata.annotation_reader'] = $instance; $instance->setDefaultAnnotationNamespace($this->getParameter('doctrine.odm.mongodb.metadata.annotation_default_namespace')); return $instance; }
/** * Loads a Routes collection by parsing Controller method names. * * @param string $controller Some identifier for the controller * @param string $type The resource type * * @return RouteCollection A RouteCollection instance */ public function load($controller, $type = null) { if (class_exists($controller)) { // full class name $class = $controller; $controllerPrefix = $class . '::'; } elseif (false !== strpos($controller, ':')) { // bundle:controller notation try { $notation = $this->parser->parse($controller . ':method'); list($class, $method) = explode('::', $notation); $controllerPrefix = $class . '::'; } catch (\Exception $e) { throw new \InvalidArgumentException(sprintf('Can\'t locate "%s" controller.', $controller)); } } elseif ($this->container->has($controller)) { // service_id $controllerPrefix = $controller . ':'; // FIXME: this is ugly, but I do not see any good alternative $this->container->enterScope('request'); $this->container->set('request', new Request()); $class = get_class($this->container->get($controller)); $this->container->leaveScope('request'); } if (empty($class)) { throw new \InvalidArgumentException(sprintf('Class could not be determined for Controller identified by "%s".', $controller)); } // Check that every passed parent has non-empty singular name foreach ($this->parents as $parent) { if (empty($parent) || '/' === substr($parent, -1)) { throw new \InvalidArgumentException('All parent controllers must have ::getSINGULAR_NAME() action'); } } $class = new \ReflectionClass($class); $collection = new RestRouteCollection(); $collection->addResource(new FileResource($class->getFileName())); $prefixAnnotationClass = 'FOS\\RestBundle\\Controller\\Annotations\\Prefix'; $prefix = $this->reader->getClassAnnotation($class, $prefixAnnotationClass); if ($prefix) { $this->prefix = $prefix->value; } $namePrefixAnnotationClass = 'FOS\\RestBundle\\Controller\\Annotations\\NamePrefix'; $namePrefix = $this->reader->getClassAnnotation($class, $namePrefixAnnotationClass); if ($namePrefix) { $this->namePrefix = $namePrefix->value; } // Trim "/" at the start if (null !== $this->prefix && isset($this->prefix[0]) && '/' === $this->prefix[0]) { $this->prefix = substr($this->prefix, 1); } $routeAnnotationClass = 'FOS\\RestBundle\\Controller\\Annotations\\Route'; $patternStartRoute = $this->reader->getClassAnnotation($class, $routeAnnotationClass); $patternStart = null; if ($patternStartRoute) { $patternStart = trim($patternStartRoute->getPattern(), "/"); } $routes = array(); foreach ($class->getMethods(\ReflectionMethod::IS_PUBLIC) as $method) { $matches = array(); // If method name starts with underscore - skip if ('_' === substr($method->getName(), 0, 1)) { continue; } // If method has @NoRoute annotation - skip $noAnnotationClass = 'FOS\\RestBundle\\Controller\\Annotations\\NoRoute'; if (null !== $this->reader->getMethodAnnotation($method, $noAnnotationClass)) { continue; } if (preg_match('/([a-z][_a-z0-9]+)(.*)Action/', $method->getName(), $matches)) { $httpMethod = $matches[1]; $resources = preg_split('/([A-Z][^A-Z]*)/', $matches[2], -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE); $arguments = $method->getParameters(); // Ignore arguments that are or extend from Symfony\Component\HttpFoundation\Request foreach ($arguments as $key => $argument) { $class = $argument->getClass(); if ($class && ($class->getName() === 'Symfony\\Component\\HttpFoundation\\Request' || is_subclass_of($class->getName(), 'Symfony\\Component\\HttpFoundation\\Request'))) { unset($arguments[$key]); } } // If we have 1 resource passed & 1 argument, then it's object call, so // we can set collection singular name if (1 === count($resources) && 1 === count($arguments) - count($this->parents)) { $collection->setSingularName($resources[0]); } // If we have parents passed - merge them with own resource names if (count($this->parents)) { $resources = array_merge($this->parents, $resources); } $urlParts = array(); $routeName = $httpMethod; if (empty($resources)) { $resources[] = null; } foreach ($resources as $i => $resource) { if (null !== $resource) { $routeName .= '_' . basename($resource); } // If we already added all parent routes paths to URL & we have prefix - add it if (!empty($this->prefix) && $i === count($this->parents)) { $urlParts[] = $this->prefix; } // If we have argument for current resource, then it's object. Otherwise - it's collection if (isset($arguments[$i])) { if ($patternStart) { $urlParts[] = strtolower($patternStart) . '/{' . $arguments[$i]->getName() . '}'; } elseif (null !== $resource) { $urlParts[] = strtolower(Pluralization::pluralize($resource)) . '/{' . $arguments[$i]->getName() . '}'; } else { $urlParts[] = '{' . $arguments[$i]->getName() . '}'; } } else { if ($patternStart) { $urlParts[] = $patternStart; } elseif (null !== $resource) { $urlParts[] = strtolower($resource); } } } // If passed method is not valid HTTP method // then it's either a hypertext driver, // a custom object (PUT) or collection (GET) method if (!in_array($httpMethod, $this->availableHTTPMethods)) { $urlParts[] = $httpMethod; // allow hypertext as the engine of application state // through conventional GET actions if (in_array($httpMethod, $this->availableConventionalActions)) { $httpMethod = 'get'; } else { //custom object $httpMethod = 'post'; // resource collection if (count($arguments) < count($resources)) { $httpMethod = 'get'; } } } $pattern = implode('/', $urlParts); $defaults = array('_controller' => $controllerPrefix . $method->getName(), '_format' => $this->defaultFormat); $requirements = array('_method' => strtoupper($httpMethod)); $options = array(); // Read annotations foreach ($this->annotationClasses as $annotationClass) { $routeAnnnotation = $this->reader->getMethodAnnotation($method, $annotationClass); if (null !== $routeAnnnotation) { $annoRequirements = $routeAnnnotation->getRequirements(); if (!isset($annoRequirements['_method']) || null === $annoRequirements['_method']) { $annoRequirements['_method'] = $requirements['_method']; } $pattern = $routeAnnnotation->getPattern() ?: $pattern; $requirements = array_merge($requirements, $annoRequirements); $options = array_merge($options, $routeAnnnotation->getOptions()); $defaults = array_merge($defaults, $routeAnnnotation->getDefaults()); break; } } //Adding in the optional _format param for serialization $pattern .= ".{_format}"; // Create route with gathered parameters $route = new Route($pattern, $defaults, $requirements, $options); $routeName = $this->namePrefix . strtolower($routeName); // Move custom actions at the beginning, default at the end if (!preg_match('/^(' . implode('|', $this->availableHTTPMethods) . ')/', $routeName)) { array_unshift($routes, array('name' => $routeName, 'route' => $route)); } else { $routes[] = array('name' => $routeName, 'route' => $route); } } } foreach ($routes as $routeInfo) { $collection->add($routeInfo['name'], $routeInfo['route']); } $this->prefix = null; $this->namePrefix = null; return $collection; }
/** * * @param \Doctrine\ORM\Event\LifecycleEventArgs $args * @param type $event * @return boolean */ public function isEventActive(LifecycleEventArgs $args, $event) { $metadata = $args->getEntityManager()->getClassMetadata(get_class($args->getEntity())); $reader = new \Doctrine\Common\Annotations\AnnotationReader(); $logger = $reader->getClassAnnotation($metadata->getReflectionClass(), '\\Core\\Model\\OWM\\Mapping\\Logger'); if ($logger) { return in_array($event, explode('::', $logger->getEventLog())); } return false; }
/** * Setup the metadata driver if necessary options are set. Otherwise Doctrine defaults are used (AnnotationReader). * * @param array $options * @param Doctrine\ORM\Configuration $config * @param Doctrine\Common\Cache\AbstractCache $cache * @param Doctrine\DBAL\Connection $conn */ protected function _setupMetadataDriver($options, $config, $cache, $conn) { $driver = false; if (isset($options['metadata'])) { if (isset($options['metadata']['driver'])) { $driverName = $options['metadata']['driver']; switch (strtolower($driverName)) { case 'annotation': $driverName = 'Doctrine\\ORM\\Mapping\\Driver\\AnnotationDriver'; break; case 'yaml': $driverName = 'Doctrine\\ORM\\Mapping\\Driver\\YamlDriver'; break; case 'xml': $driverName = 'Doctrine\\ORM\\Mapping\\Driver\\XmlDriver'; break; case 'php': $driverName = 'Doctrine\\ORM\\Mapping\\Driver\\PhpDriver'; break; case 'database': $driverName = 'Doctrine\\ORM\\Mapping\\Driver\\DatabaseDriver'; break; } if (!class_exists($driverName)) { throw new ZendX_Doctrine2_Exception("MetadataDriver class '" . $driverName . "' does not exist"); } if (in_array('Doctrine\\ORM\\Mapping\\Driver\\AbstractFileDriver', class_parents($driverName))) { if (!isset($options['metadata']['paths'])) { throw new ZendX_Doctrine2_Exception("Metadata Driver is file based, but no config file paths were given."); } if (!isset($options['metadata']['mode'])) { $options['metadata']['mode'] = \Doctrine\ORM\Mapping\Driver\AbstractFileDriver::FILE_PER_CLASS; } $driver = new $driverName($options['metadata']['paths'], $options['metadata']['mode']); } elseif ($driverName == 'Doctrine\\ORM\\Mapping\\Driver\\AnnotationDriver') { $reader = new \Doctrine\Common\Annotations\AnnotationReader($cache); $reader->setDefaultAnnotationNamespace('Doctrine\\ORM\\Mapping\\'); $driver = new \Doctrine\ORM\Mapping\Driver\AnnotationDriver($reader); if (isset($options['metadata']['classDirectory'])) { $driver->addPaths(array($options['metadata']['classDirectory'])); } else { throw new ZendX_Doctrine2_Exception("Doctrine Annotation Driver requires to set a class directory for the entities."); } //$driverImpl = $config->newDefaultAnnotationDriver("var/www/zfbench/application/models")); //$config->setMetadataDriverImpl($driverImpl); } elseif ($driverName == 'Doctrine\\ORM\\Mapping\\Driver\\DatabaseDriver') { $schemaManager = $conn->getSchemaManager(); $driver = new \Doctrine\ORM\Mapping\Driver\DatabaseDriver($schemaManager); } if (!$driver instanceof \Doctrine\ORM\Mapping\Driver\Driver) { throw new ZendX_Doctrine2_Exception("No metadata driver could be loaded."); } $config->setMetadataDriverImpl($driver); } } }
if ($path) { $classLoader = new \Doctrine\Common\ClassLoader($name, $path); } else { $classLoader = new \Doctrine\Common\ClassLoader($name); } $classLoader->register(); } foreach ($entitiesPath as $name => $path) { $classLoader = new \Doctrine\Common\ClassLoader($name, $path); $classLoader->register(); } // Setup Entity Manager // **************************************************************** $ormConfig = new \Doctrine\ORM\Configuration(); // custom zend form annotations $annoReader = new \Doctrine\Common\Annotations\AnnotationReader(); $annoReader->setAutoloadAnnotations(true); $annoReader->setDefaultAnnotationNamespace('Doctrine\\ORM\\Mapping\\'); $annoReader->setAnnotationNamespaceAlias('Awe\\Annotations\\', 'awe'); $annoDriver = new \Doctrine\ORM\Mapping\Driver\AnnotationDriver($annoReader, $entitiesPath); $ormConfig->setMetadataDriverImpl($annoDriver); // logging $ormConfig->setSQLLogger(new \Doctrine\DBAL\Logging\FileSQLLogger($logPath)); // caching if (is_array($cacheType)) { $ormConfig->setQueryCacheImpl(new $cacheType['query']()); $ormConfig->setMetadataCacheImpl(new $cacheType['metadata']()); } else { $ormConfig->setQueryCacheImpl(new $cacheType()); $ormConfig->setMetadataCacheImpl(new $cacheType()); }
/** * Add a new default annotation driver with a correctly configured annotation reader. * * @param array $paths * @return Mapping\Driver\AnnotationDriver */ public function newDefaultAnnotationDriver($paths = array()) { $reader = new \Doctrine\Common\Annotations\AnnotationReader(); $reader->setDefaultAnnotationNamespace('Doctrine\\ODM\\MongoDB\\Mapping\\'); return new \Doctrine\ODM\MongoDB\Mapping\Driver\AnnotationDriver($reader, (array) $paths); }
/** * Gets the cache driver implementation that is used for the mapping metadata. * * @return object */ public function getMetadataDriverImpl() { if ($this->_attributes['metadataDriverImpl'] == null) { $reader = new \Doctrine\Common\Annotations\AnnotationReader(new \Doctrine\Common\Cache\ArrayCache()); $reader->setDefaultAnnotationNamespace('Doctrine\\ORM\\Mapping\\'); $this->_attributes['metadataDriverImpl'] = new \Doctrine\ORM\Mapping\Driver\AnnotationDriver($reader); } return $this->_attributes['metadataDriverImpl']; }
/** * Gets the 'doctrine.orm.default_configuration' service. * * This service is shared. * This method always returns the same instance of the service. * * @return Doctrine\ORM\Configuration A Doctrine\ORM\Configuration instance. */ protected function getDoctrine_Orm_DefaultConfigurationService() { $a = new \Doctrine\Common\Cache\ArrayCache(); $a->setNamespace('sf2orm_default_40ceb0fc2536c243bed418a2d3ecc2f2'); $b = new \Doctrine\Common\Cache\ArrayCache(); $b->setNamespace('sf2orm_default_40ceb0fc2536c243bed418a2d3ecc2f2'); $c = new \Doctrine\Common\Cache\ArrayCache(); $c->setNamespace('sf2orm_default_40ceb0fc2536c243bed418a2d3ecc2f2'); $d = new \Doctrine\Common\Annotations\AnnotationReader(); $d->setAnnotationNamespaceAlias('Doctrine\\ORM\\Mapping\\', 'orm'); $e = new \Doctrine\ORM\Mapping\Driver\DriverChain(); $e->addDriver(new \Doctrine\ORM\Mapping\Driver\AnnotationDriver($d, array(0 => '/var/www/symfony2.0/alf/src/Alf/ShopBundle/Entity')), 'Alf\\ShopBundle\\Entity'); $this->services['doctrine.orm.default_configuration'] = $instance = new \Doctrine\ORM\Configuration(); $instance->setEntityNamespaces(array('AlfShopBundle' => 'Alf\\ShopBundle\\Entity')); $instance->setMetadataCacheImpl($a); $instance->setQueryCacheImpl($b); $instance->setResultCacheImpl($c); $instance->setMetadataDriverImpl($e); $instance->setProxyDir('/var/www/symfony2.0/alf/app/cache/dev/doctrine/orm/Proxies'); $instance->setProxyNamespace('Proxies'); $instance->setAutoGenerateProxyClasses(true); $instance->setClassMetadataFactoryName('Doctrine\\ORM\\Mapping\\ClassMetadataFactory'); return $instance; }
/** * @return $this */ public function connect() { // Prevent to connect twice if ($this->entityManager) { return $this; } $applicationDir = $this->core->getApplicationDir(); $this->createModuleDirCache(); $cache = $this->cache->getCacheProvider(); $config = new \Doctrine\ORM\Configuration(); $config->setMetadataCacheImpl($cache); $config->addCustomStringFunction('MD5', '\\DoctrineExtensions\\Query\\Mysql\\Md5'); $config->addCustomStringFunction('ACOS', '\\DoctrineExtensions\\Query\\Mysql\\Acos'); $config->addCustomStringFunction('ASIN', '\\DoctrineExtensions\\Query\\Mysql\\Asin'); $config->addCustomStringFunction('ATAN', '\\DoctrineExtensions\\Query\\Mysql\\Atan'); $config->addCustomStringFunction('ATAN2', '\\DoctrineExtensions\\Query\\Mysql\\Atan2'); $config->addCustomStringFunction('BINARY', '\\DoctrineExtensions\\Query\\Mysql\\Binary'); $config->addCustomStringFunction('CHARLENGTH', '\\DoctrineExtensions\\Query\\Mysql\\CharLength'); $config->addCustomStringFunction('CONCATWS', '\\DoctrineExtensions\\Query\\Mysql\\ConcatWs'); $config->addCustomStringFunction('COS', '\\DoctrineExtensions\\Query\\Mysql\\Cos'); $config->addCustomStringFunction('COT', '\\DoctrineExtensions\\Query\\Mysql\\COT'); $config->addCustomStringFunction('COUNTIF', '\\DoctrineExtensions\\Query\\Mysql\\CountIf'); $config->addCustomStringFunction('CRC32', '\\DoctrineExtensions\\Query\\Mysql\\Crc32'); $config->addCustomStringFunction('DATE', '\\DoctrineExtensions\\Query\\Mysql\\Date'); $config->addCustomStringFunction('DATEADD', '\\DoctrineExtensions\\Query\\Mysql\\DateAdd'); $config->addCustomStringFunction('DATEDIFF', '\\DoctrineExtensions\\Query\\Mysql\\DateFormat'); $config->addCustomStringFunction('DAY', '\\DoctrineExtensions\\Query\\Mysql\\Day'); $config->addCustomStringFunction('DEGREES', '\\DoctrineExtensions\\Query\\Mysql\\Degrees'); $config->addCustomStringFunction('FIELD', '\\DoctrineExtensions\\Query\\Mysql\\Field'); $config->addCustomStringFunction('FINDINSET', '\\DoctrineExtensions\\Query\\Mysql\\FindInSet'); $config->addCustomStringFunction('GROUPCONCAT', '\\DoctrineExtensions\\Query\\Mysql\\GroupConcat'); $config->addCustomStringFunction('HOUR', '\\DoctrineExtensions\\Query\\Mysql\\Hour'); $config->addCustomStringFunction('IFELSE', '\\DoctrineExtensions\\Query\\Mysql\\IfElse'); $config->addCustomStringFunction('IFNULL', '\\DoctrineExtensions\\Query\\Mysql\\IfNUll'); $config->addCustomStringFunction('MATCHAGAINST', '\\DoctrineExtensions\\Query\\Mysql\\MatchAgainst'); $config->addCustomStringFunction('MONTH', '\\DoctrineExtensions\\Query\\Mysql\\Month'); $config->addCustomStringFunction('NULLIF', '\\DoctrineExtensions\\Query\\Mysql\\NullIf'); $config->addCustomStringFunction('PI', '\\DoctrineExtensions\\Query\\Mysql\\Pi'); $config->addCustomStringFunction('RADIANS', '\\DoctrineExtensions\\Query\\Mysql\\Radians'); $config->addCustomStringFunction('RAND', '\\DoctrineExtensions\\Query\\Mysql\\Rand'); $config->addCustomStringFunction('REGEXP', '\\DoctrineExtensions\\Query\\Mysql\\Regexp'); $config->addCustomStringFunction('ROUND', '\\DoctrineExtensions\\Query\\Mysql\\Round'); $config->addCustomStringFunction('SHA1', '\\DoctrineExtensions\\Query\\Mysql\\Sha1'); $config->addCustomStringFunction('SHA2', '\\DoctrineExtensions\\Query\\Mysql\\Sha2'); $config->addCustomStringFunction('SIN', '\\DoctrineExtensions\\Query\\Mysql\\Sin'); $config->addCustomStringFunction('STRTODATE', '\\DoctrineExtensions\\Query\\Mysql\\StrToDate'); $config->addCustomStringFunction('TAN', '\\DoctrineExtensions\\Query\\Mysql\\Tan'); $config->addCustomStringFunction('TIMESTAMPDIFF', '\\DoctrineExtensions\\Query\\Mysql\\TimestampDiff'); $config->addCustomStringFunction('WEEK', '\\DoctrineExtensions\\Query\\Mysql\\Week'); $config->addCustomStringFunction('YEAR', '\\DoctrineExtensions\\Query\\Mysql\\Year'); if (!defined('ENV') || ENV === \Fraym\Core::ENV_DEVELOPMENT) { $config->setAutoGenerateProxyClasses(true); } $modelDirs = $this->getModuleDirCache(); \Doctrine\Common\Annotations\AnnotationRegistry::registerLoader(function ($class) { return class_exists($class, true); }); $annotationReader = new \Doctrine\Common\Annotations\AnnotationReader(); $this->cachedAnnotationReader = new \Doctrine\Common\Annotations\CachedReader($annotationReader, $cache); $this->annotationDriver = new \Doctrine\ORM\Mapping\Driver\AnnotationDriver($this->cachedAnnotationReader, $modelDirs); /** * Ignore PHP-DI Annotation */ $annotationReader->addGlobalIgnoredName('Injectable'); $annotationReader->addGlobalIgnoredName('Inject'); $config->setMetadataDriverImpl($this->annotationDriver); $config->setQueryCacheImpl($cache); $config->setResultCacheImpl($cache); $config->setProxyDir($applicationDir . DIRECTORY_SEPARATOR . CACHE_DOCTRINE_PROXY_PATH); $config->setProxyNamespace('Proxies'); $this->fetchMode = \PDO::FETCH_OBJ; $tablePrefix = new TablePrefix(DB_TABLE_PREFIX); $this->eventManager = new \Doctrine\Common\EventManager(); $this->eventManager->addEventListener(\Doctrine\ORM\Events::loadClassMetadata, $tablePrefix); $this->entityManager = \Doctrine\ORM\EntityManager::create($this->connectionOptions, $config, $this->eventManager); $this->pdo = $this->entityManager->getConnection(); $this->pdo->getDatabasePlatform()->registerDoctrineTypeMapping('set', 'string'); $driverChain = new \Doctrine\Common\Persistence\Mapping\Driver\MappingDriverChain(); \Gedmo\DoctrineExtensions::registerAbstractMappingIntoDriverChainORM($driverChain, $this->cachedAnnotationReader); $this->eventManager->addEventListener([\Doctrine\ORM\Events::preRemove, \Doctrine\ORM\Events::postRemove, \Doctrine\ORM\Events::prePersist, \Doctrine\ORM\Events::postPersist, \Doctrine\ORM\Events::preUpdate, \Doctrine\ORM\Events::postUpdate, \Doctrine\ORM\Events::postLoad, \Doctrine\ORM\Events::onFlush], $this->eventListener); return $this; }
require_once __DIR__ . '/libraries/Doctrine/Common/ClassLoader.php'; $doctrineClassLoader = new ClassLoader('Doctrine', __DIR__.'libraries'); $doctrineClassLoader->register(); $entitiesClassLoader = new ClassLoader('models', __DIR__); $entitiesClassLoader->register(); $proxiesClassLoader = new ClassLoader('Proxies', __DIR__.'models/proxies'); $proxiesClassLoader->register(); $config = new \Doctrine\ORM\Configuration(); $config->setMetadataCacheImpl(new \Doctrine\Common\Cache\ArrayCache); $config->setProxyDir(__DIR__ . '/Proxies'); $config->setProxyNamespace('Proxies'); $cache = new ArrayCache; // Set up driver $Doctrine_AnnotationReader = new \Doctrine\Common\Annotations\AnnotationReader($cache); $Doctrine_AnnotationReader->setDefaultAnnotationNamespace('Doctrine\ORM\Mapping\\'); $driver = new \Doctrine\ORM\Mapping\Driver\AnnotationDriver($Doctrine_AnnotationReader, realpath('../models')); $config->setMetadataDriverImpl($driver); // Database connection information $connectionOptions = array( 'driver' => 'pdo_mysql', 'user' => $db['default']['username'], 'password' => $db['default']['password'], 'host' => $db['default']['hostname'], 'dbname' => $db['default']['database'] ); $em = \Doctrine\ORM\EntityManager::create($connectionOptions, $config);