.gitignore000064400000000127144760112570006543 0ustar00build/ logs/ reports/ dist/ tests/Doctrine/Tests/Common/Proxy/generated/ vendor/ .idea .gitmodules000064400000000223144760112570006725 0ustar00[submodule "lib/vendor/doctrine-build-common"] path = lib/vendor/doctrine-build-common url = git://github.com/doctrine/doctrine-build-common.git .travis.yml000064400000000267144760112570006671 0ustar00language: php env: - OPCODE_CACHE=apc php: - 5.3.3 - 5.3 - 5.4 - 5.5 before_script: - composer --prefer-source install - php ./bin/travis-setup.php $OPCODE_CACHE LICENSE000064400000002051144760112570005556 0ustar00Copyright (c) 2006-2012 Doctrine Project Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. README.md000064400000000757144760112570006043 0ustar00# Doctrine Common [![Build Status](https://secure.travis-ci.org/doctrine/common.png)](http://travis-ci.org/doctrine/common) The Doctrine Common project is a library that provides extensions to core PHP functionality. ## More resources: * [Website](http://www.doctrine-project.org) * [Documentation](http://www.doctrine-project.org/projects/common/current/docs/en) * [Issue Tracker](http://www.doctrine-project.org/jira/browse/DCOM) * [Downloads](http://github.com/doctrine/common/downloads) UPGRADE_TO_2_1000064400000004121144760112570006626 0ustar00This document details all the possible changes that you should investigate when updating your project from Doctrine Common 2.0.x to 2.1 ## AnnotationReader changes The annotation reader was heavily refactored between 2.0 and 2.1-RC1. In theory the operation of the new reader should be backwards compatible, but it has to be setup differently to work that way: $reader = new \Doctrine\Common\Annotations\AnnotationReader(); $reader->setDefaultAnnotationNamespace('Doctrine\ORM\Mapping\\'); // new code necessary starting here $reader->setIgnoreNotImportedAnnotations(true); $reader->setEnableParsePhpImports(false); $reader = new \Doctrine\Common\Annotations\CachedReader( new \Doctrine\Common\Annotations\IndexedReader($reader), new ArrayCache() ); ## Annotation Base class or @Annotation Beginning after 2.1-RC2 you have to either extend ``Doctrine\Common\Annotations\Annotation`` or add @Annotation to your annotations class-level docblock, otherwise the class will simply be ignored. ## Removed methods on AnnotationReader * AnnotationReader::setAutoloadAnnotations() * AnnotationReader::getAutoloadAnnotations() * AnnotationReader::isAutoloadAnnotations() ## AnnotationRegistry Autoloading through the PHP autoloader is removed from the 2.1 AnnotationReader. Instead you have to use the global AnnotationRegistry for loading purposes: \Doctrine\Common\Annotations\AnnotationRegistry::registerFile($fileWithAnnotations); \Doctrine\Common\Annotations\AnnotationRegistry::registerAutoloadNamespace($namespace, $dirs = null); \Doctrine\Common\Annotations\AnnotationRegistry::registerAutoloadNamespaces($namespaces); \Doctrine\Common\Annotations\AnnotationRegistry::registerLoader($callable); The $callable for registering a loader accepts a class as first and only parameter and must try to silently autoload it. On success true has to be returned. The registerAutoloadNamespace function registers a PSR-0 compatible silent autoloader for all classes with the given namespace in the given directories. If null is passed as directory the include path will be used. UPGRADE_TO_2_2000064400000004573144760112570006642 0ustar00This document details all the possible changes that you should investigate when updating your project from Doctrine Common 2.1 to 2.2: ## Annotation Changes - AnnotationReader::setIgnoreNotImportedAnnotations has been removed, you need to add ignore annotation names which are supposed to be ignored via AnnotationReader::addGlobalIgnoredName - AnnotationReader::setAutoloadAnnotations was deprecated by the AnnotationRegistry in 2.1 and has been removed in 2.2 - AnnotationReader::setEnableParsePhpImports was added to ease transition to the new annotation mechanism in 2.1 and is removed in 2.2 - AnnotationReader::isParsePhpImportsEnabled is removed (see above) - AnnotationReader::setDefaultAnnotationNamespace was deprecated in favor of explicit configuration in 2.1 and will be removed in 2.2 (for isolated projects where you have full-control over _all_ available annotations, we offer a dedicated reader class ``SimpleAnnotationReader``) - AnnotationReader::setAnnotationCreationFunction was deprecated in 2.1 and will be removed in 2.2. We only offer two creation mechanisms which cannot be changed anymore to allow the same reader instance to work with all annotations regardless of which library they are coming from. - AnnotationReader::setAnnotationNamespaceAlias was deprecated in 2.1 and will be removed in 2.2 (see setDefaultAnnotationNamespace) - If you use a class as annotation which has not the @Annotation marker in it's class block, we will now throw an exception instead of silently ignoring it. You can however still achieve the previous behavior using the @IgnoreAnnotation, or AnnotationReader::addGlobalIgnoredName (the exception message will contain detailed instructions when you run into this problem). ## Cache Changes - Renamed old AbstractCache to CacheProvider - Dropped the support to the following functions of all cache providers: - CacheProvider::deleteByWildcard - CacheProvider::deleteByRegEx - CacheProvider::deleteByPrefix - CacheProvider::deleteBySuffix - CacheProvider::deleteAll will not remove ALL entries, it will only mark them as invalid - CacheProvider::flushAll will remove ALL entries, namespaced or not - Added support to MemcachedCache - Added support to WincacheCache ## ClassLoader Changes - ClassLoader::fileExistsInIncludePath() no longer exists. Use the native stream_resolve_include_path() PHP functionbin/travis-setup.php000064400000011450144760112570010503 0ustar00. */ /** * Install PHP extensions required for testing by Travis CI. * * @author Victor Berchet * @since 2.2 */ $installer = new PhpExtensions(); if (isset($argv[1]) && 'APC' === strtoupper($argv[1])) { $installer->install('apc'); } else { $installer->install('xcache'); } $installer->install('memcache'); $installer->install('memcached'); class PhpExtensions { protected $extensions; protected $phpVersion; protected $iniPath; public function __construct() { $this->phpVersion = phpversion(); $this->iniPath = php_ini_loaded_file(); $this->extensions = array( 'memcache' => array( 'url' => 'http://pecl.php.net/get/memcache-2.2.6.tgz', 'php_version' => array(), 'cfg' => array('--enable-memcache'), 'ini' => array('extension=memcache.so'), ), 'memcached' => array( 'url' => 'http://pecl.php.net/get/memcached-1.0.2.tgz', 'php_version' => array( // memcached 1.0.2 does not build on PHP 5.4 array('<', '5.4'), ), 'cfg' => array(), 'ini' => array('extension=memcached.so'), ), 'apc' => array( 'url' => 'http://pecl.php.net/get/APC-3.1.9.tgz', 'php_version' => array( // apc 3.1.9 causes a segfault on PHP 5.4 array('<', '5.4'), ), 'cfg' => array(), 'ini' => array( 'extension=apc.so', 'apc.enabled=1', 'apc.enable_cli=1' ), ), 'xcache' => array( 'url' => 'http://xcache.lighttpd.net/pub/Releases/1.2.2/xcache-1.2.2.tar.gz', 'php_version' => array( // xcache does not build with Travis CI (as of 2012-01-09) array('<', '5'), ), 'cfg' => array('--enable-xcache'), 'ini' => array( 'extension=xcache.so', 'xcache.cacher=false', 'xcache.admin.enable_auth=0', 'xcache.var_size=1M', ), ), ); } public function install($name) { if (array_key_exists($name, $this->extensions)) { $extension = $this->extensions[$name]; echo "== extension: $name ==\n"; foreach ($extension['php_version'] as $version) { if (!version_compare($this->phpVersion, $version[1], $version[0])) { printf( "=> not installed, requires a PHP version %s %s (%s installed)\n", $version[0], $version[1], $this->phpVersion ); return; } } $this->system(sprintf("wget %s > /dev/null 2>&1", $extension['url'])); $file = basename($extension['url']); $this->system(sprintf("tar -xzf %s > /dev/null 2>&1", $file)); $folder = basename($file, ".tgz"); $folder = basename($folder, ".tar.gz"); $this->system(sprintf( 'sh -c "cd %s && phpize && ./configure %s && make && sudo make install" > /dev/null 2>&1', $folder, implode(' ', $extension['cfg']) )); foreach ($extension['ini'] as $ini) { $this->system(sprintf("echo %s >> %s", $ini, $this->iniPath)); } printf("=> installed (%s)\n", $folder); } } private function system($cmd) { $ret = 0; system($cmd, $ret); if (0 !== $ret) { printf("=> Command '%s' failed !", $cmd); exit($ret); } } } build.properties000064400000000254144760112570007771 0ustar00# Project Name project.name=DoctrineCommon # Version class and file project.version_class = Doctrine\Common\Version project.version_file = lib/Doctrine/Common/Version.php build.xml000064400000004544144760112570006403 0ustar00 DoctrineCommon Doctrine Common PHP Extensions pear.doctrine-project.org The Doctrine Common package contains shared code between the other packages. LGPL - composer.json000064400000002062144760112570007275 0ustar00{ "name": "doctrine/common", "type": "library","version":"2.4.0-RC1", "description": "Common Library for Doctrine projects", "keywords": ["collections", "spl", "eventmanager", "annotations", "persistence"], "homepage": "http://www.doctrine-project.org", "license": "MIT", "authors": [ {"name": "Guilherme Blanco", "email": "guilhermeblanco@gmail.com"}, {"name": "Roman Borschel", "email": "roman@code-factory.org"}, {"name": "Benjamin Eberlei", "email": "kontakt@beberlei.de"}, {"name": "Jonathan Wage", "email": "jonwage@gmail.com"}, {"name": "Johannes Schmitt", "email": "schmittjoh@gmail.com"} ], "require": { "php": ">=5.3.2", "doctrine/inflector": "1.*", "doctrine/cache": "1.*", "doctrine/collections": "1.*", "doctrine/lexer": "1.*", "doctrine/annotations": "1.*" }, "autoload": { "psr-0": { "Doctrine\\Common\\": "lib/" } }, "extra": { "branch-alias": { "dev-master": "2.4.x-dev" } } } composer.lock000064400000025260144760112570007261 0ustar00{ "hash": "f763db6a8f5bcaff6e51ae516283a4c9", "packages": [ { "name": "doctrine/annotations", "version": "v1.0", "source": { "type": "git", "url": "https://github.com/doctrine/annotations.git", "reference": "v1.0" }, "dist": { "type": "zip", "url": "https://github.com/doctrine/annotations/archive/v1.0.zip", "reference": "v1.0", "shasum": "" }, "require": { "php": ">=5.3.2", "doctrine/lexer": "1.*" }, "require-dev": { "doctrine/cache": "1.*" }, "time": "2013-01-12 19:23:32", "type": "library", "installation-source": "dist", "autoload": { "psr-0": { "Doctrine\\Common\\Annotations\\": "lib/" } }, "notification-url": "https://packagist.org/downloads/", "license": [ "MIT" ], "authors": [ { "name": "Jonathan Wage", "email": "jonwage@gmail.com", "homepage": "http://www.jwage.com/" }, { "name": "Guilherme Blanco", "email": "guilhermeblanco@gmail.com", "homepage": "http://www.instaclick.com" }, { "name": "Roman Borschel", "email": "roman@code-factory.org" }, { "name": "Benjamin Eberlei", "email": "kontakt@beberlei.de" }, { "name": "Johannes Schmitt", "email": "schmittjoh@gmail.com", "homepage": "https://github.com/schmittjoh", "role": "Developer of wrapped JMSSerializerBundle" } ], "description": "Docblock Annotations Parser", "homepage": "http://www.doctrine-project.org", "keywords": [ "annotations", "parser", "docblock" ] }, { "name": "doctrine/cache", "version": "v1.0", "source": { "type": "git", "url": "https://github.com/doctrine/cache.git", "reference": "v1.0" }, "dist": { "type": "zip", "url": "https://github.com/doctrine/cache/archive/v1.0.zip", "reference": "v1.0", "shasum": "" }, "require": { "php": ">=5.3.2" }, "time": "2013-01-10 22:43:46", "type": "library", "installation-source": "dist", "autoload": { "psr-0": { "Doctrine\\Common\\Cache\\": "lib/" } }, "notification-url": "https://packagist.org/downloads/", "license": [ "MIT" ], "authors": [ { "name": "Jonathan Wage", "email": "jonwage@gmail.com", "homepage": "http://www.jwage.com/" }, { "name": "Guilherme Blanco", "email": "guilhermeblanco@gmail.com", "homepage": "http://www.instaclick.com" }, { "name": "Roman Borschel", "email": "roman@code-factory.org" }, { "name": "Benjamin Eberlei", "email": "kontakt@beberlei.de" }, { "name": "Johannes Schmitt", "email": "schmittjoh@gmail.com", "homepage": "https://github.com/schmittjoh", "role": "Developer of wrapped JMSSerializerBundle" } ], "description": "Caching library offering an object-oriented API for many cache backends", "homepage": "http://www.doctrine-project.org", "keywords": [ "cache", "caching" ] }, { "name": "doctrine/collections", "version": "v1.0", "source": { "type": "git", "url": "https://github.com/doctrine/collections.git", "reference": "v1.0" }, "dist": { "type": "zip", "url": "https://github.com/doctrine/collections/archive/v1.0.zip", "reference": "v1.0", "shasum": "" }, "require": { "php": ">=5.3.2" }, "time": "2013-01-12 16:36:50", "type": "library", "installation-source": "dist", "autoload": { "psr-0": { "Doctrine\\Common\\Collections\\": "lib/" } }, "notification-url": "https://packagist.org/downloads/", "license": [ "MIT" ], "authors": [ { "name": "Jonathan Wage", "email": "jonwage@gmail.com", "homepage": "http://www.jwage.com/" }, { "name": "Guilherme Blanco", "email": "guilhermeblanco@gmail.com", "homepage": "http://www.instaclick.com" }, { "name": "Roman Borschel", "email": "roman@code-factory.org" }, { "name": "Benjamin Eberlei", "email": "kontakt@beberlei.de" }, { "name": "Johannes Schmitt", "email": "schmittjoh@gmail.com", "homepage": "https://github.com/schmittjoh", "role": "Developer of wrapped JMSSerializerBundle" } ], "description": "Collections Abstraction library", "homepage": "http://www.doctrine-project.org", "keywords": [ "collections", "iterator", "array" ] }, { "name": "doctrine/inflector", "version": "v1.0", "source": { "type": "git", "url": "https://github.com/doctrine/inflector.git", "reference": "v1.0" }, "dist": { "type": "zip", "url": "https://github.com/doctrine/inflector/archive/v1.0.zip", "reference": "v1.0", "shasum": "" }, "require": { "php": ">=5.3.2" }, "time": "2013-01-10 21:49:15", "type": "library", "installation-source": "dist", "autoload": { "psr-0": { "Doctrine\\Common\\Inflector\\": "lib/" } }, "notification-url": "https://packagist.org/downloads/", "license": [ "MIT" ], "authors": [ { "name": "Jonathan Wage", "email": "jonwage@gmail.com", "homepage": "http://www.jwage.com/" }, { "name": "Guilherme Blanco", "email": "guilhermeblanco@gmail.com", "homepage": "http://www.instaclick.com" }, { "name": "Roman Borschel", "email": "roman@code-factory.org" }, { "name": "Benjamin Eberlei", "email": "kontakt@beberlei.de" }, { "name": "Johannes Schmitt", "email": "schmittjoh@gmail.com", "homepage": "https://github.com/schmittjoh", "role": "Developer of wrapped JMSSerializerBundle" } ], "description": "Common String Manipulations with regard to casing and singular/plural rules.", "homepage": "http://www.doctrine-project.org", "keywords": [ "string", "inflection", "singuarlize", "pluarlize" ] }, { "name": "doctrine/lexer", "version": "v1.0", "source": { "type": "git", "url": "https://github.com/doctrine/lexer.git", "reference": "v1.0" }, "dist": { "type": "zip", "url": "https://github.com/doctrine/lexer/archive/v1.0.zip", "reference": "v1.0", "shasum": "" }, "require": { "php": ">=5.3.2" }, "time": "2013-01-12 18:59:04", "type": "library", "installation-source": "dist", "autoload": { "psr-0": { "Doctrine\\Common\\Lexer\\": "lib/" } }, "notification-url": "https://packagist.org/downloads/", "license": [ "MIT" ], "authors": [ { "name": "Guilherme Blanco", "email": "guilhermeblanco@gmail.com", "homepage": "http://www.instaclick.com" }, { "name": "Roman Borschel", "email": "roman@code-factory.org" }, { "name": "Johannes Schmitt", "email": "schmittjoh@gmail.com", "homepage": "https://github.com/schmittjoh", "role": "Developer of wrapped JMSSerializerBundle" } ], "description": "Base library for a lexer that can be used in Top-Down, Recursive Descent Parsers.", "homepage": "http://www.doctrine-project.org", "keywords": [ "parser", "lexer" ] } ], "packages-dev": null, "aliases": [ ], "minimum-stability": "stable", "stability-flags": [ ] } lib/Doctrine/Common/ClassLoader.php000064400000022014144760112570013224 0ustar00. */ namespace Doctrine\Common; /** * A ClassLoader is an autoloader for class files that can be * installed on the SPL autoload stack. It is a class loader that either loads only classes * of a specific namespace or all namespaces and it is suitable for working together * with other autoloaders in the SPL autoload stack. * * If no include path is configured through the constructor or {@link setIncludePath}, a ClassLoader * relies on the PHP include_path. * * @author Roman Borschel * @since 2.0 */ class ClassLoader { /** * @var string PHP file extension */ protected $fileExtension = '.php'; /** * @var string Current namespace */ protected $namespace; /** * @var string Current include path */ protected $includePath; /** * @var string PHP namespace separator */ protected $namespaceSeparator = '\\'; /** * Creates a new ClassLoader that loads classes of the * specified namespace from the specified include path. * * If no include path is given, the ClassLoader relies on the PHP include_path. * If neither a namespace nor an include path is given, the ClassLoader will * be responsible for loading all classes, thereby relying on the PHP include_path. * * @param string $ns The namespace of the classes to load. * @param string $includePath The base include path to use. */ public function __construct($ns = null, $includePath = null) { $this->namespace = $ns; $this->includePath = $includePath; } /** * Sets the namespace separator used by classes in the namespace of this ClassLoader. * * @param string $sep The separator to use. */ public function setNamespaceSeparator($sep) { $this->namespaceSeparator = $sep; } /** * Gets the namespace separator used by classes in the namespace of this ClassLoader. * * @return string */ public function getNamespaceSeparator() { return $this->namespaceSeparator; } /** * Sets the base include path for all class files in the namespace of this ClassLoader. * * @param string $includePath */ public function setIncludePath($includePath) { $this->includePath = $includePath; } /** * Gets the base include path for all class files in the namespace of this ClassLoader. * * @return string */ public function getIncludePath() { return $this->includePath; } /** * Sets the file extension of class files in the namespace of this ClassLoader. * * @param string $fileExtension */ public function setFileExtension($fileExtension) { $this->fileExtension = $fileExtension; } /** * Gets the file extension of class files in the namespace of this ClassLoader. * * @return string */ public function getFileExtension() { return $this->fileExtension; } /** * Registers this ClassLoader on the SPL autoload stack. */ public function register() { spl_autoload_register(array($this, 'loadClass')); } /** * Removes this ClassLoader from the SPL autoload stack. */ public function unregister() { spl_autoload_unregister(array($this, 'loadClass')); } /** * Loads the given class or interface. * * @param string $className The name of the class to load. * @return boolean TRUE if the class has been successfully loaded, FALSE otherwise. */ public function loadClass($className) { if ($this->namespace !== null && strpos($className, $this->namespace.$this->namespaceSeparator) !== 0) { return false; } require ($this->includePath !== null ? $this->includePath . DIRECTORY_SEPARATOR : '') . str_replace($this->namespaceSeparator, DIRECTORY_SEPARATOR, $className) . $this->fileExtension; return true; } /** * Asks this ClassLoader whether it can potentially load the class (file) with * the given name. * * @param string $className The fully-qualified name of the class. * @return boolean TRUE if this ClassLoader can load the class, FALSE otherwise. */ public function canLoadClass($className) { if ($this->namespace !== null && strpos($className, $this->namespace.$this->namespaceSeparator) !== 0) { return false; } $file = str_replace($this->namespaceSeparator, DIRECTORY_SEPARATOR, $className) . $this->fileExtension; if ($this->includePath !== null) { return is_file($this->includePath . DIRECTORY_SEPARATOR . $file); } return (false !== stream_resolve_include_path($file)); } /** * Checks whether a class with a given name exists. A class "exists" if it is either * already defined in the current request or if there is an autoloader on the SPL * autoload stack that is a) responsible for the class in question and b) is able to * load a class file in which the class definition resides. * * If the class is not already defined, each autoloader in the SPL autoload stack * is asked whether it is able to tell if the class exists. If the autoloader is * a ClassLoader, {@link canLoadClass} is used, otherwise the autoload * function of the autoloader is invoked and expected to return a value that * evaluates to TRUE if the class (file) exists. As soon as one autoloader reports * that the class exists, TRUE is returned. * * Note that, depending on what kinds of autoloaders are installed on the SPL * autoload stack, the class (file) might already be loaded as a result of checking * for its existence. This is not the case with a ClassLoader, who separates * these responsibilities. * * @param string $className The fully-qualified name of the class. * @return boolean TRUE if the class exists as per the definition given above, FALSE otherwise. */ public static function classExists($className) { if (class_exists($className, false) || interface_exists($className, false)) { return true; } foreach (spl_autoload_functions() as $loader) { if (is_array($loader)) { // array(???, ???) if (is_object($loader[0])) { if ($loader[0] instanceof ClassLoader) { // array($obj, 'methodName') if ($loader[0]->canLoadClass($className)) { return true; } } else if ($loader[0]->{$loader[1]}($className)) { return true; } } else if ($loader[0]::$loader[1]($className)) { // array('ClassName', 'methodName') return true; } } else if ($loader instanceof \Closure) { // function($className) {..} if ($loader($className)) { return true; } } else if (is_string($loader) && $loader($className)) { // "MyClass::loadClass" return true; } if (class_exists($className, false) || interface_exists($className, false)) { return true; } } return false; } /** * Gets the ClassLoader from the SPL autoload stack that is responsible * for (and is able to load) the class with the given name. * * @param string $className The name of the class. * @return ClassLoader The ClassLoader for the class or NULL if no such ClassLoader exists. */ public static function getClassLoader($className) { foreach (spl_autoload_functions() as $loader) { if (is_array($loader) && $loader[0] instanceof ClassLoader && $loader[0]->canLoadClass($className) ) { return $loader[0]; } } return null; } } lib/Doctrine/Common/CommonException.php000064400000002171144760112570014141 0ustar00. */ namespace Doctrine\Common; /** * Base exception class for package Doctrine\Common * @author heinrich * */ class CommonException extends \Exception { } lib/Doctrine/Common/Comparable.php000064400000003574144760112570013107 0ustar00. */ namespace Doctrine\Common; /** * Comparable interface that allows to compare two value objects to each other for similarity. * * @license http://www.opensource.org/licenses/lgpl-license.php LGPL * @link www.doctrine-project.com * @since 2.2 * @author Benjamin Eberlei * @author Guilherme Blanco */ interface Comparable { /** * Compare the current object to the passed $other. * * Returns 0 if they are semantically equal, 1 if the other object * is less than the current one, or -1 if its more than the current one. * * This method should not check for identity using ===, only for semantical equality for example * when two different DateTime instances point to the exact same Date + TZ. * * @param mixed $other * * @return int */ public function compareTo($other); } lib/Doctrine/Common/EventArgs.php000064400000005014144760112570012727 0ustar00. */ namespace Doctrine\Common; /** * EventArgs is the base class for classes containing event data. * * This class contains no event data. It is used by events that do not pass state * information to an event handler when an event is raised. The single empty EventArgs * instance can be obtained through {@link getEmptyInstance}. * * @license http://www.opensource.org/licenses/lgpl-license.php LGPL * @link www.doctrine-project.org * @since 2.0 * @version $Revision: 3938 $ * @author Guilherme Blanco * @author Jonathan Wage * @author Roman Borschel */ class EventArgs { /** * @var EventArgs Single instance of EventArgs */ private static $_emptyEventArgsInstance; /** * Gets the single, empty and immutable EventArgs instance. * * This instance will be used when events are dispatched without any parameter, * like this: EventManager::dispatchEvent('eventname'); * * The benefit from this is that only one empty instance is instantiated and shared * (otherwise there would be instances for every dispatched in the abovementioned form) * * @see EventManager::dispatchEvent * @link http://msdn.microsoft.com/en-us/library/system.eventargs.aspx * @return EventArgs */ public static function getEmptyInstance() { if ( ! self::$_emptyEventArgsInstance) { self::$_emptyEventArgsInstance = new EventArgs; } return self::$_emptyEventArgsInstance; } } lib/Doctrine/Common/EventManager.php000064400000012213144760112570013404 0ustar00. */ namespace Doctrine\Common; /** * The EventManager is the central point of Doctrine's event listener system. * Listeners are registered on the manager and events are dispatched through the * manager. * * @license http://www.opensource.org/licenses/lgpl-license.php LGPL * @link www.doctrine-project.org * @since 2.0 * @version $Revision: 3938 $ * @author Guilherme Blanco * @author Jonathan Wage * @author Roman Borschel */ class EventManager { /** * Map of registered listeners. * => * * @var array */ private $_listeners = array(); /** * Dispatches an event to all registered listeners. * * @param string $eventName The name of the event to dispatch. The name of the event is * the name of the method that is invoked on listeners. * @param EventArgs $eventArgs The event arguments to pass to the event handlers/listeners. * If not supplied, the single empty EventArgs instance is used. * @return boolean */ public function dispatchEvent($eventName, EventArgs $eventArgs = null) { if (isset($this->_listeners[$eventName])) { $eventArgs = $eventArgs === null ? EventArgs::getEmptyInstance() : $eventArgs; foreach ($this->_listeners[$eventName] as $listener) { $listener->$eventName($eventArgs); } } } /** * Gets the listeners of a specific event or all listeners. * * @param string $event The name of the event. * @return array The event listeners for the specified event, or all event listeners. */ public function getListeners($event = null) { return $event ? $this->_listeners[$event] : $this->_listeners; } /** * Checks whether an event has any registered listeners. * * @param string $event * @return boolean TRUE if the specified event has any listeners, FALSE otherwise. */ public function hasListeners($event) { return isset($this->_listeners[$event]) && $this->_listeners[$event]; } /** * Adds an event listener that listens on the specified events. * * @param string|array $events The event(s) to listen on. * @param object $listener The listener object. */ public function addEventListener($events, $listener) { // Picks the hash code related to that listener $hash = spl_object_hash($listener); foreach ((array) $events as $event) { // Overrides listener if a previous one was associated already // Prevents duplicate listeners on same event (same instance only) $this->_listeners[$event][$hash] = $listener; } } /** * Removes an event listener from the specified events. * * @param string|array $events * @param object $listener */ public function removeEventListener($events, $listener) { // Picks the hash code related to that listener $hash = spl_object_hash($listener); foreach ((array) $events as $event) { // Check if actually have this listener associated if (isset($this->_listeners[$event][$hash])) { unset($this->_listeners[$event][$hash]); } } } /** * Adds an EventSubscriber. The subscriber is asked for all the events he is * interested in and added as a listener for these events. * * @param \Doctrine\Common\EventSubscriber $subscriber The subscriber. */ public function addEventSubscriber(EventSubscriber $subscriber) { $this->addEventListener($subscriber->getSubscribedEvents(), $subscriber); } /** * Removes an EventSubscriber. The subscriber is asked for all the events it is * interested in and removed as a listener for these events. * * @param \Doctrine\Common\EventSubscriber $subscriber The subscriber. */ public function removeEventSubscriber(EventSubscriber $subscriber) { $this->removeEventListener($subscriber->getSubscribedEvents(), $subscriber); } } lib/Doctrine/Common/EventSubscriber.php000064400000003405144760112570014140 0ustar00. */ namespace Doctrine\Common; /** * An EventSubscriber knows himself what events he is interested in. * If an EventSubscriber is added to an EventManager, the manager invokes * {@link getSubscribedEvents} and registers the subscriber as a listener for all * returned events. * * @license http://www.opensource.org/licenses/lgpl-license.php LGPL * @link www.doctrine-project.org * @since 2.0 * @author Guilherme Blanco * @author Jonathan Wage * @author Roman Borschel */ interface EventSubscriber { /** * Returns an array of events this subscriber wants to listen to. * * @return array */ function getSubscribedEvents(); } lib/Doctrine/Common/Lexer.php000064400000002670144760112570012115 0ustar00. */ namespace Doctrine\Common; use Doctrine\Common\Lexer\AbstractLexer; /** * Base class for writing simple lexers, i.e. for creating small DSLs. * * Lexer moved into its own Component Doctrine\Common\Lexer. This class * only stays for being BC. * * @since 2.0 * @author Guilherme Blanco * @author Jonathan Wage * @author Roman Borschel */ abstract class Lexer extends AbstractLexer { } lib/Doctrine/Common/NotifyPropertyChanged.php000064400000003261144760112570015322 0ustar00. */ namespace Doctrine\Common; /** * Contract for classes that provide the service of notifying listeners of * changes to their properties. * * @license http://www.opensource.org/licenses/lgpl-license.php LGPL * @link www.doctrine-project.org * @since 2.0 * @version $Revision: 3938 $ * @author Guilherme Blanco * @author Jonathan Wage * @author Roman Borschel */ interface NotifyPropertyChanged { /** * Adds a listener that wants to be notified about property changes. * * @param PropertyChangedListener $listener */ function addPropertyChangedListener(PropertyChangedListener $listener); } lib/Doctrine/Common/Persistence/AbstractManagerRegistry.php000064400000015053144760112570020110 0ustar00. */ namespace Doctrine\Common\Persistence; use Doctrine\Common\Persistence\ManagerRegistry; /** * Abstract implementation of the ManagerRegistry contract. * * @license http://www.opensource.org/licenses/lgpl-license.php LGPL * @link www.doctrine-project.org * @since 2.2 * @author Fabien Potencier * @author Benjamin Eberlei * @author Lukas Kahwe Smith */ abstract class AbstractManagerRegistry implements ManagerRegistry { /** * @var string */ private $name; /** * @var array */ private $connections; /** * @var array */ private $managers; /** * @var string */ private $defaultConnection; /** * @var string */ private $defaultManager; /** * @var string */ private $proxyInterfaceName; /** * Constructor * * @param string $name * @param array $connections * @param array $managers * @param string $defaultConnection * @param string $defaultManager * @param string $proxyInterfaceName */ public function __construct($name, array $connections, array $managers, $defaultConnection, $defaultManager, $proxyInterfaceName) { $this->name = $name; $this->connections = $connections; $this->managers = $managers; $this->defaultConnection = $defaultConnection; $this->defaultManager = $defaultManager; $this->proxyInterfaceName = $proxyInterfaceName; } /** * Fetches/creates the given services * * A service in this context is connection or a manager instance * * @param string $name name of the service * @return object instance of the given service */ abstract protected function getService($name); /** * Resets the given services * * A service in this context is connection or a manager instance * * @param string $name name of the service * @return void */ abstract protected function resetService($name); /** * Get the name of the registry * * @return string */ public function getName() { return $this->name; } /** * {@inheritdoc} */ public function getConnection($name = null) { if (null === $name) { $name = $this->defaultConnection; } if (!isset($this->connections[$name])) { throw new \InvalidArgumentException(sprintf('Doctrine %s Connection named "%s" does not exist.', $this->name, $name)); } return $this->getService($this->connections[$name]); } /** * {@inheritdoc} */ public function getConnectionNames() { return $this->connections; } /** * {@inheritdoc} */ public function getConnections() { $connections = array(); foreach ($this->connections as $name => $id) { $connections[$name] = $this->getService($id); } return $connections; } /** * {@inheritdoc} */ public function getDefaultConnectionName() { return $this->defaultConnection; } /** * {@inheritdoc} */ public function getDefaultManagerName() { return $this->defaultManager; } /** * {@inheritdoc} * * @throws \InvalidArgumentException */ public function getManager($name = null) { if (null === $name) { $name = $this->defaultManager; } if (!isset($this->managers[$name])) { throw new \InvalidArgumentException(sprintf('Doctrine %s Manager named "%s" does not exist.', $this->name, $name)); } return $this->getService($this->managers[$name]); } /** * {@inheritdoc} */ public function getManagerForClass($class) { // Check for namespace alias if (strpos($class, ':') !== false) { list($namespaceAlias, $simpleClassName) = explode(':', $class); $class = $this->getAliasNamespace($namespaceAlias) . '\\' . $simpleClassName; } $proxyClass = new \ReflectionClass($class); if ($proxyClass->implementsInterface($this->proxyInterfaceName)) { $class = $proxyClass->getParentClass()->getName(); } foreach ($this->managers as $id) { $manager = $this->getService($id); if (!$manager->getMetadataFactory()->isTransient($class)) { return $manager; } } } /** * {@inheritdoc} */ public function getManagerNames() { return $this->managers; } /** * {@inheritdoc} */ public function getManagers() { $dms = array(); foreach ($this->managers as $name => $id) { $dms[$name] = $this->getService($id); } return $dms; } /** * {@inheritdoc} */ public function getRepository($persistentObjectName, $persistentManagerName = null) { return $this->getManager($persistentManagerName)->getRepository($persistentObjectName); } /** * {@inheritdoc} */ public function resetManager($name = null) { if (null === $name) { $name = $this->defaultManager; } if (!isset($this->managers[$name])) { throw new \InvalidArgumentException(sprintf('Doctrine %s Manager named "%s" does not exist.', $this->name, $name)); } // force the creation of a new document manager // if the current one is closed $this->resetService($this->managers[$name]); } } lib/Doctrine/Common/Persistence/ConnectionRegistry.php000064400000004077144760112570017155 0ustar00. */ namespace Doctrine\Common\Persistence; /** * Contract covering connection for a Doctrine persistence layer ManagerRegistry class to implement. * * @license http://www.opensource.org/licenses/lgpl-license.php LGPL * @link www.doctrine-project.org * @since 2.2 * @author Fabien Potencier * @author Benjamin Eberlei * @author Lukas Kahwe Smith */ interface ConnectionRegistry { /** * Gets the default connection name. * * @return string The default connection name */ function getDefaultConnectionName(); /** * Gets the named connection. * * @param string $name The connection name (null for the default one) * * @return object */ function getConnection($name = null); /** * Gets an array of all registered connections * * @return array An array of Connection instances */ function getConnections(); /** * Gets all connection names. * * @return array An array of connection names */ function getConnectionNames(); } lib/Doctrine/Common/Persistence/Event/LifecycleEventArgs.php000064400000004440144760112570020116 0ustar00. */ namespace Doctrine\Common\Persistence\Event; use Doctrine\Common\EventArgs; use Doctrine\Common\Persistence\ObjectManager; /** * Lifecycle Events are triggered by the UnitOfWork during lifecycle transitions * of entities. * * @link www.doctrine-project.org * @since 2.2 * @author Roman Borschel * @author Benjamin Eberlei */ class LifecycleEventArgs extends EventArgs { /** * @var ObjectManager */ private $objectManager; /** * @var object */ private $object; /** * Constructor * * @param object $object * @param ObjectManager $objectManager */ public function __construct($object, ObjectManager $objectManager) { $this->object = $object; $this->objectManager = $objectManager; } /** * Retrieve associated entity. * @deprecated * * @return object */ public function getEntity() { return $this->object; } /** * Retrieve associated object. * * @return object */ public function getObject() { return $this->object; } /** * Retrieve associated ObjectManager. * * @return ObjectManager */ public function getObjectManager() { return $this->objectManager; } } lib/Doctrine/Common/Persistence/Event/LoadClassMetadataEventArgs.php000064400000004224144760112570021525 0ustar00. */ namespace Doctrine\Common\Persistence\Event; use Doctrine\Common\EventArgs; use Doctrine\Common\Persistence\ObjectManager; use Doctrine\Common\Persistence\Mapping\ClassMetadata; /** * Class that holds event arguments for a loadMetadata event. * * @author Jonathan H. Wage * @since 2.2 */ class LoadClassMetadataEventArgs extends EventArgs { /** * @var ClassMetadata */ private $classMetadata; /** * @var ObjectManager */ private $objectManager; /** * Constructor. * * @param ClassMetadata $classMetadata * @param ObjectManager $objectManager */ public function __construct(ClassMetadata $classMetadata, ObjectManager $objectManager) { $this->classMetadata = $classMetadata; $this->objectManager = $objectManager; } /** * Retrieve associated ClassMetadata. * * @return ClassMetadata */ public function getClassMetadata() { return $this->classMetadata; } /** * Retrieve associated ObjectManager. * * @return ObjectManager */ public function getObjectManager() { return $this->objectManager; } } lib/Doctrine/Common/Persistence/Event/ManagerEventArgs.php000064400000003570144760112570017574 0ustar00. */ namespace Doctrine\Common\Persistence\Event; use Doctrine\Common\Persistence\ObjectManager; /** * Provides event arguments for the preFlush event. * * @license http://www.opensource.org/licenses/lgpl-license.php LGPL * @link www.doctrine-project.org * @since 2.2 * @author Roman Borschel * @author Benjamin Eberlei */ class ManagerEventArgs extends \Doctrine\Common\EventArgs { /** * @var ObjectManager */ private $objectManager; /** * Constructor. * * @param ObjectManager $objectManager */ public function __construct(ObjectManager $objectManager) { $this->objectManager = $objectManager; } /** * Retrieve associated ObjectManager. * * @return ObjectManager */ public function getObjectManager() { return $this->objectManager; } } lib/Doctrine/Common/Persistence/Event/OnClearEventArgs.php000064400000004720144760112570017543 0ustar00. */ namespace Doctrine\Common\Persistence\Event; /** * Provides event arguments for the onClear event. * * @license http://www.opensource.org/licenses/lgpl-license.php LGPL * @link www.doctrine-project.org * @since 2.2 * @author Roman Borschel * @author Benjamin Eberlei */ class OnClearEventArgs extends \Doctrine\Common\EventArgs { /** * @var \Doctrine\Common\Persistence\ObjectManager */ private $objectManager; /** * @var string */ private $entityClass; /** * Constructor. * * @param \Doctrine\Common\Persistence\ObjectManager $objectManager * @param string $entityClass Optional entity class */ public function __construct($objectManager, $entityClass = null) { $this->objectManager = $objectManager; $this->entityClass = $entityClass; } /** * Retrieve associated ObjectManager. * * @return \Doctrine\Common\Persistence\ObjectManager */ public function getObjectManager() { return $this->objectManager; } /** * Name of the entity class that is cleared, or empty if all are cleared. * * @return string */ public function getEntityClass() { return $this->entityClass; } /** * Check if event clears all entities. * * @return bool */ public function clearsAllEntities() { return ($this->entityClass === null); } } lib/Doctrine/Common/Persistence/Event/PreUpdateEventArgs.php000064400000006765144760112570020124 0ustar00. */ namespace Doctrine\Common\Persistence\Event; use Doctrine\Common\EventArgs, Doctrine\Common\Persistence\ObjectManager; /** * Class that holds event arguments for a preUpdate event. * * @author Guilherme Blanco * @author Roman Borschel * @author Benjamin Eberlei * @since 2.2 */ class PreUpdateEventArgs extends LifecycleEventArgs { /** * @var array */ private $entityChangeSet; /** * Constructor. * * @param object $entity * @param ObjectManager $objectManager * @param array $changeSet */ public function __construct($entity, ObjectManager $objectManager, array &$changeSet) { parent::__construct($entity, $objectManager); $this->entityChangeSet = &$changeSet; } /** * Retrieve entity changeset. * * @return array */ public function getEntityChangeSet() { return $this->entityChangeSet; } /** * Check if field has a changeset. * * @param string $field * * @return boolean */ public function hasChangedField($field) { return isset($this->entityChangeSet[$field]); } /** * Get the old value of the changeset of the changed field. * * @param string $field * @return mixed */ public function getOldValue($field) { $this->assertValidField($field); return $this->entityChangeSet[$field][0]; } /** * Get the new value of the changeset of the changed field. * * @param string $field * @return mixed */ public function getNewValue($field) { $this->assertValidField($field); return $this->entityChangeSet[$field][1]; } /** * Set the new value of this field. * * @param string $field * @param mixed $value */ public function setNewValue($field, $value) { $this->assertValidField($field); $this->entityChangeSet[$field][1] = $value; } /** * Assert the field exists in changeset. * * @param string $field * * @throws \InvalidArgumentException */ private function assertValidField($field) { if ( ! isset($this->entityChangeSet[$field])) { throw new \InvalidArgumentException(sprintf( 'Field "%s" is not a valid field of the entity "%s" in PreUpdateEventArgs.', $field, get_class($this->getEntity()) )); } } } lib/Doctrine/Common/Persistence/ManagerRegistry.php000064400000007551144760112570016430 0ustar00. */ namespace Doctrine\Common\Persistence; /** * Contract covering object managers for a Doctrine persistence layer ManagerRegistry class to implement. * * @license http://www.opensource.org/licenses/lgpl-license.php LGPL * @link www.doctrine-project.org * @since 2.2 * @author Fabien Potencier * @author Benjamin Eberlei * @author Lukas Kahwe Smith */ interface ManagerRegistry extends ConnectionRegistry { /** * Gets the default object manager name. * * @return string The default object manager name */ function getDefaultManagerName(); /** * Gets a named object manager. * * @param string $name The object manager name (null for the default one) * * @return \Doctrine\Common\Persistence\ObjectManager */ function getManager($name = null); /** * Gets an array of all registered object managers * * @return \Doctrine\Common\Persistence\ObjectManager[] An array of ObjectManager instances */ function getManagers(); /** * Resets a named object manager. * * This method is useful when an object manager has been closed * because of a rollbacked transaction AND when you think that * it makes sense to get a new one to replace the closed one. * * Be warned that you will get a brand new object manager as * the existing one is not useable anymore. This means that any * other object with a dependency on this object manager will * hold an obsolete reference. You can inject the registry instead * to avoid this problem. * * @param string $name The object manager name (null for the default one) * * @return \Doctrine\Common\Persistence\ObjectManager */ function resetManager($name = null); /** * Resolves a registered namespace alias to the full namespace. * * This method looks for the alias in all registered object managers. * * @param string $alias The alias * * @return string The full namespace */ function getAliasNamespace($alias); /** * Gets all connection names. * * @return array An array of connection names */ function getManagerNames(); /** * Gets the ObjectRepository for an persistent object. * * @param string $persistentObject The name of the persistent object. * @param string $persistentManagerName The object manager name (null for the default one) * * @return \Doctrine\Common\Persistence\ObjectRepository */ function getRepository($persistentObject, $persistentManagerName = null); /** * Gets the object manager associated with a given class. * * @param string $class A persistent object class name * * @return \Doctrine\Common\Persistence\ObjectManager|null */ function getManagerForClass($class); } lib/Doctrine/Common/Persistence/Mapping/AbstractClassMetadataFactory.php000064400000027207144760112570022442 0ustar00. */ namespace Doctrine\Common\Persistence\Mapping; use Doctrine\Common\Cache\Cache, Doctrine\Common\Util\ClassUtils; /** * The ClassMetadataFactory is used to create ClassMetadata objects that contain all the * metadata mapping informations of a class which describes how a class should be mapped * to a relational database. * * This class was abstracted from the ORM ClassMetadataFactory * * @since 2.2 * @author Benjamin Eberlei * @author Guilherme Blanco * @author Jonathan Wage * @author Roman Borschel */ abstract class AbstractClassMetadataFactory implements ClassMetadataFactory { /** * Salt used by specific Object Manager implementation. * * @var string */ protected $cacheSalt = "\$CLASSMETADATA"; /** * @var \Doctrine\Common\Cache\Cache */ private $cacheDriver; /** * @var array */ private $loadedMetadata = array(); /** * @var bool */ protected $initialized = false; /** * @var ReflectionService */ private $reflectionService; /** * Sets the cache driver used by the factory to cache ClassMetadata instances. * * @param Doctrine\Common\Cache\Cache $cacheDriver */ public function setCacheDriver(Cache $cacheDriver = null) { $this->cacheDriver = $cacheDriver; } /** * Gets the cache driver used by the factory to cache ClassMetadata instances. * * @return Doctrine\Common\Cache\Cache */ public function getCacheDriver() { return $this->cacheDriver; } /** * Return an array of all the loaded metadata currently in memory. * * @return array */ public function getLoadedMetadata() { return $this->loadedMetadata; } /** * Forces the factory to load the metadata of all classes known to the underlying * mapping driver. * * @return array The ClassMetadata instances of all mapped classes. */ public function getAllMetadata() { if ( ! $this->initialized) { $this->initialize(); } $driver = $this->getDriver(); $metadata = array(); foreach ($driver->getAllClassNames() as $className) { $metadata[] = $this->getMetadataFor($className); } return $metadata; } /** * Lazy initialization of this stuff, especially the metadata driver, * since these are not needed at all when a metadata cache is active. * * @return void */ abstract protected function initialize(); /** * Get the fully qualified class-name from the namespace alias. * * @param string $namespaceAlias * @param string $simpleClassName * @return string */ abstract protected function getFqcnFromAlias($namespaceAlias, $simpleClassName); /** * Return the mapping driver implementation. * * @return \Doctrine\Common\Persistence\Mapping\Driver\MappingDriver */ abstract protected function getDriver(); /** * Wakeup reflection after ClassMetadata gets unserialized from cache. * * @param ClassMetadata $class * @param ReflectionService $reflService * @return void */ abstract protected function wakeupReflection(ClassMetadata $class, ReflectionService $reflService); /** * Initialize Reflection after ClassMetadata was constructed. * * @param ClassMetadata $class * @param ReflectionService $reflService * @return void */ abstract protected function initializeReflection(ClassMetadata $class, ReflectionService $reflService); /** * Checks whether the class metadata is an entity. * * This method should false for mapped superclasses or * embedded classes. * * @param ClassMetadata $class * @return boolean */ abstract protected function isEntity(ClassMetadata $class); /** * Gets the class metadata descriptor for a class. * * @param string $className The name of the class. * @return \Doctrine\Common\Persistence\Mapping\ClassMetadata */ public function getMetadataFor($className) { if (isset($this->loadedMetadata[$className])) { return $this->loadedMetadata[$className]; } $realClassName = $className; // Check for namespace alias if (strpos($className, ':') !== false) { list($namespaceAlias, $simpleClassName) = explode(':', $className); $realClassName = $this->getFqcnFromAlias($namespaceAlias, $simpleClassName); } else { $realClassName = ClassUtils::getRealClass($realClassName); } if (isset($this->loadedMetadata[$realClassName])) { // We do not have the alias name in the map, include it $this->loadedMetadata[$className] = $this->loadedMetadata[$realClassName]; return $this->loadedMetadata[$realClassName]; } if ($this->cacheDriver) { if (($cached = $this->cacheDriver->fetch($realClassName . $this->cacheSalt)) !== false) { $this->loadedMetadata[$realClassName] = $cached; $this->wakeupReflection($cached, $this->getReflectionService()); } else { foreach ($this->loadMetadata($realClassName) as $loadedClassName) { $this->cacheDriver->save( $loadedClassName . $this->cacheSalt, $this->loadedMetadata[$loadedClassName], null ); } } } else { $this->loadMetadata($realClassName); } if ($className != $realClassName) { // We do not have the alias name in the map, include it $this->loadedMetadata[$className] = $this->loadedMetadata[$realClassName]; } return $this->loadedMetadata[$className]; } /** * Checks whether the factory has the metadata for a class loaded already. * * @param string $className * @return boolean TRUE if the metadata of the class in question is already loaded, FALSE otherwise. */ public function hasMetadataFor($className) { return isset($this->loadedMetadata[$className]); } /** * Sets the metadata descriptor for a specific class. * * NOTE: This is only useful in very special cases, like when generating proxy classes. * * @param string $className * @param ClassMetadata $class */ public function setMetadataFor($className, $class) { $this->loadedMetadata[$className] = $class; } /** * Get array of parent classes for the given entity class * * @param string $name * @return array $parentClasses */ protected function getParentClasses($name) { // Collect parent classes, ignoring transient (not-mapped) classes. $parentClasses = array(); foreach (array_reverse($this->getReflectionService()->getParentClasses($name)) as $parentClass) { if ( ! $this->getDriver()->isTransient($parentClass)) { $parentClasses[] = $parentClass; } } return $parentClasses; } /** * Loads the metadata of the class in question and all it's ancestors whose metadata * is still not loaded. * * @param string $name The name of the class for which the metadata should get loaded. * * @return array */ protected function loadMetadata($name) { if ( ! $this->initialized) { $this->initialize(); } $loaded = array(); $parentClasses = $this->getParentClasses($name); $parentClasses[] = $name; // Move down the hierarchy of parent classes, starting from the topmost class $parent = null; $rootEntityFound = false; $visited = array(); $reflService = $this->getReflectionService(); foreach ($parentClasses as $className) { if (isset($this->loadedMetadata[$className])) { $parent = $this->loadedMetadata[$className]; if ($this->isEntity($parent)) { $rootEntityFound = true; array_unshift($visited, $className); } continue; } $class = $this->newClassMetadataInstance($className); $this->initializeReflection($class, $reflService); $this->doLoadMetadata($class, $parent, $rootEntityFound, $visited); $this->loadedMetadata[$className] = $class; $parent = $class; if ($this->isEntity($class)) { $rootEntityFound = true; array_unshift($visited, $className); } $this->wakeupReflection($class, $reflService); $loaded[] = $className; } return $loaded; } /** * Actually load the metadata from the underlying metadata * * @param ClassMetadata $class * @param ClassMetadata|null $parent * @param bool $rootEntityFound * @param array $nonSuperclassParents classnames all parent classes that are not marked as mapped superclasses * @return void */ abstract protected function doLoadMetadata($class, $parent, $rootEntityFound, array $nonSuperclassParents); /** * Creates a new ClassMetadata instance for the given class name. * * @param string $className * @return ClassMetadata */ abstract protected function newClassMetadataInstance($className); /** * Check if this class is mapped by this Object Manager + ClassMetadata configuration * * @param $class * @return bool */ public function isTransient($class) { if ( ! $this->initialized) { $this->initialize(); } // Check for namespace alias if (strpos($class, ':') !== false) { list($namespaceAlias, $simpleClassName) = explode(':', $class); $class = $this->getFqcnFromAlias($namespaceAlias, $simpleClassName); } return $this->getDriver()->isTransient($class); } /** * Set reflectionService. * * @param ReflectionService $reflectionService */ public function setReflectionService(ReflectionService $reflectionService) { $this->reflectionService = $reflectionService; } /** * Get the reflection service associated with this metadata factory. * * @return ReflectionService */ public function getReflectionService() { if ($this->reflectionService === null) { $this->reflectionService = new RuntimeReflectionService(); } return $this->reflectionService; } } lib/Doctrine/Common/Persistence/Mapping/ClassMetadata.php000064400000011146144760112570017421 0ustar00. */ namespace Doctrine\Common\Persistence\Mapping; /** * Contract for a Doctrine persistence layer ClassMetadata class to implement. * * @license http://www.opensource.org/licenses/lgpl-license.php LGPL * @link www.doctrine-project.org * @since 2.1 * @author Benjamin Eberlei * @author Jonathan Wage */ interface ClassMetadata { /** * Get fully-qualified class name of this persistent class. * * @return string */ function getName(); /** * Gets the mapped identifier field name. * * The returned structure is an array of the identifier field names. * * @return array */ function getIdentifier(); /** * Gets the ReflectionClass instance for this mapped class. * * @return \ReflectionClass */ function getReflectionClass(); /** * Checks if the given field name is a mapped identifier for this class. * * @param string $fieldName * @return boolean */ function isIdentifier($fieldName); /** * Checks if the given field is a mapped property for this class. * * @param string $fieldName * @return boolean */ function hasField($fieldName); /** * Checks if the given field is a mapped association for this class. * * @param string $fieldName * @return boolean */ function hasAssociation($fieldName); /** * Checks if the given field is a mapped single valued association for this class. * * @param string $fieldName * @return boolean */ function isSingleValuedAssociation($fieldName); /** * Checks if the given field is a mapped collection valued association for this class. * * @param string $fieldName * @return boolean */ function isCollectionValuedAssociation($fieldName); /** * A numerically indexed list of field names of this persistent class. * * This array includes identifier fields if present on this class. * * @return array */ function getFieldNames(); /** * Returns an array of identifier field names numerically indexed. * * @return array */ function getIdentifierFieldNames(); /** * A numerically indexed list of association names of this persistent class. * * This array includes identifier associations if present on this class. * * @return array */ function getAssociationNames(); /** * Returns a type name of this field. * * This type names can be implementation specific but should at least include the php types: * integer, string, boolean, float/double, datetime. * * @param string $fieldName * @return string */ function getTypeOfField($fieldName); /** * Returns the target class name of the given association. * * @param string $assocName * @return string */ function getAssociationTargetClass($assocName); /** * Checks if the association is the inverse side of a bidirectional association * * @param string $assocName * @return boolean */ function isAssociationInverseSide($assocName); /** * Returns the target field of the owning side of the association * * @param string $assocName * @return string */ function getAssociationMappedByTargetField($assocName); /** * Return the identifier of this object as an array with field name as key. * * Has to return an empty array if no identifier isset. * * @param object $object * @return array */ function getIdentifierValues($object); } lib/Doctrine/Common/Persistence/Mapping/ClassMetadataFactory.php000064400000005040144760112570020745 0ustar00. */ namespace Doctrine\Common\Persistence\Mapping; /** * Contract for a Doctrine persistence layer ClassMetadata class to implement. * * @license http://www.opensource.org/licenses/lgpl-license.php LGPL * @link www.doctrine-project.org * @since 2.1 * @author Benjamin Eberlei * @author Jonathan Wage */ interface ClassMetadataFactory { /** * Forces the factory to load the metadata of all classes known to the underlying * mapping driver. * * @return array The ClassMetadata instances of all mapped classes. */ function getAllMetadata(); /** * Gets the class metadata descriptor for a class. * * @param string $className The name of the class. * @return ClassMetadata */ function getMetadataFor($className); /** * Checks whether the factory has the metadata for a class loaded already. * * @param string $className * @return boolean TRUE if the metadata of the class in question is already loaded, FALSE otherwise. */ function hasMetadataFor($className); /** * Sets the metadata descriptor for a specific class. * * @param string $className * @param ClassMetadata $class */ function setMetadataFor($className, $class); /** * Whether the class with the specified name should have its metadata loaded. * This is only the case if it is either mapped directly or as a * MappedSuperclass. * * @param string $className * @return boolean */ function isTransient($className); } lib/Doctrine/Common/Persistence/Mapping/Driver/AnnotationDriver.php000064400000013672144760112570021442 0ustar00. */ namespace Doctrine\Common\Persistence\Mapping\Driver; use Doctrine\Common\Cache\ArrayCache, Doctrine\Common\Annotations\AnnotationReader, Doctrine\Common\Annotations\AnnotationRegistry, Doctrine\Common\Persistence\Mapping\MappingException; /** * The AnnotationDriver reads the mapping metadata from docblock annotations. * * @since 2.2 * @author Benjamin Eberlei * @author Guilherme Blanco * @author Jonathan H. Wage * @author Roman Borschel */ abstract class AnnotationDriver implements MappingDriver { /** * The AnnotationReader. * * @var AnnotationReader */ protected $reader; /** * The paths where to look for mapping files. * * @var array */ protected $paths = array(); /** * The file extension of mapping documents. * * @var string */ protected $fileExtension = '.php'; /** * Cache for AnnotationDriver#getAllClassNames() * * @var array */ protected $classNames; /** * Name of the entity annotations as keys * * @var array */ protected $entityAnnotationClasses = array(); /** * Initializes a new AnnotationDriver that uses the given AnnotationReader for reading * docblock annotations. * * @param AnnotationReader $reader The AnnotationReader to use, duck-typed. * @param string|array $paths One or multiple paths where mapping classes can be found. */ public function __construct($reader, $paths = null) { $this->reader = $reader; if ($paths) { $this->addPaths((array) $paths); } } /** * Append lookup paths to metadata driver. * * @param array $paths */ public function addPaths(array $paths) { $this->paths = array_unique(array_merge($this->paths, $paths)); } /** * Retrieve the defined metadata lookup paths. * * @return array */ public function getPaths() { return $this->paths; } /** * Retrieve the current annotation reader * * @return AnnotationReader */ public function getReader() { return $this->reader; } /** * Get the file extension used to look for mapping files under * * @return string */ public function getFileExtension() { return $this->fileExtension; } /** * Set the file extension used to look for mapping files under * * @param string $fileExtension The file extension to set * @return void */ public function setFileExtension($fileExtension) { $this->fileExtension = $fileExtension; } /** * Whether the class with the specified name is transient. Only non-transient * classes, that is entities and mapped superclasses, should have their metadata loaded. * * A class is non-transient if it is annotated with an annotation * from the {@see AnnotationDriver::entityAnnotationClasses}. * * @param string $className * @return boolean */ public function isTransient($className) { $classAnnotations = $this->reader->getClassAnnotations(new \ReflectionClass($className)); foreach ($classAnnotations as $annot) { if (isset($this->entityAnnotationClasses[get_class($annot)])) { return false; } } return true; } /** * {@inheritDoc} */ public function getAllClassNames() { if ($this->classNames !== null) { return $this->classNames; } if (!$this->paths) { throw MappingException::pathRequired(); } $classes = array(); $includedFiles = array(); foreach ($this->paths as $path) { if ( ! is_dir($path)) { throw MappingException::fileMappingDriversRequireConfiguredDirectoryPath($path); } $iterator = new \RegexIterator( new \RecursiveIteratorIterator( new \RecursiveDirectoryIterator($path, \FilesystemIterator::SKIP_DOTS), \RecursiveIteratorIterator::LEAVES_ONLY ), '/^.+' . preg_quote($this->fileExtension) . '$/i', \RecursiveRegexIterator::GET_MATCH ); foreach ($iterator as $file) { $sourceFile = realpath($file[0]); require_once $sourceFile; $includedFiles[] = $sourceFile; } } $declared = get_declared_classes(); foreach ($declared as $className) { $rc = new \ReflectionClass($className); $sourceFile = $rc->getFileName(); if (in_array($sourceFile, $includedFiles) && ! $this->isTransient($className)) { $classes[] = $className; } } $this->classNames = $classes; return $classes; } } lib/Doctrine/Common/Persistence/Mapping/Driver/DefaultFileLocator.php000064400000011654144760112570021662 0ustar00. */ namespace Doctrine\Common\Persistence\Mapping\Driver; use Doctrine\Common\Persistence\Mapping\MappingException; /** * Locate the file that contains the metadata information for a given class name. * * This behavior is independent of the actual content of the file. It just detects * the file which is responsible for the given class name. * * @author Benjamin Eberlei * @author Johannes M. Schmitt */ class DefaultFileLocator implements FileLocator { /** * The paths where to look for mapping files. * * @var array */ protected $paths = array(); /** * The file extension of mapping documents. * * @var string */ protected $fileExtension; /** * Initializes a new FileDriver that looks in the given path(s) for mapping * documents and operates in the specified operating mode. * * @param string|array $paths One or multiple paths where mapping documents can be found. * @param string|null $fileExtension */ public function __construct($paths, $fileExtension = null) { $this->addPaths((array) $paths); $this->fileExtension = $fileExtension; } /** * Append lookup paths to metadata driver. * * @param array $paths */ public function addPaths(array $paths) { $this->paths = array_unique(array_merge($this->paths, $paths)); } /** * Retrieve the defined metadata lookup paths. * * @return array */ public function getPaths() { return $this->paths; } /** * Get the file extension used to look for mapping files under * * @return string */ public function getFileExtension() { return $this->fileExtension; } /** * Set the file extension used to look for mapping files under * * @param string $fileExtension The file extension to set * @return void */ public function setFileExtension($fileExtension) { $this->fileExtension = $fileExtension; } /** * {@inheritDoc} */ public function findMappingFile($className) { $fileName = str_replace('\\', '.', $className) . $this->fileExtension; // Check whether file exists foreach ($this->paths as $path) { if (is_file($path . DIRECTORY_SEPARATOR . $fileName)) { return $path . DIRECTORY_SEPARATOR . $fileName; } } throw MappingException::mappingFileNotFound($className, $fileName); } /** * {@inheritDoc} */ public function getAllClassNames($globalBasename) { $classes = array(); if ($this->paths) { foreach ($this->paths as $path) { if ( ! is_dir($path)) { throw MappingException::fileMappingDriversRequireConfiguredDirectoryPath($path); } $iterator = new \RecursiveIteratorIterator( new \RecursiveDirectoryIterator($path), \RecursiveIteratorIterator::LEAVES_ONLY ); foreach ($iterator as $file) { $fileName = $file->getBasename($this->fileExtension); if ($fileName == $file->getBasename() || $fileName == $globalBasename) { continue; } // NOTE: All files found here means classes are not transient! $classes[] = str_replace('.', '\\', $fileName); } } } return $classes; } /** * {@inheritDoc} */ public function fileExists($className) { $fileName = str_replace('\\', '.', $className) . $this->fileExtension; // Check whether file exists foreach ((array) $this->paths as $path) { if (is_file($path . DIRECTORY_SEPARATOR . $fileName)) { return true; } } return false; } } lib/Doctrine/Common/Persistence/Mapping/Driver/FileDriver.php000064400000015071144760112570020202 0ustar00. */ namespace Doctrine\Common\Persistence\Mapping\Driver; use Doctrine\Common\Persistence\Mapping\MappingException; /** * Base driver for file-based metadata drivers. * * A file driver operates in a mode where it loads the mapping files of individual * classes on demand. This requires the user to adhere to the convention of 1 mapping * file per class and the file names of the mapping files must correspond to the full * class name, including namespace, with the namespace delimiters '\', replaced by dots '.'. * * @license http://www.opensource.org/licenses/lgpl-license.php LGPL * @link www.doctrine-project.com * @since 2.2 * @author Benjamin Eberlei * @author Guilherme Blanco * @author Jonathan H. Wage * @author Roman Borschel */ abstract class FileDriver implements MappingDriver { /** * @var FileLocator */ protected $locator; /** * @var array */ protected $classCache; /** * @var string */ protected $globalBasename; /** * Initializes a new FileDriver that looks in the given path(s) for mapping * documents and operates in the specified operating mode. * * @param string|array|FileLocator $locator A FileLocator or one/multiple paths where mapping documents can be found. * @param string $fileExtension */ public function __construct($locator, $fileExtension = null) { if ($locator instanceof FileLocator) { $this->locator = $locator; } else { $this->locator = new DefaultFileLocator((array)$locator, $fileExtension); } } /** * Set global basename * * @param string $file */ public function setGlobalBasename($file) { $this->globalBasename = $file; } /** * Retrieve global basename * * @return string */ public function getGlobalBasename() { return $this->globalBasename; } /** * Get the element of schema meta data for the class from the mapping file. * This will lazily load the mapping file if it is not loaded yet * * @param string $className * * @throws MappingException * @return array The element of schema meta data */ public function getElement($className) { if ($this->classCache === null) { $this->initialize(); } if (isset($this->classCache[$className])) { return $this->classCache[$className]; } $result = $this->loadMappingFile($this->locator->findMappingFile($className)); if (!isset($result[$className])) { throw MappingException::invalidMappingFile($className, str_replace('\\', '.', $className) . $this->locator->getFileExtension()); } return $result[$className]; } /** * Whether the class with the specified name should have its metadata loaded. * This is only the case if it is either mapped as an Entity or a * MappedSuperclass. * * @param string $className * @return boolean */ public function isTransient($className) { if ($this->classCache === null) { $this->initialize(); } if (isset($this->classCache[$className])) { return false; } return !$this->locator->fileExists($className); } /** * Gets the names of all mapped classes known to this driver. * * @return array The names of all mapped classes known to this driver. */ public function getAllClassNames() { if ($this->classCache === null) { $this->initialize(); } $classNames = (array)$this->locator->getAllClassNames($this->globalBasename); if ($this->classCache) { $classNames = array_merge(array_keys($this->classCache), $classNames); } return $classNames; } /** * Loads a mapping file with the given name and returns a map * from class/entity names to their corresponding file driver elements. * * @param string $file The mapping file to load. * @return array */ abstract protected function loadMappingFile($file); /** * Initialize the class cache from all the global files. * * Using this feature adds a substantial performance hit to file drivers as * more metadata has to be loaded into memory than might actually be * necessary. This may not be relevant to scenarios where caching of * metadata is in place, however hits very hard in scenarios where no * caching is used. * * @return void */ protected function initialize() { $this->classCache = array(); if (null !== $this->globalBasename) { foreach ($this->locator->getPaths() as $path) { $file = $path.'/'.$this->globalBasename.$this->locator->getFileExtension(); if (is_file($file)) { $this->classCache = array_merge( $this->classCache, $this->loadMappingFile($file) ); } } } } /** * Retrieve the locator used to discover mapping files by className * * @return FileLocator */ public function getLocator() { return $this->locator; } /** * Set the locator used to discover mapping files by className * * @param FileLocator $locator */ public function setLocator(FileLocator $locator) { $this->locator = $locator; } } lib/Doctrine/Common/Persistence/Mapping/Driver/FileLocator.php000064400000004355144760112570020355 0ustar00. */ namespace Doctrine\Common\Persistence\Mapping\Driver; /** * Locate the file that contains the metadata information for a given class name. * * This behavior is independent of the actual content of the file. It just detects * the file which is responsible for the given class name. * * @author Benjamin Eberlei * @author Johannes M. Schmitt */ interface FileLocator { /** * Locate mapping file for the given class name. * * @param string $className * @return string */ function findMappingFile($className); /** * Get all class names that are found with this file locator. * * @param string $globalBasename Passed to allow excluding the basename * @return array */ function getAllClassNames($globalBasename); /** * Check if a file can be found for this class name. * * @param string $className * * @return bool */ function fileExists($className); /** * Get all the paths that this file locator looks for mapping files. * * @return array */ function getPaths(); /** * Get the file extension that mapping files are suffixed with. * * @return string */ function getFileExtension(); } lib/Doctrine/Common/Persistence/Mapping/Driver/MappingDriver.php000064400000003663144760112570020722 0ustar00. */ namespace Doctrine\Common\Persistence\Mapping\Driver; use Doctrine\Common\Persistence\Mapping\ClassMetadata; /** * Contract for metadata drivers. * * @since 2.2 * @author Jonathan H. Wage */ interface MappingDriver { /** * Loads the metadata for the specified class into the provided container. * * @param string $className * @param ClassMetadata $metadata */ function loadMetadataForClass($className, ClassMetadata $metadata); /** * Gets the names of all mapped classes known to this driver. * * @return array The names of all mapped classes known to this driver. */ function getAllClassNames(); /** * Whether the class with the specified name should have its metadata loaded. * This is only the case if it is either mapped as an Entity or a * MappedSuperclass. * * @param string $className * @return boolean */ function isTransient($className); } lib/Doctrine/Common/Persistence/Mapping/Driver/MappingDriverChain.php000064400000011511144760112570021654 0ustar00. */ namespace Doctrine\Common\Persistence\Mapping\Driver; use Doctrine\Common\Persistence\Mapping\Driver\MappingDriver, Doctrine\Common\Persistence\Mapping\ClassMetadata, Doctrine\Common\Persistence\Mapping\MappingException; /** * The DriverChain allows you to add multiple other mapping drivers for * certain namespaces * * @since 2.2 * @author Benjamin Eberlei * @author Guilherme Blanco * @author Jonathan H. Wage * @author Roman Borschel */ class MappingDriverChain implements MappingDriver { /** * The default driver * * @var MappingDriver */ private $defaultDriver; /** * @var array */ private $drivers = array(); /** * Get the default driver. * * @return MappingDriver|null */ public function getDefaultDriver() { return $this->defaultDriver; } /** * Set the default driver. * * @param MappingDriver $driver */ public function setDefaultDriver(MappingDriver $driver) { $this->defaultDriver = $driver; } /** * Add a nested driver. * * @param MappingDriver $nestedDriver * @param string $namespace */ public function addDriver(MappingDriver $nestedDriver, $namespace) { $this->drivers[$namespace] = $nestedDriver; } /** * Get the array of nested drivers. * * @return array $drivers */ public function getDrivers() { return $this->drivers; } /** * Loads the metadata for the specified class into the provided container. * * @param string $className * @param ClassMetadata $metadata * * @throws MappingException */ public function loadMetadataForClass($className, ClassMetadata $metadata) { /* @var $driver MappingDriver */ foreach ($this->drivers as $namespace => $driver) { if (strpos($className, $namespace) === 0) { $driver->loadMetadataForClass($className, $metadata); return; } } if (null !== $this->defaultDriver) { $this->defaultDriver->loadMetadataForClass($className, $metadata); return; } throw MappingException::classNotFoundInNamespaces($className, array_keys($this->drivers)); } /** * Gets the names of all mapped classes known to this driver. * * @return array The names of all mapped classes known to this driver. */ public function getAllClassNames() { $classNames = array(); $driverClasses = array(); /* @var $driver MappingDriver */ foreach ($this->drivers AS $namespace => $driver) { $oid = spl_object_hash($driver); if (!isset($driverClasses[$oid])) { $driverClasses[$oid] = $driver->getAllClassNames(); } foreach ($driverClasses[$oid] AS $className) { if (strpos($className, $namespace) === 0) { $classNames[$className] = true; } } } return array_keys($classNames); } /** * Whether the class with the specified name should have its metadata loaded. * * This is only the case for non-transient classes either mapped as an Entity or MappedSuperclass. * * @param string $className * @return boolean */ public function isTransient($className) { /* @var $driver MappingDriver */ foreach ($this->drivers AS $namespace => $driver) { if (strpos($className, $namespace) === 0) { return $driver->isTransient($className); } } if ($this->defaultDriver !== null) { return $this->defaultDriver->isTransient($className); } return true; } } lib/Doctrine/Common/Persistence/Mapping/Driver/PHPDriver.php000064400000004465144760112570017757 0ustar00. */ namespace Doctrine\Common\Persistence\Mapping\Driver; use Doctrine\Common\Persistence\Mapping\ClassMetadata; /** * The PHPDriver includes php files which just populate ClassMetadataInfo * instances with plain php code * * @license http://www.opensource.org/licenses/lgpl-license.php LGPL * @link www.doctrine-project.org * @since 2.0 * @version $Revision$ * @author Benjamin Eberlei * @author Guilherme Blanco * @author Jonathan H. Wage * @author Roman Borschel */ class PHPDriver extends FileDriver { /** * {@inheritdoc} */ protected $metadata; /** * {@inheritDoc} */ public function __construct($locator, $fileExtension = null) { $fileExtension = ".php"; parent::__construct($locator, $fileExtension); } /** * {@inheritdoc} */ public function loadMetadataForClass($className, ClassMetadata $metadata) { $this->metadata = $metadata; $this->loadMappingFile($this->locator->findMappingFile($className)); } /** * {@inheritdoc} */ protected function loadMappingFile($file) { $metadata = $this->metadata; include $file; return array($metadata->getName() => $metadata); } } lib/Doctrine/Common/Persistence/Mapping/Driver/StaticPHPDriver.php000064400000010120144760112570021110 0ustar00. */ namespace Doctrine\Common\Persistence\Mapping\Driver; use Doctrine\Common\Persistence\Mapping\ClassMetadata; use Doctrine\Common\Persistence\Mapping\MappingException; /** * The StaticPHPDriver calls a static loadMetadata() method on your entity * classes where you can manually populate the ClassMetadata instance. * * @license http://www.opensource.org/licenses/lgpl-license.php LGPL * @link www.doctrine-project.org * @since 2.2 * @author Benjamin Eberlei * @author Guilherme Blanco * @author Jonathan H. Wage * @author Roman Borschel */ class StaticPHPDriver implements MappingDriver { /** * Paths of entity directories. * * @var array */ private $paths = array(); /** * Map of all class names. * * @var array */ private $classNames; /** * Constructor * * @param array|string $paths */ public function __construct($paths) { $this->addPaths((array) $paths); } /** * Add paths * * @param array $paths */ public function addPaths(array $paths) { $this->paths = array_unique(array_merge($this->paths, $paths)); } /** * {@inheritdoc} */ public function loadMetadataForClass($className, ClassMetadata $metadata) { $className::loadMetadata($metadata); } /** * {@inheritDoc} * @todo Same code exists in AnnotationDriver, should we re-use it somehow or not worry about it? */ public function getAllClassNames() { if ($this->classNames !== null) { return $this->classNames; } if (!$this->paths) { throw MappingException::pathRequired(); } $classes = array(); $includedFiles = array(); foreach ($this->paths as $path) { if (!is_dir($path)) { throw MappingException::fileMappingDriversRequireConfiguredDirectoryPath($path); } $iterator = new \RecursiveIteratorIterator( new \RecursiveDirectoryIterator($path), \RecursiveIteratorIterator::LEAVES_ONLY ); foreach ($iterator as $file) { if ($file->getBasename('.php') == $file->getBasename()) { continue; } $sourceFile = realpath($file->getPathName()); require_once $sourceFile; $includedFiles[] = $sourceFile; } } $declared = get_declared_classes(); foreach ($declared as $className) { $rc = new \ReflectionClass($className); $sourceFile = $rc->getFileName(); if (in_array($sourceFile, $includedFiles) && !$this->isTransient($className)) { $classes[] = $className; } } $this->classNames = $classes; return $classes; } /** * {@inheritdoc} */ public function isTransient($className) { return ! method_exists($className, 'loadMetadata'); } } lib/Doctrine/Common/Persistence/Mapping/Driver/SymfonyFileLocator.php000064400000014265144760112570021743 0ustar00. */ namespace Doctrine\Common\Persistence\Mapping\Driver; use Doctrine\Common\Persistence\Mapping\MappingException; /** * The Symfony File Locator makes a simplifying assumptions compared * to the DefaultFileLocator. By assuming paths only contain entities of a certain * namespace the mapping files consists of the short classname only. * * @author Fabien Potencier * @author Benjamin Eberlei * @license MIT */ class SymfonyFileLocator implements FileLocator { /** * The paths where to look for mapping files. * * @var array */ protected $paths = array(); /** * A map of mapping directory path to namespace prefix used to expand class shortnames. * * @var array */ protected $prefixes = array(); /** * File extension that is searched for. * * @var string */ protected $fileExtension; /** * Constructor * * @param array $prefixes * @param string|null $fileExtension */ public function __construct(array $prefixes, $fileExtension = null) { $this->addNamespacePrefixes($prefixes); $this->fileExtension = $fileExtension; } /** * Add Namespace Prefixes * * @param array $prefixes */ public function addNamespacePrefixes(array $prefixes) { $this->prefixes = array_merge($this->prefixes, $prefixes); $this->paths = array_merge($this->paths, array_keys($prefixes)); } /** * Get Namespace Prefixes * * @return array */ public function getNamespacePrefixes() { return $this->prefixes; } /** * {@inheritDoc} */ public function getPaths() { return $this->paths; } /** * {@inheritDoc} */ public function getFileExtension() { return $this->fileExtension; } /** * Set the file extension used to look for mapping files under * * @param string $fileExtension The file extension to set * @return void */ public function setFileExtension($fileExtension) { $this->fileExtension = $fileExtension; } /** * {@inheritDoc} */ public function fileExists($className) { $defaultFileName = str_replace('\\', '.', $className).$this->fileExtension; foreach ($this->paths as $path) { if (!isset($this->prefixes[$path])) { // global namespace class if (is_file($path.DIRECTORY_SEPARATOR.$defaultFileName)) { return true; } continue; } $prefix = $this->prefixes[$path]; if (0 !== strpos($className, $prefix.'\\')) { continue; } $filename = $path.'/'.strtr(substr($className, strlen($prefix)+1), '\\', '.').$this->fileExtension; return is_file($filename); } return false; } /** * {@inheritDoc} */ public function getAllClassNames($globalBasename = null) { $classes = array(); if ($this->paths) { foreach ((array) $this->paths as $path) { if (!is_dir($path)) { throw MappingException::fileMappingDriversRequireConfiguredDirectoryPath($path); } $iterator = new \RecursiveIteratorIterator( new \RecursiveDirectoryIterator($path), \RecursiveIteratorIterator::LEAVES_ONLY ); foreach ($iterator as $file) { $fileName = $file->getBasename($this->fileExtension); if ($fileName == $file->getBasename() || $fileName == $globalBasename) { continue; } // NOTE: All files found here means classes are not transient! if (isset($this->prefixes[$path])) { $classes[] = $this->prefixes[$path].'\\'.str_replace('.', '\\', $fileName); } else { $classes[] = str_replace('.', '\\', $fileName); } } } } return $classes; } /** * {@inheritDoc} */ public function findMappingFile($className) { $defaultFileName = str_replace('\\', '.', $className).$this->fileExtension; foreach ($this->paths as $path) { if (!isset($this->prefixes[$path])) { if (is_file($path.DIRECTORY_SEPARATOR.$defaultFileName)) { return $path.DIRECTORY_SEPARATOR.$defaultFileName; } continue; } $prefix = $this->prefixes[$path]; if (0 !== strpos($className, $prefix.'\\')) { continue; } $filename = $path.'/'.strtr(substr($className, strlen($prefix)+1), '\\', '.').$this->fileExtension; if (is_file($filename)) { return $filename; } throw MappingException::mappingFileNotFound($className, $filename); } throw MappingException::mappingFileNotFound($className, substr($className, strrpos($className, '\\') + 1).$this->fileExtension); } } lib/Doctrine/Common/Persistence/Mapping/MappingException.php000064400000005403144760112570020164 0ustar00. */ namespace Doctrine\Common\Persistence\Mapping; /** * A MappingException indicates that something is wrong with the mapping setup. * * @since 2.2 */ class MappingException extends \Exception { /** * * @param string $className * @param array $namespaces * * @return MappingException */ public static function classNotFoundInNamespaces($className, $namespaces) { return new self("The class '" . $className . "' was not found in the ". "chain configured namespaces " . implode(", ", $namespaces)); } /** * @return MappingException */ public static function pathRequired() { return new self("Specifying the paths to your entities is required ". "in the AnnotationDriver to retrieve all class names."); } /** * @param string|null $path * @return MappingException */ public static function fileMappingDriversRequireConfiguredDirectoryPath($path = null) { if ( ! empty($path)) { $path = '[' . $path . ']'; } return new self( 'File mapping drivers must have a valid directory path, ' . 'however the given path ' . $path . ' seems to be incorrect!' ); } /** * @param string $entityName * @param string $fileName * @return MappingException */ public static function mappingFileNotFound($entityName, $fileName) { return new self("No mapping file found named '$fileName' for class '$entityName'."); } /** * @param string $entityName * @param string $fileName * @return MappingException */ public static function invalidMappingFile($entityName, $fileName) { return new self("Invalid mapping file '$fileName' for class '$entityName'."); } } lib/Doctrine/Common/Persistence/Mapping/ReflectionService.php000064400000004476144760112570020336 0ustar00. */ namespace Doctrine\Common\Persistence\Mapping; /** * Very simple reflection service abstraction. * * This is required inside metadata layers that may require either * static or runtime reflection. * * @author Benjamin Eberlei */ interface ReflectionService { /** * Return an array of the parent classes (not interfaces) for the given class. * * @param string $class * @return array */ function getParentClasses($class); /** * Return the shortname of a class. * * @param string $class * @return string */ function getClassShortName($class); /** * @param string $class * @return string */ function getClassNamespace($class); /** * Return a reflection class instance or null * * @param string $class * @return \ReflectionClass|null */ function getClass($class); /** * Return an accessible property (setAccessible(true)) or null. * * @param string $class * @param string $property * @return \ReflectionProperty|null */ function getAccessibleProperty($class, $property); /** * Check if the class have a public method with the given name. * * @param mixed $class * @param mixed $method * @return bool */ function hasPublicMethod($class, $method); } lib/Doctrine/Common/Persistence/Mapping/RuntimeReflectionService.php000064400000005033144760112570021670 0ustar00. */ namespace Doctrine\Common\Persistence\Mapping; use ReflectionClass; use ReflectionProperty; use Doctrine\Common\Reflection\RuntimePublicReflectionProperty; /** * PHP Runtime Reflection Service * * @author Benjamin Eberlei */ class RuntimeReflectionService implements ReflectionService { /** * {@inheritDoc} */ public function getParentClasses($class) { return class_parents($class); } /** * {@inheritDoc} */ public function getClassShortName($class) { $reflectionClass = new ReflectionClass($class); return $reflectionClass->getShortName(); } /** * {@inheritDoc} */ public function getClassNamespace($class) { $reflectionClass = new ReflectionClass($class); return $reflectionClass->getNamespaceName(); } /** * {@inheritDoc} */ public function getClass($class) { return new ReflectionClass($class); } /** * {@inheritDoc} */ public function getAccessibleProperty($class, $property) { $reflectionProperty = new ReflectionProperty($class, $property); if ($reflectionProperty->isPublic()) { $reflectionProperty = new RuntimePublicReflectionProperty($class, $property); } $reflectionProperty->setAccessible(true); return $reflectionProperty; } /** * {@inheritDoc} */ public function hasPublicMethod($class, $method) { return method_exists($class, $method) && is_callable(array($class, $method)); } } lib/Doctrine/Common/Persistence/Mapping/StaticReflectionService.php000064400000005714144760112570021502 0ustar00. */ namespace Doctrine\Common\Persistence\Mapping; use ReflectionClass; use ReflectionProperty; /** * PHP Runtime Reflection Service * * @author Benjamin Eberlei */ class StaticReflectionService implements ReflectionService { /** * Return an array of the parent classes (not interfaces) for the given class. * * @param string $class * @return array */ public function getParentClasses($class) { return array(); } /** * Return the shortname of a class. * * @param string $className * @return string */ public function getClassShortName($className) { if (strpos($className, '\\') !== false) { $className = substr($className, strrpos($className, "\\")+1); } return $className; } /** * Return the namespace of a class. * * @param string $className * @return string */ public function getClassNamespace($className) { $namespace = ''; if (strpos($className, '\\') !== false) { $namespace = strrev(substr( strrev($className), strpos(strrev($className), '\\')+1 )); } return $namespace; } /** * Return a reflection class instance or null * * @param string $class * @return ReflectionClass|null */ public function getClass($class) { return null; } /** * Return an accessible property (setAccessible(true)) or null. * * @param string $class * @param string $property * @return ReflectionProperty|null */ public function getAccessibleProperty($class, $property) { return null; } /** * Check if the class have a public method with the given name. * * @param mixed $class * @param mixed $method * @return bool */ public function hasPublicMethod($class, $method) { return method_exists($class, $method) && is_callable(array($class, $method)); } } lib/Doctrine/Common/Persistence/ObjectManager.php000064400000011710144760112570016016 0ustar00. */ namespace Doctrine\Common\Persistence; /** * Contract for a Doctrine persistence layer ObjectManager class to implement. * * @license http://www.opensource.org/licenses/lgpl-license.php LGPL * @link www.doctrine-project.org * @since 2.1 * @author Benjamin Eberlei * @author Jonathan Wage */ interface ObjectManager { /** * Finds a object by its identifier. * * This is just a convenient shortcut for getRepository($className)->find($id). * * @param string * @param mixed * @return object */ function find($className, $id); /** * Tells the ObjectManager to make an instance managed and persistent. * * The object will be entered into the database as a result of the flush operation. * * NOTE: The persist operation always considers objects that are not yet known to * this ObjectManager as NEW. Do not pass detached objects to the persist operation. * * @param object $object The instance to make managed and persistent. */ function persist($object); /** * Removes an object instance. * * A removed object will be removed from the database as a result of the flush operation. * * @param object $object The object instance to remove. */ function remove($object); /** * Merges the state of a detached object into the persistence context * of this ObjectManager and returns the managed copy of the object. * The object passed to merge will not become associated/managed with this ObjectManager. * * @param object $object * @return object */ function merge($object); /** * Clears the ObjectManager. All objects that are currently managed * by this ObjectManager become detached. * * @param string $objectName if given, only objects of this type will get detached */ function clear($objectName = null); /** * Detaches an object from the ObjectManager, causing a managed object to * become detached. Unflushed changes made to the object if any * (including removal of the object), will not be synchronized to the database. * Objects which previously referenced the detached object will continue to * reference it. * * @param object $object The object to detach. */ function detach($object); /** * Refreshes the persistent state of an object from the database, * overriding any local changes that have not yet been persisted. * * @param object $object The object to refresh. */ function refresh($object); /** * Flushes all changes to objects that have been queued up to now to the database. * This effectively synchronizes the in-memory state of managed objects with the * database. */ function flush(); /** * Gets the repository for a class. * * @param string $className * @return \Doctrine\Common\Persistence\ObjectRepository */ function getRepository($className); /** * Returns the ClassMetadata descriptor for a class. * * The class name must be the fully-qualified class name without a leading backslash * (as it is returned by get_class($obj)). * * @param string $className * @return \Doctrine\Common\Persistence\Mapping\ClassMetadata */ function getClassMetadata($className); /** * Gets the metadata factory used to gather the metadata of classes. * * @return \Doctrine\Common\Persistence\Mapping\ClassMetadataFactory */ function getMetadataFactory(); /** * Helper method to initialize a lazy loading proxy or persistent collection. * * This method is a no-op for other objects. * * @param object $obj */ function initializeObject($obj); /** * Check if the object is part of the current UnitOfWork and therefore * managed. * * @param object $object * @return bool */ function contains($object); } lib/Doctrine/Common/Persistence/ObjectManagerAware.php000064400000004130144760112570016774 0ustar00. */ namespace Doctrine\Common\Persistence; use Doctrine\Common\Persistence\Mapping\ClassMetadata; /** * Makes a Persistent Objects aware of its own object-manager. * * Using this interface the managing object manager and class metadata instances * are injected into the persistent object after construction. This allows * you to implement ActiveRecord functionality on top of the persistence-ignorance * that Doctrine propagates. * * Word of Warning: This is a very powerful hook to change how you can work with your domain models. * Using this hook will break the Single Responsibility Principle inside your Domain Objects * and increase the coupling of database and objects. * * Every ObjectManager has to implement this functionality itself. * * @author Benjamin Eberlei */ interface ObjectManagerAware { /** * Injects responsible ObjectManager and the ClassMetadata into this persistent object. * * @param ObjectManager $objectManager * @param ClassMetadata $classMetadata */ public function injectObjectManager(ObjectManager $objectManager, ClassMetadata $classMetadata); } lib/Doctrine/Common/Persistence/ObjectManagerDecorator.php000064400000006177144760112570017674 0ustar00. */ namespace Doctrine\Common\Persistence; /** * Base class to simplify ObjectManager decorators * * @license http://opensource.org/licenses/MIT MIT * @link www.doctrine-project.org * @since 2.4 * @author Lars Strojny */ abstract class ObjectManagerDecorator implements ObjectManager { /** * @var ObjectManager */ protected $wrapped; /** * {@inheritdoc} */ public function find($className, $id) { return $this->wrapped->find($className, $id); } /** * {@inheritdoc} */ public function persist($object) { return $this->wrapped->persist($object); } /** * {@inheritdoc} */ public function remove($object) { return $this->wrapped->remove($object); } /** * {@inheritdoc} */ public function merge($object) { return $this->wrapped->merge($object); } /** * {@inheritdoc} */ public function clear($objectName = null) { return $this->wrapped->clear($objectName); } /** * {@inheritdoc} */ public function detach($object) { return $this->wrapped->detach($object); } /** * {@inheritdoc} */ public function refresh($object) { return $this->wrapped->refresh($object); } /** * {@inheritdoc} */ public function flush() { return $this->wrapped->flush(); } /** * {@inheritdoc} */ public function getRepository($className) { return $this->wrapped->getRepository($className); } /** * {@inheritdoc} */ public function getClassMetadata($className) { return $this->wrapped->getClassMetadata($className); } /** * {@inheritdoc} */ public function getMetadataFactory() { return $this->wrapped->getMetadataFactory(); } /** * {@inheritdoc} */ public function initializeObject($obj) { return $this->wrapped->initializeObject($obj); } /** * {@inheritdoc} */ public function contains($object) { return $this->wrapped->contains($object); } } lib/Doctrine/Common/Persistence/ObjectRepository.php000064400000005010144760112570016617 0ustar00. */ namespace Doctrine\Common\Persistence; /** * Contract for a Doctrine persistence layer ObjectRepository class to implement. * * @license http://www.opensource.org/licenses/lgpl-license.php LGPL * @link www.doctrine-project.org * @since 2.1 * @author Benjamin Eberlei * @author Jonathan Wage */ interface ObjectRepository { /** * Finds an object by its primary key / identifier. * * @param int $id The identifier. * @return object The object. */ function find($id); /** * Finds all objects in the repository. * * @return mixed The objects. */ function findAll(); /** * Finds objects by a set of criteria. * * Optionally sorting and limiting details can be passed. An implementation may throw * an UnexpectedValueException if certain values of the sorting or limiting details are * not supported. * * @throws \UnexpectedValueException * @param array $criteria * @param array|null $orderBy * @param int|null $limit * @param int|null $offset * @return mixed The objects. */ function findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null); /** * Finds a single object by a set of criteria. * * @param array $criteria * @return object The object. */ function findOneBy(array $criteria); /** * Returns the class name of the object managed by the repository * * @return string */ function getClassName(); } lib/Doctrine/Common/Persistence/PersistentObject.php000064400000020511144760112570016603 0ustar00. */ namespace Doctrine\Common\Persistence; use Doctrine\Common\Persistence\Mapping\ClassMetadata; use Doctrine\Common\Collections\ArrayCollection; use Doctrine\Common\Collections\Collection; /** * PersistentObject base class that implements getter/setter methods for all mapped fields and associations * by overriding __call. * * This class is a forward compatible implementation of the PersistentObject trait. * * * Limitations: * * 1. All persistent objects have to be associated with a single ObjectManager, multiple * ObjectManagers are not supported. You can set the ObjectManager with `PersistentObject#setObjectManager()`. * 2. Setters and getters only work if a ClassMetadata instance was injected into the PersistentObject. * This is either done on `postLoad` of an object or by accessing the global object manager. * 3. There are no hooks for setters/getters. Just implement the method yourself instead of relying on __call(). * 4. Slower than handcoded implementations: An average of 7 method calls per access to a field and 11 for an association. * 5. Only the inverse side associations get autoset on the owning side as well. Setting objects on the owning side * will not set the inverse side associations. * * @example * * PersistentObject::setObjectManager($em); * * class Foo extends PersistentObject * { * private $id; * } * * $foo = new Foo(); * $foo->getId(); // method exists through __call * * @author Benjamin Eberlei */ abstract class PersistentObject implements ObjectManagerAware { /** * @var ObjectManager */ private static $objectManager; /** * @var ClassMetadata */ private $cm; /** * Set the object manager responsible for all persistent object base classes. * * @param ObjectManager $objectManager */ static public function setObjectManager(ObjectManager $objectManager = null) { self::$objectManager = $objectManager; } /** * @return ObjectManager */ static public function getObjectManager() { return self::$objectManager; } /** * Inject Doctrine Object Manager * * @param ObjectManager $objectManager * @param ClassMetadata $classMetadata * * @throws \RuntimeException */ public function injectObjectManager(ObjectManager $objectManager, ClassMetadata $classMetadata) { if ($objectManager !== self::$objectManager) { throw new \RuntimeException("Trying to use PersistentObject with different ObjectManager instances. " . "Was PersistentObject::setObjectManager() called?"); } $this->cm = $classMetadata; } /** * Sets a persistent fields value. * * @param string $field * @param array $args * * @throws \BadMethodCallException - When no persistent field exists by that name. * @throws \InvalidArgumentException - When the wrong target object type is passed to an association * @return void */ private function set($field, $args) { $this->initializeDoctrine(); if ($this->cm->hasField($field) && !$this->cm->isIdentifier($field)) { $this->$field = $args[0]; } else if ($this->cm->hasAssociation($field) && $this->cm->isSingleValuedAssociation($field)) { $targetClass = $this->cm->getAssociationTargetClass($field); if (!($args[0] instanceof $targetClass) && $args[0] !== null) { throw new \InvalidArgumentException("Expected persistent object of type '".$targetClass."'"); } $this->$field = $args[0]; $this->completeOwningSide($field, $targetClass, $args[0]); } else { throw new \BadMethodCallException("no field with name '".$field."' exists on '".$this->cm->getName()."'"); } } /** * Get persistent field value. * * * @param string $field * * @throws \BadMethodCallException - When no persistent field exists by that name. * @return mixed */ private function get($field) { $this->initializeDoctrine(); if ( $this->cm->hasField($field) || $this->cm->hasAssociation($field) ) { return $this->$field; } else { throw new \BadMethodCallException("no field with name '".$field."' exists on '".$this->cm->getName()."'"); } } /** * If this is an inverse side association complete the owning side. * * @param string $field * @param ClassMetadata $targetClass * @param object $targetObject */ private function completeOwningSide($field, $targetClass, $targetObject) { // add this object on the owning side as well, for obvious infinite recursion // reasons this is only done when called on the inverse side. if ($this->cm->isAssociationInverseSide($field)) { $mappedByField = $this->cm->getAssociationMappedByTargetField($field); $targetMetadata = self::$objectManager->getClassMetadata($targetClass); $setter = ($targetMetadata->isCollectionValuedAssociation($mappedByField) ? "add" : "set").$mappedByField; $targetObject->$setter($this); } } /** * Add an object to a collection * * @param string $field * @param array $args * * @throws \BadMethodCallException * @throws \InvalidArgumentException */ private function add($field, $args) { $this->initializeDoctrine(); if ($this->cm->hasAssociation($field) && $this->cm->isCollectionValuedAssociation($field)) { $targetClass = $this->cm->getAssociationTargetClass($field); if (!($args[0] instanceof $targetClass)) { throw new \InvalidArgumentException("Expected persistent object of type '".$targetClass."'"); } if (!($this->$field instanceof Collection)) { $this->$field = new ArrayCollection($this->$field ?: array()); } $this->$field->add($args[0]); $this->completeOwningSide($field, $targetClass, $args[0]); } else { throw new \BadMethodCallException("There is no method add".$field."() on ".$this->cm->getName()); } } /** * Initialize Doctrine Metadata for this class. * * @throws \RuntimeException * @return void */ private function initializeDoctrine() { if ($this->cm !== null) { return; } if (!self::$objectManager) { throw new \RuntimeException("No runtime object manager set. Call PersistentObject#setObjectManager()."); } $this->cm = self::$objectManager->getClassMetadata(get_class($this)); } /** * Magic method that implements * * @param string $method * @param array $args * * @throws \BadMethodCallException * @return mixed */ public function __call($method, $args) { $command = substr($method, 0, 3); $field = lcfirst(substr($method, 3)); if ($command == "set") { $this->set($field, $args); } else if ($command == "get") { return $this->get($field); } else if ($command == "add") { $this->add($field, $args); } else { throw new \BadMethodCallException("There is no method ".$method." on ".$this->cm->getName()); } } } lib/Doctrine/Common/Persistence/Proxy.php000064400000003222144760112570014435 0ustar00. */ namespace Doctrine\Common\Persistence; /** * Interface for proxy classes. * * @author Roman Borschel * @since 2.2 */ interface Proxy { /** * Marker for Proxy class names. * * @var string */ const MARKER = '__CG__'; /** * Length of the proxy marker * * @var integer */ const MARKER_LENGTH = 6; /** * Initialize this proxy if its not yet initialized. * * Acts as a no-op if already initialized. * * @return void */ public function __load(); /** * Is this proxy initialized or not. * * @return bool */ public function __isInitialized(); } lib/Doctrine/Common/PropertyChangedListener.php000064400000003620144760112570015636 0ustar00. */ namespace Doctrine\Common; /** * Contract for classes that are potential listeners of a NotifyPropertyChanged * implementor. * * @license http://www.opensource.org/licenses/lgpl-license.php LGPL * @link www.doctrine-project.org * @since 2.0 * @version $Revision: 3938 $ * @author Guilherme Blanco * @author Jonathan Wage * @author Roman Borschel */ interface PropertyChangedListener { /** * Notifies the listener of a property change. * * @param object $sender The object on which the property changed. * @param string $propertyName The name of the property that changed. * @param mixed $oldValue The old value of the property that changed. * @param mixed $newValue The new value of the property that changed. */ function propertyChanged($sender, $propertyName, $oldValue, $newValue); } lib/Doctrine/Common/Proxy/AbstractProxyFactory.php000064400000014373144760112570016317 0ustar00. */ namespace Doctrine\Common\Proxy; use Doctrine\Common\Persistence\Mapping\ClassMetadataFactory; use Doctrine\Common\Proxy\Exception\InvalidArgumentException; use Doctrine\Common\Util\ClassUtils; use Doctrine\Common\Persistence\Mapping\ClassMetadata; /** * Abstract factory for proxy objects. * * @author Benjamin Eberlei */ abstract class AbstractProxyFactory { /** * @var \Doctrine\Common\Persistence\Mapping\ClassMetadataFactory */ private $metadataFactory; /** * @var \Doctrine\Common\Proxy\ProxyGenerator the proxy generator responsible for creating the proxy classes/files. */ private $proxyGenerator; /** * @var bool Whether to automatically (re)generate proxy classes. */ private $autoGenerate; /** * @var \Doctrine\Common\Proxy\ProxyDefinition[] */ private $definitions = array(); /** * @param \Doctrine\Common\Proxy\ProxyGenerator $proxyGenerator * @param \Doctrine\Common\Persistence\Mapping\ClassMetadataFactory $metadataFactory * @param bool $autoGenerate */ public function __construct(ProxyGenerator $proxyGenerator, ClassMetadataFactory $metadataFactory, $autoGenerate) { $this->proxyGenerator = $proxyGenerator; $this->metadataFactory = $metadataFactory; $this->autoGenerate = $autoGenerate; } /** * Gets a reference proxy instance for the entity of the given type and identified by * the given identifier. * * @param string $className * @param array $identifier * * @return \Doctrine\Common\Proxy\Proxy */ public function getProxy($className, array $identifier) { $definition = isset($this->definitions[$className]) ? $this->definitions[$className] : $this->getProxyDefinition($className); $fqcn = $definition->proxyClassName; $proxy = new $fqcn($definition->initializer, $definition->cloner); foreach ($definition->identifierFields as $idField) { $definition->reflectionFields[$idField]->setValue($proxy, $identifier[$idField]); } return $proxy; } /** * Generates proxy classes for all given classes. * * @param \Doctrine\Common\Persistence\Mapping\ClassMetadata[] $classes The classes (ClassMetadata instances) * for which to generate proxies. * @param string $proxyDir The target directory of the proxy classes. If not specified, the * directory configured on the Configuration of the EntityManager used * by this factory is used. * @return int Number of generated proxies. */ public function generateProxyClasses(array $classes, $proxyDir = null) { $generated = 0; foreach ($classes as $class) { if ($this->skipClass($class)) { continue; } $proxyFileName = $this->proxyGenerator->getProxyFileName($class->getName(), $proxyDir); $this->proxyGenerator->generateProxyClass($class, $proxyFileName); $generated += 1; } return $generated; } /** * Reset initialization/cloning logic for an un-initialized proxy * * @param \Doctrine\Common\Proxy\Proxy $proxy * * @return \Doctrine\Common\Proxy\Proxy * * @throws \Doctrine\Common\Proxy\Exception\InvalidArgumentException */ public function resetUninitializedProxy(Proxy $proxy) { if ($proxy->__isInitialized()) { throw InvalidArgumentException::unitializedProxyExpected($proxy); } $className = ClassUtils::getClass($proxy); $definition = isset($this->definitions[$className]) ? $this->definitions[$className] : $this->getProxyDefinition($className); $proxy->__setInitializer($definition->initializer); $proxy->__setCloner($definition->cloner); return $proxy; } /** * Get a proxy definition for the given class name. * * @return ProxyDefinition */ private function getProxyDefinition($className) { $classMetadata = $this->metadataFactory->getMetadataFor($className); $className = $classMetadata->getName(); // aliases and case sensitivity $this->definitions[$className] = $this->createProxyDefinition($className); $proxyClassName = $this->definitions[$className]->proxyClassName; if ( ! class_exists($proxyClassName, false)) { $fileName = $this->proxyGenerator->getProxyFileName($className); if ($this->autoGenerate) { $this->proxyGenerator->generateProxyClass($classMetadata); } require $fileName; } return $this->definitions[$className]; } /** * Determine if this class should be skipped during proxy generation. * * @param \Doctrine\Common\Persistence\Mapping\ClassMetadata $metadata * @return bool */ abstract protected function skipClass(ClassMetadata $metadata); /** * @return ProxyDefinition */ abstract protected function createProxyDefinition($className); } lib/Doctrine/Common/Proxy/Autoloader.php000064400000006457144760112570014265 0ustar00. */ namespace Doctrine\Common\Proxy; use Doctrine\Common\Proxy\Exception\InvalidArgumentException; /** * Special Autoloader for Proxy classes, which are not PSR-0 compliant. * * @author Benjamin Eberlei */ class Autoloader { /** * Resolves proxy class name to a filename based on the following pattern. * * 1. Remove Proxy namespace from class name * 2. Remove namespace separators from remaining class name. * 3. Return PHP filename from proxy-dir with the result from 2. * * @param string $proxyDir * @param string $proxyNamespace * @param string $className * * @return string * * @throws InvalidArgumentException */ public static function resolveFile($proxyDir, $proxyNamespace, $className) { if (0 !== strpos($className, $proxyNamespace)) { throw InvalidArgumentException::notProxyClass($className, $proxyNamespace); } $className = str_replace('\\', '', substr($className, strlen($proxyNamespace) + 1)); return $proxyDir . DIRECTORY_SEPARATOR . $className . '.php'; } /** * Register and return autoloader callback for the given proxy dir and * namespace. * * @param string $proxyDir * @param string $proxyNamespace * @param callable $notFoundCallback Invoked when the proxy file is not found. * * @return \Closure * * @throws InvalidArgumentException */ public static function register($proxyDir, $proxyNamespace, $notFoundCallback = null) { $proxyNamespace = ltrim($proxyNamespace, '\\'); if ( ! (null === $notFoundCallback || is_callable($notFoundCallback))) { throw InvalidArgumentException::invalidClassNotFoundCallback($notFoundCallback); } $autoloader = function ($className) use ($proxyDir, $proxyNamespace, $notFoundCallback) { if (0 === strpos($className, $proxyNamespace)) { $file = Autoloader::resolveFile($proxyDir, $proxyNamespace, $className); if ($notFoundCallback && ! file_exists($file)) { call_user_func($notFoundCallback, $proxyDir, $proxyNamespace, $className); } require $file; } }; spl_autoload_register($autoloader); return $autoloader; } } lib/Doctrine/Common/Proxy/Exception/InvalidArgumentException.php000064400000005510144760112570021061 0ustar00. */ namespace Doctrine\Common\Proxy\Exception; use Doctrine\Common\Persistence\Proxy; use InvalidArgumentException as BaseInvalidArgumentException; /** * Proxy Invalid Argument Exception * * @link www.doctrine-project.com * @since 2.4 * @author Marco Pivetta */ class InvalidArgumentException extends BaseInvalidArgumentException implements ProxyException { /** * @return self */ public static function proxyDirectoryRequired() { return new self('You must configure a proxy directory. See docs for details'); } /** * @param string $className * @param string $proxyNamespace * * @return self */ public static function notProxyClass($className, $proxyNamespace) { return new self(sprintf('The class "%s" is not part of the proxy namespace "%s"', $className, $proxyNamespace)); } /** * @param string $name * * @return self */ public static function invalidPlaceholder($name) { return new self(sprintf('Provided placeholder for "%s" must be either a string or a valid callable', $name)); } /** * @return self */ public static function proxyNamespaceRequired() { return new self('You must configure a proxy namespace'); } /** * @return self */ public static function unitializedProxyExpected(Proxy $proxy) { return new self(sprintf('Provided proxy of type "%s" must not be initialized.', get_class($proxy))); } /** * @param mixed $callback * * @return self */ public static function invalidClassNotFoundCallback($callback) { $type = is_object($callback) ? get_class($callback) : gettype($callback); return new self(sprintf('Invalid \$notFoundCallback given: must be a callable, "%s" given', $type)); } } lib/Doctrine/Common/Proxy/Exception/ProxyException.php000064400000002322144760112570017107 0ustar00. */ namespace Doctrine\Common\Proxy\Exception; /** * Base exception interface for proxy exceptions * * @link www.doctrine-project.com * @since 2.4 * @author Marco Pivetta */ interface ProxyException { } lib/Doctrine/Common/Proxy/Exception/UnexpectedValueException.php000064400000004043144760112570021071 0ustar00. */ namespace Doctrine\Common\Proxy\Exception; use UnexpectedValueException as BaseUnexpectedValueException; /** * Proxy Unexpected Value Exception * * @link www.doctrine-project.com * @since 2.4 * @author Marco Pivetta */ class UnexpectedValueException extends BaseUnexpectedValueException implements ProxyException { /** * @return self */ public static function proxyDirectoryNotWritable() { return new self('Your proxy directory must be writable'); } /** * @param string $className * @param string $methodName * @param string $parameterName * * @return self */ public static function invalidParameterTypeHint($className, $methodName, $parameterName, \Exception $previous) { return new self( sprintf( 'The type hint of parameter "%s" in method "%s" in class "%s" is invalid.', $parameterName, $methodName, $className ), 0, $previous ); } } lib/Doctrine/Common/Proxy/Proxy.php000064400000005362144760112570013301 0ustar00. */ namespace Doctrine\Common\Proxy; use Doctrine\Common\Persistence\Proxy as BaseProxy; use Closure; /** * Interface for proxy classes. * * @author Roman Borschel * @author Marco Pivetta * @since 2.4 */ interface Proxy extends BaseProxy { /** * Marks the proxy as initialized or not. * * @param boolean $initialized */ public function __setInitialized($initialized); /** * Set the initializer callback to be used when initializing the proxy. That * initializer should accept 3 parameters: $proxy, $method and $params. Those * are respectively the proxy object that is being initialized, the method name * that triggered initialization and the parameters passed to that method * * @param Closure $initializer */ public function __setInitializer(Closure $initializer = null); /** * Retrieves the initializer callback used to initialize the proxy. * @see __setInitializer * * @return Closure|null */ public function __getInitializer(); /** * Set the callback to be used when cloning the proxy. That initializer should accept * a single parameter, which is the cloned proxy instance itself * * @param Closure $cloner */ public function __setCloner(Closure $cloner = null); /** * Retrieves the callback to be used when cloning the proxy. * @see __setCloner * * @return Closure|null */ public function __getCloner(); /** * Retrieves the list of lazy loaded properties for a given proxy * * @return array with keys being the property names, and values being the default values * for those properties */ public function __getLazyProperties(); } lib/Doctrine/Common/Proxy/ProxyDefinition.php000064400000004033144760112570015304 0ustar00. */ namespace Doctrine\Common\Proxy; /** * Definition structure how to create a proxy. * * @author Benjamin Eberlei */ class ProxyDefinition { /** * @var string */ public $proxyClassName; /** * @var array */ public $identifierFields; /** * @var \ReflectionProperty[] */ public $reflectionFields; /** * @var callable */ public $initializer; /** * @var callable */ public $cloner; /** * @param string $proxyClassName * @param array $identifierFields * @param array $reflectionFields * @param callable $initializer * @param callable $cloner */ public function __construct($proxyClassName, array $identifierFields, array $reflectionFields, $initializer, $cloner) { $this->proxyClassName = $proxyClassName; $this->identifierFields = $identifierFields; $this->reflectionFields = $reflectionFields; $this->initializer = $initializer; $this->cloner = $cloner; } } lib/Doctrine/Common/Proxy/ProxyGenerator.php000064400000066324144760112570015155 0ustar00. */ namespace Doctrine\Common\Proxy; use Doctrine\Common\Persistence\Mapping\ClassMetadata; use Doctrine\Common\Util\ClassUtils; use Doctrine\Common\Proxy\Exception\InvalidArgumentException; use Doctrine\Common\Proxy\Exception\UnexpectedValueException; /** * This factory is used to generate proxy classes. It builds proxies from given parameters, a template and class * metadata. * * @author Marco Pivetta * @since 2.4 */ class ProxyGenerator { /** * Used to match very simple id methods that don't need * to be decorated since the identifier is known. */ const PATTERN_MATCH_ID_METHOD = '((public\s)?(function\s{1,}%s\s?\(\)\s{1,})\s{0,}{\s{0,}return\s{0,}\$this->%s;\s{0,}})i'; /** * @var string The namespace that contains all proxy classes. */ private $proxyNamespace; /** * @var string The directory that contains all proxy classes. */ private $proxyDirectory; /** * @var string[]|callable[] map of callables used to fill in placeholders set in the template */ protected $placeholders = array( 'baseProxyInterface' => 'Doctrine\Common\Proxy\Proxy', 'additionalProperties' => '', ); /** * @var string template used as a blueprint to generate proxies */ protected $proxyClassTemplate = '; /** * DO NOT EDIT THIS FILE - IT WAS CREATED BY DOCTRINE\'S PROXY GENERATOR */ class extends \ implements \ { /** * @var \Closure the callback responsible for loading properties in the proxy object. This callback is called with * three parameters, being respectively the proxy object to be initialized, the method that triggered the * initialization process and an array of ordered parameters that were passed to that method. * * @see \Doctrine\Common\Persistence\Proxy::__setInitializer */ public $__initializer__; /** * @var \Closure the callback responsible of loading properties that need to be copied in the cloned object * * @see \Doctrine\Common\Persistence\Proxy::__setCloner */ public $__cloner__; /** * @var boolean flag indicating if this object was already initialized * * @see \Doctrine\Common\Persistence\Proxy::__isInitialized */ public $__isInitialized__ = false; /** * @var array properties to be lazy loaded, with keys being the property * names and values being their default values * * @see \Doctrine\Common\Persistence\Proxy::__getLazyProperties */ public static $lazyPropertiesDefaults = array(); /** * Forces initialization of the proxy */ public function __load() { $this->__initializer__ && $this->__initializer__->__invoke($this, \'__load\', array()); } /** * {@inheritDoc} * @internal generated method: use only when explicitly handling proxy specific loading logic */ public function __isInitialized() { return $this->__isInitialized__; } /** * {@inheritDoc} * @internal generated method: use only when explicitly handling proxy specific loading logic */ public function __setInitialized($initialized) { $this->__isInitialized__ = $initialized; } /** * {@inheritDoc} * @internal generated method: use only when explicitly handling proxy specific loading logic */ public function __setInitializer(\Closure $initializer = null) { $this->__initializer__ = $initializer; } /** * {@inheritDoc} * @internal generated method: use only when explicitly handling proxy specific loading logic */ public function __getInitializer() { return $this->__initializer__; } /** * {@inheritDoc} * @internal generated method: use only when explicitly handling proxy specific loading logic */ public function __setCloner(\Closure $cloner = null) { $this->__cloner__ = $cloner; } /** * {@inheritDoc} * @internal generated method: use only when explicitly handling proxy specific cloning logic */ public function __getCloner() { return $this->__cloner__; } /** * {@inheritDoc} * @internal generated method: use only when explicitly handling proxy specific loading logic * @static */ public function __getLazyProperties() { return self::$lazyPropertiesDefaults; } } '; /** * Initializes a new instance of the ProxyFactory class that is * connected to the given EntityManager. * * @param string $proxyDirectory The directory to use for the proxy classes. It must exist. * @param string $proxyNamespace The namespace to use for the proxy classes. * * @throws InvalidArgumentException */ public function __construct($proxyDirectory, $proxyNamespace) { if ( ! $proxyDirectory) { throw InvalidArgumentException::proxyDirectoryRequired(); } if ( ! $proxyNamespace) { throw InvalidArgumentException::proxyNamespaceRequired(); } $this->proxyDirectory = $proxyDirectory; $this->proxyNamespace = $proxyNamespace; } /** * Set a placeholder to be replaced in the template * * @param string $name * @param string|callable $placeholder * * @throws InvalidArgumentException */ public function setPlaceholder($name, $placeholder) { if ( ! is_string($placeholder) && ! is_callable($placeholder)) { throw InvalidArgumentException::invalidPlaceholder($name); } $this->placeholders[$name] = $placeholder; } /** * Set the base template used to create proxy classes * * @param string $proxyClassTemplate */ public function setProxyClassTemplate($proxyClassTemplate) { $this->proxyClassTemplate = (string) $proxyClassTemplate; } /** * Generates a proxy class file. * * @param \Doctrine\Common\Persistence\Mapping\ClassMetadata $class Metadata for the original class * @param string $fileName Filename (full path) for the generated class * * @throws UnexpectedValueException */ public function generateProxyClass(ClassMetadata $class, $fileName = null) { preg_match_all('(<([a-zA-Z]+)>)', $this->proxyClassTemplate, $placeholderMatches); $placeholderMatches = array_combine($placeholderMatches[0], $placeholderMatches[1]); $placeholders = array(); foreach ($placeholderMatches as $placeholder => $name) { $placeholders[$placeholder] = isset($this->placeholders[$name]) ? $this->placeholders[$name] : array($this, 'generate' . $name); } foreach ($placeholders as & $placeholder) { if (is_callable($placeholder)) { $placeholder = call_user_func($placeholder, $class); } } $proxyCode = strtr($this->proxyClassTemplate, $placeholders); $fileName = $fileName ?: $this->getProxyFileName($class->getName()); $parentDirectory = dirname($fileName); if ( ! is_dir($parentDirectory) && (false === @mkdir($parentDirectory, 0775, true))) { throw UnexpectedValueException::proxyDirectoryNotWritable(); } if ( ! is_writable($parentDirectory)) { throw UnexpectedValueException::proxyDirectoryNotWritable(); } $tmpFileName = $fileName . '.' . uniqid('', true); file_put_contents($tmpFileName, $proxyCode); rename($tmpFileName, $fileName); } /** * Generates the proxy short class name to be used in the template * * @param \Doctrine\Common\Persistence\Mapping\ClassMetadata $class * * @return string */ private function generateProxyShortClassName(ClassMetadata $class) { $proxyClassName = ClassUtils::generateProxyClassName($class->getName(), $this->proxyNamespace); $parts = explode('\\', strrev($proxyClassName), 2); return strrev($parts[0]); } /** * Generates the proxy namespace * * @param \Doctrine\Common\Persistence\Mapping\ClassMetadata $class * * @return string */ private function generateNamespace(ClassMetadata $class) { $proxyClassName = ClassUtils::generateProxyClassName($class->getName(), $this->proxyNamespace); $parts = explode('\\', strrev($proxyClassName), 2); return strrev($parts[1]); } /** * Generates the original class name * * @param \Doctrine\Common\Persistence\Mapping\ClassMetadata $class * * @return string */ private function generateClassName(ClassMetadata $class) { return ltrim($class->getName(), '\\'); } /** * Generates the array representation of lazy loaded public properties and their default values * * @param \Doctrine\Common\Persistence\Mapping\ClassMetadata $class * * @return string */ private function generateLazyPropertiesDefaults(ClassMetadata $class) { $lazyPublicProperties = $this->getLazyLoadedPublicProperties($class); $values = array(); foreach ($lazyPublicProperties as $key => $value) { $values[] = var_export($key, true) . ' => ' . var_export($value, true); } return implode(', ', $values); } /** * Generates the constructor code (un-setting public lazy loaded properties, setting identifier field values) * * @param \Doctrine\Common\Persistence\Mapping\ClassMetadata $class * * @return string */ private function generateConstructorImpl(ClassMetadata $class) { $constructorImpl = <<<'EOT' /** * @param \Closure $initializer * @param \Closure $cloner */ public function __construct($initializer = null, $cloner = null) { EOT; $toUnset = array(); foreach ($this->getLazyLoadedPublicProperties($class) as $lazyPublicProperty => $unused) { $toUnset[] = '$this->' . $lazyPublicProperty; } $constructorImpl .= (empty($toUnset) ? '' : ' unset(' . implode(', ', $toUnset) . ");\n") . <<<'EOT' $this->__initializer__ = $initializer; $this->__cloner__ = $cloner; } EOT; return $constructorImpl; } /** * Generates the magic getter invoked when lazy loaded public properties are requested * * @param \Doctrine\Common\Persistence\Mapping\ClassMetadata $class * * @return string */ private function generateMagicGet(ClassMetadata $class) { $lazyPublicProperties = array_keys($this->getLazyLoadedPublicProperties($class)); $hasParentGet = $class->getReflectionClass()->hasMethod('__get'); if (empty($lazyPublicProperties) && ! $hasParentGet) { return ''; } $inheritDoc = $hasParentGet ? '{@inheritDoc}' : ''; $magicGet = <<__getLazyProperties())) { $this->__initializer__ && $this->__initializer__->__invoke($this, '__get', array($name)); return $this->$name; } EOT; } if ($hasParentGet) { $magicGet .= <<<'EOT' $this->__initializer__ && $this->__initializer__->__invoke($this, '__get', array($name)); return parent::__get($name); EOT; } else { $magicGet .= <<<'EOT' trigger_error(sprintf('Undefined property: %s::$%s', __CLASS__, $name), E_USER_NOTICE); EOT; } $magicGet .= " }"; return $magicGet; } /** * Generates the magic setter (currently unused) * * @param \Doctrine\Common\Persistence\Mapping\ClassMetadata $class * * @return string */ private function generateMagicSet(ClassMetadata $class) { $lazyPublicProperties = $this->getLazyLoadedPublicProperties($class); $hasParentSet = $class->getReflectionClass()->hasMethod('__set'); if (empty($lazyPublicProperties) && ! $hasParentSet) { return ''; } $inheritDoc = $hasParentSet ? '{@inheritDoc}' : ''; $magicSet = <<__getLazyProperties())) { $this->__initializer__ && $this->__initializer__->__invoke($this, '__set', array($name, $value)); $this->$name = $value; return; } EOT; } if ($hasParentSet) { $magicSet .= <<<'EOT' $this->__initializer__ && $this->__initializer__->__invoke($this, '__set', array($name, $value)); return parent::__set($name, $value); EOT; } else { $magicSet .= " \$this->\$name = \$value;"; } $magicSet .= "\n }"; return $magicSet; } /** * Generates the magic issetter invoked when lazy loaded public properties are checked against isset() * * @param \Doctrine\Common\Persistence\Mapping\ClassMetadata $class * * @return string */ private function generateMagicIsset(ClassMetadata $class) { $lazyPublicProperties = array_keys($this->getLazyLoadedPublicProperties($class)); $hasParentIsset = $class->getReflectionClass()->hasMethod('__isset'); if (empty($lazyPublicProperties) && ! $hasParentIsset) { return ''; } $inheritDoc = $hasParentIsset ? '{@inheritDoc}' : ''; $magicIsset = <<__getLazyProperties())) { $this->__initializer__ && $this->__initializer__->__invoke($this, '__isset', array($name)); return isset($this->$name); } EOT; } if ($hasParentIsset) { $magicIsset .= <<<'EOT' $this->__initializer__ && $this->__initializer__->__invoke($this, '__isset', array($name)); return parent::__isset($name); EOT; } else { $magicIsset .= " return false;"; } return $magicIsset . "\n }"; } /** * Generates implementation for the `__sleep` method of proxies. * * @param \Doctrine\Common\Persistence\Mapping\ClassMetadata $class * * @return string */ private function generateSleepImpl(ClassMetadata $class) { $hasParentSleep = $class->getReflectionClass()->hasMethod('__sleep'); $inheritDoc = $hasParentSleep ? '{@inheritDoc}' : ''; $sleepImpl = <<__isInitialized__) { $properties = array_diff($properties, array_keys($this->__getLazyProperties())); } return $properties; } EOT; } $allProperties = array('__isInitialized__'); /* @var $prop \ReflectionProperty */ foreach ($class->getReflectionClass()->getProperties() as $prop) { $allProperties[] = $prop->getName(); } $lazyPublicProperties = array_keys($this->getLazyLoadedPublicProperties($class)); $protectedProperties = array_diff($allProperties, $lazyPublicProperties); foreach ($allProperties as &$property) { $property = var_export($property, true); } foreach ($protectedProperties as &$property) { $property = var_export($property, true); } $allProperties = implode(', ', $allProperties); $protectedProperties = implode(', ', $protectedProperties); return $sleepImpl . <<__isInitialized__) { return array($allProperties); } return array($protectedProperties); } EOT; } /** * Generates implementation for the `__wakeup` method of proxies. * * @param \Doctrine\Common\Persistence\Mapping\ClassMetadata $class * * @return string */ private function generateWakeupImpl(ClassMetadata $class) { $unsetPublicProperties = array(); $hasWakeup = $class->getReflectionClass()->hasMethod('__wakeup'); foreach (array_keys($this->getLazyLoadedPublicProperties($class)) as $lazyPublicProperty) { $unsetPublicProperties[] = '$this->' . $lazyPublicProperty; } $shortName = $this->generateProxyShortClassName($class); $inheritDoc = $hasWakeup ? '{@inheritDoc}' : ''; $wakeupImpl = <<__isInitialized__) { \$this->__initializer__ = function ($shortName \$proxy) { \$proxy->__setInitializer(null); \$proxy->__setCloner(null); \$existingProperties = get_object_vars(\$proxy); foreach (\$proxy->__getLazyProperties() as \$property => \$defaultValue) { if ( ! array_key_exists(\$property, \$existingProperties)) { \$proxy->\$property = \$defaultValue; } } }; EOT; if ( ! empty($unsetPublicProperties)) { $wakeupImpl .= "\n unset(" . implode(', ', $unsetPublicProperties) . ");"; } $wakeupImpl .= "\n }"; if ($hasWakeup) { $wakeupImpl .= "\n parent::__wakeup();"; } $wakeupImpl .= "\n }"; return $wakeupImpl; } /** * Generates implementation for the `__clone` method of proxies. * * @param \Doctrine\Common\Persistence\Mapping\ClassMetadata $class * * @return string */ private function generateCloneImpl(ClassMetadata $class) { $hasParentClone = $class->getReflectionClass()->hasMethod('__clone'); $inheritDoc = $hasParentClone ? '{@inheritDoc}' : ''; $callParentClone = $hasParentClone ? "\n parent::__clone();\n" : ''; return <<__cloner__ && \$this->__cloner__->__invoke(\$this, '__clone', array()); $callParentClone } EOT; } /** * Generates decorated methods by picking those available in the parent class * * @param \Doctrine\Common\Persistence\Mapping\ClassMetadata $class * * @return string */ private function generateMethods(ClassMetadata $class) { $methods = ''; $methodNames = array(); $reflectionMethods = $class->getReflectionClass()->getMethods(\ReflectionMethod::IS_PUBLIC); $skippedMethods = array( '__sleep' => true, '__clone' => true, '__wakeup' => true, '__get' => true, '__set' => true, '__isset' => true, ); foreach ($reflectionMethods as $method) { $name = $method->getName(); if ( $method->isConstructor() || isset($skippedMethods[strtolower($name)]) || isset($methodNames[$name]) || $method->isFinal() || $method->isStatic() || ( ! $method->isPublic()) ) { continue; } $methodNames[$name] = true; $methods .= "\n /**\n" . " * {@inheritDoc}\n" . " */\n" . ' public function '; if ($method->returnsReference()) { $methods .= '&'; } $methods .= $name . '('; $firstParam = true; $parameterString = ''; $argumentString = ''; $parameters = array(); foreach ($method->getParameters() as $param) { if ($firstParam) { $firstParam = false; } else { $parameterString .= ', '; $argumentString .= ', '; } try { $paramClass = $param->getClass(); } catch (\ReflectionException $previous) { throw UnexpectedValueException::invalidParameterTypeHint( $class->getName(), $method->getName(), $param->getName(), $previous ); } // We need to pick the type hint class too if (null !== $paramClass) { $parameterString .= '\\' . $paramClass->getName() . ' '; } elseif ($param->isArray()) { $parameterString .= 'array '; } elseif (method_exists($param, 'isCallable') && $param->isCallable()) { $parameterString .= 'callable '; } if ($param->isPassedByReference()) { $parameterString .= '&'; } $parameters[] = '$' . $param->getName(); $parameterString .= '$' . $param->getName(); $argumentString .= '$' . $param->getName(); if ($param->isDefaultValueAvailable()) { $parameterString .= ' = ' . var_export($param->getDefaultValue(), true); } } $methods .= $parameterString . ')'; $methods .= "\n" . ' {' . "\n"; if ($this->isShortIdentifierGetter($method, $class)) { $identifier = lcfirst(substr($name, 3)); $fieldType = $class->getTypeOfField($identifier); $cast = in_array($fieldType, array('integer', 'smallint')) ? '(int) ' : ''; $methods .= ' if ($this->__isInitialized__ === false) {' . "\n"; $methods .= ' return ' . $cast . ' parent::' . $method->getName() . "();\n"; $methods .= ' }' . "\n\n"; } $methods .= "\n \$this->__initializer__ " . "&& \$this->__initializer__->__invoke(\$this, " . var_export($name, true) . ", array(" . implode(', ', $parameters) . "));" . "\n\n return parent::" . $name . '(' . $argumentString . ');' . "\n" . ' }' . "\n"; } return $methods; } /** * Generate the Proxy file name * * @param string $className * @param string $baseDirectory Optional base directory for proxy file name generation. * If not specified, the directory configured on the Configuration of the * EntityManager will be used by this factory. * * @return string */ public function getProxyFileName($className, $baseDirectory = null) { $baseDirectory = $baseDirectory ?: $this->proxyDirectory; return rtrim($baseDirectory, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . Proxy::MARKER . str_replace('\\', '', $className) . '.php'; } /** * Check if the method is a short identifier getter. * * What does this mean? For proxy objects the identifier is already known, * however accessing the getter for this identifier usually triggers the * lazy loading, leading to a query that may not be necessary if only the * ID is interesting for the userland code (for example in views that * generate links to the entity, but do not display anything else). * * @param \ReflectionMethod $method * @param \Doctrine\Common\Persistence\Mapping\ClassMetadata $class * * @return boolean */ private function isShortIdentifierGetter($method, ClassMetadata $class) { $identifier = lcfirst(substr($method->getName(), 3)); $startLine = $method->getStartLine(); $endLine = $method->getEndLine(); $cheapCheck = ( $method->getNumberOfParameters() == 0 && substr($method->getName(), 0, 3) == 'get' && in_array($identifier, $class->getIdentifier(), true) && $class->hasField($identifier) && (($endLine - $startLine) <= 4) ); if ($cheapCheck) { $code = file($method->getDeclaringClass()->getFileName()); $code = trim(implode(' ', array_slice($code, $startLine - 1, $endLine - $startLine + 1))); $pattern = sprintf(self::PATTERN_MATCH_ID_METHOD, $method->getName(), $identifier); if (preg_match($pattern, $code)) { return true; } } return false; } /** * Generates the list of public properties to be lazy loaded, with their default values * * @param \Doctrine\Common\Persistence\Mapping\ClassMetadata $class * * @return mixed[] */ private function getLazyLoadedPublicProperties(ClassMetadata $class) { $defaultProperties = $class->getReflectionClass()->getDefaultProperties(); $properties = array(); foreach ($class->getReflectionClass()->getProperties(\ReflectionProperty::IS_PUBLIC) as $property) { $name = $property->getName(); if (($class->hasField($name) || $class->hasAssociation($name)) && ! $class->isIdentifier($name)) { $properties[$name] = $defaultProperties[$name]; } } return $properties; } } lib/Doctrine/Common/Reflection/ClassFinderInterface.php000064400000002533144760112570017144 0ustar00. */ namespace Doctrine\Common\Reflection; /** * Finds a class in a PSR-0 structure. * * @author Karoly Negyesi */ interface ClassFinderInterface { /** * Finds a class. * * @param string $class The name of the class. * * @return * The name of the class or NULL if not found. */ public function findFile($class); } lib/Doctrine/Common/Reflection/Psr0FindFile.php000064400000005210144760112570015346 0ustar00. */ namespace Doctrine\Common\Reflection; /** * Finds a class in a PSR-0 structure. * * @author Karoly Negyesi */ class Psr0FindFile implements ClassFinderInterface { /** * The PSR-0 prefixes. * * @var string */ protected $prefixes; /** * @param string $prefixes * An array of prefixes. Each key is a PHP namespace and each value is * a list of directories. */ public function __construct($prefixes) { $this->prefixes = $prefixes; } /** * Finds a class. * * @param string $class The name of the class. * * @return * The name of the class or NULL if not found. */ public function findFile($class) { $lastNsPos = strrpos($class, '\\'); if ('\\' == $class[0]) { $class = substr($class, 1); } if (false !== $lastNsPos) { // namespaced class name $classPath = str_replace('\\', DIRECTORY_SEPARATOR, substr($class, 0, $lastNsPos)) . DIRECTORY_SEPARATOR; $className = substr($class, $lastNsPos + 1); } else { // PEAR-like class name $classPath = null; $className = $class; } $classPath .= str_replace('_', DIRECTORY_SEPARATOR, $className) . '.php'; foreach ($this->prefixes as $prefix => $dirs) { if (0 === strpos($class, $prefix)) { foreach ($dirs as $dir) { if (is_file($dir . DIRECTORY_SEPARATOR . $classPath)) { return $dir . DIRECTORY_SEPARATOR . $classPath; } } } } } } lib/Doctrine/Common/Reflection/ReflectionProviderInterface.php000064400000003017144760112570020552 0ustar00. */ namespace Doctrine\Common\Reflection; interface ReflectionProviderInterface { /** * Get the ReflectionClass equivalent for this class. * * @return ReflectionClass */ public function getReflectionClass(); /** * Get the ReflectionClass equivalent for this class. * * @return ReflectionMethod */ public function getReflectionMethod($name); /** * Get the ReflectionClass equivalent for this class. * * @return ReflectionMethod */ public function getReflectionProperty($name); } lib/Doctrine/Common/Reflection/RuntimePublicReflectionProperty.php000064400000005176144760112570021476 0ustar00. */ namespace Doctrine\Common\Reflection; use ReflectionProperty; use Doctrine\Common\Proxy\Proxy; /** * PHP Runtime Reflection Public Property - special overrides for public properties * * @author Marco Pivetta * @since 2.4 */ class RuntimePublicReflectionProperty extends ReflectionProperty { /** * {@inheritDoc} * * Checks is the value actually exist before fetching it. * This is to avoid calling `__get` on the provided $object if it * is a {@see \Doctrine\Common\Proxy\Proxy}. */ public function getValue($object = null) { $name = $this->getName(); if ($object instanceof Proxy && ! $object->__isInitialized()) { $originalInitializer = $object->__getInitializer(); $object->__setInitializer(null); $val = isset($object->$name) ? $object->$name : null; $object->__setInitializer($originalInitializer); return $val; } return isset($object->$name) ? parent::getValue($object) : null; } /** * {@inheritDoc} * * Avoids triggering lazy loading via `__set` if the provided object * is a {@see \Doctrine\Common\Proxy\Proxy}. * @link https://bugs.php.net/bug.php?id=63463 */ public function setValue($object, $value = null) { if ( ! ($object instanceof Proxy && ! $object->__isInitialized())) { parent::setValue($object, $value); return; } $originalInitializer = $object->__getInitializer(); $object->__setInitializer(null); parent::setValue($object, $value); $object->__setInitializer($originalInitializer); } } lib/Doctrine/Common/Reflection/StaticReflectionClass.php000064400000014504144760112570017357 0ustar00. */ namespace Doctrine\Common\Reflection; use ReflectionClass; use ReflectionException; class StaticReflectionClass extends ReflectionClass { /** * The static reflection parser object. * * @var StaticReflectionParser */ private $staticReflectionParser; public function __construct(StaticReflectionParser $staticReflectionParser) { $this->staticReflectionParser = $staticReflectionParser; } public function getName() { return $this->staticReflectionParser->getClassName(); } public function getDocComment() { return $this->staticReflectionParser->getDocComment(); } public function getNamespaceName() { return $this->staticReflectionParser->getNamespaceName(); } public function getUseStatements() { return $this->staticReflectionParser->getUseStatements(); } public function getMethod($name) { return $this->staticReflectionParser->getReflectionMethod($name); } public function getProperty($name) { return $this->staticReflectionParser->getReflectionProperty($name); } public static function export($argument, $return = false) { throw new ReflectionException('Method not implemented'); } public function getConstant($name) { throw new ReflectionException('Method not implemented'); } public function getConstants() { throw new ReflectionException('Method not implemented'); } public function getConstructor() { throw new ReflectionException('Method not implemented'); } public function getDefaultProperties() { throw new ReflectionException('Method not implemented'); } public function getEndLine() { throw new ReflectionException('Method not implemented'); } public function getExtension() { throw new ReflectionException('Method not implemented'); } public function getExtensionName() { throw new ReflectionException('Method not implemented'); } public function getFileName() { throw new ReflectionException('Method not implemented'); } public function getInterfaceNames() { throw new ReflectionException('Method not implemented'); } public function getInterfaces() { throw new ReflectionException('Method not implemented'); } public function getMethods($filter = NULL) { throw new ReflectionException('Method not implemented'); } public function getModifiers() { throw new ReflectionException('Method not implemented'); } public function getParentClass() { throw new ReflectionException('Method not implemented'); } public function getProperties($filter = NULL) { throw new ReflectionException('Method not implemented'); } public function getShortName() { throw new ReflectionException('Method not implemented'); } public function getStartLine() { throw new ReflectionException('Method not implemented'); } public function getStaticProperties() { throw new ReflectionException('Method not implemented'); } public function getStaticPropertyValue($name, $default = '') { throw new ReflectionException('Method not implemented'); } public function getTraitAliases() { throw new ReflectionException('Method not implemented'); } public function getTraitNames() { throw new ReflectionException('Method not implemented'); } public function getTraits() { throw new ReflectionException('Method not implemented'); } public function hasConstant($name) { throw new ReflectionException('Method not implemented'); } public function hasMethod($name) { throw new ReflectionException('Method not implemented'); } public function hasProperty($name) { throw new ReflectionException('Method not implemented'); } public function implementsInterface($interface) { throw new ReflectionException('Method not implemented'); } public function inNamespace() { throw new ReflectionException('Method not implemented'); } public function isAbstract() { throw new ReflectionException('Method not implemented'); } public function isCloneable() { throw new ReflectionException('Method not implemented'); } public function isFinal() { throw new ReflectionException('Method not implemented'); } public function isInstance($object) { throw new ReflectionException('Method not implemented'); } public function isInstantiable() { throw new ReflectionException('Method not implemented'); } public function isInterface() { throw new ReflectionException('Method not implemented'); } public function isInternal() { throw new ReflectionException('Method not implemented'); } public function isIterateable() { throw new ReflectionException('Method not implemented'); } public function isSubclassOf($class) { throw new ReflectionException('Method not implemented'); } public function isTrait() { throw new ReflectionException('Method not implemented'); } public function isUserDefined() { throw new ReflectionException('Method not implemented'); } public function newInstance($args) { throw new ReflectionException('Method not implemented'); } public function newInstanceArgs(array $args = array()) { throw new ReflectionException('Method not implemented'); } public function newInstanceWithoutConstructor() { throw new ReflectionException('Method not implemented'); } public function setStaticPropertyValue($name, $value) { throw new ReflectionException('Method not implemented'); } public function __toString() { throw new ReflectionException('Method not implemented'); } } lib/Doctrine/Common/Reflection/StaticReflectionMethod.php000064400000012757144760112570017542 0ustar00. */ namespace Doctrine\Common\Reflection; use ReflectionMethod; use ReflectionException; class StaticReflectionMethod extends ReflectionMethod { /** * The PSR-0 parser object. * * @var StaticReflectionParser */ protected $staticReflectionParser; /** * The name of the method. * * @var string */ protected $methodName; public function __construct(StaticReflectionParser $staticReflectionParser, $methodName) { $this->staticReflectionParser = $staticReflectionParser; $this->methodName = $methodName; } public function getName() { return $this->methodName; } protected function getStaticReflectionParser() { return $this->staticReflectionParser->getStaticReflectionParserForDeclaringClass('method', $this->methodName); } public function getDeclaringClass() { return $this->getStaticReflectionParser()->getReflectionClass(); } public function getNamespaceName() { return $this->getStaticReflectionParser()->getNamespaceName(); } public function getDocComment() { return $this->getStaticReflectionParser()->getDocComment('method', $this->methodName); } public function getUseStatements() { return $this->getStaticReflectionParser()->getUseStatements(); } public static function export($class, $name, $return = false) { throw new ReflectionException('Method not implemented'); } public function getClosure($object) { throw new ReflectionException('Method not implemented'); } public function getModifiers() { throw new ReflectionException('Method not implemented'); } public function getPrototype() { throw new ReflectionException('Method not implemented'); } public function invoke($object, $parameter = NULL) { throw new ReflectionException('Method not implemented'); } public function invokeArgs($object, array $args) { throw new ReflectionException('Method not implemented'); } public function isAbstract() { throw new ReflectionException('Method not implemented'); } public function isConstructor() { throw new ReflectionException('Method not implemented'); } public function isDestructor() { throw new ReflectionException('Method not implemented'); } public function isFinal() { throw new ReflectionException('Method not implemented'); } public function isPrivate() { throw new ReflectionException('Method not implemented'); } public function isProtected() { throw new ReflectionException('Method not implemented'); } public function isPublic() { throw new ReflectionException('Method not implemented'); } public function isStatic() { throw new ReflectionException('Method not implemented'); } public function setAccessible($accessible) { throw new ReflectionException('Method not implemented'); } public function __toString() { throw new ReflectionException('Method not implemented'); } public function getClosureThis() { throw new ReflectionException('Method not implemented'); } public function getEndLine() { throw new ReflectionException('Method not implemented'); } public function getExtension() { throw new ReflectionException('Method not implemented'); } public function getExtensionName() { throw new ReflectionException('Method not implemented'); } public function getFileName() { throw new ReflectionException('Method not implemented'); } public function getNumberOfParameters() { throw new ReflectionException('Method not implemented'); } public function getNumberOfRequiredParameters() { throw new ReflectionException('Method not implemented'); } public function getParameters() { throw new ReflectionException('Method not implemented'); } public function getShortName() { throw new ReflectionException('Method not implemented'); } public function getStartLine() { throw new ReflectionException('Method not implemented'); } public function getStaticVariables() { throw new ReflectionException('Method not implemented'); } public function inNamespace() { throw new ReflectionException('Method not implemented'); } public function isClosure() { throw new ReflectionException('Method not implemented'); } public function isDeprecated() { throw new ReflectionException('Method not implemented'); } public function isInternal() { throw new ReflectionException('Method not implemented'); } public function isUserDefined() { throw new ReflectionException('Method not implemented'); } public function returnsReference() { throw new ReflectionException('Method not implemented'); } } lib/Doctrine/Common/Reflection/StaticReflectionParser.php000064400000022704144760112570017547 0ustar00. */ namespace Doctrine\Common\Reflection; use ReflectionException; use Doctrine\Common\Annotations\TokenParser; /** * Parses a file for namespaces/use/class declarations. * * @author Karoly Negyesi */ class StaticReflectionParser implements ReflectionProviderInterface { /** * The fully qualified class name. * * @var string */ protected $className; /** * The short class name. * * @var string */ protected $shortClassName; /** * TRUE if the caller only wants class annotations. * * @var boolean. */ protected $classAnnotationOptimize; /** * TRUE when the parser has ran. * * @var boolean */ protected $parsed = false; /** * The namespace of the class * * @var string */ protected $namespace = ''; /** * The use statements of this class. * * @var array */ protected $useStatements = array(); /** * The docComment of the class. * * @var string */ protected $docComment = array( 'class' => '', 'property' => array(), 'method' => array(), ); /** * The name of the class this class extends, if any. * * @var string */ protected $parentClassName = ''; /** * The parent PSR-0 Parser. * * @var \Doctrine\Common\Annotations\StaticReflectionParser */ protected $parentStaticReflectionParser; /** * Parses a class residing in a PSR-0 hierarchy. * * @param string $class * The full, namespaced class name. * @param ClassFinder $finder * A ClassFinder object which finds the class. * @param boolean $classAnnotationOptimize * Only retrieve the class docComment. Presumes there is only one * statement per line. */ public function __construct($className, $finder, $classAnnotationOptimize = false) { $this->className = ltrim($className, '\\'); $lastNsPos = strrpos($this->className, '\\'); if ($lastNsPos !== false) { $this->namespace = substr($this->className, 0, $lastNsPos); $this->shortClassName = substr($this->className, $lastNsPos + 1); } else { $this->shortClassName = $this->className; } $this->finder = $finder; $this->classAnnotationOptimize = $classAnnotationOptimize; } protected function parse() { if ($this->parsed || !$fileName = $this->finder->findFile($this->className)) { return; } $this->parsed = true; $contents = file_get_contents($fileName); if ($this->classAnnotationOptimize) { if (preg_match("/(\A.*)^\s+(abstract|final)?\s+class\s+{$this->shortClassName}\s+{/sm", $contents, $matches)) { $contents = $matches[1]; } } $tokenParser = new TokenParser($contents); $docComment = ''; while ($token = $tokenParser->next(false)) { if (is_array($token)) { switch ($token[0]) { case T_USE: $this->useStatements = array_merge($this->useStatements, $tokenParser->parseUseStatement()); break; case T_DOC_COMMENT: $docComment = $token[1]; break; case T_CLASS: $this->docComment['class'] = $docComment; $docComment = ''; break; case T_VAR: case T_PRIVATE: case T_PROTECTED: case T_PUBLIC: $token = $tokenParser->next(); if ($token[0] === T_VARIABLE) { $propertyName = substr($token[1], 1); $this->docComment['property'][$propertyName] = $docComment; continue 2; } if ($token[0] !== T_FUNCTION) { // For example, it can be T_FINAL. continue 2; } // No break. case T_FUNCTION: // The next string after function is the name, but // there can be & before the function name so find the // string. while (($token = $tokenParser->next()) && $token[0] !== T_STRING); $methodName = $token[1]; $this->docComment['method'][$methodName] = $docComment; $docComment = ''; break; case T_EXTENDS: $this->parentClassName = $tokenParser->parseClass(); $nsPos = strpos($this->parentClassName, '\\'); $fullySpecified = false; if ($nsPos === 0) { $fullySpecified = true; } else { if ($nsPos) { $prefix = strtolower(substr($this->parentClassName, 0, $nsPos)); $postfix = substr($this->parentClassName, $nsPos); } else { $prefix = strtolower($this->parentClassName); $postfix = ''; } foreach ($this->useStatements as $alias => $use) { if ($alias == $prefix) { $this->parentClassName = '\\' . $use . $postfix; $fullySpecified = true; } } } if (!$fullySpecified) { $this->parentClassName = '\\' . $this->namespace . '\\' . $this->parentClassName; } break; } } } } protected function getParentStaticReflectionParser() { if (empty($this->parentStaticReflectionParser)) { $this->parentStaticReflectionParser = new static($this->parentClassName, $this->finder); } return $this->parentStaticReflectionParser; } public function getClassName() { return $this->className; } public function getNamespaceName() { return $this->namespace; } /** * Get the ReflectionClass equivalent for this file / class. */ public function getReflectionClass() { return new StaticReflectionClass($this); } /** * Get the ReflectionMethod equivalent for the method of this file / class. */ public function getReflectionMethod($methodName) { return new StaticReflectionMethod($this, $methodName); } /** * Get the ReflectionProperty equivalent for the method of this file / class. */ public function getReflectionProperty($propertyName) { return new StaticReflectionProperty($this, $propertyName); } /** * Get the use statements from this file. */ public function getUseStatements() { $this->parse(); return $this->useStatements; } /** * Get docComment. * * @param string $type class, property or method. * @param string $name Name of the property or method, not needed for class. * * @return string the doc comment or empty string if none. */ public function getDocComment($type = 'class', $name = '') { $this->parse(); return $name ? $this->docComment[$type][$name] : $this->docComment[$type]; } /** * Get the PSR-0 parser for the declaring class. * * @param string $type property or method. * @param string $name Name of the property or method. * * @return StaticReflectionParser A static reflection parser for the declaring class. */ public function getStaticReflectionParserForDeclaringClass($type, $name) { $this->parse(); if (isset($this->docComment[$type][$name])) { return $this; } if (!empty($this->parentClassName)) { return $this->getParentStaticReflectionParser()->getStaticReflectionParserForDeclaringClass($type, $name); } throw new ReflectionException('Invalid ' . $type . ' "' . $name . '"'); } } lib/Doctrine/Common/Reflection/StaticReflectionProperty.php000064400000006443144760112570020141 0ustar00. */ namespace Doctrine\Common\Reflection; use ReflectionProperty; use ReflectionException; class StaticReflectionProperty extends ReflectionProperty { /** * The PSR-0 parser object. * * @var StaticReflectionParser */ protected $staticReflectionParser; /** * The name of the property. * * @var string */ protected $propertyName; public function __construct(StaticReflectionParser $staticReflectionParser, $propertyName) { $this->staticReflectionParser = $staticReflectionParser; $this->propertyName = $propertyName; } public function getName() { return $this->propertyName; } protected function getStaticReflectionParser() { return $this->staticReflectionParser->getStaticReflectionParserForDeclaringClass('property', $this->propertyName); } public function getDeclaringClass() { return $this->getStaticReflectionParser()->getReflectionClass(); } public function getDocComment() { return $this->getStaticReflectionParser()->getDocComment('property', $this->propertyName); } public function getUseStatements() { return $this->getStaticReflectionParser()->getUseStatements(); } public static function export ($class, $name, $return = false) { throw new ReflectionException('Method not implemented'); } public function getModifiers() { throw new ReflectionException('Method not implemented'); } public function getValue($object = NULL) { throw new ReflectionException('Method not implemented'); } public function isDefault() { throw new ReflectionException('Method not implemented'); } public function isPrivate() { throw new ReflectionException('Method not implemented'); } public function isProtected() { throw new ReflectionException('Method not implemented'); } public function isPublic() { throw new ReflectionException('Method not implemented'); } public function isStatic() { throw new ReflectionException('Method not implemented'); } public function setAccessible ($accessible) { throw new ReflectionException('Method not implemented'); } public function setValue ($object, $value = NULL) { throw new ReflectionException('Method not implemented'); } public function __toString() { throw new ReflectionException('Method not implemented'); } } lib/Doctrine/Common/Util/ClassUtils.php000064400000005764144760112570014050 0ustar00. */ namespace Doctrine\Common\Util; use Doctrine\Common\Persistence\Proxy; /** * Class and reflection related functionality for objects that * might or not be proxy objects at the moment. * * @author Benjamin Eberlei * @author Johannes Schmitt */ class ClassUtils { /** * Get the real class name of a class name that could be a proxy. * * @param string * @return string */ public static function getRealClass($class) { if (false === $pos = strrpos($class, '\\'.Proxy::MARKER.'\\')) { return $class; } return substr($class, $pos + Proxy::MARKER_LENGTH + 2); } /** * Get the real class name of an object (even if its a proxy) * * @param object * @return string */ public static function getClass($object) { return self::getRealClass(get_class($object)); } /** * Get the real parent class name of a class or object * * @param string * @return string */ public static function getParentClass($className) { return get_parent_class( self::getRealClass( $className ) ); } /** * Create a new reflection class * * @param string * @return \ReflectionClass */ public static function newReflectionClass($class) { return new \ReflectionClass( self::getRealClass( $class ) ); } /** * Create a new reflection object * * @param object * @return \ReflectionObject */ public static function newReflectionObject($object) { return self::newReflectionClass( self::getClass( $object ) ); } /** * Given a class name and a proxy namespace return the proxy name. * * @param string $className * @param string $proxyNamespace * @return string */ public static function generateProxyClassName($className, $proxyNamespace) { return rtrim($proxyNamespace, '\\') . '\\'.Proxy::MARKER.'\\' . ltrim($className, '\\'); } } lib/Doctrine/Common/Util/Debug.php000064400000011244144760112570012776 0ustar00. */ namespace Doctrine\Common\Util; /** * Static class containing most used debug methods. * * @license http://www.opensource.org/licenses/lgpl-license.php LGPL * @link www.doctrine-project.org * @since 2.0 * @author Guilherme Blanco * @author Jonathan Wage * @author Roman Borschel * @author Giorgio Sironi */ final class Debug { /** * Private constructor (prevents from instantiation) * */ private function __construct() {} /** * Prints a dump of the public, protected and private properties of $var. * * @link http://xdebug.org/ * @param mixed $var * @param integer $maxDepth Maximum nesting level for object properties * @param boolean $stripTags Flag that indicate if output should strip HTML tags */ public static function dump($var, $maxDepth = 2, $stripTags = true) { ini_set('html_errors', 'On'); if (extension_loaded('xdebug')) { ini_set('xdebug.var_display_max_depth', $maxDepth); } $var = self::export($var, $maxDepth++); ob_start(); var_dump($var); $dump = ob_get_contents(); ob_end_clean(); echo ($stripTags ? strip_tags(html_entity_decode($dump)) : $dump); ini_set('html_errors', 'Off'); } /** * Export * * @param mixed $var * @param int $maxDepth * @return mixed */ public static function export($var, $maxDepth) { $return = null; $isObj = is_object($var); if ($isObj && in_array('Doctrine\Common\Collections\Collection', class_implements($var))) { $var = $var->toArray(); } if ($maxDepth) { if (is_array($var)) { $return = array(); foreach ($var as $k => $v) { $return[$k] = self::export($v, $maxDepth - 1); } } else if ($isObj) { $return = new \stdclass(); if ($var instanceof \DateTime) { $return->__CLASS__ = "DateTime"; $return->date = $var->format('c'); $return->timezone = $var->getTimeZone()->getName(); } else { $reflClass = ClassUtils::newReflectionObject($var); $return->__CLASS__ = ClassUtils::getClass($var); if ($var instanceof \Doctrine\Common\Persistence\Proxy) { $return->__IS_PROXY__ = true; $return->__PROXY_INITIALIZED__ = $var->__isInitialized(); } if ($var instanceof \ArrayObject || $var instanceof \ArrayIterator) { $return->__STORAGE__ = self::export($var->getArrayCopy(), $maxDepth - 1); } foreach ($reflClass->getProperties() as $reflProperty) { $name = $reflProperty->getName(); $reflProperty->setAccessible(true); $return->$name = self::export($reflProperty->getValue($var), $maxDepth - 1); } } } else { $return = $var; } } else { $return = is_object($var) ? get_class($var) : (is_array($var) ? 'Array(' . count($var) . ')' : $var); } return $return; } /** * Convert to string * * @param object $obj * @return string */ public static function toString($obj) { return method_exists($obj, '__toString') ? (string) $obj : get_class($obj) . '@' . spl_object_hash($obj); } } lib/Doctrine/Common/Util/Inflector.php000064400000002373144760112570013700 0ustar00. */ namespace Doctrine\Common\Util; use Doctrine\Common\Inflector\Inflector as BaseInflector; /** * Doctrine inflector has static methods for inflecting text * * Kept for backwards compatibility reasons, was moved to its * own component. */ class Inflector extends BaseInflector { } lib/Doctrine/Common/Version.php000064400000003770144760112570012465 0ustar00. */ namespace Doctrine\Common; /** * Class to store and retrieve the version of Doctrine * * @license http://www.opensource.org/licenses/lgpl-license.php LGPL * @link www.doctrine-project.org * @since 2.0 * @version $Revision$ * @author Benjamin Eberlei * @author Guilherme Blanco * @author Jonathan Wage * @author Roman Borschel */ class Version { /** * Current Doctrine Version */ const VERSION = '2.4.0-RC1'; /** * Compares a Doctrine version with the current one. * * @param string $version Doctrine version to compare. * @return int Returns -1 if older, 0 if it is the same, 1 if version * passed as argument is newer. */ public static function compare($version) { $currentVersion = str_replace(' ', '', strtolower(self::VERSION)); $version = str_replace(' ', '', $version); return version_compare($version, $currentVersion); } } phpunit.xml.dist000064400000001462144760112570007731 0ustar00 ./tests/Doctrine/ ./lib/Doctrine/ performance tests/.gitignore000064400000000143144760112570007703 0ustar00Doctrine/Tests/Proxies/ Doctrine/Tests/ORM/Proxy/generated/ Doctrine/Tests/ORM/Tools/Export/export tests/Doctrine/Tests/Common/ClassLoaderTest.php000064400000005027144760112570015567 0ustar00setIncludePath(__DIR__); $classLoader->setFileExtension('.class.php'); $classLoader->setNamespaceSeparator('_'); $this->assertTrue($classLoader->canLoadClass('ClassLoaderTest_ClassA')); $this->assertTrue($classLoader->canLoadClass('ClassLoaderTest_ClassB')); $this->assertTrue($classLoader->canLoadClass('ClassLoaderTest_ClassC')); $this->assertFalse($classLoader->canLoadClass('OtherClass')); $this->assertEquals($classLoader->loadClass('ClassLoaderTest_ClassA'), true); $this->assertEquals($classLoader->loadClass('ClassLoaderTest_ClassB'), true); $this->assertEquals($classLoader->loadClass('ClassLoaderTest_ClassC'), true); } public function testClassExists() { $this->assertFalse(ClassLoader::classExists('ClassLoaderTest\ClassD')); $badLoader = function($className) { require __DIR__ . '/ClassLoaderTest/ClassD.php'; return true; }; spl_autoload_register($badLoader); $this->assertTrue(ClassLoader::classExists('ClassLoaderTest\ClassD')); spl_autoload_unregister($badLoader); } public function testGetClassLoader() { $cl = new ClassLoader('ClassLoaderTest', __DIR__); $cl->register(); $this->assertTrue(ClassLoader::getClassLoader('ClassLoaderTest\ClassD') instanceof \Doctrine\Common\ClassLoader); $this->assertNull(ClassLoader::getClassLoader('This\Class\Does\Not\Exist')); $cl->unregister(); } public function testClassExistsWithSilentAutoloader() { $test = $this; $silentLoader = function ($className) use ($test) { $test->assertSame('ClassLoaderTest\ClassE', $className); require __DIR__ . '/ClassLoaderTest/ClassE.php'; }; $additionalLoader = function () use ($test) { $test->fail('Should not call this loader, class was already loaded'); }; $this->assertFalse(ClassLoader::classExists('ClassLoaderTest\ClassE')); spl_autoload_register($silentLoader); spl_autoload_register($additionalLoader); $this->assertTrue(ClassLoader::classExists('ClassLoaderTest\ClassE')); spl_autoload_unregister($additionalLoader); spl_autoload_unregister($silentLoader); } } tests/Doctrine/Tests/Common/ClassLoaderTest/ClassA.class.php000064400000000050144760112570020030 0ustar00_eventManager = new EventManager; $this->_preFooInvoked = false; $this->_postFooInvoked = false; } public function testInitialState() { $this->assertEquals(array(), $this->_eventManager->getListeners()); $this->assertFalse($this->_eventManager->hasListeners(self::preFoo)); $this->assertFalse($this->_eventManager->hasListeners(self::postFoo)); } public function testAddEventListener() { $this->_eventManager->addEventListener(array('preFoo', 'postFoo'), $this); $this->assertTrue($this->_eventManager->hasListeners(self::preFoo)); $this->assertTrue($this->_eventManager->hasListeners(self::postFoo)); $this->assertEquals(1, count($this->_eventManager->getListeners(self::preFoo))); $this->assertEquals(1, count($this->_eventManager->getListeners(self::postFoo))); $this->assertEquals(2, count($this->_eventManager->getListeners())); } public function testDispatchEvent() { $this->_eventManager->addEventListener(array('preFoo', 'postFoo'), $this); $this->_eventManager->dispatchEvent(self::preFoo); $this->assertTrue($this->_preFooInvoked); $this->assertFalse($this->_postFooInvoked); } public function testRemoveEventListener() { $this->_eventManager->addEventListener(array('preBar'), $this); $this->assertTrue($this->_eventManager->hasListeners(self::preBar)); $this->_eventManager->removeEventListener(array('preBar'), $this); $this->assertFalse($this->_eventManager->hasListeners(self::preBar)); } public function testAddEventSubscriber() { $eventSubscriber = new TestEventSubscriber(); $this->_eventManager->addEventSubscriber($eventSubscriber); $this->assertTrue($this->_eventManager->hasListeners(self::preFoo)); $this->assertTrue($this->_eventManager->hasListeners(self::postFoo)); } /* Listener methods */ public function preFoo(EventArgs $e) { $this->_preFooInvoked = true; } public function postFoo(EventArgs $e) { $this->_postFooInvoked = true; } } class TestEventSubscriber implements \Doctrine\Common\EventSubscriber { public function getSubscribedEvents() { return array('preFoo', 'postFoo'); } }tests/Doctrine/Tests/Common/Persistence/Mapping/ChainDriverTest.php000064400000011717144760112570021453 0ustar00getMock('Doctrine\Common\Persistence\Mapping\ClassMetadata'); $chain = new MappingDriverChain(); $driver1 = $this->getMock('Doctrine\Common\Persistence\Mapping\Driver\MappingDriver'); $driver1->expects($this->never()) ->method('loadMetadataForClass'); $driver1->expectS($this->never()) ->method('isTransient'); $driver2 = $this->getMock('Doctrine\Common\Persistence\Mapping\Driver\MappingDriver'); $driver2->expects($this->at(0)) ->method('loadMetadataForClass') ->with($this->equalTo($className), $this->equalTo($classMetadata)); $driver2->expects($this->at(1)) ->method('isTransient') ->with($this->equalTo($className)) ->will($this->returnValue( true )); $chain->addDriver($driver1, 'Doctrine\Tests\Models\Company'); $chain->addDriver($driver2, 'Doctrine\Tests\Common\Persistence\Mapping'); $chain->loadMetadataForClass($className, $classMetadata); $this->assertTrue( $chain->isTransient($className) ); } public function testLoadMetadata_NoDelegatorFound_ThrowsMappingException() { $className = 'Doctrine\Tests\Common\Persistence\Mapping\DriverChainEntity'; $classMetadata = $this->getMock('Doctrine\Common\Persistence\Mapping\ClassMetadata'); $chain = new MappingDriverChain(); $this->setExpectedException('Doctrine\Common\Persistence\Mapping\MappingException'); $chain->loadMetadataForClass($className, $classMetadata); } public function testGatherAllClassNames() { $className = 'Doctrine\Tests\Common\Persistence\Mapping\DriverChainEntity'; $classMetadata = $this->getMock('Doctrine\Common\Persistence\ClassMetadata'); $chain = new MappingDriverChain(); $driver1 = $this->getMock('Doctrine\Common\Persistence\Mapping\Driver\MappingDriver'); $driver1->expects($this->once()) ->method('getAllClassNames') ->will($this->returnValue(array('Doctrine\Tests\Models\Company\Foo'))); $driver2 = $this->getMock('Doctrine\Common\Persistence\Mapping\Driver\MappingDriver'); $driver2->expects($this->once()) ->method('getAllClassNames') ->will($this->returnValue(array('Doctrine\Tests\ORM\Mapping\Bar', 'Doctrine\Tests\ORM\Mapping\Baz', 'FooBarBaz'))); $chain->addDriver($driver1, 'Doctrine\Tests\Models\Company'); $chain->addDriver($driver2, 'Doctrine\Tests\ORM\Mapping'); $this->assertEquals(array( 'Doctrine\Tests\Models\Company\Foo', 'Doctrine\Tests\ORM\Mapping\Bar', 'Doctrine\Tests\ORM\Mapping\Baz' ), $chain->getAllClassNames()); } /** * @group DDC-706 */ public function testIsTransient() { $driver1 = $this->getMock('Doctrine\Common\Persistence\Mapping\Driver\MappingDriver'); $chain = new MappingDriverChain(); $chain->addDriver($driver1, 'Doctrine\Tests\Models\CMS'); $this->assertTrue($chain->isTransient('stdClass'), "stdClass isTransient"); } /** * @group DDC-1412 */ public function testDefaultDriver() { $companyDriver = $this->getMock('Doctrine\Common\Persistence\Mapping\Driver\MappingDriver'); $defaultDriver = $this->getMock('Doctrine\Common\Persistence\Mapping\Driver\MappingDriver'); $entityClassName = 'Doctrine\Tests\ORM\Mapping\DriverChainEntity'; $managerClassName = 'Doctrine\Tests\Models\Company\CompanyManager'; $chain = new MappingDriverChain(); $companyDriver->expects($this->never()) ->method('loadMetadataForClass'); $companyDriver->expects($this->once()) ->method('isTransient') ->with($this->equalTo($managerClassName)) ->will($this->returnValue(false)); $defaultDriver->expects($this->never()) ->method('loadMetadataForClass'); $defaultDriver->expects($this->once()) ->method('isTransient') ->with($this->equalTo($entityClassName)) ->will($this->returnValue(true)); $this->assertNull($chain->getDefaultDriver()); $chain->setDefaultDriver($defaultDriver); $chain->addDriver($companyDriver, 'Doctrine\Tests\Models\Company'); $this->assertSame($defaultDriver, $chain->getDefaultDriver()); $this->assertTrue($chain->isTransient($entityClassName)); $this->assertFalse($chain->isTransient($managerClassName)); } } class DriverChainEntity { }tests/Doctrine/Tests/Common/Persistence/Mapping/ClassMetadataFactoryTest.php000064400000007551144760112570023314 0ustar00getMock('Doctrine\Common\Persistence\Mapping\Driver\MappingDriver'); $metadata = $this->getMock('Doctrine\Common\Persistence\Mapping\ClassMetadata'); $this->cmf = new TestClassMetadataFactory($driver, $metadata); } public function testGetCacheDriver() { $this->assertNull($this->cmf->getCacheDriver()); $cache = new ArrayCache(); $this->cmf->setCacheDriver($cache); $this->assertSame($cache, $this->cmf->getCacheDriver()); } public function testGetMetadataFor() { $metadata = $this->cmf->getMetadataFor('stdClass'); $this->assertInstanceOf('Doctrine\Common\Persistence\Mapping\ClassMetadata', $metadata); $this->assertTrue($this->cmf->hasMetadataFor('stdClass')); } public function testGetParentMetadata() { $metadata = $this->cmf->getMetadataFor(__NAMESPACE__ . '\ChildEntity'); $this->assertInstanceOf('Doctrine\Common\Persistence\Mapping\ClassMetadata', $metadata); $this->assertTrue($this->cmf->hasMetadataFor(__NAMESPACE__ . '\ChildEntity')); $this->assertTrue($this->cmf->hasMetadataFor(__NAMESPACE__ . '\RootEntity')); } public function testGetCachedMetadata() { $metadata = $this->getMock('Doctrine\Common\Persistence\Mapping\ClassMetadata'); $cache = new ArrayCache(); $cache->save(__NAMESPACE__. '\ChildEntity$CLASSMETADATA', $metadata); $this->cmf->setCacheDriver($cache); $loadedMetadata = $this->cmf->getMetadataFor(__NAMESPACE__ . '\ChildEntity'); $this->assertSame($loadedMetadata, $metadata); } public function testCacheGetMetadataFor() { $cache = new ArrayCache(); $this->cmf->setCacheDriver($cache); $loadedMetadata = $this->cmf->getMetadataFor(__NAMESPACE__ . '\ChildEntity'); $this->assertSame($loadedMetadata, $cache->fetch(__NAMESPACE__. '\ChildEntity$CLASSMETADATA')); } public function testGetAliasedMetadata() { $loadedMetadata = $this->cmf->getMetadataFor('prefix:ChildEntity'); $this->assertTrue($this->cmf->hasMetadataFor(__NAMESPACE__ . '\ChildEntity')); $this->assertTrue($this->cmf->hasMetadataFor('prefix:ChildEntity')); } } class TestClassMetadataFactory extends AbstractClassMetadataFactory { public $driver; public $metadata; public function __construct($driver, $metadata) { $this->driver = $driver; $this->metadata = $metadata; } protected function doLoadMetadata($class, $parent, $rootEntityFound, array $nonSuperclassParents) { } protected function getFqcnFromAlias($namespaceAlias, $simpleClassName) { return __NAMESPACE__ . '\\' . $simpleClassName; } protected function initialize() { } protected function newClassMetadataInstance($className) { return $this->metadata; } protected function getDriver() { return $this->driver; } protected function wakeupReflection(ClassMetadata $class, ReflectionService $reflService) { } protected function initializeReflection(ClassMetadata $class, ReflectionService $reflService) { } protected function isEntity(ClassMetadata $class) { return true; } } class RootEntity { } class ChildEntity extends RootEntity { } tests/Doctrine/Tests/Common/Persistence/Mapping/DefaultFileLocatorTest.php000064400000005365144760112570022767 0ustar00assertEquals(array($path), $locator->getPaths()); $locator = new DefaultFileLocator($path); $this->assertEquals(array($path), $locator->getPaths()); } public function testGetFileExtension() { $locator = new DefaultFileLocator(array(), ".yml"); $this->assertEquals(".yml", $locator->getFileExtension()); $locator->setFileExtension(".xml"); $this->assertEquals(".xml", $locator->getFileExtension()); } public function testUniquePaths() { $path = __DIR__ . "/_files"; $locator = new DefaultFileLocator(array($path, $path)); $this->assertEquals(array($path), $locator->getPaths()); } public function testFindMappingFile() { $path = __DIR__ . "/_files"; $locator = new DefaultFileLocator(array($path), ".yml"); $this->assertEquals(__DIR__ . '/_files' . DIRECTORY_SEPARATOR . 'stdClass.yml', $locator->findMappingFile('stdClass')); } public function testFindMappingFileNotFound() { $path = __DIR__ . "/_files"; $locator = new DefaultFileLocator(array($path), ".yml"); $this->setExpectedException( 'Doctrine\Common\Persistence\Mapping\MappingException', "No mapping file found named 'stdClass2.yml' for class 'stdClass2'" ); $locator->findMappingFile('stdClass2'); } public function testGetAllClassNames() { $path = __DIR__ . "/_files"; $locator = new DefaultFileLocator(array($path), ".yml"); $classes = $locator->getAllClassNames(null); sort($classes); $this->assertEquals(array('global', 'stdClass'), $classes); $this->assertEquals(array('stdClass'), $locator->getAllClassNames("global")); } public function testGetAllClassNamesNonMatchingFileExtension() { $path = __DIR__ . "/_files"; $locator = new DefaultFileLocator(array($path), ".xml"); $this->assertEquals(array(), $locator->getAllClassNames("global")); } public function testFileExists() { $path = __DIR__ . "/_files"; $locator = new DefaultFileLocator(array($path), ".yml"); $this->assertTrue($locator->fileExists("stdClass")); $this->assertFalse($locator->fileExists("stdClass2")); $this->assertTrue($locator->fileExists("global")); $this->assertFalse($locator->fileExists("global2")); } } tests/Doctrine/Tests/Common/Persistence/Mapping/FileDriverTest.php000064400000010661144760112570021305 0ustar00assertNull($driver->getGlobalBasename()); $driver->setGlobalBasename("global"); $this->assertEquals("global", $driver->getGlobalBasename()); } public function testGetElementFromGlobalFile() { $driver = new TestFileDriver($this->newLocator()); $driver->setGlobalBasename("global"); $element = $driver->getElement('stdGlobal'); $this->assertEquals('stdGlobal', $element); } public function testGetElementFromFile() { $locator = $this->newLocator(); $locator->expects($this->once()) ->method('findMappingFile') ->with($this->equalTo('stdClass')) ->will($this->returnValue(__DIR__ . '/_files/stdClass.yml')); $driver = new TestFileDriver($locator); $this->assertEquals('stdClass', $driver->getElement('stdClass')); } public function testGetAllClassNamesGlobalBasename() { $driver = new TestFileDriver($this->newLocator()); $driver->setGlobalBasename("global"); $classNames = $driver->getAllClassNames(); $this->assertEquals(array('stdGlobal', 'stdGlobal2'), $classNames); } public function testGetAllClassNamesFromMappingFile() { $locator = $this->newLocator(); $locator->expects($this->any()) ->method('getAllClassNames') ->with($this->equalTo(null)) ->will($this->returnValue(array('stdClass'))); $driver = new TestFileDriver($locator); $classNames = $driver->getAllClassNames(); $this->assertEquals(array('stdClass'), $classNames); } public function testGetAllClassNamesBothSources() { $locator = $this->newLocator(); $locator->expects($this->any()) ->method('getAllClassNames') ->with($this->equalTo('global')) ->will($this->returnValue(array('stdClass'))); $driver = new TestFileDriver($locator); $driver->setGlobalBasename("global"); $classNames = $driver->getAllClassNames(); $this->assertEquals(array('stdGlobal', 'stdGlobal2', 'stdClass'), $classNames); } public function testIsNotTransient() { $locator = $this->newLocator(); $locator->expects($this->once()) ->method('fileExists') ->with($this->equalTo('stdClass')) ->will($this->returnValue( true )); $driver = new TestFileDriver($locator); $driver->setGlobalBasename("global"); $this->assertFalse($driver->isTransient('stdClass')); $this->assertFalse($driver->isTransient('stdGlobal')); $this->assertFalse($driver->isTransient('stdGlobal2')); } public function testIsTransient() { $locator = $this->newLocator(); $locator->expects($this->once()) ->method('fileExists') ->with($this->equalTo('stdClass2')) ->will($this->returnValue( false )); $driver = new TestFileDriver($locator); $this->assertTrue($driver->isTransient('stdClass2')); } public function testNonLocatorFallback() { $driver = new TestFileDriver(__DIR__ . '/_files', '.yml'); $this->assertTrue($driver->isTransient('stdClass2')); $this->assertFalse($driver->isTransient('stdClass')); } private function newLocator() { $locator = $this->getMock('Doctrine\Common\Persistence\Mapping\Driver\FileLocator'); $locator->expects($this->any())->method('getFileExtension')->will($this->returnValue('.yml')); $locator->expects($this->any())->method('getPaths')->will($this->returnValue(array(__DIR__ . "/_files"))); return $locator; } } class TestFileDriver extends FileDriver { protected function loadMappingFile($file) { if (strpos($file, "global.yml") !== false) { return array('stdGlobal' => 'stdGlobal', 'stdGlobal2' => 'stdGlobal2'); } return array('stdClass' => 'stdClass'); } public function loadMetadataForClass($className, ClassMetadata $metadata) { } }tests/Doctrine/Tests/Common/Persistence/Mapping/PHPDriverTest.php000064400000001033144760112570021046 0ustar00getMock('Doctrine\Common\Persistence\Mapping\ClassMetadata'); $metadata->expects($this->once())->method('getFieldNames'); $driver = new PHPDriver(array(__DIR__ . "/_files")); $driver->loadMetadataForClass('TestEntity', $metadata); } }tests/Doctrine/Tests/Common/Persistence/Mapping/RuntimeReflectionServiceTest.php000064400000005526144760112570024235 0ustar00. */ namespace Doctrine\Tests\Common\Persistence\Mapping; use Doctrine\Common\Persistence\Mapping\RuntimeReflectionService; /** * @group DCOM-93 */ class RuntimeReflectionServiceTest extends \PHPUnit_Framework_TestCase { /** * @var RuntimeReflectionService */ private $reflectionService; public $unusedPublicProperty; public function setUp() { $this->reflectionService = new RuntimeReflectionService(); } public function testShortname() { $this->assertEquals("RuntimeReflectionServiceTest", $this->reflectionService->getClassShortName(__CLASS__)); } public function testClassNamespaceName() { $this->assertEquals("Doctrine\Tests\Common\Persistence\Mapping", $this->reflectionService->getClassNamespace(__CLASS__)); } public function testGetParentClasses() { $classes = $this->reflectionService->getParentClasses(__CLASS__); $this->assertTrue(count($classes) >= 1, "The test class ".__CLASS__." should have at least one parent."); } public function testGetReflectionClass() { $class = $this->reflectionService->getClass(__CLASS__); $this->assertInstanceOf("ReflectionClass", $class); } public function testGetMethods() { $this->assertTrue($this->reflectionService->hasPublicMethod(__CLASS__, "testGetMethods")); $this->assertFalse($this->reflectionService->hasPublicMethod(__CLASS__, "testGetMethods2")); } public function testGetAccessibleProperty() { $reflProp = $this->reflectionService->getAccessibleProperty(__CLASS__, "reflectionService"); $this->assertInstanceOf("ReflectionProperty", $reflProp); $reflProp = $this->reflectionService->getAccessibleProperty(__CLASS__, "unusedPublicProperty"); $this->assertInstanceOf("Doctrine\Common\Reflection\RuntimePublicReflectionProperty", $reflProp); } } tests/Doctrine/Tests/Common/Persistence/Mapping/StaticPHPDriverTest.php000064400000001700144760112570022217 0ustar00getMock('Doctrine\Common\Persistence\Mapping\ClassMetadata'); $metadata->expects($this->once())->method('getFieldNames'); $driver = new StaticPHPDriver(array(__DIR__)); $driver->loadMetadataForClass(__NAMESPACE__ . '\\TestEntity', $metadata); } public function testGetAllClassNames() { $driver = new StaticPHPDriver(array(__DIR__)); $classNames = $driver->getAllClassNames(); $this->assertContains( 'Doctrine\Tests\Common\Persistence\Mapping\TestEntity', $classNames); } } class TestEntity { static public function loadMetadata($metadata) { $metadata->getFieldNames(); } }tests/Doctrine/Tests/Common/Persistence/Mapping/StaticReflectionServiceTest.php000064400000005010144760112570024025 0ustar00. */ namespace Doctrine\Tests\Common\Persistence\Mapping; use Doctrine\Common\Persistence\Mapping\StaticReflectionService; /** * @group DCOM-93 */ class StaticReflectionServiceTest extends \PHPUnit_Framework_TestCase { private $reflectionService; public function setUp() { $this->reflectionService = new StaticReflectionService(); } public function testShortname() { $this->assertEquals("StaticReflectionServiceTest", $this->reflectionService->getClassShortName(__CLASS__)); } public function testClassNamespaceName() { $this->assertEquals("Doctrine\Tests\Common\Persistence\Mapping", $this->reflectionService->getClassNamespace(__CLASS__)); } public function testGetParentClasses() { $classes = $this->reflectionService->getParentClasses(__CLASS__); $this->assertTrue(count($classes) == 0, "The test class ".__CLASS__." should have no parents according to static reflection."); } public function testGetReflectionClass() { $class = $this->reflectionService->getClass(__CLASS__); $this->assertNull($class); } public function testGetMethods() { $this->assertTrue($this->reflectionService->hasPublicMethod(__CLASS__, "testGetMethods")); $this->assertFalse($this->reflectionService->hasPublicMethod(__CLASS__, "testGetMethods2")); } public function testGetAccessibleProperty() { $reflProp = $this->reflectionService->getAccessibleProperty(__CLASS__, "reflectionService"); $this->assertNull($reflProp); } } tests/Doctrine/Tests/Common/Persistence/Mapping/SymfonyFileLocatorTest.php000064400000005423144760112570023042 0ustar00 $prefix)); $this->assertEquals(array($path), $locator->getPaths()); $locator = new SymfonyFileLocator(array($path => $prefix)); $this->assertEquals(array($path), $locator->getPaths()); } public function testGetPrefixes() { $path = __DIR__ . "/_files"; $prefix = "Foo"; $locator = new SymfonyFileLocator(array($path => $prefix)); $this->assertEquals(array($path => $prefix), $locator->getNamespacePrefixes()); } public function testGetFileExtension() { $locator = new SymfonyFileLocator(array(), ".yml"); $this->assertEquals(".yml", $locator->getFileExtension()); $locator->setFileExtension(".xml"); $this->assertEquals(".xml", $locator->getFileExtension()); } public function testFileExists() { $path = __DIR__ . "/_files"; $prefix = "Foo"; $locator = new SymfonyFileLocator(array($path => $prefix), ".yml"); $this->assertTrue($locator->fileExists("Foo\stdClass")); $this->assertTrue($locator->fileExists("Foo\global")); $this->assertFalse($locator->fileExists("Foo\stdClass2")); $this->assertFalse($locator->fileExists("Foo\global2")); } public function testGetAllClassNames() { $path = __DIR__ . "/_files"; $prefix = "Foo"; $locator = new SymfonyFileLocator(array($path => $prefix), ".yml"); $classes = $locator->getAllClassNames(null); sort($classes); $this->assertEquals(array("Foo\\global", "Foo\\stdClass"), $classes); $this->assertEquals(array("Foo\\stdClass"), $locator->getAllClassNames("global")); } public function testFindMappingFile() { $path = __DIR__ . "/_files"; $prefix = "Foo"; $locator = new SymfonyFileLocator(array($path => $prefix), ".yml"); $this->assertEquals(__DIR__ . "/_files/stdClass.yml", $locator->findMappingFile("Foo\\stdClass")); } public function testFindMappingFileNotFound() { $path = __DIR__ . "/_files"; $prefix = "Foo"; $locator = new SymfonyFileLocator(array($path => $prefix), ".yml"); $this->setExpectedException( "Doctrine\Common\Persistence\Mapping\MappingException", "No mapping file found named '".__DIR__."/_files/stdClass2.yml' for class 'Foo\stdClass2'." ); $locator->findMappingFile("Foo\\stdClass2"); } } tests/Doctrine/Tests/Common/Persistence/Mapping/_files/TestEntity.php000064400000000042144760112570021757 0ustar00getFieldNames();tests/Doctrine/Tests/Common/Persistence/Mapping/_files/global.yml000064400000000004144760112570021113 0ustar00testtests/Doctrine/Tests/Common/Persistence/Mapping/_files/stdClass.yml000064400000000004144760112570021433 0ustar00testtests/Doctrine/Tests/Common/Persistence/ObjectManagerDecoratorTest.php000064400000003737144760112570022231 0ustar00wrapped = $wrapped; } } class ObjectManagerDecoratorTest extends \PHPUnit_Framework_TestCase { private $wrapped; private $decorated; public function setUp() { $this->wrapped = $this->getMock('Doctrine\Common\Persistence\ObjectManager'); $this->decorated = new NullObjectManagerDecorator($this->wrapped); } public function getMethodParameters() { $class = new \ReflectionClass('Doctrine\Common\Persistence\ObjectManager'); $methods = array(); foreach ($class->getMethods() as $method) { if ($method->getNumberOfRequiredParameters() === 0) { $methods[] = array($method->getName(), array()); } elseif ($method->getNumberOfRequiredParameters() > 0) { $methods[] = array($method->getName(), array_fill(0, $method->getNumberOfRequiredParameters(), 'req') ?: array()); } if ($method->getNumberOfParameters() != $method->getNumberOfRequiredParameters()) { $methods[] = array($method->getName(), array_fill(0, $method->getNumberOfParameters(), 'all') ?: array()); } } return $methods; } /** * @dataProvider getMethodParameters */ public function testAllMethodCallsAreDelegatedToTheWrappedInstance($method, array $parameters) { $stub = $this->wrapped ->expects($this->once()) ->method($method) ->will($this->returnValue('INNER VALUE FROM ' . $method)); call_user_func_array(array($stub, 'with'), $parameters); $this->assertSame('INNER VALUE FROM ' . $method, call_user_func_array(array($this->decorated, $method), $parameters)); } }tests/Doctrine/Tests/Common/Persistence/PersistentObjectTest.php000064400000013646144760112570021154 0ustar00cm = new TestObjectMetadata; $this->om = $this->getMock('Doctrine\Common\Persistence\ObjectManager'); $this->om->expects($this->any())->method('getClassMetadata') ->will($this->returnValue($this->cm)); $this->object = new TestObject; PersistentObject::setObjectManager($this->om); $this->object->injectObjectManager($this->om, $this->cm); } public function testGetObjectManager() { $this->assertSame($this->om, PersistentObject::getObjectManager()); } public function testNonMatchingObjectManager() { $this->setExpectedException('RuntimeException'); $om = $this->getMock('Doctrine\Common\Persistence\ObjectManager'); $this->object->injectObjectManager($om, $this->cm); } public function testGetField() { $this->assertEquals('beberlei', $this->object->getName()); } public function testSetField() { $this->object->setName("test"); $this->assertEquals("test", $this->object->getName()); } public function testGetIdentifier() { $this->assertEquals(1, $this->object->getId()); } public function testSetIdentifier() { $this->setExpectedException('BadMethodCallException'); $this->object->setId(2); } public function testSetUnknownField() { $this->setExpectedException('BadMethodCallException'); $this->object->setUnknown("test"); } public function testGetUnknownField() { $this->setExpectedException('BadMethodCallException'); $this->object->getUnknown(); } public function testGetToOneAssociation() { $this->assertNull($this->object->getParent()); } public function testSetToOneAssociation() { $parent = new TestObject(); $this->object->setParent($parent); $this->assertSame($parent, $this->object->getParent($parent)); } public function testSetInvalidToOneAssociation() { $parent = new \stdClass(); $this->setExpectedException('InvalidArgumentException'); $this->object->setParent($parent); } public function testSetToOneAssociationNull() { $parent = new TestObject(); $this->object->setParent($parent); $this->object->setParent(null); $this->assertNull($this->object->getParent()); } public function testAddToManyAssociation() { $child = new TestObject(); $this->object->addChildren($child); $this->assertSame($this->object, $child->getParent()); $this->assertEquals(1, count($this->object->getChildren())); $child = new TestObject(); $this->object->addChildren($child); $this->assertEquals(2, count($this->object->getChildren())); } public function testAddInvalidToManyAssociation() { $this->setExpectedException('InvalidArgumentException'); $this->object->addChildren(new \stdClass()); } public function testNoObjectManagerSet() { PersistentObject::setObjectManager(null); $child = new TestObject(); $this->setExpectedException('RuntimeException'); $child->setName("test"); } public function testInvalidMethod() { $this->setExpectedException('BadMethodCallException'); $this->object->asdf(); } public function testAddInvalidCollection() { $this->setExpectedException('BadMethodCallException'); $this->object->addAsdf(new \stdClass()); } } class TestObject extends PersistentObject { protected $id = 1; protected $name = 'beberlei'; protected $parent; protected $children; } class TestObjectMetadata implements ClassMetadata { public function getAssociationMappedByTargetField($assocName) { $assoc = array('children' => 'parent'); return $assoc[$assocName]; } public function getAssociationNames() { return array('parent', 'children'); } public function getAssociationTargetClass($assocName) { return __NAMESPACE__ . '\TestObject'; } public function getFieldNames() { return array('id', 'name'); } public function getIdentifier() { return array('id'); } public function getName() { return __NAMESPACE__ . '\TestObject'; } public function getReflectionClass() { return new \ReflectionClass($this->getName()); } public function getTypeOfField($fieldName) { $types = array('id' => 'integer', 'name' => 'string'); return $types[$fieldName]; } public function hasAssociation($fieldName) { return in_array($fieldName, array('parent', 'children')); } public function hasField($fieldName) { return in_array($fieldName, array('id', 'name')); } public function isAssociationInverseSide($assocName) { return ($assocName === 'children'); } public function isCollectionValuedAssociation($fieldName) { return ($fieldName === 'children'); } public function isIdentifier($fieldName) { return $fieldName === 'id'; } public function isSingleValuedAssociation($fieldName) { return $fieldName === 'parent'; } public function getIdentifierValues($entity) { } public function getIdentifierFieldNames() { } public function initializeReflection(ReflectionService $reflService) { } public function wakeupReflection(ReflectionService $reflService) { } } tests/Doctrine/Tests/Common/Proxy/AbstractProxyFactoryTest.php000064400000010502144760112570020643 0ustar00getMock('Doctrine\Common\Persistence\Mapping\ClassMetadata'); $proxyGenerator = $this->getMock('Doctrine\Common\Proxy\ProxyGenerator', array(), array(), '', false); $proxyGenerator ->expects($this->once()) ->method('getProxyFileName'); $proxyGenerator ->expects($this->once()) ->method('generateProxyClass'); $metadataFactory = $this->getMock('Doctrine\Common\Persistence\Mapping\ClassMetadataFactory'); $proxyFactory = $this->getMockForAbstractClass( 'Doctrine\Common\Proxy\AbstractProxyFactory', array($proxyGenerator, $metadataFactory, true) ); $proxyFactory ->expects($this->any()) ->method('skipClass') ->will($this->returnValue(false)); $generated = $proxyFactory->generateProxyClasses(array($metadata), sys_get_temp_dir()); $this->assertEquals(1, $generated, 'One proxy was generated'); } public function testGetProxy() { $metadata = $this->getMock('Doctrine\Common\Persistence\Mapping\ClassMetadata'); $proxy = $this->getMock('Doctrine\Common\Proxy\Proxy'); $definition = new ProxyDefinition(get_class($proxy), array(), array(), null, null); $proxyGenerator = $this->getMock('Doctrine\Common\Proxy\ProxyGenerator', array(), array(), '', false); $metadataFactory = $this->getMock('Doctrine\Common\Persistence\Mapping\ClassMetadataFactory'); $metadataFactory ->expects($this->once()) ->method('getMetadataFor') ->will($this->returnValue($metadata)); $proxyFactory = $this->getMockForAbstractClass( 'Doctrine\Common\Proxy\AbstractProxyFactory', array($proxyGenerator, $metadataFactory, true) ); $proxyFactory ->expects($this->any()) ->method('createProxyDefinition') ->will($this->returnValue($definition)); $generatedProxy = $proxyFactory->getProxy('Class', array('id' => 1)); $this->assertInstanceOf(get_class($proxy), $generatedProxy); } public function testResetUnitializedProxy() { $metadata = $this->getMock('Doctrine\Common\Persistence\Mapping\ClassMetadata'); $proxy = $this->getMock('Doctrine\Common\Proxy\Proxy'); $definition = new ProxyDefinition(get_class($proxy), array(), array(), null, null); $proxyGenerator = $this->getMock('Doctrine\Common\Proxy\ProxyGenerator', array(), array(), '', false); $metadataFactory = $this->getMock('Doctrine\Common\Persistence\Mapping\ClassMetadataFactory'); $metadataFactory ->expects($this->once()) ->method('getMetadataFor') ->will($this->returnValue($metadata)); $proxyFactory = $this->getMockForAbstractClass( 'Doctrine\Common\Proxy\AbstractProxyFactory', array($proxyGenerator, $metadataFactory, true) ); $proxyFactory ->expects($this->any()) ->method('createProxyDefinition') ->will($this->returnValue($definition)); $proxy ->expects($this->once()) ->method('__isInitialized') ->will($this->returnValue(false)); $proxy ->expects($this->once()) ->method('__setInitializer'); $proxy ->expects($this->once()) ->method('__setCloner'); $proxyFactory->resetUninitializedProxy($proxy); } public function testDisallowsResettingInitializedProxy() { $proxyFactory = $this->getMockForAbstractClass('Doctrine\Common\Proxy\AbstractProxyFactory', array(), '', false); $proxy = $this->getMock('Doctrine\Common\Proxy\Proxy'); $proxy ->expects($this->any()) ->method('__isInitialized') ->will($this->returnValue(true)); $this->setExpectedException('Doctrine\Common\Proxy\Exception\InvalidArgumentException'); $proxyFactory->resetUninitializedProxy($proxy); } } tests/Doctrine/Tests/Common/Proxy/AutoloaderTest.php000064400000005621144760112570016613 0ustar00. */ namespace Doctrine\Tests\Common\Proxy; use PHPUnit_Framework_TestCase; use Doctrine\Common\Proxy\Autoloader; /** * @group DDC-1698 */ class AutoloaderTest extends PHPUnit_Framework_TestCase { public static function dataResolveFile() { return array( array('/tmp', 'MyProxy', 'MyProxy\__CG__\RealClass', '/tmp' . DIRECTORY_SEPARATOR . '__CG__RealClass.php'), array('/tmp', 'MyProxy\Subdir', 'MyProxy\Subdir\__CG__\RealClass', '/tmp' . DIRECTORY_SEPARATOR . '__CG__RealClass.php'), array('/tmp', 'MyProxy', 'MyProxy\__CG__\Other\RealClass', '/tmp' . DIRECTORY_SEPARATOR . '__CG__OtherRealClass.php'), ); } /** * @dataProvider dataResolveFile */ public function testResolveFile($proxyDir, $proxyNamespace, $className, $expectedProxyFile) { $actualProxyFile = Autoloader::resolveFile($proxyDir, $proxyNamespace, $className); $this->assertEquals($expectedProxyFile, $actualProxyFile); } public function testAutoload() { if (file_exists(sys_get_temp_dir() ."/AutoloaderTestClass.php")) { unlink(sys_get_temp_dir() ."/AutoloaderTestClass.php"); } $autoloader = Autoloader::register(sys_get_temp_dir(), 'ProxyAutoloaderTest', function($proxyDir, $proxyNamespace, $className) { file_put_contents(sys_get_temp_dir() . "/AutoloaderTestClass.php", "assertTrue(class_exists('ProxyAutoloaderTest\AutoloaderTestClass', true)); unlink(sys_get_temp_dir() ."/AutoloaderTestClass.php"); } public function testRegisterWithInvalidCallback() { $this->setExpectedException( 'Doctrine\Common\Proxy\Exception\InvalidArgumentException', 'Invalid \$notFoundCallback given: must be a callable, "stdClass" given' ); Autoloader::register('', '', new \stdClass()); } } tests/Doctrine/Tests/Common/Proxy/CallableTypeHintClass.php000064400000000313144760112570020017 0ustar00. */ namespace Doctrine\Tests\Common\Proxy; /** * Test asset representing a lazy loadable object * * @author Marco Pivetta * @since 2.4 */ class LazyLoadableObject { /** * @var string */ public $publicIdentifierField; /** * @var string */ protected $protectedIdentifierField; /** * @var string */ public $publicTransientField = 'publicTransientFieldValue'; /** * @var string */ protected $protectedTransientField = 'protectedTransientFieldValue'; /** * @var string */ public $publicPersistentField = 'publicPersistentFieldValue'; /** * @var string */ protected $protectedPersistentField = 'protectedPersistentFieldValue'; /** * @var string */ public $publicAssociation = 'publicAssociationValue'; /** * @var string */ protected $protectedAssociation = 'protectedAssociationValue'; /** * @return string */ public function getProtectedIdentifierField() { return $this->protectedIdentifierField; } /** * @return string */ public function testInitializationTriggeringMethod() { return 'testInitializationTriggeringMethod'; } /** * @return string */ public function getProtectedAssociation() { return $this->protectedAssociation; } /** * @param \stdClass $param */ public function publicTypeHintedMethod(\stdClass $param) { } /** * */ public function &byRefMethod() { } /** * @param mixed $thisIsNotByRef * @param &mixed $thisIsByRef */ public function byRefParamMethod($thisIsNotByRef, &$thisIsByRef) { } } tests/Doctrine/Tests/Common/Proxy/LazyLoadableObjectClassMetadata.php000064400000010623144760112570021773 0ustar00. */ namespace Doctrine\Tests\Common\Proxy; use ReflectionClass; use Doctrine\Common\Persistence\Mapping\ClassMetadata; /** * Class metadata test asset for @see LazyLoadableObject * * @author Marco Pivetta * @since 2.4 */ class LazyLoadableObjectClassMetadata implements ClassMetadata { /** * @var ReflectionClass */ protected $reflectionClass; /** * @var array */ protected $identifier = array( 'publicIdentifierField' => true, 'protectedIdentifierField' => true, ); /** * @var array */ protected $fields = array( 'publicIdentifierField' => true, 'protectedIdentifierField' => true, 'publicPersistentField' => true, 'protectedPersistentField' => true, ); /** * @var array */ protected $associations = array( 'publicAssociation' => true, 'protectedAssociation' => true, ); /** * {@inheritDoc} */ public function getName() { return $this->getReflectionClass()->getName(); } /** * {@inheritDoc} */ public function getIdentifier() { return array_keys($this->identifier); } /** * {@inheritDoc} */ public function getReflectionClass() { if (null === $this->reflectionClass) { $this->reflectionClass = new \ReflectionClass(__NAMESPACE__ . '\LazyLoadableObject'); } return $this->reflectionClass; } /** * {@inheritDoc} */ public function isIdentifier($fieldName) { return isset($this->identifier[$fieldName]); } /** * {@inheritDoc} */ public function hasField($fieldName) { return isset($this->fields[$fieldName]); } /** * {@inheritDoc} */ public function hasAssociation($fieldName) { return isset($this->associations[$fieldName]); } /** * {@inheritDoc} */ public function isSingleValuedAssociation($fieldName) { throw new \BadMethodCallException('not implemented'); } /** * {@inheritDoc} */ public function isCollectionValuedAssociation($fieldName) { throw new \BadMethodCallException('not implemented'); } /** * {@inheritDoc} */ public function getFieldNames() { return array_keys($this->fields); } /** * {@inheritDoc} */ public function getIdentifierFieldNames() { return $this->getIdentifier(); } /** * {@inheritDoc} */ public function getAssociationNames() { return array_keys($this->associations); } /** * {@inheritDoc} */ public function getTypeOfField($fieldName) { return 'string'; } /** * {@inheritDoc} */ public function getAssociationTargetClass($assocName) { throw new \BadMethodCallException('not implemented'); } /** * {@inheritDoc} */ public function isAssociationInverseSide($assocName) { throw new \BadMethodCallException('not implemented'); } /** * {@inheritDoc} */ public function getAssociationMappedByTargetField($assocName) { throw new \BadMethodCallException('not implemented'); } /** * {@inheritDoc} */ public function getIdentifierValues($object) { throw new \BadMethodCallException('not implemented'); } } tests/Doctrine/Tests/Common/Proxy/MagicCloneClass.php000064400000000771144760112570016644 0ustar00clonedValue = 'newClonedValue'; } } tests/Doctrine/Tests/Common/Proxy/MagicGetClass.php000064400000001213144760112570016313 0ustar00testAttribute = $value; } if ($name === 'publicField' || $name === 'id') { throw new \BadMethodCallException('Should never be called for "publicField" or "id"'); } $this->testAttribute = $value; } } tests/Doctrine/Tests/Common/Proxy/MagicSleepClass.php000064400000001014144760112570016643 0ustar00wakeupValue = 'newWakeupValue'; } } tests/Doctrine/Tests/Common/Proxy/ProxyClassGeneratorTest.php000064400000020035144760112570020466 0ustar00. */ namespace Doctrine\Tests\Common\Proxy; use Doctrine\Common\Proxy\ProxyGenerator; use ReflectionClass; use ReflectionMethod; use PHPUnit_Framework_TestCase; /** * Test the proxy generator. Its work is generating on-the-fly subclasses of a given model, which implement the Proxy * pattern. * * @author Giorgio Sironi * @author Marco Pivetta */ class ProxyClassGeneratorTest extends PHPUnit_Framework_TestCase { /** * @var string */ protected $proxyClass = 'Doctrine\Tests\Common\ProxyProxy\__CG__\Doctrine\Tests\Common\Proxy\LazyLoadableObject'; /** * @var LazyLoadableObjectClassMetadata */ protected $metadata; /** * @var ProxyGenerator */ protected $proxyGenerator; /** * {@inheritDoc} */ protected function setUp() { $this->metadata = new LazyLoadableObjectClassMetadata(); $this->proxyGenerator = new ProxyGenerator(__DIR__ . '/generated', __NAMESPACE__ . 'Proxy', true); if (class_exists($this->proxyClass, false)) { return; } $this->proxyGenerator->generateProxyClass($this->metadata); require_once $this->proxyGenerator->getProxyFileName($this->metadata->getName()); } public function testReferenceProxyRespectsMethodsParametersTypeHinting() { $method = new ReflectionMethod($this->proxyClass, 'publicTypeHintedMethod'); $params = $method->getParameters(); $this->assertEquals(1, count($params)); $this->assertEquals('stdClass', $params[0]->getClass()->getName()); } public function testProxyRespectsMethodsWhichReturnValuesByReference() { $method = new ReflectionMethod($this->proxyClass, 'byRefMethod'); $this->assertTrue($method->returnsReference()); } public function testProxyRespectsByRefMethodParameters() { $method = new ReflectionMethod($this->proxyClass, 'byRefParamMethod'); $parameters = $method->getParameters(); $this->assertSame('thisIsNotByRef', $parameters[0]->getName()); $this->assertFalse($parameters[0]->isPassedByReference()); $this->assertSame('thisIsByRef', $parameters[1]->getName()); $this->assertTrue($parameters[1]->isPassedByReference()); } public function testCreatesAssociationProxyAsSubclassOfTheOriginalOne() { $this->assertTrue(is_subclass_of($this->proxyClass, $this->metadata->getName())); } public function testNonNamespacedProxyGeneration() { $classCode = file_get_contents($this->proxyGenerator->getProxyFileName($this->metadata->getName())); $this->assertNotContains("class LazyLoadableObject extends \\\\" . $this->metadata->getName(), $classCode); $this->assertContains("class LazyLoadableObject extends \\" . $this->metadata->getName(), $classCode); } public function testClassWithSleepProxyGeneration() { if (!class_exists('Doctrine\Tests\Common\ProxyProxy\__CG__\SleepClass', false)) { $metadata = $this->getMock('Doctrine\Common\Persistence\Mapping\ClassMetadata'); $reflClass = new ReflectionClass('Doctrine\Tests\Common\Proxy\SleepClass'); $metadata->expects($this->any())->method('getReflectionClass')->will($this->returnValue($reflClass)); $metadata->expects($this->any())->method('getIdentifierFieldNames')->will($this->returnValue(array('id'))); $metadata->expects($this->any())->method('getName')->will($this->returnValue($reflClass->getName())); $proxyGenerator = new ProxyGenerator(__DIR__ . '/generated', __NAMESPACE__ . 'Proxy', true); $proxyGenerator->generateProxyClass($metadata); require_once $proxyGenerator->getProxyFileName($metadata->getName()); } $classCode = file_get_contents(__DIR__ . '/generated/__CG__DoctrineTestsCommonProxySleepClass.php'); $this->assertEquals(1, substr_count($classCode, 'function __sleep')); $this->assertEquals(1, substr_count($classCode, 'parent::__sleep()')); } public function testClassWithCallableTypeHintOnProxiedMethod() { if (PHP_VERSION_ID < 50400) { $this->markTestSkipped('`callable` is only supported in PHP >=5.4.0'); } if (!class_exists('Doctrine\Tests\Common\ProxyProxy\__CG__\CallableTypeHintClass', false)) { $metadata = $this->getMock('Doctrine\Common\Persistence\Mapping\ClassMetadata'); $reflClass = new ReflectionClass('Doctrine\Tests\Common\Proxy\CallableTypeHintClass'); $proxyGenerator = new ProxyGenerator(__DIR__ . '/generated', __NAMESPACE__ . 'Proxy', true); $metadata->expects($this->any())->method('getReflectionClass')->will($this->returnValue($reflClass)); $metadata->expects($this->any())->method('getIdentifierFieldNames')->will($this->returnValue(array('id'))); $metadata->expects($this->any())->method('getName')->will($this->returnValue($reflClass->getName())); $proxyGenerator->generateProxyClass($metadata); require_once $proxyGenerator->getProxyFileName($metadata->getName()); } $classCode = file_get_contents(__DIR__ . '/generated/__CG__DoctrineTestsCommonProxyCallableTypeHintClass.php'); $this->assertEquals(1, substr_count($classCode, 'call(callable $foo)')); } public function testClassWithInvalidTypeHintOnProxiedMethod() { $className = 'Doctrine\Tests\Common\Proxy\InvalidTypeHintClass'; $metadata = $this->getMock('Doctrine\Common\Persistence\Mapping\ClassMetadata'); $reflClass = new ReflectionClass($className); $metadata->expects($this->any())->method('getReflectionClass')->will($this->returnValue($reflClass)); $metadata->expects($this->any())->method('getIdentifierFieldNames')->will($this->returnValue(array())); $metadata->expects($this->any())->method('getName')->will($this->returnValue($className)); $proxyGenerator = new ProxyGenerator(__DIR__ . '/generated', __NAMESPACE__ . 'Proxy', true); $this->setExpectedException( 'Doctrine\Common\Proxy\Exception\UnexpectedValueException', 'The type hint of parameter "foo" in method "invalidTypeHintMethod"' .' in class "' . $className . '" is invalid.' ); $proxyGenerator->generateProxyClass($metadata); } public function testNoConfigDirThrowsException() { $this->setExpectedException('Doctrine\Common\Proxy\Exception\InvalidArgumentException'); new ProxyGenerator(null, null); } public function testNoNamespaceThrowsException() { $this->setExpectedException('Doctrine\Common\Proxy\Exception\InvalidArgumentException'); new ProxyGenerator(__DIR__ . '/generated', null); } public function testInvalidPlaceholderThrowsException() { $this->setExpectedException('Doctrine\Common\Proxy\Exception\InvalidArgumentException'); $generator = new ProxyGenerator(__DIR__ . '/generated', 'SomeNamespace'); $generator->setPlaceholder('', array()); } } tests/Doctrine/Tests/Common/Proxy/ProxyLogicTest.php000064400000064142144760112570016616 0ustar00. */ namespace Doctrine\Tests\Common\Proxy; use Doctrine\Common\Proxy\ProxyGenerator; use Doctrine\Common\Proxy\Proxy; use Doctrine\Common\Proxy\Exception\UnexpectedValueException; use Doctrine\Common\Persistence\Mapping\ClassMetadata; use PHPUnit_Framework_TestCase; /** * Test the generated proxies behavior. These tests make assumptions about the structure of LazyLoadableObject * * @author Marco Pivetta */ class ProxyLogicTest extends PHPUnit_Framework_TestCase { /** * @var \PHPUnit_Framework_MockObject_MockObject */ protected $proxyLoader; /** * @var ClassMetadata */ protected $lazyLoadableObjectMetadata; /** * @var LazyLoadableObject|Proxy */ protected $lazyObject; protected $identifier = array( 'publicIdentifierField' => 'publicIdentifierFieldValue', 'protectedIdentifierField' => 'protectedIdentifierFieldValue', ); /** * @var \PHPUnit_Framework_MockObject_MockObject|Callable */ protected $initializerCallbackMock; /** * {@inheritDoc} */ public function setUp() { $this->proxyLoader = $loader = $this->getMock('stdClass', array('load'), array(), '', false); $this->initializerCallbackMock = $this->getMock('stdClass', array('__invoke')); $identifier = $this->identifier; $this->lazyLoadableObjectMetadata = $metadata = new LazyLoadableObjectClassMetadata(); // emulating what should happen in a proxy factory $cloner = function (LazyLoadableObject $proxy) use ($loader, $identifier, $metadata) { /* @var $proxy LazyLoadableObject|Proxy */ if ($proxy->__isInitialized()) { return; } $proxy->__setInitialized(true); $proxy->__setInitializer(null); $original = $loader->load($identifier); if (null === $original) { throw new UnexpectedValueException(); } foreach ($metadata->getReflectionClass()->getProperties() as $reflProperty) { $propertyName = $reflProperty->getName(); if ($metadata->hasField($propertyName) || $metadata->hasAssociation($propertyName)) { $reflProperty->setAccessible(true); $reflProperty->setValue($proxy, $reflProperty->getValue($original)); } } }; $proxyClassName = 'Doctrine\Tests\Common\ProxyProxy\__CG__\Doctrine\Tests\Common\Proxy\LazyLoadableObject'; // creating the proxy class if (!class_exists($proxyClassName, false)) { $proxyGenerator = new ProxyGenerator(__DIR__ . '/generated', __NAMESPACE__ . 'Proxy', true); $proxyGenerator->generateProxyClass($metadata); require_once $proxyGenerator->getProxyFileName($metadata->getName()); } $this->lazyObject = new $proxyClassName($this->getClosure($this->initializerCallbackMock), $cloner); // setting identifiers in the proxy via reflection foreach ($metadata->getIdentifierFieldNames() as $idField) { $prop = $metadata->getReflectionClass()->getProperty($idField); $prop->setAccessible(true); $prop->setValue($this->lazyObject, $identifier[$idField]); } $this->assertFalse($this->lazyObject->__isInitialized()); } public function testFetchingPublicIdentifierDoesNotCauseLazyLoading() { $this->configureInitializerMock(0); $this->assertSame('publicIdentifierFieldValue', $this->lazyObject->publicIdentifierField); } public function testFetchingIdentifiersViaPublicGetterDoesNotCauseLazyLoading() { $this->configureInitializerMock(0); $this->assertSame('protectedIdentifierFieldValue', $this->lazyObject->getProtectedIdentifierField()); } public function testCallingMethodCausesLazyLoading() { $this->configureInitializerMock( 1, array($this->lazyObject, 'testInitializationTriggeringMethod', array()), function (Proxy $proxy) { $proxy->__setInitializer(null); } ); $this->lazyObject->testInitializationTriggeringMethod(); $this->lazyObject->testInitializationTriggeringMethod(); } public function testFetchingPublicFieldsCausesLazyLoading() { $test = $this; $this->configureInitializerMock( 1, array($this->lazyObject, '__get', array('publicPersistentField')), function () use ($test) { $test->setProxyValue('publicPersistentField', 'loadedValue'); } ); $this->assertSame('loadedValue', $this->lazyObject->publicPersistentField); $this->assertSame('loadedValue', $this->lazyObject->publicPersistentField); } public function testFetchingPublicAssociationCausesLazyLoading() { $test = $this; $this->configureInitializerMock( 1, array($this->lazyObject, '__get', array('publicAssociation')), function () use ($test) { $test->setProxyValue('publicAssociation', 'loadedAssociation'); } ); $this->assertSame('loadedAssociation', $this->lazyObject->publicAssociation); $this->assertSame('loadedAssociation', $this->lazyObject->publicAssociation); } public function testFetchingProtectedAssociationViaPublicGetterCausesLazyLoading() { $this->configureInitializerMock( 1, array($this->lazyObject, 'getProtectedAssociation', array()), function (Proxy $proxy) { $proxy->__setInitializer(null); } ); $this->assertSame('protectedAssociationValue', $this->lazyObject->getProtectedAssociation()); $this->assertSame('protectedAssociationValue', $this->lazyObject->getProtectedAssociation()); } public function testLazyLoadingTriggeredOnlyAtFirstPublicPropertyRead() { $test = $this; $this->configureInitializerMock( 1, array($this->lazyObject, '__get', array('publicPersistentField')), function () use ($test) { $test->setProxyValue('publicPersistentField', 'loadedValue'); $test->setProxyValue('publicAssociation', 'publicAssociationValue'); } ); $this->assertSame('loadedValue', $this->lazyObject->publicPersistentField); $this->assertSame('publicAssociationValue', $this->lazyObject->publicAssociation); } public function testNoticeWhenReadingNonExistentPublicProperties() { $this->configureInitializerMock(0); $class = get_class($this->lazyObject); $this->setExpectedException( 'PHPUnit_Framework_Error_Notice', 'Undefined property: ' . $class . '::$non_existing_property' ); $this->lazyObject->non_existing_property; } public function testFalseWhenCheckingNonExistentProperty() { $this->configureInitializerMock(0); $this->assertFalse(isset($this->lazyObject->non_existing_property)); } public function testNoErrorWhenSettingNonExistentProperty() { $this->configureInitializerMock(0); $this->lazyObject->non_existing_property = 'now has a value'; $this->assertSame('now has a value', $this->lazyObject->non_existing_property); } public function testCloningCallsClonerWithClonedObject() { $lazyObject = $this->lazyObject; $test = $this; $cb = $this->getMock('stdClass', array('cb')); $cb ->expects($this->once()) ->method('cb') ->will($this->returnCallback(function (LazyLoadableObject $proxy) use ($lazyObject, $test) { /* @var $proxy LazyLoadableObject|Proxy */ $test->assertNotSame($proxy, $lazyObject); $proxy->__setInitializer(null); $proxy->publicAssociation = 'clonedAssociation'; })); $this->lazyObject->__setCloner($this->getClosure(array($cb, 'cb'))); $cloned = clone $this->lazyObject; $this->assertSame('clonedAssociation', $cloned->publicAssociation); $this->assertNotSame($cloned, $lazyObject, 'a clone of the lazy object is retrieved'); } public function testFetchingTransientPropertiesWillNotTriggerLazyLoading() { $this->configureInitializerMock(0); $this->assertSame( 'publicTransientFieldValue', $this->lazyObject->publicTransientField, 'fetching public transient field won\'t trigger lazy loading' ); $property = $this ->lazyLoadableObjectMetadata ->getReflectionClass() ->getProperty('protectedTransientField'); $property->setAccessible(true); $this->assertSame( 'protectedTransientFieldValue', $property->getValue($this->lazyObject), 'fetching protected transient field via reflection won\'t trigger lazy loading' ); } /** * Provided to guarantee backwards compatibility */ public function testLoadProxyMethod() { $this->configureInitializerMock(2, array($this->lazyObject, '__load', array())); $this->lazyObject->__load(); $this->lazyObject->__load(); } public function testLoadingWithPersisterWillBeTriggeredOnlyOnce() { $this ->proxyLoader ->expects($this->once()) ->method('load') ->with( array( 'publicIdentifierField' => 'publicIdentifierFieldValue', 'protectedIdentifierField' => 'protectedIdentifierFieldValue', ), $this->lazyObject ) ->will($this->returnCallback(function ($id, LazyLoadableObject $lazyObject) { // setting a value to verify that the persister can actually set something in the object $lazyObject->publicAssociation = $id['publicIdentifierField'] . '-test'; return true; })); $this->lazyObject->__setInitializer($this->getSuggestedInitializerImplementation()); $this->lazyObject->__load(); $this->lazyObject->__load(); $this->assertSame('publicIdentifierFieldValue-test', $this->lazyObject->publicAssociation); } public function testFailedLoadingWillThrowException() { $this->proxyLoader->expects($this->any())->method('load')->will($this->returnValue(null)); $this->setExpectedException('UnexpectedValueException'); $this->lazyObject->__setInitializer($this->getSuggestedInitializerImplementation()); $this->lazyObject->__load(); } public function testCloningWithPersister() { $this->lazyObject->publicTransientField = 'should-not-change'; $this ->proxyLoader ->expects($this->exactly(2)) ->method('load') ->with(array( 'publicIdentifierField' => 'publicIdentifierFieldValue', 'protectedIdentifierField' => 'protectedIdentifierFieldValue', )) ->will($this->returnCallback(function () { $blueprint = new LazyLoadableObject(); $blueprint->publicPersistentField = 'checked-persistent-field'; $blueprint->publicAssociation = 'checked-association-field'; $blueprint->publicTransientField = 'checked-transient-field'; return $blueprint; })); $firstClone = clone $this->lazyObject; $this->assertSame( 'checked-persistent-field', $firstClone->publicPersistentField, 'Persistent fields are cloned correctly' ); $this->assertSame( 'checked-association-field', $firstClone->publicAssociation, 'Associations are cloned correctly' ); $this->assertSame( 'should-not-change', $firstClone->publicTransientField, 'Transient fields are not overwritten' ); $secondClone = clone $this->lazyObject; $this->assertSame( 'checked-persistent-field', $secondClone->publicPersistentField, 'Persistent fields are cloned correctly' ); $this->assertSame( 'checked-association-field', $secondClone->publicAssociation, 'Associations are cloned correctly' ); $this->assertSame( 'should-not-change', $secondClone->publicTransientField, 'Transient fields are not overwritten' ); // those should not trigger lazy loading $firstClone->__load(); $secondClone->__load(); } public function testNotInitializedProxyUnserialization() { $this->configureInitializerMock(); $serialized = serialize($this->lazyObject); /* @var $unserialized LazyLoadableObject|Proxy */ $unserialized = unserialize($serialized); $reflClass = $this->lazyLoadableObjectMetadata->getReflectionClass(); $this->assertFalse($unserialized->__isInitialized(), 'serialization didn\'t cause intialization'); // Checking identifiers $this->assertSame('publicIdentifierFieldValue', $unserialized->publicIdentifierField, 'identifiers are kept'); $protectedIdentifierField = $reflClass->getProperty('protectedIdentifierField'); $protectedIdentifierField->setAccessible(true); $this->assertSame( 'protectedIdentifierFieldValue', $protectedIdentifierField->getValue($unserialized), 'identifiers are kept' ); // Checking transient fields $this->assertSame( 'publicTransientFieldValue', $unserialized->publicTransientField, 'transient fields are kept' ); $protectedTransientField = $reflClass->getProperty('protectedTransientField'); $protectedTransientField->setAccessible(true); $this->assertSame( 'protectedTransientFieldValue', $protectedTransientField->getValue($unserialized), 'transient fields are kept' ); // Checking persistent fields $this->assertSame( 'publicPersistentFieldValue', $unserialized->publicPersistentField, 'persistent fields are kept' ); $protectedPersistentField = $reflClass->getProperty('protectedPersistentField'); $protectedPersistentField->setAccessible(true); $this->assertSame( 'protectedPersistentFieldValue', $protectedPersistentField->getValue($unserialized), 'persistent fields are kept' ); // Checking associations $this->assertSame('publicAssociationValue', $unserialized->publicAssociation, 'associations are kept'); $protectedAssociationField = $reflClass->getProperty('protectedAssociation'); $protectedAssociationField->setAccessible(true); $this->assertSame( 'protectedAssociationValue', $protectedAssociationField->getValue($unserialized), 'associations are kept' ); } public function testInitializedProxyUnserialization() { // persister will retrieve the lazy object itself, so that we don't have to re-define all field values $this->proxyLoader->expects($this->once())->method('load')->will($this->returnValue($this->lazyObject)); $this->lazyObject->__setInitializer($this->getSuggestedInitializerImplementation()); $this->lazyObject->__load(); $serialized = serialize($this->lazyObject); $reflClass = $this->lazyLoadableObjectMetadata->getReflectionClass(); /* @var $unserialized LazyLoadableObject|Proxy */ $unserialized = unserialize($serialized); $this->assertTrue($unserialized->__isInitialized(), 'serialization didn\'t cause intialization'); // Checking transient fields $this->assertSame( 'publicTransientFieldValue', $unserialized->publicTransientField, 'transient fields are kept' ); $protectedTransientField = $reflClass->getProperty('protectedTransientField'); $protectedTransientField->setAccessible(true); $this->assertSame( 'protectedTransientFieldValue', $protectedTransientField->getValue($unserialized), 'transient fields are kept' ); // Checking persistent fields $this->assertSame( 'publicPersistentFieldValue', $unserialized->publicPersistentField, 'persistent fields are kept' ); $protectedPersistentField = $reflClass->getProperty('protectedPersistentField'); $protectedPersistentField->setAccessible(true); $this->assertSame( 'protectedPersistentFieldValue', $protectedPersistentField->getValue($unserialized), 'persistent fields are kept' ); // Checking identifiers $this->assertSame( 'publicIdentifierFieldValue', $unserialized->publicIdentifierField, 'identifiers are kept' ); $protectedIdentifierField = $reflClass->getProperty('protectedIdentifierField'); $protectedIdentifierField->setAccessible(true); $this->assertSame( 'protectedIdentifierFieldValue', $protectedIdentifierField->getValue($unserialized), 'identifiers are kept' ); // Checking associations $this->assertSame('publicAssociationValue', $unserialized->publicAssociation, 'associations are kept'); $protectedAssociationField = $reflClass->getProperty('protectedAssociation'); $protectedAssociationField->setAccessible(true); $this->assertSame( 'protectedAssociationValue', $protectedAssociationField->getValue($unserialized), 'associations are kept' ); } public function testInitializationRestoresDefaultPublicLazyLoadedFieldValues() { // setting noop persister $this->proxyLoader->expects($this->once())->method('load')->will($this->returnValue($this->lazyObject)); $this->lazyObject->__setInitializer($this->getSuggestedInitializerImplementation()); $this->assertSame( 'publicPersistentFieldValue', $this->lazyObject->publicPersistentField, 'Persistent field is restored to default value' ); $this->assertSame( 'publicAssociationValue', $this->lazyObject->publicAssociation, 'Association is restored to default value' ); } public function testSettingPublicFieldsCausesLazyLoading() { $test = $this; $this->configureInitializerMock( 1, array($this->lazyObject, '__set', array('publicPersistentField', 'newPublicPersistentFieldValue')), function () use ($test) { $test->setProxyValue('publicPersistentField', 'overrideValue'); $test->setProxyValue('publicAssociation', 'newAssociationValue'); } ); $this->lazyObject->publicPersistentField = 'newPublicPersistentFieldValue'; $this->assertSame('newPublicPersistentFieldValue', $this->lazyObject->publicPersistentField); $this->assertSame('newAssociationValue', $this->lazyObject->publicAssociation); } public function testSettingPublicAssociationCausesLazyLoading() { $test = $this; $this->configureInitializerMock( 1, array($this->lazyObject, '__set', array('publicAssociation', 'newPublicAssociationValue')), function () use ($test) { $test->setProxyValue('publicPersistentField', 'newPublicPersistentFieldValue'); $test->setProxyValue('publicAssociation', 'overrideValue'); } ); $this->lazyObject->publicAssociation = 'newPublicAssociationValue'; $this->assertSame('newPublicAssociationValue', $this->lazyObject->publicAssociation); $this->assertSame('newPublicPersistentFieldValue', $this->lazyObject->publicPersistentField); } public function testCheckingPublicFieldsCausesLazyLoading() { $test = $this; $this->configureInitializerMock( 1, array($this->lazyObject, '__isset', array('publicPersistentField')), function () use ($test) { $test->setProxyValue('publicPersistentField', null); $test->setProxyValue('publicAssociation', 'setPublicAssociation'); } ); $this->assertFalse(isset($this->lazyObject->publicPersistentField)); $this->assertNull($this->lazyObject->publicPersistentField); $this->assertTrue(isset($this->lazyObject->publicAssociation)); $this->assertSame('setPublicAssociation', $this->lazyObject->publicAssociation); } public function testCheckingPublicAssociationCausesLazyLoading() { $test = $this; $this->configureInitializerMock( 1, array($this->lazyObject, '__isset', array('publicAssociation')), function () use ($test) { $test->setProxyValue('publicPersistentField', 'newPersistentFieldValue'); $test->setProxyValue('publicAssociation', 'setPublicAssociation'); } ); $this->assertTrue(isset($this->lazyObject->publicAssociation)); $this->assertSame('setPublicAssociation', $this->lazyObject->publicAssociation); $this->assertTrue(isset($this->lazyObject->publicPersistentField)); $this->assertSame('newPersistentFieldValue', $this->lazyObject->publicPersistentField); } /** * Converts a given callable into a closure * * @param callable $callable * @return \Closure */ public function getClosure($callable) { return function () use ($callable) { call_user_func_array($callable, func_get_args()); }; } /** * Configures the current initializer callback mock with provided matcher params * * @param int $expectedCallCount the number of invocations to be expected. If a value< 0 is provided, `any` is used * @param array $callParamsMatch an ordered array of parameters to be expected * @param callable $callbackClosure a return callback closure * * @return \PHPUnit_Framework_MockObject_MockObject| */ protected function configureInitializerMock( $expectedCallCount = 0, array $callParamsMatch = null, \Closure $callbackClosure = null ) { if (!$expectedCallCount) { $invocationCountMatcher = $this->exactly((int) $expectedCallCount); } else { $invocationCountMatcher = $expectedCallCount < 0 ? $this->any() : $this->exactly($expectedCallCount); } $invocationMocker = $this->initializerCallbackMock->expects($invocationCountMatcher)->method('__invoke'); if (null !== $callParamsMatch) { call_user_func_array(array($invocationMocker, 'with'), $callParamsMatch); } if ($callbackClosure) { $invocationMocker->will($this->returnCallback($callbackClosure)); } } /** * Sets a value in the current proxy object without triggering lazy loading through `__set` * * @link https://bugs.php.net/bug.php?id=63463 * * @param string $property * @param mixed $value */ public function setProxyValue($property, $value) { $reflectionProperty = new \ReflectionProperty($this->lazyObject, $property); $initializer = $this->lazyObject->__getInitializer(); // disabling initializer since setting `publicPersistentField` triggers `__set`/`__get` $this->lazyObject->__setInitializer(null); $reflectionProperty->setValue($this->lazyObject, $value); $this->lazyObject->__setInitializer($initializer); } /** * Retrieves the suggested implementation of an initializer that proxy factories in O*M * are currently following, and that should be used to initialize the current proxy object * * @return \Closure */ protected function getSuggestedInitializerImplementation() { $loader = $this->proxyLoader; $identifier = $this->identifier; return function (LazyLoadableObject $proxy) use ($loader, $identifier) { /* @var $proxy LazyLoadableObject|Proxy */ $proxy->__setInitializer(null); $proxy->__setCloner(null); if ($proxy->__isInitialized()) { return; } $properties = $proxy->__getLazyProperties(); foreach ($properties as $propertyName => $property) { if (!isset($proxy->$propertyName)) { $proxy->$propertyName = $properties[$propertyName]; } } $proxy->__setInitialized(true); if (method_exists($proxy, '__wakeup')) { $proxy->__wakeup(); } if (null === $loader->load($identifier, $proxy)) { throw new \UnexpectedValueException('Couldn\'t load'); } }; } }tests/Doctrine/Tests/Common/Proxy/ProxyMagicMethodsTest.php000064400000022323144760112570020120 0ustar00. */ namespace Doctrine\Tests\Common\Proxy; use Doctrine\Common\Proxy\ProxyGenerator; use Doctrine\Common\Proxy\Proxy; use Doctrine\Common\Proxy\Exception\UnexpectedValueException; use PHPUnit_Framework_TestCase; use ReflectionClass; /** * Test for behavior of proxies with inherited magic methods * * @author Marco Pivetta */ class ProxyMagicMethodsTest extends PHPUnit_Framework_TestCase { /** * @var \Doctrine\Common\Proxy\ProxyGenerator */ protected $proxyGenerator; /** * @var LazyLoadableObject|Proxy */ protected $lazyObject; protected $identifier = array( 'publicIdentifierField' => 'publicIdentifierFieldValue', 'protectedIdentifierField' => 'protectedIdentifierFieldValue', ); /** * @var \PHPUnit_Framework_MockObject_MockObject|Callable */ protected $initializerCallbackMock; /** * {@inheritDoc} */ public function setUp() { $this->proxyGenerator = new ProxyGenerator(__DIR__ . '/generated', __NAMESPACE__ . '\\MagicMethodProxy'); } public static function tearDownAfterClass() { } public function testInheritedMagicGet() { $proxyClassName = $this->generateProxyClass(__NAMESPACE__ . '\\MagicGetClass'); $proxy = new $proxyClassName( function (Proxy $proxy, $method, $params) use (&$counter) { if ( ! in_array($params[0], array('publicField', 'test', 'notDefined'))) { throw new \InvalidArgumentException('Unexpected access to field "' . $params[0] . '"'); } $initializer = $proxy->__getInitializer(); $proxy->__setInitializer(null); $proxy->publicField = 'modifiedPublicField'; $counter += 1; $proxy->__setInitializer($initializer); } ); $this->assertSame('id', $proxy->id); $this->assertSame('modifiedPublicField', $proxy->publicField); $this->assertSame('test', $proxy->test); $this->assertSame('not defined', $proxy->notDefined); $this->assertSame(3, $counter); } public function testInheritedMagicSet() { $proxyClassName = $this->generateProxyClass(__NAMESPACE__ . '\\MagicSetClass'); $proxy = new $proxyClassName( function (Proxy $proxy, $method, $params) use (&$counter) { if ( ! in_array($params[0], array('publicField', 'test', 'notDefined'))) { throw new \InvalidArgumentException('Unexpected access to field "' . $params[0] . '"'); } $counter += 1; } ); $this->assertSame('id', $proxy->id); $proxy->publicField = 'publicFieldValue'; $this->assertSame('publicFieldValue', $proxy->publicField); $proxy->test = 'testValue'; $this->assertSame('testValue', $proxy->testAttribute); $proxy->notDefined = 'not defined'; $this->assertSame('not defined', $proxy->testAttribute); $this->assertSame(3, $counter); } public function testInheritedMagicSleep() { $proxyClassName = $this->generateProxyClass(__NAMESPACE__ . '\\MagicSleepClass'); $proxy = new $proxyClassName(); $this->assertSame('defaultValue', $proxy->serializedField); $this->assertSame('defaultValue', $proxy->nonSerializedField); $proxy->serializedField = 'changedValue'; $proxy->nonSerializedField = 'changedValue'; $unserialized = unserialize(serialize($proxy)); $this->assertSame('changedValue', $unserialized->serializedField); $this->assertSame('defaultValue', $unserialized->nonSerializedField, 'Field was not returned by "__sleep"'); } public function testInheritedMagicWakeup() { $proxyClassName = $this->generateProxyClass(__NAMESPACE__ . '\\MagicWakeupClass'); $proxy = new $proxyClassName(); $this->assertSame('defaultValue', $proxy->wakeupValue); $proxy->wakeupValue = 'changedValue'; $unserialized = unserialize(serialize($proxy)); $this->assertSame('newWakeupValue', $unserialized->wakeupValue, '"__wakeup" was called'); $unserialized->__setInitializer(function (Proxy $proxy) { $proxy->__setInitializer(null); $proxy->publicField = 'newPublicFieldValue'; }); $this->assertSame('newPublicFieldValue', $unserialized->publicField, 'Proxy can still be initialized'); } public function testInheritedMagicIsset() { $proxyClassName = $this->generateProxyClass(__NAMESPACE__ . '\\MagicIssetClass'); $proxy = new $proxyClassName(function (Proxy $proxy, $method, $params) use (&$counter) { if (in_array($params[0], array('publicField', 'test', 'nonExisting'))) { $initializer = $proxy->__getInitializer(); $proxy->__setInitializer(null); $proxy->publicField = 'modifiedPublicField'; $counter += 1; $proxy->__setInitializer($initializer); return; } throw new \InvalidArgumentException( sprintf('Should not be initialized when checking isset("%s")', $params[0]) ); }); $this->assertTrue(isset($proxy->id)); $this->assertTrue(isset($proxy->publicField)); $this->assertTrue(isset($proxy->test)); $this->assertFalse(isset($proxy->nonExisting)); $this->assertSame(3, $counter); } public function testInheritedMagicClone() { $proxyClassName = $this->generateProxyClass(__NAMESPACE__ . '\\MagicCloneClass'); $proxy = new $proxyClassName( null, function ($proxy) { $proxy->cloned = true; } ); $cloned = clone $proxy; $this->assertSame('newClonedValue', $cloned->clonedValue); $this->assertFalse($proxy->cloned); $this->assertTrue($cloned->cloned); } /** * @param $className * * @return string */ private function generateProxyClass($className) { $proxyClassName = 'Doctrine\\Tests\\Common\\Proxy\\MagicMethodProxy\\__CG__\\' . $className; if (class_exists($proxyClassName, false)) { return $proxyClassName; } $metadata = $this->getMock('Doctrine\\Common\\Persistence\\Mapping\\ClassMetadata'); $metadata ->expects($this->any()) ->method('getName') ->will($this->returnValue($className)); $metadata ->expects($this->any()) ->method('getIdentifier') ->will($this->returnValue(array('id'))); $metadata ->expects($this->any()) ->method('getReflectionClass') ->will($this->returnValue(new ReflectionClass($className))); $metadata ->expects($this->any()) ->method('isIdentifier') ->will($this->returnCallback(function ($fieldName) { return 'id' === $fieldName; })); $metadata ->expects($this->any()) ->method('hasField') ->will($this->returnCallback(function ($fieldName) { return in_array($fieldName, array('id', 'publicField')); })); $metadata ->expects($this->any()) ->method('hasAssociation') ->will($this->returnValue(false)); $metadata ->expects($this->any()) ->method('getFieldNames') ->will($this->returnValue(array('id', 'publicField'))); $metadata ->expects($this->any()) ->method('getIdentifierFieldNames') ->will($this->returnValue(array('id'))); $metadata ->expects($this->any()) ->method('getAssociationNames') ->will($this->returnValue(array())); $metadata ->expects($this->any()) ->method('getTypeOfField') ->will($this->returnValue('string')); $this->proxyGenerator->generateProxyClass($metadata); require_once $this->proxyGenerator->getProxyFileName($className); return $proxyClassName; } }tests/Doctrine/Tests/Common/Proxy/SleepClass.php000064400000000334144760112570015706 0ustar00getMock('stdClass', array('callGet')); $getCheckMock->expects($this->never())->method('callGet'); $initializer = function () use ($getCheckMock) { call_user_func($getCheckMock); }; $mockProxy = new RuntimePublicReflectionPropertyTestProxyMock(); $mockProxy->__setInitializer($initializer); $reflProperty = new RuntimePublicReflectionProperty( __NAMESPACE__ . '\RuntimePublicReflectionPropertyTestProxyMock', 'checkedProperty' ); $this->assertSame('testValue', $reflProperty->getValue($mockProxy)); unset($mockProxy->checkedProperty); $this->assertNull($reflProperty->getValue($mockProxy)); } public function testSetValueOnProxyPublicProperty() { $setCheckMock = $this->getMock('stdClass', array('neverCallSet')); $setCheckMock->expects($this->never())->method('neverCallSet'); $initializer = function () use ($setCheckMock) { call_user_func(array($setCheckMock, 'neverCallSet')); }; $mockProxy = new RuntimePublicReflectionPropertyTestProxyMock(); $mockProxy->__setInitializer($initializer); $reflProperty = new RuntimePublicReflectionProperty( __NAMESPACE__ . '\RuntimePublicReflectionPropertyTestProxyMock', 'checkedProperty' ); $reflProperty->setValue($mockProxy, 'newValue'); $this->assertSame('newValue', $mockProxy->checkedProperty); unset($mockProxy->checkedProperty); $reflProperty->setValue($mockProxy, 'otherNewValue'); $this->assertSame('otherNewValue', $mockProxy->checkedProperty); $setCheckMock = $this->getMock('stdClass', array('callSet')); $setCheckMock->expects($this->once())->method('callSet'); $initializer = function () use ($setCheckMock) { call_user_func(array($setCheckMock, 'callSet')); }; $mockProxy->__setInitializer($initializer); $mockProxy->__setInitialized(true); unset($mockProxy->checkedProperty); $reflProperty->setValue($mockProxy, 'againNewValue'); $this->assertSame('againNewValue', $mockProxy->checkedProperty); } } /** * Mock that simulates proxy public property lazy loading */ class RuntimePublicReflectionPropertyTestProxyMock implements Proxy { /** * @var \Closure|null */ private $initializer = null; /** * @var \Closure|null */ private $initialized = false; /** * @var string */ public $checkedProperty = 'testValue'; /** * {@inheritDoc} */ public function __getInitializer() { return $this->initializer; } /** * {@inheritDoc} */ public function __setInitializer(\Closure $initializer = null) { $this->initializer = $initializer; } /** * {@inheritDoc} */ public function __getLazyProperties() { } /** * {@inheritDoc} */ public function __load() { } /** * {@inheritDoc} */ public function __isInitialized() { return $this->initialized; } /** * {@inheritDoc} */ public function __setInitialized($initialized) { $this->initialized = (bool) $initialized; } /** * @param string $name */ public function __get($name) { if ($this->initializer) { $cb = $this->initializer; $cb(); } return $this->checkedProperty; } /** * @param string $name * @param mixed $value */ public function __set($name, $value) { if ($this->initializer) { $cb = $this->initializer; $cb(); } // triggers notices if `$name` is used: see https://bugs.php.net/bug.php?id=63463 $this->checkedProperty = $value; } /** * @param string $name * * @return integer */ public function __isset($name) { if ($this->initializer) { $cb = $this->initializer; $cb(); } return isset($this->checkedProperty); } /** * {@inheritDoc} */ public function __setCloner(\Closure $cloner = null) { } /** * {@inheritDoc} */ public function __getCloner() { } }tests/Doctrine/Tests/Common/Reflection/SameNamespaceParent.php000064400000000143144760112570020473 0ustar00 array($testsRoot), ); $noParentClassName = 'Doctrine\\Tests\\Common\\Reflection\\NoParent'; $staticReflectionParser = new StaticReflectionParser($noParentClassName, new Psr0FindFile($paths), $classAnnotationOptimize); $declaringClassName = $staticReflectionParser->getStaticReflectionParserForDeclaringClass('property', 'test')->getClassName(); $this->assertEquals($noParentClassName, $declaringClassName); $className = 'Doctrine\\Tests\\Common\\Reflection\\FullyClassifiedParent'; $staticReflectionParser = new StaticReflectionParser($className, new Psr0FindFile($paths), $classAnnotationOptimize); $declaringClassName = $staticReflectionParser->getStaticReflectionParserForDeclaringClass('property', 'test')->getClassName(); $this->assertEquals($noParentClassName, $declaringClassName); $className = 'Doctrine\\Tests\\Common\\Reflection\\SameNamespaceParent'; $staticReflectionParser = new StaticReflectionParser($className, new Psr0FindFile($paths), $classAnnotationOptimize); $declaringClassName = $staticReflectionParser->getStaticReflectionParserForDeclaringClass('property', 'test')->getClassName(); $this->assertEquals($noParentClassName, $declaringClassName); $dummyParentClassName = 'Doctrine\\Tests\\Common\\Reflection\\Dummies\\NoParent'; $className = 'Doctrine\\Tests\\Common\\Reflection\\DeeperNamespaceParent'; $staticReflectionParser = new StaticReflectionParser($className, new Psr0FindFile($paths), $classAnnotationOptimize); $declaringClassName = $staticReflectionParser->getStaticReflectionParserForDeclaringClass('property', 'test')->getClassName(); $this->assertEquals($dummyParentClassName, $declaringClassName); $className = 'Doctrine\\Tests\\Common\\Reflection\\UseParent'; $staticReflectionParser = new StaticReflectionParser($className, new Psr0FindFile($paths), $classAnnotationOptimize); $declaringClassName = $staticReflectionParser->getStaticReflectionParserForDeclaringClass('property', 'test')->getClassName(); $this->assertEquals($dummyParentClassName, $declaringClassName); } /** * @return array */ public function classAnnotationOptimize() { return array( array(false), array(true) ); } } tests/Doctrine/Tests/Common/Reflection/UseParent.php000064400000000225144760112570016526 0ustar00assertEquals($expectedClassName, ClassUtils::getRealClass($className)); } /** * @dataProvider dataGetClass */ public function testGetClass( $className, $expectedClassName ) { $object = new $className(); $this->assertEquals($expectedClassName, ClassUtils::getClass($object)); } public function testGetParentClass() { $parentClass = ClassUtils::getParentClass( 'MyProject\Proxies\__CG__\OtherProject\Proxies\__CG__\Doctrine\Tests\Common\Util\ChildObject' ); $this->assertEquals('stdClass', $parentClass); } public function testGenerateProxyClassName() { $this->assertEquals( 'Proxies\__CG__\stdClass', ClassUtils::generateProxyClassName( 'stdClass', 'Proxies' ) ); } /** * @dataProvider dataGetClass */ public function testNewReflectionClass( $className, $expectedClassName ) { $reflClass = ClassUtils::newReflectionClass( $className ); $this->assertEquals( $expectedClassName, $reflClass->getName() ); } /** * @dataProvider dataGetClass */ public function testNewReflectionObject( $className, $expectedClassName ) { $object = new $className; $reflClass = ClassUtils::newReflectionObject( $object ); $this->assertEquals( $expectedClassName, $reflClass->getName() ); } } class ChildObject extends \stdClass { } } namespace MyProject\Proxies\__CG__ { class stdClass extends \stdClass { } } namespace MyProject\Proxies\__CG__\Doctrine\Tests\Common\Util { class ChildObject extends \Doctrine\Tests\Common\Util\ChildObject { } } namespace MyProject\Proxies\__CG__\OtherProject\Proxies\__CG__ { class stdClass extends \MyProject\Proxies\__CG__\stdClass { } } namespace MyProject\Proxies\__CG__\OtherProject\Proxies\__CG__\Doctrine\Tests\Common\Util { class ChildObject extends \MyProject\Proxies\__CG__\Doctrine\Tests\Common\Util\ChildObject { } } tests/Doctrine/Tests/Common/Util/DebugTest.php000064400000001712144760112570015333 0ustar00foo = "bar"; $obj->bar = 1234; $var = Debug::export($obj, 2); $this->assertEquals( "stdClass", $var->__CLASS__ ); } public function testExportDateTime() { $obj = new \DateTime( "2010-10-10 10:10:10" ); $var = Debug::export( $obj, 2 ); $this->assertEquals( "DateTime", $var->__CLASS__ ); } public function testExportArrayTraversable() { $obj = new \ArrayObject(array('foobar')); $var = Debug::export($obj, 2); $this->assertContains('foobar', $var->__STORAGE__); $it = new \ArrayIterator(array('foobar')); $var = Debug::export($it, 5); $this->assertContains('foobar', $var->__STORAGE__); } } tests/Doctrine/Tests/DoctrineTestCase.php000064400000000244144760112570014502 0ustar00 */ class NativePhpunitTask extends Task { private $test; private $testfile; private $testdirectory; private $configuration = null; private $coverageClover = null; private $junitlogfile = null; private $haltonfailure = true; private $haltonerror = true; public function setTestdirectory($directory) { $this->testdirectory = $directory; } public function setTest($test) { $this->test = $test; } public function setTestfile($testfile) { $this->testfile = $testfile; } public function setJunitlogfile($junitlogfile) { if (strlen($junitlogfile) == 0) { $junitlogfile = NULL; } $this->junitlogfile = $junitlogfile; } public function setConfiguration($configuration) { if (strlen($configuration) == 0) { $configuration = NULL; } $this->configuration = $configuration; } public function setCoverageClover($coverageClover) { if (strlen($coverageClover) == 0) { $coverageClover = NULL; } $this->coverageClover = $coverageClover; } public function setHaltonfailure($haltonfailures) { $this->haltonfailure = $haltonfailures; } public function setHaltonerror($haltonerrors) { $this->haltonerror = $haltonerrors; } public function init() { require_once "PHPUnit/Runner/Version.php"; $version = PHPUnit_Runner_Version::id(); if (version_compare($version, '3.4.0') < 0) { throw new BuildException("NativePHPUnitTask requires PHPUnit version >= 3.2.0", $this->getLocation()); } require_once 'PHPUnit/Util/Filter.php'; // point PHPUnit_MAIN_METHOD define to non-existing method if (!defined('PHPUnit_MAIN_METHOD')) { define('PHPUnit_MAIN_METHOD', 'PHPUnitTask::undefined'); } } public function main() { if (!is_dir(realpath($this->testdirectory))) { throw new BuildException("NativePHPUnitTask requires a Test Directory path given, '".$this->testdirectory."' given."); } set_include_path(realpath($this->testdirectory) . PATH_SEPARATOR . get_include_path()); $printer = new NativePhpunitPrinter(); $arguments = array( 'configuration' => $this->configuration, 'coverageClover' => $this->coverageClover, 'junitLogfile' => $this->junitlogfile, 'printer' => $printer, ); $runner = new PHPUnit_TextUI_TestRunner(); $suite = $runner->getTest($this->test, $this->testfile, true); try { $result = $runner->doRun($suite, $arguments); /* @var $result PHPUnit_Framework_TestResult */ if ( ($this->haltonfailure && $result->failureCount() > 0) || ($this->haltonerror && $result->errorCount() > 0) ) { throw new BuildException("PHPUnit: ".$result->failureCount()." Failures and ".$result->errorCount()." Errors, ". "last failure message: ".$printer->getMessages()); } $this->log("PHPUnit Success: ".count($result->passed())." tests passed, no ". "failures (".$result->skippedCount()." skipped, ".$result->notImplementedCount()." not implemented)"); // Hudson for example doesn't like the backslash in class names if (is_file($this->coverageClover)) { $this->log("Generated Clover Coverage XML to: ".$this->coverageClover); $content = file_get_contents($this->coverageClover); $content = str_replace("\\", ".", $content); file_put_contents($this->coverageClover, $content); unset($content); } } catch(\Exception $e) { throw new BuildException("NativePhpunitTask failed: ".$e->getMessage()); } } } class NativePhpunitPrinter extends PHPUnit_Util_Printer implements PHPUnit_Framework_TestListener { private $_messages = array(); public function write($buffer) { // do nothing } public function getMessages() { return $this->_messages; } /** * An error occurred. * * @param PHPUnit_Framework_Test $test * @param Exception $e * @param float $time */ public function addError(PHPUnit_Framework_Test $test, Exception $e, $time) { $this->_messages[] = "Test ERROR: ".$test->getName().": ".$e->getMessage(); } /** * A failure occurred. * * @param PHPUnit_Framework_Test $test * @param PHPUnit_Framework_AssertionFailedError $e * @param float $time */ public function addFailure(PHPUnit_Framework_Test $test, PHPUnit_Framework_AssertionFailedError $e, $time) { $this->_messages[] = "Test FAILED: ".$test->getName().": ".$e->getMessage(); } /** * Incomplete test. * * @param PHPUnit_Framework_Test $test * @param Exception $e * @param float $time */ public function addIncompleteTest(PHPUnit_Framework_Test $test, Exception $e, $time) { } /** * Skipped test. * * @param PHPUnit_Framework_Test $test * @param Exception $e * @param float $time * @since Method available since Release 3.0.0 */ public function addSkippedTest(PHPUnit_Framework_Test $test, Exception $e, $time) { } /** * A test suite started. * * @param PHPUnit_Framework_TestSuite $suite * @since Method available since Release 2.2.0 */ public function startTestSuite(PHPUnit_Framework_TestSuite $suite) { } /** * A test suite ended. * * @param PHPUnit_Framework_TestSuite $suite * @since Method available since Release 2.2.0 */ public function endTestSuite(PHPUnit_Framework_TestSuite $suite) { } /** * A test started. * * @param PHPUnit_Framework_Test $test */ public function startTest(PHPUnit_Framework_Test $test) { } /** * A test ended. * * @param PHPUnit_Framework_Test $test * @param float $time */ public function endTest(PHPUnit_Framework_Test $test, $time) { } } tests/README.markdown000064400000001523144760112570010417 0ustar00# Running the Doctrine 2 Testsuite ## Running tests Execute PHPUnit in the root folder of your doctrine-common clone. phpunit ## Testing Lock-Support The Lock support in Doctrine 2 is tested using Gearman, which allows to run concurrent tasks in parallel. Install Gearman with PHP as follows: 1. Go to http://www.gearman.org and download the latest Gearman Server 2. Compile it and then call ldconfig 3. Start it up "gearmand -vvvv" 4. Install pecl/gearman by calling "gearman-beta" You can then go into tests/ and start up two workers: php Doctrine/Tests/ORM/Functional/Locking/LockAgentWorker.php Then run the locking test-suite: phpunit --configuration Doctrine/Tests/ORM/Functional/Locking/GearmanLockTest.php This can run considerable time, because it is using sleep() to test for the timing ranges of locks.lib/vendor/doctrine-build-common000077700000000000144760112570012735 5ustar00