compare() public static method

Compares a Doctrine version with the current one.
public static compare ( string $version ) : integer
$version string Doctrine version to compare.
return integer Returns -1 if older, 0 if it is the same, 1 if version passed as argument is newer.
 private function prepare()
 {
     $cmf = $this->em->getMetadataFactory();
     $metadata = new ClassMetadata('Mapping\\Fixture\\Unmapped\\Timestampable');
     $id = array();
     $id['fieldName'] = 'id';
     $id['type'] = 'integer';
     $id['nullable'] = false;
     $id['columnName'] = 'id';
     $id['id'] = true;
     $metadata->mapField($id);
     $created = array();
     $created['fieldName'] = 'created';
     $created['type'] = 'datetime';
     $created['nullable'] = false;
     $created['columnName'] = 'created';
     $metadata->mapField($created);
     $metadata->setIdGeneratorType(ClassMetadata::GENERATOR_TYPE_IDENTITY);
     $metadata->setIdGenerator(new \Doctrine\ORM\Id\IdentityGenerator(null));
     $metadata->setPrimaryTable(array('name' => 'temp_test'));
     $cmf->setMetadataFor('Mapping\\Fixture\\Unmapped\\Timestampable', $metadata);
     // trigger loadClassMetadata event
     $evm = $this->em->getEventManager();
     $eventArgs = new \Doctrine\ORM\Event\LoadClassMetadataEventArgs($metadata, $this->em);
     $evm->dispatchEvent(\Doctrine\ORM\Events::loadClassMetadata, $eventArgs);
     if (Version::compare('2.3.0-dev') <= 0) {
         $metadata->wakeupReflection($cmf->getReflectionService());
     }
     $schemaTool = new \Doctrine\ORM\Tools\SchemaTool($this->em);
     $schemaTool->dropSchema(array());
     $schemaTool->createSchema(array($this->em->getClassMetadata('Mapping\\Fixture\\Unmapped\\Timestampable')));
 }
 /**
  * @param \PHPUnit_Framework_TestCase $test
  * @param \Closure                    $qbCallback
  * @param array                       $fields
  *
  * @return \Doctrine\ORM\EntityManagerInterface
  */
 public static function create(\PHPUnit_Framework_TestCase $test, \Closure $qbCallback, $fields)
 {
     $query = $test->getMockForAbstractClass('Doctrine\\ORM\\AbstractQuery', [], '', false, true, true, ['execute']);
     $query->expects($test->any())->method('execute')->will($test->returnValue(true));
     if (Version::compare('2.5.0') < 1) {
         $entityManager = $test->getMock('Doctrine\\ORM\\EntityManagerInterface');
         $qb = $test->getMockBuilder('Doctrine\\ORM\\QueryBuilder')->setConstructorArgs([$entityManager])->getMock();
     } else {
         $qb = $test->getMockBuilder('Doctrine\\ORM\\QueryBuilder')->disableOriginalConstructor()->getMock();
     }
     $qb->expects($test->any())->method('select')->will($test->returnValue($qb));
     $qb->expects($test->any())->method('getQuery')->will($test->returnValue($query));
     $qb->expects($test->any())->method('where')->will($test->returnValue($qb));
     $qb->expects($test->any())->method('orderBy')->will($test->returnValue($qb));
     $qb->expects($test->any())->method('andWhere')->will($test->returnValue($qb));
     $qb->expects($test->any())->method('leftJoin')->will($test->returnValue($qb));
     $qbCallback($qb);
     $repository = $test->getMockBuilder('Doctrine\\ORM\\EntityRepository')->disableOriginalConstructor()->getMock();
     $repository->expects($test->any())->method('createQueryBuilder')->will($test->returnValue($qb));
     $metadata = $test->getMock('Doctrine\\Common\\Persistence\\Mapping\\ClassMetadata');
     $metadata->expects($test->any())->method('getFieldNames')->will($test->returnValue($fields));
     $metadata->expects($test->any())->method('getName')->will($test->returnValue('className'));
     $em = $test->getMockBuilder('Doctrine\\ORM\\EntityManager')->disableOriginalConstructor()->getMock();
     $em->expects($test->any())->method('getRepository')->will($test->returnValue($repository));
     $em->expects($test->any())->method('getClassMetadata')->will($test->returnValue($metadata));
     return $em;
 }
Example #3
0
 /**
  * {@inheritdoc}
  */
 public function processMetadataLoad($em, $meta)
 {
     $config = $this->listener->getConfiguration($em, $meta->name);
     $closureMetadata = $em->getClassMetadata($config['closure']);
     $cmf = $em->getMetadataFactory();
     if (!$closureMetadata->hasAssociation('ancestor')) {
         // create ancestor mapping
         $ancestorMapping = array('fieldName' => 'ancestor', 'id' => false, 'joinColumns' => array(array('name' => 'ancestor', 'referencedColumnName' => 'id', 'unique' => false, 'nullable' => false, 'onDelete' => 'CASCADE', 'onUpdate' => null, 'columnDefinition' => null)), 'inversedBy' => null, 'targetEntity' => $meta->name, 'cascade' => null, 'fetch' => ClassMetadataInfo::FETCH_LAZY);
         $closureMetadata->mapManyToOne($ancestorMapping);
         if (Version::compare('2.3.0-dev') <= 0) {
             $closureMetadata->reflFields['ancestor'] = $cmf->getReflectionService()->getAccessibleProperty($closureMetadata->name, 'ancestor');
         }
     }
     if (!$closureMetadata->hasAssociation('descendant')) {
         // create descendant mapping
         $descendantMapping = array('fieldName' => 'descendant', 'id' => false, 'joinColumns' => array(array('name' => 'descendant', 'referencedColumnName' => 'id', 'unique' => false, 'nullable' => false, 'onDelete' => 'CASCADE', 'onUpdate' => null, 'columnDefinition' => null)), 'inversedBy' => null, 'targetEntity' => $meta->name, 'cascade' => null, 'fetch' => ClassMetadataInfo::FETCH_LAZY);
         $closureMetadata->mapManyToOne($descendantMapping);
         if (Version::compare('2.3.0-dev') <= 0) {
             $closureMetadata->reflFields['descendant'] = $cmf->getReflectionService()->getAccessibleProperty($closureMetadata->name, 'descendant');
         }
     }
     // create unique index on ancestor and descendant
     $indexName = substr(strtoupper("IDX_" . md5($closureMetadata->name)), 0, 20);
     $closureMetadata->table['uniqueConstraints'][$indexName] = array('columns' => array($this->getJoinColumnFieldName($em->getClassMetadata($config['closure'])->getAssociationMapping('ancestor')), $this->getJoinColumnFieldName($em->getClassMetadata($config['closure'])->getAssociationMapping('descendant'))));
     // this one may not be very usefull
     $indexName = substr(strtoupper("IDX_" . md5($meta->name . 'depth')), 0, 20);
     $closureMetadata->table['indexes'][$indexName] = array('columns' => array('depth'));
     if ($cacheDriver = $cmf->getCacheDriver()) {
         $cacheDriver->save($closureMetadata->name . "\$CLASSMETADATA", $closureMetadata, null);
     }
 }
Example #4
0
 /**
  * @throws \Nette\InvalidStateException
  */
 protected function verifyDoctrineVersion()
 {
     if (!class_exists('Doctrine\\ORM\\Version')) {
         throw new \Nette\InvalidStateException('Doctrine ORM does not exists');
     } elseif (\Doctrine\ORM\Version::compare('2.3.0-RC3') > 0) {
         throw new \Nette\InvalidStateException('Doctrine version ' . \Doctrine\ORM\Version::VERSION . ' not supported (support only for 2.3+)');
     }
 }
 public static function assertEquals($expected, $actual, $message = '', $delta = 0.0, $maxDepth = 10, $canonicalize = false, $ignoreCase = false)
 {
     // expectation patch to support pre Doctrine 2.5 field aliases
     if (\Doctrine\ORM\Version::compare('2.5.0') == 1) {
         $expected = preg_replace('/(\\w+)_([0-9])/', '\\1\\2', $expected);
     }
     return parent::assertEquals($expected, $actual, $message);
 }
 public function getQuery()
 {
     $query = parent::getQuery();
     if (\Doctrine\ORM\Version::compare('2.5.0-DEV') > 0) {
         $query->setHydrationMode(Query::HYDRATE_OBJECT);
         $query->setHint(BaseQuery::HINT_INCLUDE_META_COLUMNS, true);
     }
     return $query;
 }
 /**
  * @param mixed $id
  * @param int $lockMode
  * @param null $lockVersion
  * @return \FSi\Bundle\ResourceRepositoryBundle\Model\ResourceValue
  */
 public function find($id, $lockMode = null, $lockVersion = null)
 {
     if ($lockMode === null && \Doctrine\ORM\Version::compare('2.5.0-dev') === 1) {
         $lockMode = LockMode::NONE;
     }
     $resource = parent::find($id, $lockMode, $lockVersion);
     if (!isset($resource)) {
         $resourceClass = $this->getClassName();
         $resource = new $resourceClass();
         $resource->setKey($id);
     }
     return $resource;
 }
 public function testEmbeddedIdentifierName()
 {
     if (Version::compare('2.5.0') > 0) {
         $this->markTestSkipped('Applicable only for Doctrine >= 2.5.0');
         return;
     }
     $em = DoctrineTestHelper::createTestEntityManager();
     $query = $this->getMockBuilder('QueryMock')->setMethods(array('setParameter', 'getResult', 'getSql', '_doExecute'))->getMock();
     $query->expects($this->once())->method('setParameter')->with('ORMQueryBuilderLoader_getEntitiesByIds_id_value', array(1, 2, 3), Connection::PARAM_INT_ARRAY)->willReturn($query);
     $qb = $this->getMockBuilder('Doctrine\\ORM\\QueryBuilder')->setConstructorArgs(array($em))->setMethods(array('getQuery'))->getMock();
     $qb->expects($this->once())->method('getQuery')->willReturn($query);
     $qb->select('e')->from('Symfony\\Bridge\\Doctrine\\Tests\\Fixtures\\EmbeddedIdentifierEntity', 'e');
     $loader = new ORMQueryBuilderLoader($qb);
     $loader->getEntitiesByIds('id.value', array(1, '', 2, 3, 'foo'));
 }
Example #9
0
 public function testTableNameWithSchema()
 {
     $isDoctrine25 = ORMVersion::compare('2.5.0') <= 0;
     if (!$isDoctrine25) {
         $this->markTestSkipped('@Table schema attribute is not supported in Doctrine < 2.5.0');
     }
     $em = $this->getMockAnnotationReaderEntityManager();
     $metadata = $em->getClassMetadata(self::TEST_ENTITY_USER_WITH_SCHEMA);
     $platform = $em->getConnection()->getDatabasePlatform();
     $purger = new ORMPurger($em);
     $class = new ReflectionClass('Doctrine\\Common\\DataFixtures\\Purger\\ORMPurger');
     $method = $class->getMethod('getTableName');
     $method->setAccessible(true);
     $tableName = $method->invokeArgs($purger, array($metadata, $platform));
     $this->assertStringStartsWith('test_schema', $tableName);
 }
 public function boot()
 {
     // force Doctrine annotations to be loaded
     // should be removed when a better solution is found in Doctrine
     class_exists('Doctrine\\ORM\\Mapping\\Driver\\AnnotationDriver');
     // Register an autoloader for proxies to avoid issues when unserializing them
     // when the ORM is used.
     if ($this->container->hasParameter('doctrine.orm.proxy_namespace')) {
         $namespace = $this->container->getParameter('doctrine.orm.proxy_namespace');
         $dir = $this->container->getParameter('doctrine.orm.proxy_dir');
         $container =& $this->container;
         $this->autoloader = function ($class) use($namespace, $dir, &$container) {
             if (0 === strpos($class, $namespace)) {
                 $className = substr($class, strlen($namespace) + 1);
                 $file = $dir . DIRECTORY_SEPARATOR . str_replace('\\', '', $className) . '.php';
                 if (!file_exists($file) && $container->getParameter('kernel.debug')) {
                     $registry = $container->get('doctrine');
                     if (1 === Version::compare('2.2.0')) {
                         $originalClassName = substr($className, 0, -5);
                     } else {
                         $originalClassName = ClassUtils::getRealClass($className);
                         $originalClassName = str_replace('\\', '', $originalClassName);
                     }
                     // Tries to auto-generate the proxy file
                     foreach ($registry->getEntityManagers() as $em) {
                         if ($em->getConfiguration()->getAutoGenerateProxyClasses()) {
                             $classes = $em->getMetadataFactory()->getAllMetadata();
                             foreach ($classes as $class) {
                                 $name = str_replace('\\', '', $class->name);
                                 if ($name == $originalClassName) {
                                     $em->getProxyFactory()->generateProxyClasses(array($class));
                                 }
                             }
                         }
                     }
                     clearstatcache($file);
                     if (!file_exists($file)) {
                         throw new \RuntimeException(sprintf('The proxy file "%s" does not exist. If you still have objects serialized in the session, you need to clear the session manually.', $file));
                     }
                 }
                 require $file;
             }
         };
         spl_autoload_register($this->autoloader);
     }
 }
Example #11
0
 /**
  * Checks the dependent ORM library components
  * for compatibility
  *
  * @throws DependentComponentNotFoundException
  * @throws IncompatibleComponentVersionException
  */
 public static function checkORMDependencies()
 {
     // doctrine common library
     if (!class_exists('Doctrine\\Common\\Version')) {
         throw new DependentComponentNotFoundException("Doctrine\\Common library is either not registered by autoloader or not installed");
     }
     if (\Doctrine\Common\Version::compare(self::VERSION) > 0) {
         throw new IncompatibleComponentVersionException("Doctrine\\Common library is older than expected for these extensions");
     }
     // doctrine dbal library
     if (!class_exists('Doctrine\\DBAL\\Version')) {
         throw new DependentComponentNotFoundException("Doctrine\\DBAL library is either not registered by autoloader or not installed");
     }
     if (\Doctrine\DBAL\Version::compare(self::VERSION) > 0) {
         throw new IncompatibleComponentVersionException("Doctrine\\DBAL library is older than expected for these extensions");
     }
     // doctrine ORM library
     if (!class_exists('Doctrine\\ORM\\Version')) {
         throw new DependentComponentNotFoundException("Doctrine\\ORM library is either not registered by autoloader or not installed");
     }
     if (\Doctrine\ORM\Version::compare(self::VERSION) > 0) {
         throw new IncompatibleComponentVersionException("Doctrine\\ORM library is older than expected for these extensions");
     }
 }
Example #12
0
 /**
  * @param $version
  * @return bool
  */
 public function isAtLeastDoctrineVersion($version)
 {
     return Version::compare($version) <= 0;
 }
Example #13
0
 /**
  * @group geometry
  */
 public function testTypeWrappingWhere()
 {
     $entity = new GeometryEntity();
     $entity->setGeometry(new Point(5, 5));
     $this->getEntityManager()->persist($entity);
     $this->getEntityManager()->flush();
     $this->getEntityManager()->clear();
     $query = $this->getEntityManager()->createQuery('SELECT g FROM CrEOF\\Spatial\\Tests\\Fixtures\\GeometryEntity g WHERE g.geometry = :geometry');
     $query->setParameter('geometry', new Point(5, 5), 'point');
     $query->processParameterValue('geometry');
     $result = $query->getSQL();
     $parameter = '?';
     if (Version::compare('2.5') <= 0) {
         $parameter = Type::getType('point')->convertToDatabaseValueSQL($parameter, $this->getPlatform());
     }
     $regex = preg_quote(sprintf('/geometry = %s/', $parameter));
     $this->assertRegExp($regex, $result);
 }
 public function createService(ServiceLocatorInterface $serviceLocator)
 {
     /** @var $options \DoctrineORMModule\Options\Configuration */
     $options = $this->getOptions($serviceLocator);
     $config = new Configuration();
     $config->setAutoGenerateProxyClasses($options->getGenerateProxies());
     $config->setProxyDir($options->getProxyDir());
     $config->setProxyNamespace($options->getProxyNamespace());
     $config->setEntityNamespaces($options->getEntityNamespaces());
     $config->setCustomDatetimeFunctions($options->getDatetimeFunctions());
     $config->setCustomStringFunctions($options->getStringFunctions());
     $config->setCustomNumericFunctions($options->getNumericFunctions());
     $config->setClassMetadataFactoryName($options->getClassMetadataFactoryName());
     foreach ($options->getNamedQueries() as $name => $query) {
         $config->addNamedQuery($name, $query);
     }
     foreach ($options->getNamedNativeQueries() as $name => $query) {
         $config->addNamedNativeQuery($name, $query['sql'], new $query['rsm']());
     }
     foreach ($options->getCustomHydrationModes() as $modeName => $hydrator) {
         $config->addCustomHydrationMode($modeName, $hydrator);
     }
     foreach ($options->getFilters() as $name => $class) {
         $config->addFilter($name, $class);
     }
     $config->setMetadataCacheImpl($serviceLocator->get($options->getMetadataCache()));
     $config->setQueryCacheImpl($serviceLocator->get($options->getQueryCache()));
     $config->setResultCacheImpl($serviceLocator->get($options->getResultCache()));
     $config->setHydrationCacheImpl($serviceLocator->get($options->getHydrationCache()));
     $config->setMetadataDriverImpl($serviceLocator->get($options->getDriver()));
     if ($namingStrategy = $options->getNamingStrategy()) {
         if (is_string($namingStrategy)) {
             if (!$serviceLocator->has($namingStrategy)) {
                 throw new InvalidArgumentException(sprintf('Naming strategy "%s" not found', $namingStrategy));
             }
             $config->setNamingStrategy($serviceLocator->get($namingStrategy));
         } else {
             $config->setNamingStrategy($namingStrategy);
         }
     }
     if ($repositoryFactory = $options->getRepositoryFactory()) {
         if (is_string($repositoryFactory)) {
             if (!$serviceLocator->has($repositoryFactory)) {
                 throw new InvalidArgumentException(sprintf('Repository factory "%s" not found', $repositoryFactory));
             }
             $config->setRepositoryFactory($serviceLocator->get($repositoryFactory));
         } else {
             $config->setRepositoryFactory($repositoryFactory);
         }
     }
     if ($entityListenerResolver = $options->getEntityListenerResolver()) {
         if ($entityListenerResolver instanceof EntityListenerResolver) {
             $config->setEntityListenerResolver($entityListenerResolver);
         } else {
             $config->setEntityListenerResolver($serviceLocator->get($entityListenerResolver));
         }
     }
     if (Version::compare('2.5.0') >= 0 || Version::compare('2.5.0') == -1) {
         $secondLevelCache = $options->getSecondLevelCache();
         if ($secondLevelCache->isEnabled()) {
             $regionsConfig = new RegionsConfiguration($secondLevelCache->getDefaultLifetime(), $secondLevelCache->getDefaultLockLifetime());
             foreach ($secondLevelCache->getRegions() as $regionName => $regionConfig) {
                 if (isset($regionConfig['lifetime'])) {
                     $regionsConfig->setLifetime($regionName, $regionConfig['lifetime']);
                 }
                 if (isset($regionConfig['lock_lifetime'])) {
                     $regionsConfig->setLockLifetime($regionName, $regionConfig['lock_lifetime']);
                 }
             }
             // As Second Level Cache caches queries results, we reuse the result cache impl
             $cacheFactory = new DefaultCacheFactory($regionsConfig, $config->getResultCacheImpl());
             $cacheFactory->setFileLockRegionDirectory($secondLevelCache->getFileLockRegionDirectory());
             $cacheConfiguration = new CacheConfiguration();
             $cacheConfiguration->setCacheFactory($cacheFactory);
             $cacheConfiguration->setRegionsConfiguration($regionsConfig);
             $config->setSecondLevelCacheEnabled();
             $config->setSecondLevelCacheConfiguration($cacheConfiguration);
         }
     }
     if ($className = $options->getDefaultRepositoryClassName()) {
         $config->setDefaultRepositoryClassName($className);
     }
     $this->setupDBALConfiguration($serviceLocator, $config);
     return $config;
 }
Example #15
0
 public function testCosineLaw()
 {
     $lat = 0.0;
     $lng = 0.0;
     $radiusOfEarth = 6371;
     $cosineLaw = 'ACOS(SIN(' . deg2rad($lat) . ') * SIN(RADIANS(p.latitude)) ' . '+ COS(' . deg2rad($lat) . ') * COS(RADIANS(p.latitude)) ' . '* COS(RADIANS(p.longitude) - ' . deg2rad($lng) . ')' . ') * ' . $radiusOfEarth;
     if (\Doctrine\ORM\Version::compare('2.4.0') <= 0) {
         $dql = "SELECT " . $cosineLaw . " FROM {$this->entity} p";
     } else {
         $dql = "SELECT (" . $cosineLaw . ") FROM {$this->entity} p";
     }
     $q = $this->entityManager->createQuery($dql);
     $sql = "SELECT ACOS(SIN(0) * SIN(RADIANS(b0_.latitude)) + COS(0) * COS(RADIANS(b0_.latitude)) * COS(RADIANS(b0_.longitude) - 0)) * 6371 AS sclr_0 FROM BlogPost b0_";
     $this->assertEquals($sql, $q->getSql());
 }
 protected function expectBasicLoad($entity, $id, $lockMode = LockMode::NONE, $lockVersion = null)
 {
     if (Version::compare('2.2.0') === -1) {
         $this->em->expects($this->once())->method('find')->with(get_class($this->entity), $id, $lockMode, $lockVersion)->will($this->returnValue($entity));
     } else {
         $this->persister->expects($this->once())->method('load')->with(array('id' => $id))->will($this->returnValue($entity));
     }
 }
Example #17
0
$sfClassLoader->register();
$doctrineClassLoader = new ClassLoader('Doctrine');
$doctrineClassLoader->register();
/**
 * Check if we can load the Doctrine\ORM\Version class. If we can't load the class, then something is wrong;
 * the most likely cause is that the user has DoctrineCommon installed, but is missing DoctrineORM.
 */
if (!$ormClassLoader->canLoadClass("Doctrine\\ORM\\Version")) {
    $installDoctrineError .= "<small>The classloader can't load Doctrine\\ORM\\Version</small>";
    echo json_encode(array("error" => true, "message" => $installDoctrineError));
    exit;
}
/**
 * Check for the correct DoctrineORM version. We only support Doctrine 2.1.0 or higher.
 */
if (\Doctrine\ORM\Version::compare("2.2.0") > 0) {
    $versionInvalidMessage = "DoctrineORM is installed, but needs to be at Version 2.2.0 or higher. ";
    $versionInvalidMessage .= "Please run pear upgrade-all to bring your packages up-to-date.";
    echo json_encode(array("error" => true, "message" => $versionInvalidMessage));
    exit;
}
/**
 * Check for the Symfony YAML component. This component is required to parse YAML files and is used during installation
 * of footprints.
 */
if (!$doctrineClassLoader->canLoadClass("Doctrine\\Symfony\\Component\\Yaml\\Yaml")) {
    $yamlErrorMessage = "The YAML component of symfony is not installed. This component is required; please install ";
    $yamlErrorMessage .= "it using:<br/><br/>";
    $yamlErrorMessage .= "<code>pear install pear.doctrine-project.org/DoctrineSymfonyYaml</code><br/><br/>";
    $yamlErrorMessage .= "If you are getting the error:<br/><br/><code>doctrine/DoctrineSymfonyYaml is already ";
    $yamlErrorMessage .= "installed and is the same as the released version</code><br/><br/>";