diff --git a/.coveralls.yml b/.coveralls.yml deleted file mode 100644 index b086fff7a45..00000000000 --- a/.coveralls.yml +++ /dev/null @@ -1,4 +0,0 @@ -# for php-coveralls -service_name: travis-ci -src_dir: lib -coverage_clover: build/logs/clover*.xml diff --git a/.gitattributes b/.gitattributes index 6b4dc843e4c..c5a870fd09b 100644 --- a/.gitattributes +++ b/.gitattributes @@ -10,3 +10,4 @@ build.xml export-ignore CONTRIBUTING.md export-ignore phpunit.xml.dist export-ignore run-all.sh export-ignore +phpcs.xml.dist export-ignore diff --git a/.gitignore b/.gitignore index 490413d15f7..81e913c4313 100644 --- a/.gitignore +++ b/.gitignore @@ -10,5 +10,7 @@ lib/Doctrine/DBAL .buildpath .project .idea +*.iml vendor/ -composer.lock +/tests/Doctrine/Performance/history.db +/.phpcs-cache diff --git a/.scrutinizer.yml b/.scrutinizer.yml index 361b21e38c5..d05c72cf061 100644 --- a/.scrutinizer.yml +++ b/.scrutinizer.yml @@ -1,34 +1,34 @@ +build: + nodes: + analysis: + environment: + php: + version: 7.1 + cache: + disabled: false + directories: + - ~/.composer/cache + + project_setup: + override: true + tests: + override: + - php-scrutinizer-run + before_commands: - "composer install --no-dev --prefer-source" tools: external_code_coverage: timeout: 3600 - php_code_coverage: - enabled: true - php_code_sniffer: - enabled: false - php_cpd: - enabled: true - excluded_dirs: ["bin", "docs", "tests", "tools", "vendor"] - php_cs_fixer: - enabled: false - php_loc: - enabled: true - excluded_dirs: ["bin", "docs", "tests", "tools", "vendor"] - php_mess_detector: - enabled: true - filter: - paths: ["lib/*"] - php_pdepend: - enabled: true - excluded_dirs: ["docs", "examples", "tests", "vendor"] - php_analyzer: - enabled: true - filter: - paths: ["lib/*", "tests/*"] - php_hhvm: - enabled: true - filter: - paths: ["lib/*", "tests/*"] - sensiolabs_security_checker: true + +filter: + excluded_paths: + - docs + - tools + +build_failure_conditions: + - 'elements.rating(<= C).new.exists' # No new classes/methods with a rating of C or worse allowed + - 'issues.severity(>= MAJOR).new.exists' # New issues of major or higher severity + - 'project.metric_change("scrutinizer.test_coverage", < 0)' # Code Coverage decreased from previous inspection + - 'patches.label("Unused Use Statements").new.exists' # No new unused imports patches allowed diff --git a/.travis.yml b/.travis.yml index 5a9fb2dcb0c..9a40fe7d22f 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,64 +1,131 @@ +dist: trusty +sudo: false language: php php: - - 5.6 - - 7.0 + - 7.1 + - 7.2 + - 7.3 + - 7.4snapshot - nightly - - hhvm env: + - DB=sqlite - DB=mysql - DB=pgsql - - DB=sqlite -before_script: - - if [[ $TRAVIS_PHP_VERSION = '7.0' && $DB = 'sqlite' ]]; then PHPUNIT_FLAGS="--coverage-clover ./build/logs/clover.xml"; else PHPUNIT_FLAGS=""; fi - - if [[ $TRAVIS_PHP_VERSION != '7.0' && $TRAVIS_PHP_VERSION != 'hhvm' ]]; then phpenv config-rm xdebug.ini; fi +before_install: + - mv ~/.phpenv/versions/$(phpenv version-name)/etc/conf.d/xdebug.ini{,.disabled} || echo "xdebug not available" - composer self-update - - composer install --prefer-source + +install: travis_retry composer validate --strict && composer update --prefer-dist script: - - ENABLE_SECOND_LEVEL_CACHE=0 ./vendor/bin/phpunit -v -c tests/travis/$DB.travis.xml $PHPUNIT_FLAGS + - if [[ "$DB" == "mysql" || "$DB" == "mariadb" ]]; then mysql -e "CREATE SCHEMA doctrine_tests; GRANT ALL PRIVILEGES ON doctrine_tests.* to travis@'%'"; fi + - ENABLE_SECOND_LEVEL_CACHE=0 ./vendor/bin/phpunit -v -c tests/travis/$DB.travis.xml - ENABLE_SECOND_LEVEL_CACHE=1 ./vendor/bin/phpunit -v -c tests/travis/$DB.travis.xml --exclude-group performance,non-cacheable,locking_functional -after_script: - - if [[ $TRAVIS_PHP_VERSION = '7.0' && $DB = 'sqlite' ]]; then wget https://scrutinizer-ci.com/ocular.phar; fi - - if [[ $TRAVIS_PHP_VERSION = '7.0' && $DB = 'sqlite' ]]; then php ocular.phar code-coverage:upload --format=php-clover build/logs/clover.xml; fi - -matrix: +jobs: include: - - php: 5.6 - env: DB=mariadb - addons: - mariadb: 5.5 - - php: 7.0 - env: DB=mariadb - addons: - mariadb: 5.5 - - php: hhvm - env: DB=mariadb - addons: - mariadb: 5.5 - - - php: 5.6 + - stage: Test env: DB=mariadb addons: mariadb: 10.1 - - php: 7.0 - env: DB=mariadb - addons: - mariadb: 10.1 - - php: hhvm - env: DB=mariadb - addons: - mariadb: 10.1 - exclude: - - php: hhvm - env: DB=pgsql # driver for PostgreSQL currently unsupported by HHVM, requires 3rd party dependency + + - stage: Test + dist: xenial + env: DB=mysql MYSQL_VERSION=5.7 + php: 7.1 + services: + - mysql + before_script: + - ./tests/travis/install-mysql-$MYSQL_VERSION.sh + sudo: required + + - stage: Test + dist: xenial + env: DB=mysql MYSQL_VERSION=5.7 + php: 7.2 + services: + - mysql + before_script: + - ./tests/travis/install-mysql-$MYSQL_VERSION.sh + sudo: required + + - stage: Test + dist: xenial + env: DB=mysql MYSQL_VERSION=5.7 + php: 7.4snapshot + services: + - mysql + before_script: + - ./tests/travis/install-mysql-$MYSQL_VERSION.sh + sudo: required + + - stage: Test + env: DB=sqlite DEPENDENCIES=low + install: travis_retry composer update --prefer-dist --prefer-lowest + + - stage: Test + if: type = cron + php: 7.3 + env: DB=sqlite DEV_DEPENDENCIES + install: + - composer config minimum-stability dev + - travis_retry composer update --prefer-dist + + - stage: Test + env: DB=sqlite COVERAGE + before_script: + - mv ~/.phpenv/versions/$(phpenv version-name)/etc/conf.d/xdebug.ini{.disabled,} + - if [[ ! $(php -m | grep -si xdebug) ]]; then echo "xdebug required for coverage"; exit 1; fi + script: + - ENABLE_SECOND_LEVEL_CACHE=0 ./vendor/bin/phpunit -v -c tests/travis/$DB.travis.xml --coverage-clover ./build/logs/clover.xml + after_script: + - wget https://scrutinizer-ci.com/ocular.phar + - php ocular.phar code-coverage:upload --format=php-clover build/logs/clover.xml + + - stage: Code Quality + env: DB=none STATIC_ANALYSIS + install: travis_retry composer install --prefer-dist + before_script: + - echo "extension=memcached.so" >> ~/.phpenv/versions/$(phpenv version-name)/etc/php.ini + - echo "extension=redis.so" >> ~/.phpenv/versions/$(phpenv version-name)/etc/php.ini + - travis_retry composer require --dev --prefer-dist --prefer-stable phpstan/phpstan:^0.9 + script: vendor/bin/phpstan analyse -l 1 -c phpstan.neon lib + + - stage: Code Quality + env: DB=none BENCHMARK + before_script: wget https://phpbench.github.io/phpbench/phpbench.phar https://phpbench.github.io/phpbench/phpbench.phar.pubkey + script: php phpbench.phar run -l dots --report=default + + - stage: Code Quality + if: NOT type = pull_request + env: DB=none CODING_STANDARDS + php: 7.4snapshot + install: travis_retry composer install --prefer-dist + script: + - ./vendor/bin/phpcs + + - stage: Code Quality + if: type = pull_request + env: DB=none PULL_REQUEST_CODING_STANDARDS + php: 7.1 + install: travis_retry composer install --prefer-dist + script: + - | + if [ $TRAVIS_BRANCH != "master" ]; then + git remote set-branches --add origin $TRAVIS_BRANCH; + git fetch origin $TRAVIS_BRANCH; + fi + - git merge-base origin/$TRAVIS_BRANCH $TRAVIS_PULL_REQUEST_SHA || git fetch origin +refs/pull/$TRAVIS_PULL_REQUEST/merge --unshallow + - wget https://github.com/diff-sniffer/git/releases/download/0.2.0/git-phpcs.phar + - php git-phpcs.phar origin/$TRAVIS_BRANCH...$TRAVIS_PULL_REQUEST_SHA + allow_failures: - php: nightly - -sudo: false + - stage: Code Quality + env: DB=none CODING_STANDARDS cache: directories: diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 1034dbe0654..482fb631b7c 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -44,12 +44,12 @@ Please try to add a test for your pull-request. You can run the unit-tests by calling ``vendor/bin/phpunit`` from the root of the project. It will run all the tests with an in memory SQLite database. -In order to do that, you will need a fresh copy of doctrine2, and you +In order to do that, you will need a fresh copy of the ORM, and you will have to run a composer installation in the project: ```sh -git clone git@github.com:doctrine/doctrine2.git -cd doctrine2 +git clone git@github.com:doctrine/orm.git +cd orm curl -sS https://getcomposer.org/installer | php -- ./composer.phar install ``` @@ -66,7 +66,7 @@ sqlite database. Tips for creating unit tests: 1. If you put a test into the `Ticket` namespace as described above, put the testcase and all entities into the same class. - See `https://github.com/doctrine/doctrine2/tree/master/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2306Test.php` for an + See `https://github.com/doctrine/orm/tree/master/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2306Test.php` for an example. ## Travis diff --git a/README.md b/README.md index 6c46f637c8b..7f935fc34c1 100644 --- a/README.md +++ b/README.md @@ -3,7 +3,7 @@ | [![Build status][Master image]][Master] | [![Build status][2.5 image]][2.5] | | [![Coverage Status][Master coverage image]][Master coverage] | [![Coverage Status][2.5 coverage image]][2.5 coverage] | -Doctrine 2 is an object-relational mapper (ORM) for PHP 5.4+ that provides transparent persistence +Doctrine 2 is an object-relational mapper (ORM) for PHP 7.1+ that provides transparent persistence for PHP objects. It sits on top of a powerful database abstraction layer (DBAL). One of its key features is the option to write database queries in a proprietary object oriented SQL dialect called Doctrine Query Language (DQL), inspired by Hibernate's HQL. This provides developers with a powerful alternative to SQL that maintains flexibility @@ -16,11 +16,11 @@ without requiring unnecessary code duplication. * [Documentation](http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/index.html) - [Master image]: https://img.shields.io/travis/doctrine/doctrine2/master.svg?style=flat-square - [Master]: https://travis-ci.org/doctrine/doctrine2 - [Master coverage image]: https://img.shields.io/coveralls/doctrine/doctrine2/master.svg?style=flat-square - [Master coverage]: https://coveralls.io/r/doctrine/doctrine2?branch=master - [2.5 image]: https://img.shields.io/travis/doctrine/doctrine2/2.5.svg?style=flat-square - [2.5]: https://github.com/doctrine/doctrine2/tree/2.5 - [2.5 coverage image]: https://img.shields.io/coveralls/doctrine/doctrine2/2.5.svg?style=flat-square - [2.5 coverage]: https://coveralls.io/r/doctrine/doctrine2?branch=2.5 + [Master image]: https://img.shields.io/travis/doctrine/orm/master.svg?style=flat-square + [Master]: https://travis-ci.org/doctrine/orm + [Master coverage image]: https://img.shields.io/scrutinizer/coverage/g/doctrine/orm/master.svg?style=flat-square + [Master coverage]: https://scrutinizer-ci.com/g/doctrine/orm/?branch=master + [2.5 image]: https://img.shields.io/travis/doctrine/orm/2.5.svg?style=flat-square + [2.5]: https://github.com/doctrine/orm/tree/2.5 + [2.5 coverage image]: https://img.shields.io/scrutinizer/coverage/g/doctrine/orm/2.5.svg?style=flat-square + [2.5 coverage]: https://scrutinizer-ci.com/g/doctrine/orm/?branch=2.5 diff --git a/SECURITY.md b/SECURITY.md index 313900211e6..0789963bf70 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -11,7 +11,7 @@ Please read the documentation chapter on Security in Doctrine DBAL and ORM to understand the assumptions we make. - [DBAL Security Page](https://github.com/doctrine/dbal/blob/master/docs/en/reference/security.rst) -- [ORM Security Page](https://github.com/doctrine/doctrine2/blob/master/docs/en/reference/security.rst) +- [ORM Security Page](https://github.com/doctrine/orm/blob/master/docs/en/reference/security.rst) If you find a Security bug in Doctrine, please report it on Jira and change the Security Level to "Security Issues". It will be visible to Doctrine Core diff --git a/UPGRADE.md b/UPGRADE.md index ed9a538b3ec..c6c6eaaa016 100644 --- a/UPGRADE.md +++ b/UPGRADE.md @@ -1,5 +1,195 @@ +# Upgrade to 2.7 + +## Added `Doctrine\ORM\AbstractQuery#enableResultCache()` and `Doctrine\ORM\AbstractQuery#disableResultCache()` methods + +Method `Doctrine\ORM\AbstractQuery#useResultCache()` which could be used for both enabling and disabling the cache +(depending on passed flag) was split into two. + +## Minor BC BREAK: paginator output walkers aren't be called anymore on sub-queries for queries without max results + +To optimize DB interaction, `Doctrine\ORM\Tools\Pagination\Paginator` no longer fetches identifiers to be able to +perform the pagination with join collections when max results isn't set in the query. + +## Deprecated number unaware `Doctrine\ORM\Mapping\UnderscoreNamingStrategy` + +In the last patch of the `v2.6.x` series, we fixed a bug that was not converting names properly when they had numbers +(e.g.: `base64Encoded` was wrongly converted to `base64encoded` instead of `base64_encoded`). + +In order to not break BC we've introduced a way to enable the fixed behavior using a boolean constructor argument. This +argument will be removed in 3.0 and the default behavior will be the fixed one. + +## Deprecated: `Doctrine\ORM\AbstractQuery#useResultCache()` + +Method `Doctrine\ORM\AbstractQuery#useResultCache()` is deprecated because it is split into `enableResultCache()` +and `disableResultCache()`. It will be removed in 3.0. + +## Deprecated code generators and related console commands + +These console commands have been deprecated: + + * `orm:convert-mapping` + * `orm:generate:entities` + * `orm:generate-repositories` + +These classes have been deprecated: + + * `Doctrine\ORM\Tools\EntityGenerator` + * `Doctrine\ORM\Tools\EntityRepositoryGenerator` + +Whole Doctrine\ORM\Tools\Export namespace with all its members have been deprecated as well. + +## Deprecated `Doctrine\ORM\Proxy\Proxy` marker interface + +Proxy objects in Doctrine ORM 3.0 will no longer implement `Doctrine\ORM\Proxy\Proxy` nor +`Doctrine\Common\Persistence\Proxy`: instead, they implement +`ProxyManager\Proxy\GhostObjectInterface`. + +These related classes have been deprecated: + + * `Doctrine\ORM\Proxy\ProxyFactory` + * `Doctrine\ORM\Proxy\Autoloader` - we suggest using the composer autoloader instead + +These methods have been deprecated: + + * `Doctrine\ORM\Configuration#getAutoGenerateProxyClasses()` + * `Doctrine\ORM\Configuration#getProxyDir()` + * `Doctrine\ORM\Configuration#getProxyNamespace()` + +## Deprecated `Doctrine\ORM\Version` + +The `Doctrine\ORM\Version` class is now deprecated and will be removed in Doctrine ORM 3.0: +please refrain from checking the ORM version at runtime or use +[ocramius/package-versions](https://github.com/Ocramius/PackageVersions/). + +## Deprecated `EntityManager#merge()` and `EntityManager#detach()` methods + +Merge and detach semantics were a poor fit for the PHP "share-nothing" architecture. +In addition to that, merging/detaching caused multiple issues with data integrity +in the managed entity graph, which was constantly spawning more edge-case bugs/scenarios. + +The following API methods were therefore deprecated: + +* `EntityManager#merge()` +* `EntityManager#detach()` +* `UnitOfWork#merge()` +* `UnitOfWork#detach()` + +Users are encouraged to migrate `EntityManager#detach()` calls to `EntityManager#clear()`. + +In order to maintain performance on batch processing jobs, it is endorsed to enable +the second level cache (http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/second-level-cache.html) +on entities that are frequently reused across multiple `EntityManager#clear()` calls. + +An alternative to `EntityManager#merge()` will not be provided by ORM 3.0, since the merging +semantics should be part of the business domain rather than the persistence domain of an +application. If your application relies heavily on CRUD-alike interactions and/or `PATCH` +restful operations, you should look at alternatives such as [JMSSerializer](https://github.com/schmittjoh/serializer). + +## Extending `EntityManager` is deprecated + +Final keyword will be added to the `EntityManager::class` in Doctrine ORM 3.0 in order to ensure that EntityManager + is not used as valid extension point. Valid extension point should be EntityManagerInterface. + +## Deprecated `EntityManager#clear($entityName)` + +If your code relies on clearing a single entity type via `EntityManager#clear($entityName)`, +the signature has been changed to `EntityManager#clear()`. + +The main reason is that partial clears caused multiple issues with data integrity +in the managed entity graph, which was constantly spawning more edge-case bugs/scenarios. + +## Deprecated `EntityManager#flush($entity)` and `EntityManager#flush($entities)` + +If your code relies on single entity flushing optimisations via +`EntityManager#flush($entity)`, the signature has been changed to +`EntityManager#flush()`. + +Said API was affected by multiple data integrity bugs due to the fact +that change tracking was being restricted upon a subset of the managed +entities. The ORM cannot support committing subsets of the managed +entities while also guaranteeing data integrity, therefore this +utility was removed. + +The `flush()` semantics will remain the same, but the change tracking will be performed +on all entities managed by the unit of work, and not just on the provided +`$entity` or `$entities`, as the parameter is now completely ignored. + +The same applies to `UnitOfWork#commit($entity)`, which will simply be +`UnitOfWork#commit()`. + +If you would still like to perform batching operations over small `UnitOfWork` +instances, it is suggested to follow these paths instead: + + * eagerly use `EntityManager#clear()` in conjunction with a specific second level + cache configuration (see http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/second-level-cache.html) + * use an explicit change tracking policy (see http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/change-tracking-policies.html) + +## Deprecated `YAML` mapping drivers. + +If your code relies on `YamlDriver` or `SimpleYamlDriver`, you **MUST** change to +annotation or XML drivers instead. + +## Deprecated: `Doctrine\ORM\EntityManagerInterface#copy()` + +Method `Doctrine\ORM\EntityManagerInterface#copy()` never got its implementation and is deprecated. +It will be removed in 3.0. + +# Upgrade to 2.6 + +## Added `Doctrine\ORM\EntityRepository::count()` method + +`Doctrine\ORM\EntityRepository::count()` has been added. This new method has different +signature than `Countable::count()` (required parameter) and therefore are not compatible. +If your repository implemented the `Countable` interface, you will have to use +`$repository->count([])` instead and not implement `Countable` interface anymore. + +## Minor BC BREAK: `Doctrine\ORM\Tools\Console\ConsoleRunner` is now final + +Since it's just an utilitarian class and should not be inherited. + +## Minor BC BREAK: removed `Doctrine\ORM\Query\QueryException::associationPathInverseSideNotSupported()` + +Method `Doctrine\ORM\Query\QueryException::associationPathInverseSideNotSupported()` +now has a required parameter `$pathExpr`. + +## Minor BC BREAK: removed `Doctrine\ORM\Query\Parser#isInternalFunction()` + +Method `Doctrine\ORM\Query\Parser#isInternalFunction()` was removed because +the distinction between internal function and user defined DQL was removed. +[#6500](https://github.com/doctrine/orm/pull/6500) + +## Minor BC BREAK: removed `Doctrine\ORM\ORMException#overwriteInternalDQLFunctionNotAllowed()` + +Method `Doctrine\ORM\Query\Parser#overwriteInternalDQLFunctionNotAllowed()` was +removed because of the choice to allow users to overwrite internal functions, ie +`AVG`, `SUM`, `COUNT`, `MIN` and `MAX`. [#6500](https://github.com/doctrine/orm/pull/6500) + +## PHP 7.1 is now required + +Doctrine 2.6 now requires PHP 7.1 or newer. + +As a consequence, automatic cache setup in Doctrine\ORM\Tools\Setup::create*Configuration() was changed: +- APCu extension (ext-apcu) will now be used instead of abandoned APC (ext-apc). +- Memcached extension (ext-memcached) will be used instead of obsolete Memcache (ext-memcache). +- XCache support was dropped as it doesn't work with PHP 7. + # Upgrade to 2.5 +## Minor BC BREAK: removed `Doctrine\ORM\Query\SqlWalker#walkCaseExpression()` + +Method `Doctrine\ORM\Query\SqlWalker#walkCaseExpression()` was unused and part +of the internal API of the ORM, so it was removed. [#5600](https://github.com/doctrine/orm/pull/5600). + +## Minor BC BREAK: removed $className parameter on `AbstractEntityInheritancePersister#getSelectJoinColumnSQL()` + +As `$className` parameter was not used in the method, it was safely removed. + +## Minor BC BREAK: query cache key time is now a float + +As of 2.5.5, the `QueryCacheEntry#time` property will contain a float value +instead of an integer in order to have more precision and also to be consistent +with the `TimestampCacheEntry#time`. + ## Minor BC BREAK: discriminator map must now include all non-transient classes It is now required that you declare the root of an inheritance in the diff --git a/bin/doctrine.php b/bin/doctrine.php index 81e0166865a..81d4e7bf279 100644 --- a/bin/doctrine.php +++ b/bin/doctrine.php @@ -20,8 +20,10 @@ use Symfony\Component\Console\Helper\HelperSet; use Doctrine\ORM\Tools\Console\ConsoleRunner; -$autoloadFiles = array(__DIR__ . '/../vendor/autoload.php', - __DIR__ . '/../../../autoload.php'); +$autoloadFiles = [ + __DIR__ . '/../vendor/autoload.php', + __DIR__ . '/../../../autoload.php' +]; foreach ($autoloadFiles as $autoloadFile) { if (file_exists($autoloadFile)) { @@ -30,7 +32,7 @@ } } -$directories = array(getcwd(), getcwd() . DIRECTORY_SEPARATOR . 'config'); +$directories = [getcwd(), getcwd() . DIRECTORY_SEPARATOR . 'config']; $configFile = null; foreach ($directories as $directory) { @@ -51,7 +53,7 @@ exit(1); } -$commands = array(); +$commands = []; $helperSet = require $configFile; diff --git a/composer.json b/composer.json index 173bdd36cee..57ed2dab108 100644 --- a/composer.json +++ b/composer.json @@ -13,19 +13,26 @@ {"name": "Marco Pivetta", "email": "ocramius@gmail.com"} ], "minimum-stability": "dev", + "config": { + "sort-packages": true + }, "require": { - "php": "^5.6 || ^7.0", + "php": "^7.1", "ext-pdo": "*", - "doctrine/collections": "~1.2", - "doctrine/dbal": ">=2.5-dev,<2.7-dev", - "doctrine/instantiator": "~1.0.1", - "doctrine/common": ">=2.5-dev,<2.7-dev", - "doctrine/cache": "~1.4", - "symfony/console": "~2.5|~3.0" + "doctrine/annotations": "^1.8", + "doctrine/cache": "^1.9.1", + "doctrine/collections": "^1.5", + "doctrine/common": "^2.11", + "doctrine/dbal": "^2.9.3", + "doctrine/event-manager": "^1.1", + "doctrine/instantiator": "^1.3", + "doctrine/persistence": "^1.2", + "symfony/console": "^3.0|^4.0|^5.0" }, "require-dev": { - "symfony/yaml": "~2.3|~3.0", - "phpunit/phpunit": "^5.4" + "doctrine/coding-standard": "^5.0", + "phpunit/phpunit": "^7.5", + "symfony/yaml": "^3.4|^4.0|^5.0" }, "suggest": { "symfony/yaml": "If you want to use YAML Metadata Mapping Driver" @@ -34,15 +41,18 @@ "psr-4": { "Doctrine\\ORM\\": "lib/Doctrine/ORM" } }, "autoload-dev": { - "psr-4": { "Doctrine\\Tests\\": "tests/Doctrine/Tests" } + "psr-4": { + "Doctrine\\Tests\\": "tests/Doctrine/Tests", + "Doctrine\\Performance\\": "tests/Doctrine/Performance" + } }, "bin": ["bin/doctrine"], "extra": { "branch-alias": { - "dev-master": "2.6.x-dev" + "dev-master": "2.7.x-dev" } }, "archive": { - "exclude": ["!vendor", "tests", "*phpunit.xml", ".travis.yml", "build.xml", "build.properties", "composer.phar", "vendor/satooshi", "lib/vendor", "*.swp", "*coveralls.yml"] + "exclude": ["!vendor", "tests", "*phpunit.xml", ".travis.yml", "build.xml", "build.properties", "composer.phar", "vendor/satooshi", "lib/vendor", "*.swp"] } } diff --git a/composer.lock b/composer.lock new file mode 100644 index 00000000000..fc220d23562 --- /dev/null +++ b/composer.lock @@ -0,0 +1,2744 @@ +{ + "_readme": [ + "This file locks the dependencies of your project to a known state", + "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", + "This file is @generated automatically" + ], + "content-hash": "4e24e01f599825550170acce0dda0b49", + "packages": [ + { + "name": "doctrine/annotations", + "version": "v1.8.0", + "source": { + "type": "git", + "url": "https://github.com/doctrine/annotations.git", + "reference": "904dca4eb10715b92569fbcd79e201d5c349b6bc" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/doctrine/annotations/zipball/904dca4eb10715b92569fbcd79e201d5c349b6bc", + "reference": "904dca4eb10715b92569fbcd79e201d5c349b6bc", + "shasum": "" + }, + "require": { + "doctrine/lexer": "1.*", + "php": "^7.1" + }, + "require-dev": { + "doctrine/cache": "1.*", + "phpunit/phpunit": "^7.5" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.7.x-dev" + } + }, + "autoload": { + "psr-4": { + "Doctrine\\Common\\Annotations\\": "lib/Doctrine/Common/Annotations" + } + }, + "notification-url": "https://packagist.org/downloads/", + "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" + } + ], + "description": "Docblock Annotations Parser", + "homepage": "http://www.doctrine-project.org", + "keywords": [ + "annotations", + "docblock", + "parser" + ], + "time": "2019-10-01T18:55:10+00:00" + }, + { + "name": "doctrine/cache", + "version": "1.9.1", + "source": { + "type": "git", + "url": "https://github.com/doctrine/cache.git", + "reference": "89a5c76c39c292f7798f964ab3c836c3f8192a55" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/doctrine/cache/zipball/89a5c76c39c292f7798f964ab3c836c3f8192a55", + "reference": "89a5c76c39c292f7798f964ab3c836c3f8192a55", + "shasum": "" + }, + "require": { + "php": "~7.1" + }, + "conflict": { + "doctrine/common": ">2.2,<2.4" + }, + "require-dev": { + "alcaeus/mongo-php-adapter": "^1.1", + "doctrine/coding-standard": "^6.0", + "mongodb/mongodb": "^1.1", + "phpunit/phpunit": "^7.0", + "predis/predis": "~1.0" + }, + "suggest": { + "alcaeus/mongo-php-adapter": "Required to use legacy MongoDB driver" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.9.x-dev" + } + }, + "autoload": { + "psr-4": { + "Doctrine\\Common\\Cache\\": "lib/Doctrine/Common/Cache" + } + }, + "notification-url": "https://packagist.org/downloads/", + "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" + } + ], + "description": "PHP Doctrine Cache library is a popular cache implementation that supports many different drivers such as redis, memcache, apc, mongodb and others.", + "homepage": "https://www.doctrine-project.org/projects/cache.html", + "keywords": [ + "abstraction", + "apcu", + "cache", + "caching", + "couchdb", + "memcached", + "php", + "redis", + "riak", + "xcache" + ], + "time": "2019-11-15T14:31:57+00:00" + }, + { + "name": "doctrine/collections", + "version": "v1.5.0", + "source": { + "type": "git", + "url": "https://github.com/doctrine/collections.git", + "reference": "a01ee38fcd999f34d9bfbcee59dbda5105449cbf" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/doctrine/collections/zipball/a01ee38fcd999f34d9bfbcee59dbda5105449cbf", + "reference": "a01ee38fcd999f34d9bfbcee59dbda5105449cbf", + "shasum": "" + }, + "require": { + "php": "^7.1" + }, + "require-dev": { + "doctrine/coding-standard": "~0.1@dev", + "phpunit/phpunit": "^5.7" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.3.x-dev" + } + }, + "autoload": { + "psr-0": { + "Doctrine\\Common\\Collections\\": "lib/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Roman Borschel", + "email": "roman@code-factory.org" + }, + { + "name": "Benjamin Eberlei", + "email": "kontakt@beberlei.de" + }, + { + "name": "Guilherme Blanco", + "email": "guilhermeblanco@gmail.com" + }, + { + "name": "Jonathan Wage", + "email": "jonwage@gmail.com" + }, + { + "name": "Johannes Schmitt", + "email": "schmittjoh@gmail.com" + } + ], + "description": "Collections Abstraction library", + "homepage": "http://www.doctrine-project.org", + "keywords": [ + "array", + "collections", + "iterator" + ], + "time": "2017-07-22T10:37:32+00:00" + }, + { + "name": "doctrine/common", + "version": "v2.11.0", + "source": { + "type": "git", + "url": "https://github.com/doctrine/common.git", + "reference": "b8ca1dcf6b0dc8a2af7a09baac8d0c48345df4ff" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/doctrine/common/zipball/b8ca1dcf6b0dc8a2af7a09baac8d0c48345df4ff", + "reference": "b8ca1dcf6b0dc8a2af7a09baac8d0c48345df4ff", + "shasum": "" + }, + "require": { + "doctrine/annotations": "^1.0", + "doctrine/cache": "^1.0", + "doctrine/collections": "^1.0", + "doctrine/event-manager": "^1.0", + "doctrine/inflector": "^1.0", + "doctrine/lexer": "^1.0", + "doctrine/persistence": "^1.1", + "doctrine/reflection": "^1.0", + "php": "^7.1" + }, + "require-dev": { + "doctrine/coding-standard": "^1.0", + "phpstan/phpstan": "^0.11", + "phpstan/phpstan-phpunit": "^0.11", + "phpunit/phpunit": "^7.0", + "squizlabs/php_codesniffer": "^3.0", + "symfony/phpunit-bridge": "^4.0.5" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.11.x-dev" + } + }, + "autoload": { + "psr-4": { + "Doctrine\\Common\\": "lib/Doctrine/Common" + } + }, + "notification-url": "https://packagist.org/downloads/", + "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" + }, + { + "name": "Marco Pivetta", + "email": "ocramius@gmail.com" + } + ], + "description": "PHP Doctrine Common project is a library that provides additional functionality that other Doctrine projects depend on such as better reflection support, persistence interfaces, proxies, event system and much more.", + "homepage": "https://www.doctrine-project.org/projects/common.html", + "keywords": [ + "common", + "doctrine", + "php" + ], + "time": "2019-09-10T10:10:14+00:00" + }, + { + "name": "doctrine/dbal", + "version": "v2.9.3", + "source": { + "type": "git", + "url": "https://github.com/doctrine/dbal.git", + "reference": "7345cd59edfa2036eb0fa4264b77ae2576842035" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/doctrine/dbal/zipball/7345cd59edfa2036eb0fa4264b77ae2576842035", + "reference": "7345cd59edfa2036eb0fa4264b77ae2576842035", + "shasum": "" + }, + "require": { + "doctrine/cache": "^1.0", + "doctrine/event-manager": "^1.0", + "ext-pdo": "*", + "php": "^7.1" + }, + "require-dev": { + "doctrine/coding-standard": "^5.0", + "jetbrains/phpstorm-stubs": "^2018.1.2", + "phpstan/phpstan": "^0.10.1", + "phpunit/phpunit": "^7.4", + "symfony/console": "^2.0.5|^3.0|^4.0", + "symfony/phpunit-bridge": "^3.4.5|^4.0.5" + }, + "suggest": { + "symfony/console": "For helpful console commands such as SQL execution and import of files." + }, + "bin": [ + "bin/doctrine-dbal" + ], + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.9.x-dev", + "dev-develop": "3.0.x-dev" + } + }, + "autoload": { + "psr-4": { + "Doctrine\\DBAL\\": "lib/Doctrine/DBAL" + } + }, + "notification-url": "https://packagist.org/downloads/", + "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" + } + ], + "description": "Powerful PHP database abstraction layer (DBAL) with many features for database schema introspection and management.", + "homepage": "https://www.doctrine-project.org/projects/dbal.html", + "keywords": [ + "abstraction", + "database", + "dbal", + "mysql", + "persistence", + "pgsql", + "php", + "queryobject" + ], + "time": "2019-11-02T22:19:34+00:00" + }, + { + "name": "doctrine/event-manager", + "version": "1.1.0", + "source": { + "type": "git", + "url": "https://github.com/doctrine/event-manager.git", + "reference": "629572819973f13486371cb611386eb17851e85c" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/doctrine/event-manager/zipball/629572819973f13486371cb611386eb17851e85c", + "reference": "629572819973f13486371cb611386eb17851e85c", + "shasum": "" + }, + "require": { + "php": "^7.1" + }, + "conflict": { + "doctrine/common": "<2.9@dev" + }, + "require-dev": { + "doctrine/coding-standard": "^6.0", + "phpunit/phpunit": "^7.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + }, + "autoload": { + "psr-4": { + "Doctrine\\Common\\": "lib/Doctrine/Common" + } + }, + "notification-url": "https://packagist.org/downloads/", + "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" + }, + { + "name": "Marco Pivetta", + "email": "ocramius@gmail.com" + } + ], + "description": "The Doctrine Event Manager is a simple PHP event system that was built to be used with the various Doctrine projects.", + "homepage": "https://www.doctrine-project.org/projects/event-manager.html", + "keywords": [ + "event", + "event dispatcher", + "event manager", + "event system", + "events" + ], + "time": "2019-11-10T09:48:07+00:00" + }, + { + "name": "doctrine/inflector", + "version": "1.3.1", + "source": { + "type": "git", + "url": "https://github.com/doctrine/inflector.git", + "reference": "ec3a55242203ffa6a4b27c58176da97ff0a7aec1" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/doctrine/inflector/zipball/ec3a55242203ffa6a4b27c58176da97ff0a7aec1", + "reference": "ec3a55242203ffa6a4b27c58176da97ff0a7aec1", + "shasum": "" + }, + "require": { + "php": "^7.1" + }, + "require-dev": { + "phpunit/phpunit": "^6.2" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.3.x-dev" + } + }, + "autoload": { + "psr-4": { + "Doctrine\\Common\\Inflector\\": "lib/Doctrine/Common/Inflector" + } + }, + "notification-url": "https://packagist.org/downloads/", + "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" + } + ], + "description": "Common String Manipulations with regard to casing and singular/plural rules.", + "homepage": "http://www.doctrine-project.org", + "keywords": [ + "inflection", + "pluralize", + "singularize", + "string" + ], + "time": "2019-10-30T19:59:35+00:00" + }, + { + "name": "doctrine/instantiator", + "version": "1.3.0", + "source": { + "type": "git", + "url": "https://github.com/doctrine/instantiator.git", + "reference": "ae466f726242e637cebdd526a7d991b9433bacf1" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/doctrine/instantiator/zipball/ae466f726242e637cebdd526a7d991b9433bacf1", + "reference": "ae466f726242e637cebdd526a7d991b9433bacf1", + "shasum": "" + }, + "require": { + "php": "^7.1" + }, + "require-dev": { + "doctrine/coding-standard": "^6.0", + "ext-pdo": "*", + "ext-phar": "*", + "phpbench/phpbench": "^0.13", + "phpstan/phpstan-phpunit": "^0.11", + "phpstan/phpstan-shim": "^0.11", + "phpunit/phpunit": "^7.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.2.x-dev" + } + }, + "autoload": { + "psr-4": { + "Doctrine\\Instantiator\\": "src/Doctrine/Instantiator/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Marco Pivetta", + "email": "ocramius@gmail.com", + "homepage": "http://ocramius.github.com/" + } + ], + "description": "A small, lightweight utility to instantiate objects in PHP without invoking their constructors", + "homepage": "https://www.doctrine-project.org/projects/instantiator.html", + "keywords": [ + "constructor", + "instantiate" + ], + "time": "2019-10-21T16:45:58+00:00" + }, + { + "name": "doctrine/lexer", + "version": "1.0.2", + "source": { + "type": "git", + "url": "https://github.com/doctrine/lexer.git", + "reference": "1febd6c3ef84253d7c815bed85fc622ad207a9f8" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/doctrine/lexer/zipball/1febd6c3ef84253d7c815bed85fc622ad207a9f8", + "reference": "1febd6c3ef84253d7c815bed85fc622ad207a9f8", + "shasum": "" + }, + "require": { + "php": ">=5.3.2" + }, + "require-dev": { + "phpunit/phpunit": "^4.5" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + }, + "autoload": { + "psr-4": { + "Doctrine\\Common\\Lexer\\": "lib/Doctrine/Common/Lexer" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Roman Borschel", + "email": "roman@code-factory.org" + }, + { + "name": "Guilherme Blanco", + "email": "guilhermeblanco@gmail.com" + }, + { + "name": "Johannes Schmitt", + "email": "schmittjoh@gmail.com" + } + ], + "description": "PHP Doctrine Lexer parser library that can be used in Top-Down, Recursive Descent Parsers.", + "homepage": "https://www.doctrine-project.org/projects/lexer.html", + "keywords": [ + "annotations", + "docblock", + "lexer", + "parser", + "php" + ], + "time": "2019-06-08T11:03:04+00:00" + }, + { + "name": "doctrine/persistence", + "version": "1.2.0", + "source": { + "type": "git", + "url": "https://github.com/doctrine/persistence.git", + "reference": "43526ae63312942e5316100bb3ed589ba1aba491" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/doctrine/persistence/zipball/43526ae63312942e5316100bb3ed589ba1aba491", + "reference": "43526ae63312942e5316100bb3ed589ba1aba491", + "shasum": "" + }, + "require": { + "doctrine/annotations": "^1.0", + "doctrine/cache": "^1.0", + "doctrine/collections": "^1.0", + "doctrine/event-manager": "^1.0", + "doctrine/reflection": "^1.0", + "php": "^7.1" + }, + "conflict": { + "doctrine/common": "<2.10@dev" + }, + "require-dev": { + "doctrine/coding-standard": "^5.0", + "phpstan/phpstan": "^0.8", + "phpunit/phpunit": "^7.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.2.x-dev" + } + }, + "autoload": { + "psr-4": { + "Doctrine\\Common\\": "lib/Doctrine/Common" + } + }, + "notification-url": "https://packagist.org/downloads/", + "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" + }, + { + "name": "Marco Pivetta", + "email": "ocramius@gmail.com" + } + ], + "description": "The Doctrine Persistence project is a set of shared interfaces and functionality that the different Doctrine object mappers share.", + "homepage": "https://doctrine-project.org/projects/persistence.html", + "keywords": [ + "mapper", + "object", + "odm", + "orm", + "persistence" + ], + "time": "2019-04-23T12:39:21+00:00" + }, + { + "name": "doctrine/reflection", + "version": "v1.0.0", + "source": { + "type": "git", + "url": "https://github.com/doctrine/reflection.git", + "reference": "02538d3f95e88eb397a5f86274deb2c6175c2ab6" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/doctrine/reflection/zipball/02538d3f95e88eb397a5f86274deb2c6175c2ab6", + "reference": "02538d3f95e88eb397a5f86274deb2c6175c2ab6", + "shasum": "" + }, + "require": { + "doctrine/annotations": "^1.0", + "ext-tokenizer": "*", + "php": "^7.1" + }, + "require-dev": { + "doctrine/coding-standard": "^4.0", + "doctrine/common": "^2.8", + "phpstan/phpstan": "^0.9.2", + "phpstan/phpstan-phpunit": "^0.9.4", + "phpunit/phpunit": "^7.0", + "squizlabs/php_codesniffer": "^3.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + }, + "autoload": { + "psr-4": { + "Doctrine\\Common\\": "lib/Doctrine/Common" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Roman Borschel", + "email": "roman@code-factory.org" + }, + { + "name": "Benjamin Eberlei", + "email": "kontakt@beberlei.de" + }, + { + "name": "Guilherme Blanco", + "email": "guilhermeblanco@gmail.com" + }, + { + "name": "Jonathan Wage", + "email": "jonwage@gmail.com" + }, + { + "name": "Johannes Schmitt", + "email": "schmittjoh@gmail.com" + }, + { + "name": "Marco Pivetta", + "email": "ocramius@gmail.com" + } + ], + "description": "Doctrine Reflection component", + "homepage": "https://www.doctrine-project.org/projects/reflection.html", + "keywords": [ + "reflection" + ], + "time": "2018-06-14T14:45:07+00:00" + }, + { + "name": "psr/log", + "version": "1.1.2", + "source": { + "type": "git", + "url": "https://github.com/php-fig/log.git", + "reference": "446d54b4cb6bf489fc9d75f55843658e6f25d801" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-fig/log/zipball/446d54b4cb6bf489fc9d75f55843658e6f25d801", + "reference": "446d54b4cb6bf489fc9d75f55843658e6f25d801", + "shasum": "" + }, + "require": { + "php": ">=5.3.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.1.x-dev" + } + }, + "autoload": { + "psr-4": { + "Psr\\Log\\": "Psr/Log/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "PHP-FIG", + "homepage": "http://www.php-fig.org/" + } + ], + "description": "Common interface for logging libraries", + "homepage": "https://github.com/php-fig/log", + "keywords": [ + "log", + "psr", + "psr-3" + ], + "time": "2019-11-01T11:05:21+00:00" + }, + { + "name": "symfony/console", + "version": "v3.4.35", + "source": { + "type": "git", + "url": "https://github.com/symfony/console.git", + "reference": "17b154f932c5874cdbda6d05796b6490eec9f9f7" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/console/zipball/17b154f932c5874cdbda6d05796b6490eec9f9f7", + "reference": "17b154f932c5874cdbda6d05796b6490eec9f9f7", + "shasum": "" + }, + "require": { + "php": "^5.5.9|>=7.0.8", + "symfony/debug": "~2.8|~3.0|~4.0", + "symfony/polyfill-mbstring": "~1.0" + }, + "conflict": { + "symfony/dependency-injection": "<3.4", + "symfony/process": "<3.3" + }, + "provide": { + "psr/log-implementation": "1.0" + }, + "require-dev": { + "psr/log": "~1.0", + "symfony/config": "~3.3|~4.0", + "symfony/dependency-injection": "~3.4|~4.0", + "symfony/event-dispatcher": "~2.8|~3.0|~4.0", + "symfony/lock": "~3.4|~4.0", + "symfony/process": "~3.3|~4.0" + }, + "suggest": { + "psr/log": "For using the console logger", + "symfony/event-dispatcher": "", + "symfony/lock": "", + "symfony/process": "" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "3.4-dev" + } + }, + "autoload": { + "psr-4": { + "Symfony\\Component\\Console\\": "" + }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony Console Component", + "homepage": "https://symfony.com", + "time": "2019-11-13T07:12:39+00:00" + }, + { + "name": "symfony/debug", + "version": "v3.4.35", + "source": { + "type": "git", + "url": "https://github.com/symfony/debug.git", + "reference": "f72e33fdb1170b326e72c3157f0cd456351dd086" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/debug/zipball/f72e33fdb1170b326e72c3157f0cd456351dd086", + "reference": "f72e33fdb1170b326e72c3157f0cd456351dd086", + "shasum": "" + }, + "require": { + "php": "^5.5.9|>=7.0.8", + "psr/log": "~1.0" + }, + "conflict": { + "symfony/http-kernel": ">=2.3,<2.3.24|~2.4.0|>=2.5,<2.5.9|>=2.6,<2.6.2" + }, + "require-dev": { + "symfony/http-kernel": "~2.8|~3.0|~4.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "3.4-dev" + } + }, + "autoload": { + "psr-4": { + "Symfony\\Component\\Debug\\": "" + }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony Debug Component", + "homepage": "https://symfony.com", + "time": "2019-10-24T15:33:53+00:00" + }, + { + "name": "symfony/polyfill-mbstring", + "version": "v1.12.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/polyfill-mbstring.git", + "reference": "b42a2f66e8f1b15ccf25652c3424265923eb4f17" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/polyfill-mbstring/zipball/b42a2f66e8f1b15ccf25652c3424265923eb4f17", + "reference": "b42a2f66e8f1b15ccf25652c3424265923eb4f17", + "shasum": "" + }, + "require": { + "php": ">=5.3.3" + }, + "suggest": { + "ext-mbstring": "For best performance" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.12-dev" + } + }, + "autoload": { + "psr-4": { + "Symfony\\Polyfill\\Mbstring\\": "" + }, + "files": [ + "bootstrap.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony polyfill for the Mbstring extension", + "homepage": "https://symfony.com", + "keywords": [ + "compatibility", + "mbstring", + "polyfill", + "portable", + "shim" + ], + "time": "2019-08-06T08:03:45+00:00" + } + ], + "packages-dev": [ + { + "name": "dealerdirect/phpcodesniffer-composer-installer", + "version": "v0.5.0", + "source": { + "type": "git", + "url": "https://github.com/Dealerdirect/phpcodesniffer-composer-installer.git", + "reference": "e749410375ff6fb7a040a68878c656c2e610b132" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/Dealerdirect/phpcodesniffer-composer-installer/zipball/e749410375ff6fb7a040a68878c656c2e610b132", + "reference": "e749410375ff6fb7a040a68878c656c2e610b132", + "shasum": "" + }, + "require": { + "composer-plugin-api": "^1.0", + "php": "^5.3|^7", + "squizlabs/php_codesniffer": "^2|^3" + }, + "require-dev": { + "composer/composer": "*", + "phpcompatibility/php-compatibility": "^9.0", + "sensiolabs/security-checker": "^4.1.0" + }, + "type": "composer-plugin", + "extra": { + "class": "Dealerdirect\\Composer\\Plugin\\Installers\\PHPCodeSniffer\\Plugin" + }, + "autoload": { + "psr-4": { + "Dealerdirect\\Composer\\Plugin\\Installers\\PHPCodeSniffer\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Franck Nijhof", + "email": "franck.nijhof@dealerdirect.com", + "homepage": "http://www.frenck.nl", + "role": "Developer / IT Manager" + } + ], + "description": "PHP_CodeSniffer Standards Composer Installer Plugin", + "homepage": "http://www.dealerdirect.com", + "keywords": [ + "PHPCodeSniffer", + "PHP_CodeSniffer", + "code quality", + "codesniffer", + "composer", + "installer", + "phpcs", + "plugin", + "qa", + "quality", + "standard", + "standards", + "style guide", + "stylecheck", + "tests" + ], + "time": "2018-10-26T13:21:45+00:00" + }, + { + "name": "doctrine/coding-standard", + "version": "5.0.1", + "source": { + "type": "git", + "url": "https://github.com/doctrine/coding-standard.git", + "reference": "9017efe98b47329cbd895d43f596747c8ef27307" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/doctrine/coding-standard/zipball/9017efe98b47329cbd895d43f596747c8ef27307", + "reference": "9017efe98b47329cbd895d43f596747c8ef27307", + "shasum": "" + }, + "require": { + "dealerdirect/phpcodesniffer-composer-installer": "^0.5.0", + "php": "^7.1", + "slevomat/coding-standard": "^4.8.0", + "squizlabs/php_codesniffer": "^3.3.2" + }, + "type": "phpcodesniffer-standard", + "extra": { + "branch-alias": { + "dev-master": "5.0.x-dev" + } + }, + "autoload": { + "psr-4": { + "Doctrine\\Sniffs\\": "lib/Doctrine/Sniffs" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Benjamin Eberlei", + "email": "kontakt@beberlei.de" + }, + { + "name": "Steve Müller", + "email": "st.mueller@dzh-online.de" + } + ], + "description": "The Doctrine Coding Standard is a set of PHPCS rules applied to all Doctrine projects.", + "homepage": "https://www.doctrine-project.org/projects/coding-standard.html", + "keywords": [ + "checks", + "code", + "coding", + "cs", + "doctrine", + "rules", + "sniffer", + "sniffs", + "standard", + "style" + ], + "time": "2019-01-31T13:22:30+00:00" + }, + { + "name": "myclabs/deep-copy", + "version": "1.9.3", + "source": { + "type": "git", + "url": "https://github.com/myclabs/DeepCopy.git", + "reference": "007c053ae6f31bba39dfa19a7726f56e9763bbea" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/myclabs/DeepCopy/zipball/007c053ae6f31bba39dfa19a7726f56e9763bbea", + "reference": "007c053ae6f31bba39dfa19a7726f56e9763bbea", + "shasum": "" + }, + "require": { + "php": "^7.1" + }, + "replace": { + "myclabs/deep-copy": "self.version" + }, + "require-dev": { + "doctrine/collections": "^1.0", + "doctrine/common": "^2.6", + "phpunit/phpunit": "^7.1" + }, + "type": "library", + "autoload": { + "psr-4": { + "DeepCopy\\": "src/DeepCopy/" + }, + "files": [ + "src/DeepCopy/deep_copy.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "description": "Create deep copies (clones) of your objects", + "keywords": [ + "clone", + "copy", + "duplicate", + "object", + "object graph" + ], + "time": "2019-08-09T12:45:53+00:00" + }, + { + "name": "phar-io/manifest", + "version": "1.0.3", + "source": { + "type": "git", + "url": "https://github.com/phar-io/manifest.git", + "reference": "7761fcacf03b4d4f16e7ccb606d4879ca431fcf4" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/phar-io/manifest/zipball/7761fcacf03b4d4f16e7ccb606d4879ca431fcf4", + "reference": "7761fcacf03b4d4f16e7ccb606d4879ca431fcf4", + "shasum": "" + }, + "require": { + "ext-dom": "*", + "ext-phar": "*", + "phar-io/version": "^2.0", + "php": "^5.6 || ^7.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Arne Blankerts", + "email": "arne@blankerts.de", + "role": "Developer" + }, + { + "name": "Sebastian Heuer", + "email": "sebastian@phpeople.de", + "role": "Developer" + }, + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de", + "role": "Developer" + } + ], + "description": "Component for reading phar.io manifest information from a PHP Archive (PHAR)", + "time": "2018-07-08T19:23:20+00:00" + }, + { + "name": "phar-io/version", + "version": "2.0.1", + "source": { + "type": "git", + "url": "https://github.com/phar-io/version.git", + "reference": "45a2ec53a73c70ce41d55cedef9063630abaf1b6" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/phar-io/version/zipball/45a2ec53a73c70ce41d55cedef9063630abaf1b6", + "reference": "45a2ec53a73c70ce41d55cedef9063630abaf1b6", + "shasum": "" + }, + "require": { + "php": "^5.6 || ^7.0" + }, + "type": "library", + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Arne Blankerts", + "email": "arne@blankerts.de", + "role": "Developer" + }, + { + "name": "Sebastian Heuer", + "email": "sebastian@phpeople.de", + "role": "Developer" + }, + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de", + "role": "Developer" + } + ], + "description": "Library for handling version information and constraints", + "time": "2018-07-08T19:19:57+00:00" + }, + { + "name": "phpdocumentor/reflection-common", + "version": "2.0.0", + "source": { + "type": "git", + "url": "https://github.com/phpDocumentor/ReflectionCommon.git", + "reference": "63a995caa1ca9e5590304cd845c15ad6d482a62a" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/phpDocumentor/ReflectionCommon/zipball/63a995caa1ca9e5590304cd845c15ad6d482a62a", + "reference": "63a995caa1ca9e5590304cd845c15ad6d482a62a", + "shasum": "" + }, + "require": { + "php": ">=7.1" + }, + "require-dev": { + "phpunit/phpunit": "~6" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.x-dev" + } + }, + "autoload": { + "psr-4": { + "phpDocumentor\\Reflection\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Jaap van Otterdijk", + "email": "opensource@ijaap.nl" + } + ], + "description": "Common reflection classes used by phpdocumentor to reflect the code structure", + "homepage": "http://www.phpdoc.org", + "keywords": [ + "FQSEN", + "phpDocumentor", + "phpdoc", + "reflection", + "static analysis" + ], + "time": "2018-08-07T13:53:10+00:00" + }, + { + "name": "phpdocumentor/reflection-docblock", + "version": "4.3.2", + "source": { + "type": "git", + "url": "https://github.com/phpDocumentor/ReflectionDocBlock.git", + "reference": "b83ff7cfcfee7827e1e78b637a5904fe6a96698e" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/phpDocumentor/ReflectionDocBlock/zipball/b83ff7cfcfee7827e1e78b637a5904fe6a96698e", + "reference": "b83ff7cfcfee7827e1e78b637a5904fe6a96698e", + "shasum": "" + }, + "require": { + "php": "^7.0", + "phpdocumentor/reflection-common": "^1.0.0 || ^2.0.0", + "phpdocumentor/type-resolver": "~0.4 || ^1.0.0", + "webmozart/assert": "^1.0" + }, + "require-dev": { + "doctrine/instantiator": "^1.0.5", + "mockery/mockery": "^1.0", + "phpunit/phpunit": "^6.4" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "4.x-dev" + } + }, + "autoload": { + "psr-4": { + "phpDocumentor\\Reflection\\": [ + "src/" + ] + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Mike van Riel", + "email": "me@mikevanriel.com" + } + ], + "description": "With this component, a library can provide support for annotations via DocBlocks or otherwise retrieve information that is embedded in a DocBlock.", + "time": "2019-09-12T14:27:41+00:00" + }, + { + "name": "phpdocumentor/type-resolver", + "version": "1.0.1", + "source": { + "type": "git", + "url": "https://github.com/phpDocumentor/TypeResolver.git", + "reference": "2e32a6d48972b2c1976ed5d8967145b6cec4a4a9" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/phpDocumentor/TypeResolver/zipball/2e32a6d48972b2c1976ed5d8967145b6cec4a4a9", + "reference": "2e32a6d48972b2c1976ed5d8967145b6cec4a4a9", + "shasum": "" + }, + "require": { + "php": "^7.1", + "phpdocumentor/reflection-common": "^2.0" + }, + "require-dev": { + "ext-tokenizer": "^7.1", + "mockery/mockery": "~1", + "phpunit/phpunit": "^7.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.x-dev" + } + }, + "autoload": { + "psr-4": { + "phpDocumentor\\Reflection\\": "src" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Mike van Riel", + "email": "me@mikevanriel.com" + } + ], + "description": "A PSR-5 based resolver of Class names, Types and Structural Element Names", + "time": "2019-08-22T18:11:29+00:00" + }, + { + "name": "phpspec/prophecy", + "version": "1.9.0", + "source": { + "type": "git", + "url": "https://github.com/phpspec/prophecy.git", + "reference": "f6811d96d97bdf400077a0cc100ae56aa32b9203" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/phpspec/prophecy/zipball/f6811d96d97bdf400077a0cc100ae56aa32b9203", + "reference": "f6811d96d97bdf400077a0cc100ae56aa32b9203", + "shasum": "" + }, + "require": { + "doctrine/instantiator": "^1.0.2", + "php": "^5.3|^7.0", + "phpdocumentor/reflection-docblock": "^2.0|^3.0.2|^4.0|^5.0", + "sebastian/comparator": "^1.1|^2.0|^3.0", + "sebastian/recursion-context": "^1.0|^2.0|^3.0" + }, + "require-dev": { + "phpspec/phpspec": "^2.5|^3.2", + "phpunit/phpunit": "^4.8.35 || ^5.7 || ^6.5 || ^7.1" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.8.x-dev" + } + }, + "autoload": { + "psr-4": { + "Prophecy\\": "src/Prophecy" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Konstantin Kudryashov", + "email": "ever.zet@gmail.com", + "homepage": "http://everzet.com" + }, + { + "name": "Marcello Duarte", + "email": "marcello.duarte@gmail.com" + } + ], + "description": "Highly opinionated mocking framework for PHP 5.3+", + "homepage": "https://github.com/phpspec/prophecy", + "keywords": [ + "Double", + "Dummy", + "fake", + "mock", + "spy", + "stub" + ], + "time": "2019-10-03T11:07:50+00:00" + }, + { + "name": "phpunit/php-code-coverage", + "version": "6.1.4", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/php-code-coverage.git", + "reference": "807e6013b00af69b6c5d9ceb4282d0393dbb9d8d" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/php-code-coverage/zipball/807e6013b00af69b6c5d9ceb4282d0393dbb9d8d", + "reference": "807e6013b00af69b6c5d9ceb4282d0393dbb9d8d", + "shasum": "" + }, + "require": { + "ext-dom": "*", + "ext-xmlwriter": "*", + "php": "^7.1", + "phpunit/php-file-iterator": "^2.0", + "phpunit/php-text-template": "^1.2.1", + "phpunit/php-token-stream": "^3.0", + "sebastian/code-unit-reverse-lookup": "^1.0.1", + "sebastian/environment": "^3.1 || ^4.0", + "sebastian/version": "^2.0.1", + "theseer/tokenizer": "^1.1" + }, + "require-dev": { + "phpunit/phpunit": "^7.0" + }, + "suggest": { + "ext-xdebug": "^2.6.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "6.1-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de", + "role": "lead" + } + ], + "description": "Library that provides collection, processing, and rendering functionality for PHP code coverage information.", + "homepage": "https://github.com/sebastianbergmann/php-code-coverage", + "keywords": [ + "coverage", + "testing", + "xunit" + ], + "time": "2018-10-31T16:06:48+00:00" + }, + { + "name": "phpunit/php-file-iterator", + "version": "2.0.2", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/php-file-iterator.git", + "reference": "050bedf145a257b1ff02746c31894800e5122946" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/php-file-iterator/zipball/050bedf145a257b1ff02746c31894800e5122946", + "reference": "050bedf145a257b1ff02746c31894800e5122946", + "shasum": "" + }, + "require": { + "php": "^7.1" + }, + "require-dev": { + "phpunit/phpunit": "^7.1" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.0.x-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de", + "role": "lead" + } + ], + "description": "FilterIterator implementation that filters files based on a list of suffixes.", + "homepage": "https://github.com/sebastianbergmann/php-file-iterator/", + "keywords": [ + "filesystem", + "iterator" + ], + "time": "2018-09-13T20:33:42+00:00" + }, + { + "name": "phpunit/php-text-template", + "version": "1.2.1", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/php-text-template.git", + "reference": "31f8b717e51d9a2afca6c9f046f5d69fc27c8686" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/php-text-template/zipball/31f8b717e51d9a2afca6c9f046f5d69fc27c8686", + "reference": "31f8b717e51d9a2afca6c9f046f5d69fc27c8686", + "shasum": "" + }, + "require": { + "php": ">=5.3.3" + }, + "type": "library", + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de", + "role": "lead" + } + ], + "description": "Simple template engine.", + "homepage": "https://github.com/sebastianbergmann/php-text-template/", + "keywords": [ + "template" + ], + "time": "2015-06-21T13:50:34+00:00" + }, + { + "name": "phpunit/php-timer", + "version": "2.1.2", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/php-timer.git", + "reference": "1038454804406b0b5f5f520358e78c1c2f71501e" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/php-timer/zipball/1038454804406b0b5f5f520358e78c1c2f71501e", + "reference": "1038454804406b0b5f5f520358e78c1c2f71501e", + "shasum": "" + }, + "require": { + "php": "^7.1" + }, + "require-dev": { + "phpunit/phpunit": "^7.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.1-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de", + "role": "lead" + } + ], + "description": "Utility class for timing", + "homepage": "https://github.com/sebastianbergmann/php-timer/", + "keywords": [ + "timer" + ], + "time": "2019-06-07T04:22:29+00:00" + }, + { + "name": "phpunit/php-token-stream", + "version": "3.1.1", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/php-token-stream.git", + "reference": "995192df77f63a59e47f025390d2d1fdf8f425ff" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/php-token-stream/zipball/995192df77f63a59e47f025390d2d1fdf8f425ff", + "reference": "995192df77f63a59e47f025390d2d1fdf8f425ff", + "shasum": "" + }, + "require": { + "ext-tokenizer": "*", + "php": "^7.1" + }, + "require-dev": { + "phpunit/phpunit": "^7.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "3.1-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de" + } + ], + "description": "Wrapper around PHP's tokenizer extension.", + "homepage": "https://github.com/sebastianbergmann/php-token-stream/", + "keywords": [ + "tokenizer" + ], + "time": "2019-09-17T06:23:10+00:00" + }, + { + "name": "phpunit/phpunit", + "version": "7.5.17", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/phpunit.git", + "reference": "4c92a15296e58191a4cd74cff3b34fc8e374174a" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/phpunit/zipball/4c92a15296e58191a4cd74cff3b34fc8e374174a", + "reference": "4c92a15296e58191a4cd74cff3b34fc8e374174a", + "shasum": "" + }, + "require": { + "doctrine/instantiator": "^1.1", + "ext-dom": "*", + "ext-json": "*", + "ext-libxml": "*", + "ext-mbstring": "*", + "ext-xml": "*", + "myclabs/deep-copy": "^1.7", + "phar-io/manifest": "^1.0.2", + "phar-io/version": "^2.0", + "php": "^7.1", + "phpspec/prophecy": "^1.7", + "phpunit/php-code-coverage": "^6.0.7", + "phpunit/php-file-iterator": "^2.0.1", + "phpunit/php-text-template": "^1.2.1", + "phpunit/php-timer": "^2.1", + "sebastian/comparator": "^3.0", + "sebastian/diff": "^3.0", + "sebastian/environment": "^4.0", + "sebastian/exporter": "^3.1", + "sebastian/global-state": "^2.0", + "sebastian/object-enumerator": "^3.0.3", + "sebastian/resource-operations": "^2.0", + "sebastian/version": "^2.0.1" + }, + "conflict": { + "phpunit/phpunit-mock-objects": "*" + }, + "require-dev": { + "ext-pdo": "*" + }, + "suggest": { + "ext-soap": "*", + "ext-xdebug": "*", + "phpunit/php-invoker": "^2.0" + }, + "bin": [ + "phpunit" + ], + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "7.5-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de", + "role": "lead" + } + ], + "description": "The PHP Unit Testing framework.", + "homepage": "https://phpunit.de/", + "keywords": [ + "phpunit", + "testing", + "xunit" + ], + "time": "2019-10-28T10:37:36+00:00" + }, + { + "name": "sebastian/code-unit-reverse-lookup", + "version": "1.0.1", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/code-unit-reverse-lookup.git", + "reference": "4419fcdb5eabb9caa61a27c7a1db532a6b55dd18" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/code-unit-reverse-lookup/zipball/4419fcdb5eabb9caa61a27c7a1db532a6b55dd18", + "reference": "4419fcdb5eabb9caa61a27c7a1db532a6b55dd18", + "shasum": "" + }, + "require": { + "php": "^5.6 || ^7.0" + }, + "require-dev": { + "phpunit/phpunit": "^5.7 || ^6.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de" + } + ], + "description": "Looks up which function or method a line of code belongs to", + "homepage": "https://github.com/sebastianbergmann/code-unit-reverse-lookup/", + "time": "2017-03-04T06:30:41+00:00" + }, + { + "name": "sebastian/comparator", + "version": "3.0.2", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/comparator.git", + "reference": "5de4fc177adf9bce8df98d8d141a7559d7ccf6da" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/comparator/zipball/5de4fc177adf9bce8df98d8d141a7559d7ccf6da", + "reference": "5de4fc177adf9bce8df98d8d141a7559d7ccf6da", + "shasum": "" + }, + "require": { + "php": "^7.1", + "sebastian/diff": "^3.0", + "sebastian/exporter": "^3.1" + }, + "require-dev": { + "phpunit/phpunit": "^7.1" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "3.0-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Jeff Welch", + "email": "whatthejeff@gmail.com" + }, + { + "name": "Volker Dusch", + "email": "github@wallbash.com" + }, + { + "name": "Bernhard Schussek", + "email": "bschussek@2bepublished.at" + }, + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de" + } + ], + "description": "Provides the functionality to compare PHP values for equality", + "homepage": "https://github.com/sebastianbergmann/comparator", + "keywords": [ + "comparator", + "compare", + "equality" + ], + "time": "2018-07-12T15:12:46+00:00" + }, + { + "name": "sebastian/diff", + "version": "3.0.2", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/diff.git", + "reference": "720fcc7e9b5cf384ea68d9d930d480907a0c1a29" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/diff/zipball/720fcc7e9b5cf384ea68d9d930d480907a0c1a29", + "reference": "720fcc7e9b5cf384ea68d9d930d480907a0c1a29", + "shasum": "" + }, + "require": { + "php": "^7.1" + }, + "require-dev": { + "phpunit/phpunit": "^7.5 || ^8.0", + "symfony/process": "^2 || ^3.3 || ^4" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "3.0-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Kore Nordmann", + "email": "mail@kore-nordmann.de" + }, + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de" + } + ], + "description": "Diff implementation", + "homepage": "https://github.com/sebastianbergmann/diff", + "keywords": [ + "diff", + "udiff", + "unidiff", + "unified diff" + ], + "time": "2019-02-04T06:01:07+00:00" + }, + { + "name": "sebastian/environment", + "version": "4.2.2", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/environment.git", + "reference": "f2a2c8e1c97c11ace607a7a667d73d47c19fe404" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/environment/zipball/f2a2c8e1c97c11ace607a7a667d73d47c19fe404", + "reference": "f2a2c8e1c97c11ace607a7a667d73d47c19fe404", + "shasum": "" + }, + "require": { + "php": "^7.1" + }, + "require-dev": { + "phpunit/phpunit": "^7.5" + }, + "suggest": { + "ext-posix": "*" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "4.2-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de" + } + ], + "description": "Provides functionality to handle HHVM/PHP environments", + "homepage": "http://www.github.com/sebastianbergmann/environment", + "keywords": [ + "Xdebug", + "environment", + "hhvm" + ], + "time": "2019-05-05T09:05:15+00:00" + }, + { + "name": "sebastian/exporter", + "version": "3.1.2", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/exporter.git", + "reference": "68609e1261d215ea5b21b7987539cbfbe156ec3e" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/exporter/zipball/68609e1261d215ea5b21b7987539cbfbe156ec3e", + "reference": "68609e1261d215ea5b21b7987539cbfbe156ec3e", + "shasum": "" + }, + "require": { + "php": "^7.0", + "sebastian/recursion-context": "^3.0" + }, + "require-dev": { + "ext-mbstring": "*", + "phpunit/phpunit": "^6.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "3.1.x-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de" + }, + { + "name": "Jeff Welch", + "email": "whatthejeff@gmail.com" + }, + { + "name": "Volker Dusch", + "email": "github@wallbash.com" + }, + { + "name": "Adam Harvey", + "email": "aharvey@php.net" + }, + { + "name": "Bernhard Schussek", + "email": "bschussek@gmail.com" + } + ], + "description": "Provides the functionality to export PHP variables for visualization", + "homepage": "http://www.github.com/sebastianbergmann/exporter", + "keywords": [ + "export", + "exporter" + ], + "time": "2019-09-14T09:02:43+00:00" + }, + { + "name": "sebastian/global-state", + "version": "2.0.0", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/global-state.git", + "reference": "e8ba02eed7bbbb9e59e43dedd3dddeff4a56b0c4" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/global-state/zipball/e8ba02eed7bbbb9e59e43dedd3dddeff4a56b0c4", + "reference": "e8ba02eed7bbbb9e59e43dedd3dddeff4a56b0c4", + "shasum": "" + }, + "require": { + "php": "^7.0" + }, + "require-dev": { + "phpunit/phpunit": "^6.0" + }, + "suggest": { + "ext-uopz": "*" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.0-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de" + } + ], + "description": "Snapshotting of global state", + "homepage": "http://www.github.com/sebastianbergmann/global-state", + "keywords": [ + "global state" + ], + "time": "2017-04-27T15:39:26+00:00" + }, + { + "name": "sebastian/object-enumerator", + "version": "3.0.3", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/object-enumerator.git", + "reference": "7cfd9e65d11ffb5af41198476395774d4c8a84c5" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/object-enumerator/zipball/7cfd9e65d11ffb5af41198476395774d4c8a84c5", + "reference": "7cfd9e65d11ffb5af41198476395774d4c8a84c5", + "shasum": "" + }, + "require": { + "php": "^7.0", + "sebastian/object-reflector": "^1.1.1", + "sebastian/recursion-context": "^3.0" + }, + "require-dev": { + "phpunit/phpunit": "^6.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "3.0.x-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de" + } + ], + "description": "Traverses array structures and object graphs to enumerate all referenced objects", + "homepage": "https://github.com/sebastianbergmann/object-enumerator/", + "time": "2017-08-03T12:35:26+00:00" + }, + { + "name": "sebastian/object-reflector", + "version": "1.1.1", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/object-reflector.git", + "reference": "773f97c67f28de00d397be301821b06708fca0be" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/object-reflector/zipball/773f97c67f28de00d397be301821b06708fca0be", + "reference": "773f97c67f28de00d397be301821b06708fca0be", + "shasum": "" + }, + "require": { + "php": "^7.0" + }, + "require-dev": { + "phpunit/phpunit": "^6.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.1-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de" + } + ], + "description": "Allows reflection of object attributes, including inherited and non-public ones", + "homepage": "https://github.com/sebastianbergmann/object-reflector/", + "time": "2017-03-29T09:07:27+00:00" + }, + { + "name": "sebastian/recursion-context", + "version": "3.0.0", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/recursion-context.git", + "reference": "5b0cd723502bac3b006cbf3dbf7a1e3fcefe4fa8" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/recursion-context/zipball/5b0cd723502bac3b006cbf3dbf7a1e3fcefe4fa8", + "reference": "5b0cd723502bac3b006cbf3dbf7a1e3fcefe4fa8", + "shasum": "" + }, + "require": { + "php": "^7.0" + }, + "require-dev": { + "phpunit/phpunit": "^6.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "3.0.x-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Jeff Welch", + "email": "whatthejeff@gmail.com" + }, + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de" + }, + { + "name": "Adam Harvey", + "email": "aharvey@php.net" + } + ], + "description": "Provides functionality to recursively process PHP variables", + "homepage": "http://www.github.com/sebastianbergmann/recursion-context", + "time": "2017-03-03T06:23:57+00:00" + }, + { + "name": "sebastian/resource-operations", + "version": "2.0.1", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/resource-operations.git", + "reference": "4d7a795d35b889bf80a0cc04e08d77cedfa917a9" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/resource-operations/zipball/4d7a795d35b889bf80a0cc04e08d77cedfa917a9", + "reference": "4d7a795d35b889bf80a0cc04e08d77cedfa917a9", + "shasum": "" + }, + "require": { + "php": "^7.1" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.0-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de" + } + ], + "description": "Provides a list of PHP built-in functions that operate on resources", + "homepage": "https://www.github.com/sebastianbergmann/resource-operations", + "time": "2018-10-04T04:07:39+00:00" + }, + { + "name": "sebastian/version", + "version": "2.0.1", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/version.git", + "reference": "99732be0ddb3361e16ad77b68ba41efc8e979019" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/version/zipball/99732be0ddb3361e16ad77b68ba41efc8e979019", + "reference": "99732be0ddb3361e16ad77b68ba41efc8e979019", + "shasum": "" + }, + "require": { + "php": ">=5.6" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.0.x-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de", + "role": "lead" + } + ], + "description": "Library that helps with managing the version number of Git-hosted PHP projects", + "homepage": "https://github.com/sebastianbergmann/version", + "time": "2016-10-03T07:35:21+00:00" + }, + { + "name": "slevomat/coding-standard", + "version": "4.8.7", + "source": { + "type": "git", + "url": "https://github.com/slevomat/coding-standard.git", + "reference": "bff96313d8c7c2ba57a4edb13c1c141df8988c58" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/slevomat/coding-standard/zipball/bff96313d8c7c2ba57a4edb13c1c141df8988c58", + "reference": "bff96313d8c7c2ba57a4edb13c1c141df8988c58", + "shasum": "" + }, + "require": { + "php": "^7.1", + "squizlabs/php_codesniffer": "^3.4.0" + }, + "require-dev": { + "jakub-onderka/php-parallel-lint": "1.0.0", + "phing/phing": "2.16.1", + "phpstan/phpstan": "0.9.2", + "phpstan/phpstan-phpunit": "0.9.4", + "phpstan/phpstan-strict-rules": "0.9", + "phpunit/phpunit": "7.5.1" + }, + "type": "phpcodesniffer-standard", + "autoload": { + "psr-4": { + "SlevomatCodingStandard\\": "SlevomatCodingStandard" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "description": "Slevomat Coding Standard for PHP_CodeSniffer complements Consistence Coding Standard by providing sniffs with additional checks.", + "time": "2019-01-03T13:15:50+00:00" + }, + { + "name": "squizlabs/php_codesniffer", + "version": "3.5.2", + "source": { + "type": "git", + "url": "https://github.com/squizlabs/PHP_CodeSniffer.git", + "reference": "65b12cdeaaa6cd276d4c3033a95b9b88b12701e7" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/squizlabs/PHP_CodeSniffer/zipball/65b12cdeaaa6cd276d4c3033a95b9b88b12701e7", + "reference": "65b12cdeaaa6cd276d4c3033a95b9b88b12701e7", + "shasum": "" + }, + "require": { + "ext-simplexml": "*", + "ext-tokenizer": "*", + "ext-xmlwriter": "*", + "php": ">=5.4.0" + }, + "require-dev": { + "phpunit/phpunit": "^4.0 || ^5.0 || ^6.0 || ^7.0" + }, + "bin": [ + "bin/phpcs", + "bin/phpcbf" + ], + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "3.x-dev" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Greg Sherwood", + "role": "lead" + } + ], + "description": "PHP_CodeSniffer tokenizes PHP, JavaScript and CSS files and detects violations of a defined set of coding standards.", + "homepage": "https://github.com/squizlabs/PHP_CodeSniffer", + "keywords": [ + "phpcs", + "standards" + ], + "time": "2019-10-28T04:36:32+00:00" + }, + { + "name": "symfony/polyfill-ctype", + "version": "v1.12.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/polyfill-ctype.git", + "reference": "550ebaac289296ce228a706d0867afc34687e3f4" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/polyfill-ctype/zipball/550ebaac289296ce228a706d0867afc34687e3f4", + "reference": "550ebaac289296ce228a706d0867afc34687e3f4", + "shasum": "" + }, + "require": { + "php": ">=5.3.3" + }, + "suggest": { + "ext-ctype": "For best performance" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.12-dev" + } + }, + "autoload": { + "psr-4": { + "Symfony\\Polyfill\\Ctype\\": "" + }, + "files": [ + "bootstrap.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Gert de Pagter", + "email": "BackEndTea@gmail.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony polyfill for ctype functions", + "homepage": "https://symfony.com", + "keywords": [ + "compatibility", + "ctype", + "polyfill", + "portable" + ], + "time": "2019-08-06T08:03:45+00:00" + }, + { + "name": "symfony/yaml", + "version": "v3.4.35", + "source": { + "type": "git", + "url": "https://github.com/symfony/yaml.git", + "reference": "dab657db15207879217fc81df4f875947bf68804" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/yaml/zipball/dab657db15207879217fc81df4f875947bf68804", + "reference": "dab657db15207879217fc81df4f875947bf68804", + "shasum": "" + }, + "require": { + "php": "^5.5.9|>=7.0.8", + "symfony/polyfill-ctype": "~1.8" + }, + "conflict": { + "symfony/console": "<3.4" + }, + "require-dev": { + "symfony/console": "~3.4|~4.0" + }, + "suggest": { + "symfony/console": "For validating YAML files using the lint command" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "3.4-dev" + } + }, + "autoload": { + "psr-4": { + "Symfony\\Component\\Yaml\\": "" + }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony Yaml Component", + "homepage": "https://symfony.com", + "time": "2019-10-24T15:33:53+00:00" + }, + { + "name": "theseer/tokenizer", + "version": "1.1.3", + "source": { + "type": "git", + "url": "https://github.com/theseer/tokenizer.git", + "reference": "11336f6f84e16a720dae9d8e6ed5019efa85a0f9" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/theseer/tokenizer/zipball/11336f6f84e16a720dae9d8e6ed5019efa85a0f9", + "reference": "11336f6f84e16a720dae9d8e6ed5019efa85a0f9", + "shasum": "" + }, + "require": { + "ext-dom": "*", + "ext-tokenizer": "*", + "ext-xmlwriter": "*", + "php": "^7.0" + }, + "type": "library", + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Arne Blankerts", + "role": "Developer", + "email": "arne@blankerts.de" + } + ], + "description": "A small library for converting tokenized PHP source code into XML and potentially other formats", + "time": "2019-06-13T22:48:21+00:00" + }, + { + "name": "webmozart/assert", + "version": "1.5.0", + "source": { + "type": "git", + "url": "https://github.com/webmozart/assert.git", + "reference": "88e6d84706d09a236046d686bbea96f07b3a34f4" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/webmozart/assert/zipball/88e6d84706d09a236046d686bbea96f07b3a34f4", + "reference": "88e6d84706d09a236046d686bbea96f07b3a34f4", + "shasum": "" + }, + "require": { + "php": "^5.3.3 || ^7.0", + "symfony/polyfill-ctype": "^1.8" + }, + "require-dev": { + "phpunit/phpunit": "^4.8.36 || ^7.5.13" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.3-dev" + } + }, + "autoload": { + "psr-4": { + "Webmozart\\Assert\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Bernhard Schussek", + "email": "bschussek@gmail.com" + } + ], + "description": "Assertions to validate method input/output with nice error messages.", + "keywords": [ + "assert", + "check", + "validate" + ], + "time": "2019-08-24T08:43:50+00:00" + } + ], + "aliases": [], + "minimum-stability": "stable", + "stability-flags": [], + "prefer-stable": false, + "prefer-lowest": false, + "platform": { + "php": "^7.1", + "ext-pdo": "*" + }, + "platform-dev": [] +} diff --git a/docs/en/_theme b/docs/en/_theme index dc294be1dbc..6f1bc8bead1 160000 --- a/docs/en/_theme +++ b/docs/en/_theme @@ -1 +1 @@ -Subproject commit dc294be1dbcf9abde82d24aea1902898d6ee6314 +Subproject commit 6f1bc8bead17b8032389659c0b071d00f2c58328 diff --git a/docs/en/changelog/migration_2_5.rst b/docs/en/changelog/migration_2_5.rst deleted file mode 100644 index 408776d03c3..00000000000 --- a/docs/en/changelog/migration_2_5.rst +++ /dev/null @@ -1,711 +0,0 @@ -What is new in Doctrine ORM 2.5? -================================ - -This document describes changes between Doctrine ORM 2.4 and 2.5. -It contains a description of all the new features and sections about -behavioral changes and potential backwards compatibility breaks. -Please review this document carefully when updating to Doctrine 2.5. - -First note, that with the ORM 2.5 release we are dropping support -for PHP 5.3. We are enforcing this with Composer, servers without -at least PHP 5.4 will not allow installing Doctrine 2.5. - -New Features and Improvements ------------------------------ - -Events: PostLoad now triggered after associations are loaded -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Before Doctrine 2.5 if you had an entity with a ``@PostLoad`` event -defined then Doctrine would trigger listeners after the fields were -loaded, but before assocations are available. - -- `DDC-54 `_ -- `Commit #a90629 `_ - -Events: Add API to programatically add event listeners to Entity -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -When developing third party libraries or decoupled applications -it can be interesting to develop an entity listener without knowing -the entities that require this listener. - -You can now attach entity listeners to entities using the -``AttachEntityListenersListener`` class, which is listening to the -``loadMetadata`` event that is fired once for every entity during -metadata generation: - -.. code-block:: php - - addEntityListener( - 'MyProject\Entity\User', 'MyProject\Listener\TimestampableListener', - Events::prePersist, 'onPrePersist' - ); - - $evm->addEventListener(Events::loadClassMetadata, $listener); - - class TimestampableListener - { - public function onPrePersist($event) - { - $entity = $event->getEntity(); - $entity->setCreated(new \DateTime('now')); - } - } - -Embeddable Objects -~~~~~~~~~~~~~~~~~~ - -Doctrine now supports creating multiple PHP objects from one database table -implementing a feature called "Embeddable Objects". Next to an ``@Entity`` -class you can now define a class that is embeddable into a database table of an -entity using the ``@Embeddable`` annotation. Embeddable objects can never be -saved, updated or deleted on their own, only as part of an entity (called -"root-entity" or "aggregate"). Consequently embeddables don't have a primary -key, they are identified only by their values. - -Example of defining and using embeddables classes: - -.. code-block:: php - - `_. - -This feature was developed by external contributor `Johannes Schmitt -`_ - -- `DDC-93 `_ -- `Pull Request #835 `_ - -Second-Level-Cache -~~~~~~~~~~~~~~~~~~ - -Since version 2.0 of Doctrine, fetching the same object twice by primary key -would result in just one query. This was achieved by the identity map pattern -(first-level-cache) that kept entities in memory. - -The newly introduced second-level-cache works a bit differently. Instead -of saving objects in memory, it saves them in a fast in-memory cache such -as Memcache, Redis, Riak or MongoDB. Additionally it allows saving the result -of more complex queries than by primary key. Summarized this feature works -like the existing Query result cache, but it is much more powerful. - -As an example lets cache an entity Country that is a relation to the User -entity. We always want to display the country, but avoid the additional -query to this table. - -.. code-block:: php - - setSecondLevelCacheEnabled(); - - $cacheConfig = $config->getSecondLevelCacheConfiguration(); - $regionConfig = $cacheConfig->getRegionsConfiguration(); - $regionConfig->setLifetime('country_region', 3600); - -Now Doctrine will first check for the data of any country in the cache -instead of the database. - -- `Documentation - `_ -- `Pull Request #808 `_ - -Criteria API: Support for ManyToMany assocations -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -We introduced support for querying collections using the `Criteria API -`_ -in 2.4. This only worked efficently for One-To-Many assocations, not for -Many-To-Many. With the start of 2.5 also Many-To-Many associations get queried -instead of loading them into memory. - -Criteria API: Add new contains() expression -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -It is now possible to use the Criteria API to check for string contains needle -using ``contains()``. This translates to using a ``column LIKE '%needle%'`` SQL -condition. - -.. code-block:: php - - where(Criteria::expr()->contains('name', 'Benjamin')); - - $users = $repository->matching($criteria); - -Criteria API: Support for EXTRA_LAZY -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -A collection that is marked as ``fetch="EXTRA_LAZY"`` will now return another -lazy collection when using ``Collection::matching($criteria)``: - -.. code-block:: php - - where(Criteria->expr()->eq("published", 1)); - - $publishedComments = $post->getComments()->matching($criteria); - - echo count($publishedComments); - -The lazy criteria currently supports the ``count()`` and ``contains()`` -functionality lazily. All other operations of the ``Collection`` interface -trigger a full load of the collection. - -This feature was contributed by `Michaël Gallego `_. - -- `Pull Request #882 `_ -- `Pull Request #1032 `_ - -Mapping: Allow configuring Index flags -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -It is now possible to control the index flags in the DBAL -schema abstraction from the ORM using metadata. This was possible -only with a schema event listener before. - -.. code-block:: php - - `_. - -- `Pull Request #973 `_ - -SQLFilter API: Check if a parameter is set -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -You can now check in your SQLFilter if a parameter was set. This allows -to more easily control which features of a filter to enable or disable. - -Extending on the locale example of the documentation: - -.. code-block:: php - - reflClass->implementsInterface('LocaleAware')) { - return ""; - } - - if (!$this->hasParameter('locale')) { - return ""; - } - - return $targetTableAlias.'.locale = ' . $this->getParameter('locale'); - } - } - -This feature was contributed by `Miroslav Demovic `_ - -- `Pull Request #963 `_ - - -EXTRA_LAZY Improvements -~~~~~~~~~~~~~~~~~~~~~~~ - -1. Efficient query when using EXTRA_LAZY and containsKey - - When calling ``Collection::containsKey($key)`` on one-to-many and many-to-many - collections using ``indexBy`` and ``EXTRA_LAZY`` a query is now executed to check - for the existance for the item. Prevoiusly this operation was performed in memory - by loading all entities of the collection. - - .. code-block:: php - - getGroups()->containsKey($groupId)) { - echo "User is in group $groupId\n"; - } - - This feature was contributed by `Asmir Mustafic `_ - - - `Pull Request #937 `_ - -2. Add EXTRA_LAZY Support for get() for owning and inverse many-to-many - - This was contributed by `Sander Marechal `_. - -Improve efficiency of One-To-Many EAGER -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -When marking a one-to-many association with ``fetch="EAGER"`` it will now -execute one query less than before and work correctly in combination with -``indexBy``. - -Better support for EntityManagerInterface -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Many of the locations where previously only the ``Doctrine\ORM\EntityManager`` -was allowed are now changed to accept the ``EntityManagerInterface`` that was -introduced in 2.4. This allows you to more easily use the decorator pattern -to extend the EntityManager if you need. It's still not replaced everywhere, -so you still have to be careful. - -DQL Improvements -~~~~~~~~~~~~~~~~ - -1. It is now possible to add functions to the ``ORDER BY`` clause in DQL statements: - -.. code-block:: php - - createQuery($dql); - $query->setParameter('groups', array(1, 2, 3)); - - $users = $query->getResult(); - -6. Expressions inside ``COUNT()`` now allowed - -.. code-block:: php - - `_ to pass a callback instead that resolves -the function: - -.. code-block:: php - - addCustomNumericFunction( - 'IS_PUBLISHED', function($funcName) use ($currentSiteId) { - return new IsPublishedFunction($currentSiteId); - } - ); - -Query API: WHERE IN Query using a Collection as parameter -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -When performing a ``WHERE IN`` query for a collection of entities you can -now pass the array collection of entities as a parameter value to the query -object: - -.. code-block:: php - - getChildren(); - - $queryBuilder - ->select('p') - ->from('Product', 'p') - ->where('p.category IN (:categories)') - ->setParameter('categories', $categories) - ; - -This feature was contributed by `Michael Perrin -`_. - -- `Pull Request #590 `_ -- `DDC-2319 `_ - -Query API: Add support for default Query Hints -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -To configure multiple different features such as custom AST Walker, fetch modes, -locking and other features affecting DQL generation we have had a feature -called "query hints" since version 2.0. - -It is now possible to add query hints that are always enabled for every Query: - -.. code-block:: php - - setDefaultQueryHints( - 'doctrine.customOutputWalker' => 'MyProject\CustomOutputWalker' - ); - -This feature was contributed by `Artur Eshenbrener -`_. - -- `Pull Request #863 `_ - -ResultSetMappingBuilder: Add support for Single-Table Inheritance -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Before 2.5 the ResultSetMappingBuilder did not work with entities -that are using Single-Table-Inheritance. This restriction was lifted -by adding the missing support. - -YAML Mapping: Many-To-Many doesnt require join column definition -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -In Annotations and XML it was not necessary using conventions for naming -the many-to-many join column names, in YAML it was not possible however. - -A many-to-many definition in YAML is now possible using this minimal -definition: - -.. code-block:: yaml - - manyToMany: - groups: - targetEntity: Group - joinTable: - name: users_groups - -Schema Validator Command: Allow to skip sub-checks -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -The Schema Validator command executes two independent checks -for validity of the mappings and if the schema is synchronized -correctly. It is now possible to skip any of the two steps -when executing the command: - -:: - - $ php vendor/bin/doctrine orm:validate-schema --skip-mapping - $ php vendor/bin/doctrine orm:validate-schema --skip-sync - -This allows you to write more specialized continuous integration and automation -checks. When no changes are found the command returns the exit code 0 -and 1, 2 or 3 when failing because of mapping, sync or both. - -EntityGenerator Command: Avoid backups -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -When calling the EntityGenerator for an existing entity, Doctrine would -create a backup file every time to avoid losing changes to the code. You -can now skip generating the backup file by passing the ``--no-backup`` -flag: - -:: - - $ php vendor/bin/doctrine orm:generate-entities src/ --no-backup - -Support for Objects as Identifiers -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -It is now possible to use Objects as identifiers for Entities -as long as they implement the magic method ``__toString()``. - -.. code-block:: php - - value = $value; - } - - public function __toString() - { - return (string)$this->value; - } - } - - class User - { - /** @Id @Column(type="userid") */ - private $id; - - public function __construct(UserId $id) - { - $this->id = $id; - } - } - - class UserIdType extends \Doctrine\DBAL\Types\Type - { - // ... - } - - Doctrine\DBAL\Types\Type::addType('userid', 'MyProject\UserIdType'); - -Behavioral Changes (BC Breaks) ------------------------------- - -NamingStrategy interface changed -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -The ``Doctrine\ORM\Mapping\NamingStrategyInterface`` changed slightly -to pass the Class Name of the entity into the join column name generation: - -:: - - - function joinColumnName($propertyName); - + function joinColumnName($propertyName, $className = null); - -It also received a new method for supporting embeddables: - -:: - - public function embeddedFieldToColumnName($propertyName, $embeddedColumnName); - -Minor BC BREAK: EntityManagerInterface instead of EntityManager in type-hints -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -As of 2.5, classes requiring the ``EntityManager`` in any method signature will now require -an ``EntityManagerInterface`` instead. -If you are extending any of the following classes, then you need to check following -signatures: - -- ``Doctrine\ORM\Tools\DebugUnitOfWorkListener#dumpIdentityMap(EntityManagerInterface $em)`` -- ``Doctrine\ORM\Mapping\ClassMetadataFactory#setEntityManager(EntityManagerInterface $em)`` - -Minor BC BREAK: Custom Hydrators API change -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -As of 2.5, ``AbstractHydrator`` does not enforce the usage of cache as part of -API, and now provides you a clean API for column information through the method -``hydrateColumnInfo($column)``. -Cache variable being passed around by reference is no longer needed since -Hydrators are per query instantiated since Doctrine 2.4. - -- `DDC-3060 `_ - -Minor BC BREAK: All non-transient classes in an inheritance must be part of the inheritance map -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -As of 2.5, classes, if you define an inheritance map for an inheritance tree, you are required -to map all non-transient classes in that inheritance, including the root of the inheritance. - -So far, the root of the inheritance was allowed to be skipped in the inheritance map: this is -not possible anymore, and if you don't plan to persist instances of that class, then you should -either: - -- make that class as ``abstract`` -- add that class to your inheritance map - -If you fail to do so, then a ``Doctrine\ORM\Mapping\MappingException`` will be thrown. - - -- `DDC-3300 `_ -- `DDC-3503 `_ - -Minor BC BREAK: Entity based EntityManager#clear() calls follow cascade detach -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Whenever ``EntityManager#clear()`` method gets called with a given entity class -name, until 2.4, it was only detaching the specific requested entity. -As of 2.5, ``EntityManager`` will follow configured cascades, providing a better -memory management since associations will be garbage collected, optimizing -resources consumption on long running jobs. - -Updates on entities scheduled for deletion are no longer processed -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -In Doctrine 2.4, if you modified properties of an entity scheduled for deletion, UnitOfWork would -produce an ``UPDATE`` statement to be executed right before the ``DELETE`` statement. The entity in question -was therefore present in ``UnitOfWork#entityUpdates``, which means that ``preUpdate`` and ``postUpdate`` -listeners were (quite pointlessly) called. In ``preFlush`` listeners, it used to be possible to undo -the scheduled deletion for updated entities (by calling ``persist()`` if the entity was found in both -``entityUpdates`` and ``entityDeletions``). This does not work any longer, because the entire changeset -calculation logic is optimized away. - -Minor BC BREAK: Default lock mode changed from LockMode::NONE to null in method signatures -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -A misconception concerning default lock mode values in method signatures lead to unexpected behaviour -in SQL statements on SQL Server. With a default lock mode of ``LockMode::NONE`` throughout the -method signatures in ORM, the table lock hint ``WITH (NOLOCK)`` was appended to all locking related -queries by default. This could result in unpredictable results because an explicit ``WITH (NOLOCK)`` -table hint tells SQL Server to run a specific query in transaction isolation level READ UNCOMMITTED -instead of the default READ COMMITTED transaction isolation level. -Therefore there now is a distinction between ``LockMode::NONE`` and ``null`` to be able to tell -Doctrine whether to add table lock hints to queries by intention or not. To achieve this, the following -method signatures have been changed to declare ``$lockMode = null`` instead of ``$lockMode = LockMode::NONE``: - -- ``Doctrine\ORM\Cache\Persister\AbstractEntityPersister#getSelectSQL()`` -- ``Doctrine\ORM\Cache\Persister\AbstractEntityPersister#load()`` -- ``Doctrine\ORM\Cache\Persister\AbstractEntityPersister#refresh()`` -- ``Doctrine\ORM\Decorator\EntityManagerDecorator#find()`` -- ``Doctrine\ORM\EntityManager#find()`` -- ``Doctrine\ORM\EntityRepository#find()`` -- ``Doctrine\ORM\Persisters\BasicEntityPersister#getSelectSQL()`` -- ``Doctrine\ORM\Persisters\BasicEntityPersister#load()`` -- ``Doctrine\ORM\Persisters\BasicEntityPersister#refresh()`` -- ``Doctrine\ORM\Persisters\EntityPersister#getSelectSQL()`` -- ``Doctrine\ORM\Persisters\EntityPersister#load()`` -- ``Doctrine\ORM\Persisters\EntityPersister#refresh()`` -- ``Doctrine\ORM\Persisters\JoinedSubclassPersister#getSelectSQL()`` - -You should update signatures for these methods if you have subclassed one of the above classes. -Please also check the calling code of these methods in your application and update if necessary. - -.. note:: - - This in fact is really a minor BC BREAK and should not have any affect on database vendors - other than SQL Server because it is the only one that supports and therefore cares about - ``LockMode::NONE``. It's really just a FIX for SQL Server environments using ORM. - -Minor BC BREAK: __clone method not called anymore when entities are instantiated via metadata API -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -As of PHP 5.6, instantiation of new entities is deferred to the -`doctrine/instantiator `_ library, which will avoid calling ``__clone`` -or any public API on instantiated objects. - -BC BREAK: DefaultRepositoryFactory is now final -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Please implement the ``Doctrine\ORM\Repository\RepositoryFactory`` interface instead of extending -the ``Doctrine\ORM\Repository\DefaultRepositoryFactory``. - -BC BREAK: New object expression DQL queries now respects user provided aliasing and not return consumed fields -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -When executing DQL queries with new object expressions, instead of returning -DTOs numerically indexes, it will now respect user provided aliases. Consider -the following query: - -:: - - SELECT new UserDTO(u.id,u.name) as user,new AddressDTO(a.street,a.postalCode) as address, a.id as addressId - FROM User u INNER JOIN u.addresses a WITH a.isPrimary = true - -Previously, your result would be similar to this: - -:: - - array( - 0=>array( - 0=>{UserDTO object}, - 1=>{AddressDTO object}, - 2=>{u.id scalar}, - 3=>{u.name scalar}, - 4=>{a.street scalar}, - 5=>{a.postalCode scalar}, - 'addressId'=>{a.id scalar}, - ), - ... - ) - -From now on, the resultset will look like this: - -:: - - array( - 0=>array( - 'user'=>{UserDTO object}, - 'address'=>{AddressDTO object}, - 'addressId'=>{a.id scalar} - ), - ... - ) - diff --git a/docs/en/cookbook/advanced-field-value-conversion-using-custom-mapping-types.rst b/docs/en/cookbook/advanced-field-value-conversion-using-custom-mapping-types.rst index 5bbd2a3b11f..f735d99f46b 100644 --- a/docs/en/cookbook/advanced-field-value-conversion-using-custom-mapping-types.rst +++ b/docs/en/cookbook/advanced-field-value-conversion-using-custom-mapping-types.rst @@ -11,9 +11,9 @@ There are several ways to achieve this: converting the value inside the Type class, converting the value on the database-level or a combination of both. This article describes the third way by implementing the MySQL specific column -type `Point `_. +type `Point `_. -The ``Point`` type is part of the `Spatial extension `_ +The ``Point`` type is part of the `Spatial extension `_ of MySQL and enables you to store a single location in a coordinate space by using x and y coordinates. You can use the Point type to store a longitude/latitude pair to represent a geographic location. @@ -192,9 +192,9 @@ object into a string representation before saving to the database (in the ``convertToDatabaseValue`` method) and back into an object after fetching the value from the database (in the ``convertToPHPValue`` method). -The format of the string representation format is called `Well-known text (WKT) -`_. The advantage of this format -is, that it is both human readable and parsable by MySQL. +The format of the string representation format is called +`Well-known text (WKT) `_. +The advantage of this format is, that it is both human readable and parsable by MySQL. Internally, MySQL stores geometry values in a binary format that is not identical to the WKT format. So, we need to let MySQL transform the WKT @@ -204,8 +204,8 @@ This is where the ``convertToPHPValueSQL`` and ``convertToDatabaseValueSQL`` methods come into play. This methods wrap a sql expression (the WKT representation of the Point) into -MySQL functions `PointFromText `_ -and `AsText `_ +MySQL functions `ST_PointFromText `_ +and `ST_AsText `_ which convert WKT strings to and from the internal format of MySQL. .. note:: @@ -249,7 +249,7 @@ Example usage $em->clear(); // Fetch the Location object - $query = $em->createQuery("SELECT l FROM Geo\Entity\Location WHERE l.address = '1600 Amphitheatre Parkway, Mountain View, CA'"); + $query = $em->createQuery("SELECT l FROM Geo\Entity\Location l WHERE l.address = '1600 Amphitheatre Parkway, Mountain View, CA'"); $location = $query->getSingleResult(); /* @var Geo\ValueObject\Point */ diff --git a/docs/en/cookbook/aggregate-fields.rst b/docs/en/cookbook/aggregate-fields.rst index fdf830323e1..7e5a89dce2b 100644 --- a/docs/en/cookbook/aggregate-fields.rst +++ b/docs/en/cookbook/aggregate-fields.rst @@ -322,7 +322,7 @@ The aggregate field ``Account::$balance`` is now -200, however the SUM over all entries amounts yields -400. A violation of our max credit rule. -You can use both optimistic or pessimistic locking to save-guard +You can use both optimistic or pessimistic locking to safe-guard your aggregate fields against this kind of race-conditions. Reading Eric Evans DDD carefully he mentions that the "Aggregate Root" (Account in our example) needs a locking mechanism. diff --git a/docs/en/cookbook/custom-mapping-types.rst b/docs/en/cookbook/custom-mapping-types.rst index 1bd4f124215..d9e38560c6c 100644 --- a/docs/en/cookbook/custom-mapping-types.rst +++ b/docs/en/cookbook/custom-mapping-types.rst @@ -49,8 +49,6 @@ you wish. Here is an example skeleton of such a custom type class: The following assumptions are applied to mapping types by the ORM: - - If the value of the field is *NULL* the method - ``convertToDatabaseValue()`` is not called. - The ``UnitOfWork`` never passes values to the database convert method that did not change in the request. - The ``UnitOfWork`` internally assumes that entity identifiers are diff --git a/docs/en/cookbook/dql-user-defined-functions.rst b/docs/en/cookbook/dql-user-defined-functions.rst index a3a7606ad80..5c9b3e5d3fb 100644 --- a/docs/en/cookbook/dql-user-defined-functions.rst +++ b/docs/en/cookbook/dql-user-defined-functions.rst @@ -21,7 +21,7 @@ the :doc:`Native Query <../reference/native-sql>` chapter. The DQL Parser has hooks to register functions that can then be used in your DQL queries and transformed into SQL, allowing to extend Doctrines Query capabilities to the vendors strength. This -post explains the Used-Defined Functions API (UDF) of the Dql +post explains the User-Defined Functions API (UDF) of the Dql Parser and shows some examples to give you some hints how you would extend DQL. @@ -70,7 +70,7 @@ methods, which are quite handy in my opinion: Date Diff --------- -`Mysql's DateDiff function `_ +`Mysql's DateDiff function `_ takes two dates as argument and calculates the difference in days with ``date1-date2``. @@ -132,7 +132,7 @@ dql statement. The ``ArithmeticPrimary`` method call is the most common denominator of valid EBNF tokens taken from the -`DQL EBNF grammar `_ +`DQL EBNF grammar `_ that matches our requirements for valid input into the DateDiff Dql function. Picking the right tokens for your methods is a tricky business, but the EBNF grammar is pretty helpful finding it, as is @@ -164,7 +164,7 @@ Date Add Often useful it the ability to do some simple date calculations in your DQL query using -`MySql's DATE\_ADD function `_. +`MySql's DATE_ADD function `_. I'll skip the blah and show the code for this function: @@ -246,6 +246,6 @@ vendor sql functions and extend the DQL languages scope. Code for this Extension to DQL and other Doctrine Extensions can be found -`in my Github DoctrineExtensions repository `_. +`in the GitHub DoctrineExtensions repository `_. diff --git a/docs/en/cookbook/implementing-wakeup-or-clone.rst b/docs/en/cookbook/implementing-wakeup-or-clone.rst index 6a8ef9c91a7..1ae17753bc6 100644 --- a/docs/en/cookbook/implementing-wakeup-or-clone.rst +++ b/docs/en/cookbook/implementing-wakeup-or-clone.rst @@ -4,15 +4,15 @@ Implementing Wakeup or Clone .. sectionauthor:: Roman Borschel (roman@code-factory.org) As explained in the -`restrictions for entity classes in the manual `_, +`restrictions for entity classes in the manual `_, it is usually not allowed for an entity to implement ``__wakeup`` or ``__clone``, because Doctrine makes special use of them. However, it is quite easy to make use of these methods in a safe way by guarding the custom wakeup or clone code with an entity identity check, as demonstrated in the following sections. -Safely implementing \_\_wakeup ------------------------------- +Safely implementing __wakeup +---------------------------- To safely implement ``__wakeup``, simply enclose your implementation code in an identity check as follows: @@ -37,8 +37,8 @@ implementation code in an identity check as follows: //... } -Safely implementing \_\_clone ------------------------------ +Safely implementing __clone +--------------------------- Safely implementing ``__clone`` is pretty much the same: diff --git a/docs/en/cookbook/integrating-with-codeigniter.rst b/docs/en/cookbook/integrating-with-codeigniter.rst deleted file mode 100644 index 1c06a34e2c4..00000000000 --- a/docs/en/cookbook/integrating-with-codeigniter.rst +++ /dev/null @@ -1,140 +0,0 @@ -Integrating with CodeIgniter -============================ - -This is recipe for using Doctrine 2 in your -`CodeIgniter `_ framework. - -.. note:: - - This might not work for all CodeIgniter versions and may require - slight adjustments. - - -Here is how to set it up: - -Make a CodeIgniter library that is both a wrapper and a bootstrap -for Doctrine 2. - -Setting up the file structure ------------------------------ - -Here are the steps: - - -- Add a php file to your system/application/libraries folder - called Doctrine.php. This is going to be your wrapper/bootstrap for - the D2 entity manager. -- Put the Doctrine folder (the one that contains Common, DBAL, and - ORM) inside that same libraries folder. -- Your system/application/libraries folder now looks like this: - - system/applications/libraries -Doctrine -Doctrine.php -index.html - -- If you want, open your config/autoload.php file and autoload - your Doctrine library. - - register(); - $entitiesClassLoader = new ClassLoader('models', rtrim(APPPATH, "/" )); - $entitiesClassLoader->register(); - $proxiesClassLoader = new ClassLoader('Proxies', APPPATH.'models/proxies'); - $proxiesClassLoader->register(); - - // Set up caches - $config = new Configuration; - $cache = new ArrayCache; - $config->setMetadataCacheImpl($cache); - $driverImpl = $config->newDefaultAnnotationDriver(array(APPPATH.'models/Entities')); - $config->setMetadataDriverImpl($driverImpl); - $config->setQueryCacheImpl($cache); - - $config->setQueryCacheImpl($cache); - - // Proxy configuration - $config->setProxyDir(APPPATH.'/models/proxies'); - $config->setProxyNamespace('Proxies'); - - // Set up logger - $logger = new EchoSQLLogger; - $config->setSQLLogger($logger); - - $config->setAutoGenerateProxyClasses( TRUE ); - - // Database connection information - $connectionOptions = array( - 'driver' => 'pdo_mysql', - 'user' => $db['default']['username'], - 'password' => $db['default']['password'], - 'host' => $db['default']['hostname'], - 'dbname' => $db['default']['database'] - ); - - // Create EntityManager - $this->em = EntityManager::create($connectionOptions, $config); - } - } - -Please note that this is a development configuration; for a -production system you'll want to use a real caching system like -APC, get rid of EchoSqlLogger, and turn off -autoGenerateProxyClasses. - -For more details, consult the -`Doctrine 2 Configuration documentation `_. - -Now to use it -------------- - -Whenever you need a reference to the entity manager inside one of -your controllers, views, or models you can do this: - -.. code-block:: php - - doctrine->em; - -That's all there is to it. Once you get the reference to your -EntityManager do your Doctrine 2.0 voodoo as normal. - -Note: If you do not choose to autoload the Doctrine library, you -will need to put this line before you get a reference to it: - -.. code-block:: php - - load->library('doctrine'); - -Good luck! - - diff --git a/docs/en/cookbook/mysql-enums.rst b/docs/en/cookbook/mysql-enums.rst index 1d8df92590c..1765ecc90e8 100644 --- a/docs/en/cookbook/mysql-enums.rst +++ b/docs/en/cookbook/mysql-enums.rst @@ -98,7 +98,7 @@ For example for the previous enum type: public function getSQLDeclaration(array $fieldDeclaration, AbstractPlatform $platform) { - return sprintf("ENUM('visible', 'invisible') COMMENT '(DC2Type:%s)'", self::ENUM_VISIBILITY); + return "ENUM('visible', 'invisible')"; } public function convertToPHPValue($value, AbstractPlatform $platform) @@ -118,6 +118,11 @@ For example for the previous enum type: { return self::ENUM_VISIBILITY; } + + public function requiresSQLCommentHint(AbstractPlatform $platform) + { + return true; + } } You can register this type with ``Type::addType('enumvisibility', 'MyProject\DBAL\EnumVisibilityType');``. @@ -152,7 +157,7 @@ You can generalize this approach easily to create a base class for enums: { $values = array_map(function($val) { return "'".$val."'"; }, $this->values); - return "ENUM(".implode(", ", $values).") COMMENT '(DC2Type:".$this->name.")'"; + return "ENUM(".implode(", ", $values).")"; } public function convertToPHPValue($value, AbstractPlatform $platform) @@ -172,6 +177,11 @@ You can generalize this approach easily to create a base class for enums: { return $this->name; } + + public function requiresSQLCommentHint(AbstractPlatform $platform) + { + return true; + } } With this base class you can define an enum as easily as: diff --git a/docs/en/cookbook/sql-table-prefixes.rst b/docs/en/cookbook/sql-table-prefixes.rst index fdfd4032f3c..5ea587986b6 100644 --- a/docs/en/cookbook/sql-table-prefixes.rst +++ b/docs/en/cookbook/sql-table-prefixes.rst @@ -41,7 +41,9 @@ appropriate autoloaders. $classMetadata = $eventArgs->getClassMetadata(); if (!$classMetadata->isInheritanceTypeSingleTable() || $classMetadata->getName() === $classMetadata->rootEntityName) { - $classMetadata->setTableName($this->prefix . $classMetadata->getTableName()); + $classMetadata->setPrimaryTable([ + 'name' => $this->prefix . $classMetadata->getTableName() + ]); } foreach ($classMetadata->getAssociationMappings() as $fieldName => $mapping) { diff --git a/docs/en/cookbook/strategy-cookbook-introduction.rst b/docs/en/cookbook/strategy-cookbook-introduction.rst index d9934f577de..b434a9df4d2 100644 --- a/docs/en/cookbook/strategy-cookbook-introduction.rst +++ b/docs/en/cookbook/strategy-cookbook-introduction.rst @@ -3,7 +3,7 @@ Strategy-Pattern This recipe will give you a short introduction on how to design similar entities without using expensive (i.e. slow) inheritance -but with not more than \* the well-known strategy pattern \* event +but with not more than *the well-known strategy pattern* event listeners Scenario / Problem diff --git a/docs/en/cookbook/validation-of-entities.rst b/docs/en/cookbook/validation-of-entities.rst index fb0254417b0..dd10b8b9afa 100644 --- a/docs/en/cookbook/validation-of-entities.rst +++ b/docs/en/cookbook/validation-of-entities.rst @@ -89,7 +89,7 @@ events for one method, this will happen before Beta 1 though. Now validation is performed whenever you call ``EntityManager#persist($order)`` or when you call ``EntityManager#flush()`` and an order is about to be updated. Any -Exception that happens in the lifecycle callbacks will be cached by +Exception that happens in the lifecycle callbacks will be caught by the EntityManager and the current transaction is rolled back. Of course you can do any type of primitive checks, not null, @@ -134,4 +134,4 @@ instances. This was already discussed in the previous blog post on the Versionable extension, which requires another type of event called "onFlush". -Further readings: :doc:`Lifecycle Events <../reference/events>` +Further readings: :ref:`reference-events-lifecycle-events` diff --git a/docs/en/cookbook/working-with-datetime.rst b/docs/en/cookbook/working-with-datetime.rst index 98a1fb234c2..f599b836b41 100644 --- a/docs/en/cookbook/working-with-datetime.rst +++ b/docs/en/cookbook/working-with-datetime.rst @@ -1,7 +1,7 @@ Working with DateTime Instances =============================== -There are many nitty gritty details when working with PHPs DateTime instances. You have know their inner +There are many nitty gritty details when working with PHPs DateTime instances. You have to know their inner workings pretty well not to make mistakes with date handling. This cookbook entry holds several interesting pieces of information on how to work with PHP DateTime instances in Doctrine 2. @@ -90,7 +90,10 @@ the UTC time at the time of the booking and the timezone the event happened in. class UTCDateTimeType extends DateTimeType { - static private $utc; + /** + * @var \DateTimeZone + */ + private static $utc; public function convertToDatabaseValue($value, AbstractPlatform $platform) { @@ -110,7 +113,7 @@ the UTC time at the time of the booking and the timezone the event happened in. $converted = \DateTime::createFromFormat( $platform->getDateTimeFormatString(), $value, - self::$utc ? self::$utc : self::$utc = new \DateTimeZone('UTC') + self::getUtc() ); if (! $converted) { @@ -123,6 +126,11 @@ the UTC time at the time of the booking and the timezone the event happened in. return $converted; } + + private static function getUtc(): \DateTimeZone + { + return self::$utc ?: self::$utc = new \DateTimeZone('UTC'); + } } This database type makes sure that every DateTime instance is always saved in UTC, relative diff --git a/docs/en/index.rst b/docs/en/index.rst index 8e6afc82592..0cea054dacb 100644 --- a/docs/en/index.rst +++ b/docs/en/index.rst @@ -13,11 +13,11 @@ If this documentation is not helping to answer questions you have about Doctrine ORM don't panic. You can get help from different sources: - There is a :doc:`FAQ ` with answers to frequent questions. -- The `Doctrine Mailing List `_ -- Internet Relay Chat (IRC) in #doctrine on Freenode -- Report a bug on `JIRA `_. +- The `Doctrine Mailing List `_ +- Slack chat room `#orm `_ +- Report a bug on `GitHub `_. - On `Twitter `_ with ``#doctrine2`` -- On `StackOverflow `_ +- On `StackOverflow `_ If you need more structure over the different topics you can browse the :doc:`table of contents `. @@ -72,9 +72,9 @@ Advanced Topics * :doc:`Transactions and Concurrency ` * :doc:`Filters ` * :doc:`NamingStrategy ` -* :doc:`Improving Performance ` -* :doc:`Caching ` -* :doc:`Partial Objects ` +* :doc:`Improving Performance ` +* :doc:`Caching ` +* :doc:`Partial Objects ` * :doc:`Change Tracking Policies ` * :doc:`Best Practices ` * :doc:`Metadata Drivers ` @@ -95,7 +95,7 @@ Tutorials Changelogs ---------- -* :doc:`Migration to 2.5 ` +* `Upgrade `_ Cookbook -------- @@ -103,7 +103,7 @@ Cookbook * **Patterns**: :doc:`Aggregate Fields ` | :doc:`Decorator Pattern ` | - :doc:`Strategy Pattern ` + :doc:`Strategy Pattern ` * **DQL Extension Points**: :doc:`DQL Custom Walkers ` | @@ -118,9 +118,6 @@ Cookbook :doc:`Entities in the Session ` | :doc:`Keeping your Modules independent ` -* **Integration into Frameworks/Libraries** - :doc:`CodeIgniter ` - * **Hidden Gems** :doc:`Prefixing Table Name ` diff --git a/docs/en/reference/advanced-configuration.rst b/docs/en/reference/advanced-configuration.rst index 9d200f87005..0ddb6ef9c48 100644 --- a/docs/en/reference/advanced-configuration.rst +++ b/docs/en/reference/advanced-configuration.rst @@ -152,6 +152,7 @@ The recommended implementations for production are: - ``Doctrine\Common\Cache\ApcCache`` +- ``Doctrine\Common\Cache\ApcuCache`` - ``Doctrine\Common\Cache\MemcacheCache`` - ``Doctrine\Common\Cache\XcacheCache`` - ``Doctrine\Common\Cache\RedisCache`` @@ -183,6 +184,7 @@ The recommended implementations for production are: - ``Doctrine\Common\Cache\ApcCache`` +- ``Doctrine\Common\Cache\ApcuCache`` - ``Doctrine\Common\Cache\MemcacheCache`` - ``Doctrine\Common\Cache\XcacheCache`` - ``Doctrine\Common\Cache\RedisCache`` @@ -290,7 +292,7 @@ instance of ``Doctrine\DBAL\Connection``. If an array is passed it is directly passed along to the DBAL Factory ``Doctrine\DBAL\DriverManager::getConnection()``. The DBAL configuration is explained in the -`DBAL section <./../../../../../projects/doctrine-dbal/en/latest/reference/configuration.html>`_. +`DBAL section `_. Proxy Objects ------------- @@ -394,7 +396,7 @@ means that you have to register a special autoloader for these classes: .. code-block:: php ` - :ref:`@Cache ` - :ref:`@ChangeTrackingPolicy ` +- :ref:`@CustomIdGenerator ` - :ref:`@DiscriminatorColumn ` - :ref:`@DiscriminatorMap ` - :ref:`@Embeddable ` @@ -112,7 +113,7 @@ Optional attributes: - **unique**: Boolean value to determine if the value of the column should be unique across all rows of the underlying entities table. -- **nullable**: Determines if NULL values allowed for this column. +- **nullable**: Determines if NULL values allowed for this column. If not specified, default value is false. - **options**: Array of additional options: @@ -133,6 +134,9 @@ Optional attributes: - ``collation``: The collation of the column (only supported by Drizzle, Mysql, PostgreSQL>=9.1, Sqlite and SQLServer). + - ``check``: Adds a check constraint type to the column (might not + be supported by all vendors). + - **columnDefinition**: DDL SQL snippet that starts after the column name and specifies the complete (non-portable!) column definition. This attribute allows to make use of advanced RMDBS features. @@ -177,7 +181,7 @@ Examples: protected $initials; /** - * @Column(type="integer", name="login_count" nullable=false, options={"unsigned":true, "default":0}) + * @Column(type="integer", name="login_count", nullable=false, options={"unsigned":true, "default":0}) */ protected $loginCount; @@ -233,6 +237,30 @@ Example: */ class User {} +.. _annref_customidgenerator: + +@CustomIdGenerator +~~~~~~~~~~~~~~~~~~~~~ + +This annotations allows you to specify a user-provided class to generate identifiers. This annotation only works when both :ref:`@Id ` and :ref:`@GeneratedValue(strategy="CUSTOM") ` are specified. + +Required attributes: + +- **class**: name of the class which should extend Doctrine\ORM\Id\AbstractIdGenerator + +Example: + +.. code-block:: php + + ` -annotation to establish the relationship between two entities. +The embeddable annotation is required on a class, in order to make it +embeddable inside an entity. It works together with the :ref:`@Embedded ` +annotation to establish the relationship between the two classes. .. code-block:: php @@ -317,8 +345,8 @@ annotation to establish the relationship between two entities. @Embedded ~~~~~~~~~~~~~~~~~~~~~ -The embedded annotation is required on a member class varible targed to -embed it's class argument inside it's own class. +The embedded annotation is required on an entity's member variable, +in order to specify that it is an embedded class. Required attributes: diff --git a/docs/en/reference/architecture.rst b/docs/en/reference/architecture.rst index 6d45befc630..708acbd5fc3 100644 --- a/docs/en/reference/architecture.rst +++ b/docs/en/reference/architecture.rst @@ -18,7 +18,7 @@ well. Requirements ------------ -Doctrine 2 requires a minimum of PHP 5.4. For greatly improved +Doctrine 2 requires a minimum of PHP 7.1. For greatly improved performance it is also recommended that you use APC with PHP. Doctrine 2 Packages diff --git a/docs/en/reference/association-mapping.rst b/docs/en/reference/association-mapping.rst index a1a9f83a81a..6347d89c693 100644 --- a/docs/en/reference/association-mapping.rst +++ b/docs/en/reference/association-mapping.rst @@ -16,13 +16,24 @@ This chapter is split into three different sections. - :ref:`association_mapping_defaults` are explained that simplify the use-case examples. - :ref:`collections` are introduced that contain entities in associations. +One tip for working with relations is to read the relation from left to right, where the left word refers to the current Entity. For example: + +- OneToMany - One instance of the current Entity has Many instances (references) to the refered Entity. +- ManyToOne - Many instances of the current Entity refer to One instance of the refered Entity. +- OneToOne - One instance of the current Entity refers to One instance of the refered Entity. + +See below for all the possible relations. + +An association is considered to be unidirectional if only one side of the association has +a property referring to the other side. + To gain a full understanding of associations you should also read about :doc:`owning and inverse sides of associations ` Many-To-One, Unidirectional --------------------------- -A many-to-one association is the most common association between objects. +A many-to-one association is the most common association between objects. Example: Many Users have One Address: .. configuration-block:: @@ -96,9 +107,7 @@ One-To-One, Unidirectional -------------------------- Here is an example of a one-to-one association with a ``Product`` entity that -references one ``Shipping`` entity. The ``Shipping`` does not reference back to -the ``Product`` so that the reference is said to be unidirectional, in one -direction only. +references one ``Shipment`` entity. .. configuration-block:: @@ -111,16 +120,17 @@ direction only. // ... /** - * @OneToOne(targetEntity="Shipping") - * @JoinColumn(name="shipping_id", referencedColumnName="id") + * One Product has One Shipment. + * @OneToOne(targetEntity="Shipment") + * @JoinColumn(name="shipment_id", referencedColumnName="id") */ - private $shipping; + private $shipment; // ... } /** @Entity */ - class Shipping + class Shipment { // ... } @@ -129,8 +139,8 @@ direction only. - - + + @@ -140,10 +150,10 @@ direction only. Product: type: entity oneToOne: - shipping: - targetEntity: Shipping + shipment: + targetEntity: Shipment joinColumn: - name: shipping_id + name: shipment_id referencedColumnName: id Note that the @JoinColumn is not really necessary in this example, @@ -155,15 +165,15 @@ Generated MySQL Schema: CREATE TABLE Product ( id INT AUTO_INCREMENT NOT NULL, - shipping_id INT DEFAULT NULL, - UNIQUE INDEX UNIQ_6FBC94267FE4B2B (shipping_id), + shipment_id INT DEFAULT NULL, + UNIQUE INDEX UNIQ_6FBC94267FE4B2B (shipment_id), PRIMARY KEY(id) ) ENGINE = InnoDB; - CREATE TABLE Shipping ( + CREATE TABLE Shipment ( id INT AUTO_INCREMENT NOT NULL, PRIMARY KEY(id) ) ENGINE = InnoDB; - ALTER TABLE Product ADD FOREIGN KEY (shipping_id) REFERENCES Shipping(id); + ALTER TABLE Product ADD FOREIGN KEY (shipment_id) REFERENCES Shipment(id); One-To-One, Bidirectional ------------------------- @@ -172,6 +182,10 @@ Here is a one-to-one relationship between a ``Customer`` and a ``Cart``. The ``Cart`` has a reference back to the ``Customer`` so it is bidirectional. +Here we see the ``mappedBy`` and ``inversedBy`` annotations for the first time. +They are used to tell Doctrine which property on the other side refers to the +object. + .. configuration-block:: .. code-block:: php @@ -183,6 +197,7 @@ it is bidirectional. // ... /** + * One Customer has One Cart. * @OneToOne(targetEntity="Cart", mappedBy="customer") */ private $cart; @@ -196,6 +211,7 @@ it is bidirectional. // ... /** + * One Cart has One Customer. * @OneToOne(targetEntity="Customer", inversedBy="cart") * @JoinColumn(name="customer_id", referencedColumnName="id") */ @@ -251,8 +267,9 @@ Generated MySQL Schema: ) ENGINE = InnoDB; ALTER TABLE Cart ADD FOREIGN KEY (customer_id) REFERENCES Customer(id); -See how the foreign key is defined on the owning side of the -relation, the table ``Cart``. +We had a choice of sides on which to place the ``inversedBy`` attribute. Because it +is on the ``Cart``, that is the owning side of the relation, and thus holds the +foreign key. One-To-One, Self-referencing ---------------------------- @@ -269,6 +286,7 @@ below. // ... /** + * One Student has One Mentor. * @OneToOne(targetEntity="Student") * @JoinColumn(name="mentor_id", referencedColumnName="id") */ @@ -294,15 +312,16 @@ With the generated MySQL Schema: One-To-Many, Bidirectional -------------------------- -A one-to-many association has to be bidirectional, unless you are using an -additional join-table. This is necessary, because of the foreign key -in a one-to-many association being defined on the "many" side. Doctrine -needs a many-to-one association that defines the mapping of this -foreign key. +A one-to-many association has to be bidirectional, unless you are using a +join table. This is because the "many" side in a one-to-many association holds +the foreign key, making it the owning side. Doctrine needs the "many" side +defined in order to understand the association. This bidirectional mapping requires the ``mappedBy`` attribute on the -``OneToMany`` association and the ``inversedBy`` attribute on the ``ManyToOne`` -association. +"one" side and the ``inversedBy`` attribute on the "many" side. + +This means there is no difference between a bidirectional one-to-many and a +bidirectional many-to-one. .. configuration-block:: @@ -316,6 +335,7 @@ association. { // ... /** + * One product has many features. This is the inverse side. * @OneToMany(targetEntity="Feature", mappedBy="product") */ private $features; @@ -331,6 +351,7 @@ association. { // ... /** + * Many features have one product. This is the owning side. * @ManyToOne(targetEntity="Product", inversedBy="features") * @JoinColumn(name="product_id", referencedColumnName="id") */ @@ -408,6 +429,7 @@ The following example sets up such a unidirectional one-to-many association: // ... /** + * Many User have Many Phonenumbers. * @ManyToMany(targetEntity="Phonenumber") * @JoinTable(name="users_phonenumbers", * joinColumns={@JoinColumn(name="user_id", referencedColumnName="id")}, @@ -508,11 +530,13 @@ database perspective is known as an adjacency list approach. { // ... /** + * One Category has Many Categories. * @OneToMany(targetEntity="Category", mappedBy="parent") */ private $children; /** + * Many Categories have One Category. * @ManyToOne(targetEntity="Category", inversedBy="children") * @JoinColumn(name="parent_id", referencedColumnName="id") */ @@ -578,6 +602,7 @@ entities: // ... /** + * Many Users have Many Groups. * @ManyToMany(targetEntity="Group") * @JoinTable(name="users_groups", * joinColumns={@JoinColumn(name="user_id", referencedColumnName="id")}, @@ -678,6 +703,7 @@ one is bidirectional. // ... /** + * Many Users have Many Groups. * @ManyToMany(targetEntity="Group", inversedBy="users") * @JoinTable(name="users_groups") */ @@ -695,6 +721,7 @@ one is bidirectional. { // ... /** + * Many Groups have Many Users. * @ManyToMany(targetEntity="User", mappedBy="groups") */ private $users; @@ -754,22 +781,22 @@ one is bidirectional. The MySQL schema is exactly the same as for the Many-To-Many uni-directional case above. -Owning and Inverse Side on a ManyToMany association +Owning and Inverse Side on a ManyToMany Association ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ For Many-To-Many associations you can chose which entity is the owning and which the inverse side. There is a very simple semantic rule to decide which side is more suitable to be the owning side -from a developers perspective. You only have to ask yourself, which -entity is responsible for the connection management and pick that +from a developers perspective. You only have to ask yourself which +entity is responsible for the connection management, and pick that as the owning side. Take an example of two entities ``Article`` and ``Tag``. Whenever you want to connect an Article to a Tag and vice-versa, it is mostly the Article that is responsible for this relation. Whenever you add a new article, you want to connect it with existing or new -tags. Your create Article form will probably support this notion -and allow to specify the tags directly. This is why you should pick +tags. Your "Create Article" form will probably support this notion +and allow specifying the tags directly. This is why you should pick the Article as owning side, as it makes the code more understandable: @@ -825,11 +852,13 @@ field named ``$friendsWithMe`` and ``$myFriends``. // ... /** + * Many Users have Many Users. * @ManyToMany(targetEntity="User", mappedBy="myFriends") */ private $friendsWithMe; /** + * Many Users have many Users. * @ManyToMany(targetEntity="User", inversedBy="friendsWithMe") * @JoinTable(name="friends", * joinColumns={@JoinColumn(name="user_id", referencedColumnName="id")}, @@ -883,14 +912,14 @@ As an example, consider this mapping: .. code-block:: php - + @@ -899,8 +928,8 @@ As an example, consider this mapping: Product: type: entity oneToOne: - shipping: - targetEntity: Shipping + shipment: + targetEntity: Shipment This is essentially the same as the following, more verbose, mapping: @@ -911,17 +940,18 @@ mapping: - - + + @@ -931,10 +961,10 @@ mapping: Product: type: entity oneToOne: - shipping: - targetEntity: Shipping + shipment: + targetEntity: Shipment joinColumn: - name: shipping_id + name: shipment_id referencedColumnName: id The @JoinTable definition used for many-to-many mappings has @@ -980,6 +1010,7 @@ This is essentially the same as the following, more verbose, mapping: { //... /** + * Many Users have Many Groups. * @ManyToMany(targetEntity="Group") * @JoinTable(name="User_Group", * joinColumns={@JoinColumn(name="User_id", referencedColumnName="id")}, @@ -1064,12 +1095,17 @@ and ``@ManyToMany`` associations in the constructor of your entities: .. code-block:: php `_ + set by `date_default_timezone_set() `_ or by the php.ini configuration ``date.timezone``. Working with different timezones will cause troubles and unexpected behavior. @@ -295,7 +295,8 @@ annotation. class Message { /** - * @Id @Column(type="integer") + * @Id + * @Column(type="integer") * @GeneratedValue */ private $id; @@ -363,6 +364,8 @@ Here is the list of possible generation strategies: thus generated) by your code. The assignment must take place before a new entity is passed to ``EntityManager#persist``. NONE is the same as leaving off the @GeneratedValue entirely. +- ``CUSTOM``: With this option, you can use the ``@CustomIdGenerator`` annotation. + It will allow you to pass a :doc:`class of your own to generate the identifiers.<_annref_customidgenerator>` Sequence Generator ^^^^^^^^^^^^^^^^^^ diff --git a/docs/en/reference/batch-processing.rst b/docs/en/reference/batch-processing.rst index 5d3cf188781..e238516c561 100644 --- a/docs/en/reference/batch-processing.rst +++ b/docs/en/reference/batch-processing.rst @@ -16,6 +16,15 @@ especially what the strategies presented here provide help with. operations. +.. note:: + + Having an SQL logger enabled when processing batches can have a serious impact on performance and resource usage. + To avoid that you should disable it in the DBAL configuration: +.. code-block:: php + + getConnection()->getConfiguration()->setSQLLogger(null); + Bulk Inserts ------------ @@ -75,7 +84,7 @@ with the batching strategy that was already used for bulk inserts: createQuery('select u from MyProject\Model\User u'); $iterableResult = $q->iterate(); foreach ($iterableResult as $row) { @@ -100,7 +109,7 @@ with the batching strategy that was already used for bulk inserts: Results may be fully buffered by the database client/ connection allocating additional memory not visible to the PHP process. For large sets this - may easily kill the process for no apparant reason. + may easily kill the process for no apparent reason. Bulk Deletes @@ -136,7 +145,7 @@ The following example shows how to do this: createQuery('select u from MyProject\Model\User u'); $iterableResult = $q->iterate(); while (($row = $iterableResult->next()) !== false) { diff --git a/docs/en/reference/caching.rst b/docs/en/reference/caching.rst index 512254ef6bf..4c07e1607c5 100644 --- a/docs/en/reference/caching.rst +++ b/docs/en/reference/caching.rst @@ -29,10 +29,10 @@ abstract protected methods that each of the drivers must implement: -- \_doFetch($id) -- \_doContains($id) -- \_doSave($id, $data, $lifeTime = false) -- \_doDelete($id) +- doFetch($id) +- doContains($id) +- doSave($id, $data, $lifeTime = false) +- doDelete($id) The public methods ``fetch()``, ``contains()`` etc. use the above protected methods which are implemented by the drivers. The @@ -43,7 +43,7 @@ these methods. This documentation does not cover every single cache driver included with Doctrine. For an up-to-date-list, see the -`cache directory on GitHub `. +`cache directory on GitHub `_. APC ~~~ @@ -63,6 +63,24 @@ by itself. $cacheDriver = new \Doctrine\Common\Cache\ApcCache(); $cacheDriver->save('cache_id', 'my_data'); +APCu +~~~~ + +In order to use the APCu cache driver you must have it compiled and +enabled in your php.ini. You can read about APCu +`in the PHP Documentation `_. It will give +you a little background information about what it is and how you +can use it as well as how to install it. + +Below is a simple example of how you could use the APCu cache driver +by itself. + +.. code-block:: php + + save('cache_id', 'my_data'); + Memcache ~~~~~~~~ @@ -264,6 +282,8 @@ You can set the namespace a cache driver should use by using the setNamespace('my_namespace_'); +.. _integrating-with-the-orm: + Integrating with the ORM ------------------------ @@ -287,7 +307,7 @@ use on your ORM configuration. setQueryCacheImpl(new \Doctrine\Common\Cache\ApcCache()); + $config->setQueryCacheImpl(new \Doctrine\Common\Cache\ApcuCache()); Result Cache ~~~~~~~~~~~~ @@ -300,7 +320,7 @@ cache implementation. .. code-block:: php setResultCacheImpl(new \Doctrine\Common\Cache\ApcCache()); + $config->setResultCacheImpl(new \Doctrine\Common\Cache\ApcuCache()); Now when you're executing DQL queries you can configure them to use the result cache. @@ -317,7 +337,7 @@ result cache driver. .. code-block:: php setResultCacheDriver(new \Doctrine\Common\Cache\ApcCache()); + $query->setResultCacheDriver(new \Doctrine\Common\Cache\ApcuCache()); .. note:: @@ -369,7 +389,7 @@ first. .. code-block:: php setMetadataCacheImpl(new \Doctrine\Common\Cache\ApcCache()); + $config->setMetadataCacheImpl(new \Doctrine\Common\Cache\ApcuCache()); Now the metadata information will only be parsed once and stored in the cache driver. diff --git a/docs/en/reference/configuration.rst b/docs/en/reference/configuration.rst index 2d7ff241bd6..38775afdca4 100644 --- a/docs/en/reference/configuration.rst +++ b/docs/en/reference/configuration.rst @@ -1,9 +1,7 @@ Installation and Configuration ============================== -Doctrine can be installed with `Composer `_. For -older versions we still have `PEAR packages -`_. +Doctrine can be installed with `Composer `_. Define the following requirement in your ``composer.json`` file: @@ -16,8 +14,7 @@ Define the following requirement in your ``composer.json`` file: } Then call ``composer install`` from your command line. If you don't know -how Composer works, check out their `Getting Started -`_ to set up. +how Composer works, check out their `Getting Started `_ to set up. Class loading ------------- @@ -93,8 +90,7 @@ Inside the ``Setup`` methods several assumptions are made: - If `$isDevMode` is false, set then proxy classes have to be explicitly created through the command line. - If third argument `$proxyDir` is not set, use the systems temporary directory. -If you want to configure Doctrine in more detail, take a look at the :doc:`Advanced -Configuration ` section. +If you want to configure Doctrine in more detail, take a look at the :doc:`Advanced Configuration ` section. .. note:: diff --git a/docs/en/reference/dql-doctrine-query-language.rst b/docs/en/reference/dql-doctrine-query-language.rst index 6f987441176..5a38101be93 100644 --- a/docs/en/reference/dql-doctrine-query-language.rst +++ b/docs/en/reference/dql-doctrine-query-language.rst @@ -2,7 +2,7 @@ Doctrine Query Language =========================== DQL stands for Doctrine Query Language and is an Object -Query Language derivate that is very similar to the Hibernate +Query Language derivative that is very similar to the Hibernate Query Language (HQL) or the Java Persistence Query Language (JPQL). In essence, DQL provides powerful querying capabilities over your @@ -34,9 +34,9 @@ object model. DQL SELECT statements are a very powerful way of retrieving parts of your domain model that are not accessible via associations. -Additionally they allow to retrieve entities and their associations +Additionally they allow you to retrieve entities and their associations in one single SQL select statement which can make a huge difference -in performance in contrast to using several queries. +in performance compared to using several queries. DQL UPDATE and DELETE statements offer a way to execute bulk changes on the entities of your domain model. This is often @@ -49,10 +49,6 @@ SELECT queries DQL SELECT clause ~~~~~~~~~~~~~~~~~ -The select clause of a DQL query specifies what appears in the -query result. The composition of all the expressions in the select -clause also influences the nature of the query result. - Here is an example that selects all users with an age > 20: .. code-block:: php @@ -83,14 +79,58 @@ Lets examine the query: The result of this query would be a list of User objects where all users are older than 20. -The SELECT clause allows to specify both class identification -variables that signal the hydration of a complete entity class or -just fields of the entity using the syntax ``u.name``. Combinations -of both are also allowed and it is possible to wrap both fields and -identification values into aggregation and DQL functions. Numerical -fields can be part of computations using mathematical operations. -See the sub-section on `Functions, Operators, Aggregates`_ for -more information. +Result format +~~~~~~~~~~~~~ +The composition of the expressions in the SELECT clause also +influences the nature of the query result. There are three +cases: + +**All objects** + +.. code-block:: sql + + SELECT u, p, n FROM Users u... + +In this case, the result will be an array of User objects because of +the FROM clause, with children ``p`` and ``n`` hydrated because of +their inclusion in the SELECT clause. + +**All scalars** + +.. code-block:: sql + + SELECT u.name, u.address FROM Users u... + +In this case, the result will be an array of arrays. In the example +above, each element of the result array would be an array of the +scalar name and address values. + +You can select scalars from any entity in the query. + +**Mixed** + +.. code-block:: sql + + SELECT u, p.quantity FROM Users u... + +Here, the result will again be an array of arrays, with each element +being an array made up of a User object and the scalar value +``p.quantity``. + +Multiple FROM clauses are allowed, which would cause the result +array elements to cycle through the classes included in the +multiple FROM clauses. + +.. note:: + + You cannot select other entities unless you also select the + root of the selection (which is the first entity in FROM). + + For example, ``SELECT p,n FROM Users u...`` would be wrong because + ``u`` is not part of the SELECT + + Doctrine throws an exception if you violate this constraint. + Joins ~~~~~ @@ -319,7 +359,8 @@ article-ids: $query = $em->createQuery('SELECT u.id, a.id as article_id FROM CmsUser u LEFT JOIN u.articles a'); $results = $query->getResult(); // array of user ids and every article_id for each user -Restricting a JOIN clause by additional conditions: +Restricting a JOIN clause by additional conditions specified by +WITH: .. code-block:: php @@ -452,6 +493,18 @@ Joins between entities without associations were not possible until version createQuery('SELECT u FROM User u JOIN Blacklist b WITH u.email = b.email'); +.. note:: + The differences between WHERE, WITH and HAVING clauses may be + confusing. + + - WHERE is applied to the results of an entire query + - WITH is applied to a join as an additional condition. For + arbitrary joins (SELECT f, b FROM Foo f, Bar b WITH f.id = b.id) + the WITH is required, even if it is 1 = 1 + - HAVING is applied to the results of a query after + aggregation (GROUP BY) + + Partial Object Syntax ^^^^^^^^^^^^^^^^^^^^^ @@ -601,12 +654,15 @@ The same restrictions apply for the reference of related entities. DQL DELETE statements are ported directly into a Database DELETE statement and therefore bypass any events and checks for the version column if they are not explicitly added to the WHERE clause - of the query. Additionally Deletes of specifies entities are *NOT* + of the query. Additionally Deletes of specified entities are *NOT* cascaded to related entities even if specified in the metadata. Functions, Operators, Aggregates -------------------------------- +It is possible to wrap both fields and identification values into +aggregation and DQL functions. Numerical fields can be part of +computations using mathematical operations. DQL Functions ~~~~~~~~~~~~~ @@ -635,8 +691,8 @@ clauses: - TRIM([LEADING \| TRAILING \| BOTH] ['trchar' FROM] str) - Trim the string by the given trim char, defaults to whitespaces. - UPPER(str) - Return the upper-case of the given string. -- DATE_ADD(date, days, unit) - Add the number of days to a given date. (Supported units are DAY, MONTH) -- DATE_SUB(date, days, unit) - Substract the number of days from a given date. (Supported units are DAY, MONTH) +- DATE_ADD(date, value, unit) - Add the given time to a given date. (Supported units are SECOND, MINUTE, HOUR, DAY, WEEK, MONTH, YEAR) +- DATE_SUB(date, value, unit) - Subtract the given time from a given date. (Supported units are SECOND, MINUTE, HOUR, DAY, WEEK, MONTH, YEAR) - DATE_DIFF(date1, date2) - Calculate the difference in days between date1-date2. Arithmetic operators @@ -940,8 +996,9 @@ the Query class. Here they are: result contains more than one object, an ``NonUniqueResultException`` is thrown. If the result contains no objects, an ``NoResultException`` is thrown. The pure/mixed distinction does not apply. -- ``Query#getOneOrNullResult()``: Retrieve a single object. If no - object is found null will be returned. +- ``Query#getOneOrNullResult()``: Retrieve a single object. If the + result contains more than one object, a ``NonUniqueResultException`` + is thrown. If no object is found null will be returned. - ``Query#getArrayResult()``: Retrieves an array graph (a nested array) that is largely interchangeable with the object graph generated by ``Query#getResult()`` for read-only purposes. @@ -1004,7 +1061,7 @@ structure: .. code-block:: php - $dql = "SELECT u, 'some scalar string', count(u.groups) AS num FROM User u JOIN u.groups g GROUP BY u.id"; + $dql = "SELECT u, 'some scalar string', count(g.id) AS num FROM User u JOIN u.groups g GROUP BY u.id"; array [0] @@ -1104,6 +1161,22 @@ Object hydration hydrates the result set into the object graph: $query = $em->createQuery('SELECT u FROM CmsUser u'); $users = $query->getResult(Query::HYDRATE_OBJECT); +Sometimes the behavior in the object hydrator can be confusing, which is +why we are listing as many of the assumptions here for reference: + +- Objects fetched in a FROM clause are returned as a Set, that means every + object is only ever included in the resulting array once. This is the case + even when using JOIN or GROUP BY in ways that return the same row for an + object multiple times. If the hydrator sees the same object multiple times, + then it makes sure it is only returned once. + +- If an object is already in memory from a previous query of any kind, then + then the previous object is used, even if the database may contain more + recent data. Data from the database is discarded. This even happens if the + previous object is still an unloaded proxy. + +This list might be incomplete. + Array Hydration ^^^^^^^^^^^^^^^ @@ -1380,7 +1453,13 @@ Given that there are 10 users and corresponding addresses in the database the ex SELECT * FROM address WHERE id IN (1, 2, 3, 4, 5, 6, 7, 8, 9, 10); .. note:: - Changing the fetch mode during a query is only possible for one-to-one and many-to-one relations. + Changing the fetch mode during a query mostly makes sense for one-to-one and many-to-one relations. In that case, + all the necessary IDs are available after the root entity (``user`` in the above example) has been loaded. So, one + query per association can be executed to fetch all the referred-to entities (``address``). + + For one-to-many relations, changing the fetch mode to eager will cause to execute one query **for every root entity + loaded**. This gives no improvement over the ``lazy`` fetch mode which will also initialize the associations on + a one-by-one basis once they are accessed. EBNF diff --git a/docs/en/reference/events.rst b/docs/en/reference/events.rst index 171adca02ee..9bcafe4813b 100644 --- a/docs/en/reference/events.rst +++ b/docs/en/reference/events.rst @@ -179,7 +179,7 @@ the life-time of their registered entities. allows providing fallback metadata even when no actual metadata exists or could be found. This event is not a lifecycle callback. - preFlush - The preFlush event occurs at the very beginning of a flush - operation. This event is not a lifecycle callback. + operation. - onFlush - The onFlush event occurs after the change-sets of all managed entities are computed. This event is not a lifecycle callback. @@ -323,7 +323,7 @@ XML would look something like this: + https://www.doctrine-project.org/schemas/orm/doctrine-mapping.xsd"> @@ -406,8 +406,8 @@ behaviors across different entity classes. Note that they require much more detailed knowledge about the inner workings of the EntityManager and UnitOfWork. Please read the -*Implementing Event Listeners* section carefully if you are trying -to write your own listener. +:ref:`reference-events-implementing-listeners` section carefully if you +are trying to write your own listener. For event subscribers, there are no surprises. They declare the lifecycle events in their ``getSubscribedEvents`` method and provide @@ -434,7 +434,7 @@ A lifecycle event listener looks like the following: } } -A lifecycle event subscriber may looks like this: +A lifecycle event subscriber may look like this: .. code-block:: php @@ -548,8 +548,9 @@ preFlush ~~~~~~~~ ``preFlush`` is called at ``EntityManager#flush()`` before -anything else. ``EntityManager#flush()`` can be called safely -inside its listeners. +anything else. ``EntityManager#flush()`` should not be called inside +its listeners, since `preFlush` event is dispatched in it, which would +result in infinite loop. .. code-block:: php @@ -888,6 +889,9 @@ you need to map the listener method using the event type mapping: preRemove: [preRemoveHandler] # .... +.. note:: + + The order of execution of multiple methods for the same event (e.g. multiple @PrePersist) is not guaranteed. Entity listeners resolver diff --git a/docs/en/reference/faq.rst b/docs/en/reference/faq.rst index 45fde18d7e0..ca7784edca0 100644 --- a/docs/en/reference/faq.rst +++ b/docs/en/reference/faq.rst @@ -21,12 +21,6 @@ created database tables and columns. Entity Classes -------------- -I access a variable and its null, what is wrong? -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -If this variable is a public variable then you are violating one of the criteria for entities. -All properties have to be protected or private for the proxy object pattern to work. - How can I add default values to a column? ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -204,6 +198,21 @@ No, it is not supported to sort by function in DQL. If you need this functionali use a native-query or come up with another solution. As a side note: Sorting with ORDER BY RAND() is painfully slow starting with 1000 rows. +Is it better to write DQL or to generate it with the query builder? +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The purpose of the ``QueryBuilder`` is to generate DQL dynamically, +which is useful when you have optional filters, conditional joins, etc. + +But the ``QueryBuilder`` is not an alternative to DQL, it actually generates DQL +queries at runtime, which are then interpreted by Doctrine. This means that +using the ``QueryBuilder`` to build and run a query is actually always slower +than only running the corresponding DQL query. + +So if you only need to generate a query and bind parameters to it, +you should use plain DQL, as this is a simpler and much more readable solution. +You should only use the ``QueryBuilder`` when you can't achieve what you want to do with a DQL query. + A Query fails, how can I debug it? ---------------------------------- diff --git a/docs/en/reference/filters.rst b/docs/en/reference/filters.rst index a5c0ee4cf14..87835260b92 100644 --- a/docs/en/reference/filters.rst +++ b/docs/en/reference/filters.rst @@ -39,7 +39,7 @@ proper quoting of parameters. ` +See :ref:`dql-temporarily-change-fetch-mode` Apply Best Practices @@ -61,6 +65,7 @@ Apply Best Practices A lot of the points mentioned in the Best Practices chapter will also positively affect the performance of Doctrine. +See :doc:`Best Practices ` Change Tracking policies ------------------------ diff --git a/docs/en/reference/inheritance-mapping.rst b/docs/en/reference/inheritance-mapping.rst index 9e895fcbc82..4d21ac73b81 100644 --- a/docs/en/reference/inheritance-mapping.rst +++ b/docs/en/reference/inheritance-mapping.rst @@ -159,7 +159,7 @@ This strategy is very efficient for querying across all types in the hierarchy or for specific types. No table joins are required, only a WHERE clause listing the type identifiers. In particular, relationships involving types that employ this mapping strategy are -very performant. +very performing. There is a general performance consideration with Single Table Inheritance: If the target-entity of a many-to-one or one-to-one @@ -174,7 +174,7 @@ SQL Schema considerations For Single-Table-Inheritance to work in scenarios where you are using either a legacy database schema or a self-written database schema you have to make sure that all columns that are not in the -root entity but in any of the different sub-entities has to allows +root entity but in any of the different sub-entities has to allow null values. Columns that have NOT NULL constraints have to be on the root entity of the single-table inheritance hierarchy. @@ -455,6 +455,7 @@ Things to note: - The association type *CANNOT* be changed. - The override could redefine the joinTables or joinColumns depending on the association type. - The override could redefine inversedBy to reference more than one extended entity. +- The override could redefine fetch to modify the fetch strategy of the extended entity. Attribute Override ~~~~~~~~~~~~~~~~~~~~ @@ -492,7 +493,7 @@ Could be used by an entity that extends a mapped superclass to override a field * column=@Column( * name = "guest_id", * type = "integer", - length = 140 + * length = 140 * ) * ), * @AttributeOverride(name="name", @@ -500,7 +501,7 @@ Could be used by an entity that extends a mapped superclass to override a field * name = "guest_name", * nullable = false, * unique = true, - length = 240 + * length = 240 * ) * ) * }) diff --git a/docs/en/reference/installation.rst b/docs/en/reference/installation.rst index 8b732ad6058..fec83787eff 100644 --- a/docs/en/reference/installation.rst +++ b/docs/en/reference/installation.rst @@ -1,5 +1,4 @@ Installation ============ -The installation chapter has moved to `Installation and Configuration -`_. +The installation chapter has moved to :doc:`Installation and Configuration `_. diff --git a/docs/en/reference/limitations-and-known-issues.rst b/docs/en/reference/limitations-and-known-issues.rst index 8f273568fd1..143d53b64ae 100644 --- a/docs/en/reference/limitations-and-known-issues.rst +++ b/docs/en/reference/limitations-and-known-issues.rst @@ -63,7 +63,7 @@ Where the ``attribute_name`` column contains the key and ``$attributes``. The feature request for persistence of primitive value arrays -`is described in the DDC-298 ticket `_. +`is described in the DDC-298 ticket `_. Cascade Merge with Bi-directional Associations ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -71,8 +71,8 @@ Cascade Merge with Bi-directional Associations There are two bugs now that concern the use of cascade merge in combination with bi-directional associations. Make sure to study the behavior of cascade merge if you are using it: -- `DDC-875 `_ Merge can sometimes add the same entity twice into a collection -- `DDC-763 `_ Cascade merge on associated entities can insert too many rows through "Persistence by Reachability" +- `DDC-875 `_ Merge can sometimes add the same entity twice into a collection +- `DDC-763 `_ Cascade merge on associated entities can insert too many rows through "Persistence by Reachability" Custom Persisters ~~~~~~~~~~~~~~~~~ @@ -83,8 +83,8 @@ Currently there is no way to overwrite the persister implementation for a given entity, however there are several use-cases that can benefit from custom persister implementations: -- `Add Upsert Support `_ -- `Evaluate possible ways in which stored-procedures can be used `_ +- `Add Upsert Support `_ +- `Evaluate possible ways in which stored-procedures can be used `_ Persist Keys of Collections ~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -94,7 +94,7 @@ PHP Arrays are ordered hash-maps and so should be the evaluate a feature that optionally persists and hydrates the keys of a Collection instance. -`Ticket DDC-213 `_ +`Ticket DDC-213 `_ Mapping many tables to one entity ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -116,7 +116,6 @@ blog posts we have written on this topics: - `A re-usable Versionable behavior for Doctrine2 `_ - `Write your own ORM on top of Doctrine2 `_ - `Doctrine 2 Behavioral Extensions `_ -- `Doctrator _ Doctrine 2 has enough hooks and extension points so that **you** can add whatever you want on top of it. None of this will ever become @@ -144,9 +143,7 @@ backwards compatibility issues or where no simple fix exists (yet). We don't plan to add every bug in the tracker there, just those issues that can potentially cause nightmares or pain of any sort. -See the Open Bugs on Jira for more details on `bugs, improvement and feature -requests -`_. +See bugs, improvement and feature requests on `Github issues `_. Identifier Quoting and Legacy Databases ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ diff --git a/docs/en/reference/metadata-drivers.rst b/docs/en/reference/metadata-drivers.rst index 6b9cb31e42c..5162dee2d3f 100644 --- a/docs/en/reference/metadata-drivers.rst +++ b/docs/en/reference/metadata-drivers.rst @@ -35,7 +35,7 @@ an entity. .. code-block:: php getConfiguration()->setMetadataCacheImpl(new ApcCache()); + $em->getConfiguration()->setMetadataCacheImpl(new ApcuCache()); If you want to use one of the included core metadata drivers you diff --git a/docs/en/reference/namingstrategy.rst b/docs/en/reference/namingstrategy.rst index 9d82d8d8b7d..23aa573534c 100644 --- a/docs/en/reference/namingstrategy.rst +++ b/docs/en/reference/namingstrategy.rst @@ -3,48 +3,43 @@ Implementing a NamingStrategy .. versionadded:: 2.3 -Using a naming strategy you can provide rules for automatically generating -database identifiers, columns and tables names -when the table/column name is not given. -This feature helps reduce the verbosity of the mapping document, -eliminating repetitive noise (eg: ``TABLE_``). - +Using a naming strategy you can provide rules for generating database identifiers, +column or table names when the column or table name is not given. This feature helps +reduce the verbosity of the mapping document, eliminating repetitive noise (eg: ``TABLE_``). Configuring a naming strategy ----------------------------- The default strategy used by Doctrine is quite minimal. By default the ``Doctrine\ORM\Mapping\DefaultNamingStrategy`` -uses the simple class name and the attributes names to generate tables and columns +uses the simple class name and the attribute names to generate tables and columns. -You can specify a different strategy by calling ``Doctrine\ORM\Configuration#setNamingStrategy()`` : +You can specify a different strategy by calling ``Doctrine\ORM\Configuration#setNamingStrategy()``: .. code-block:: php setNamingStrategy($namingStrategy); + $configuration->setNamingStrategy($namingStrategy); Underscore naming strategy --------------------------- -``\Doctrine\ORM\Mapping\UnderscoreNamingStrategy`` is a built-in strategy -that might be a useful if you want to use a underlying convention. +``\Doctrine\ORM\Mapping\UnderscoreNamingStrategy`` is a built-in strategy. .. code-block:: php setNamingStrategy($namingStrategy); - -Then SomeEntityName will generate the table SOME_ENTITY_NAME when CASE_UPPER -or some_entity_name using CASE_LOWER is given. + $configuration->setNamingStrategy($namingStrategy); +For SomeEntityName the strategy will generate the table SOME_ENTITY_NAME with the +``CASE_UPPER`` option, or some_entity_name with the ``CASE_LOWER`` option. Naming strategy interface ------------------------- The interface ``Doctrine\ORM\Mapping\NamingStrategy`` allows you to specify -a "naming standard" for database tables and columns. +a naming strategy for database tables and columns. .. code-block:: php @@ -101,10 +96,11 @@ a "naming standard" for database tables and columns. Implementing a naming strategy ------------------------------- -If you have database naming standards like all tables names should be prefixed -by the application prefix, all column names should be upper case, -you can easily achieve such standards by implementing a naming strategy. -You need to implements NamingStrategy first. Following is an example +If you have database naming standards, like all table names should be prefixed +by the application prefix, all column names should be lower case, you can easily +achieve such standards by implementing a naming strategy. + +You need to create a class which implements ``Doctrine\ORM\Mapping\NamingStrategy``. .. code-block:: php @@ -139,12 +135,3 @@ You need to implements NamingStrategy first. Following is an example ($referencedColumnName ?: $this->referenceColumnName())); } } - -Configuring the namingstrategy is easy if. -Just set your naming strategy calling ``Doctrine\ORM\Configuration#setNamingStrategy()`` :. - -.. code-block:: php - - setNamingStrategy($namingStrategy); diff --git a/docs/en/reference/native-sql.rst b/docs/en/reference/native-sql.rst index 75231b7a99b..1676a8f596d 100644 --- a/docs/en/reference/native-sql.rst +++ b/docs/en/reference/native-sql.rst @@ -63,7 +63,7 @@ This has several benefits: - The API is much simpler than the usual ``ResultSetMapping`` API. One downside is that the builder API does not yet support entities -with inheritance hierachies. +with inheritance hierarchies. .. code-block:: php @@ -92,7 +92,7 @@ a mapping from DQL alias (key) to SQL alias (value) generateSelectClause(array( + $selectClause = $rsm->generateSelectClause(array( 'u' => 't1', 'g' => 't2' )); diff --git a/docs/en/reference/query-builder.rst b/docs/en/reference/query-builder.rst index 6b868c653f3..91833aee53d 100644 --- a/docs/en/reference/query-builder.rst +++ b/docs/en/reference/query-builder.rst @@ -7,14 +7,20 @@ conditionally constructing a DQL query in several steps. It provides a set of classes and methods that is able to programmatically build queries, and also provides a fluent API. This means that you can change between one methodology to the other -as you want, and also pick one if you prefer. +as you want, or just pick a preferred one. + +.. note:: + + The ``QueryBuilder`` is not an abstraction of DQL, but merely a tool to dynamically build it. + You should still use plain DQL when you can, as it is simpler and more readable. + More about this in the :doc:`FAQ `_. Constructing a new QueryBuilder object ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The same way you build a normal Query, you build a ``QueryBuilder`` -object, just providing the correct method name. Here is an example -how to build a ``QueryBuilder`` object: +object. Here is an example of how to build a ``QueryBuilder`` +object: .. code-block:: php @@ -24,9 +30,9 @@ how to build a ``QueryBuilder`` object: // example1: creating a QueryBuilder instance $qb = $em->createQueryBuilder(); -Once you have created an instance of QueryBuilder, it provides a -set of useful informative functions that you can use. One good -example is to inspect what type of object the ``QueryBuilder`` is. +An instance of QueryBuilder has several informative methods. One +good example is to inspect what type of object the +``QueryBuilder`` is. .. code-block:: php @@ -80,11 +86,11 @@ Working with QueryBuilder High level API methods ^^^^^^^^^^^^^^^^^^^^^^ -To simplify even more the way you build a query in Doctrine, we can take -advantage of what we call Helper methods. For all base code, there -is a set of useful methods to simplify a programmer's life. To -illustrate how to work with them, here is the same example 6 -re-written using ``QueryBuilder`` helper methods: +The most straightforward way to build a dynamic query with the ``QueryBuilder`` is by taking +advantage of Helper methods. For all base code, there is a set of +useful methods to simplify a programmer's life. To illustrate how +to work with them, here is the same example 6 re-written using +``QueryBuilder`` helper methods: .. code-block:: php @@ -97,10 +103,9 @@ re-written using ``QueryBuilder`` helper methods: ->orderBy('u.name', 'ASC'); ``QueryBuilder`` helper methods are considered the standard way to -build DQL queries. Although it is supported, it should be avoided -to use string based queries and greatly encouraged to use -``$qb->expr()->*`` methods. Here is a converted example 8 to -suggested standard way to build queries: +use the ``QueryBuilder``. The ``$qb->expr()->*`` methods can help you +build conditional expressions dynamically. Here is a converted example 8 to +suggested way to build queries with dynamic conditions: .. code-block:: php @@ -126,7 +131,7 @@ Here is a complete list of helper methods available in ``QueryBuilder``: // Example - $qb->select(array('u', 'p')) // Example - $qb->select($qb->expr()->select('u', 'p')) public function select($select = null); - + // addSelect does not override previous calls to select // // Example - $qb->select('u'); @@ -317,7 +322,7 @@ the Query object which can be retrieved from ``EntityManager#createQuery()``. Executing a Query ^^^^^^^^^^^^^^^^^ -The QueryBuilder is a builder object only, it has no means of actually +The QueryBuilder is a builder object only - it has no means of actually executing the Query. Additionally a set of parameters such as query hints cannot be set on the QueryBuilder itself. This is why you always have to convert a querybuilder instance into a Query object: @@ -499,14 +504,32 @@ complete list of supported helper methods available: public function countDistinct($x); // Returns Expr\Func } +Adding a Criteria to a Query +^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +You can also add a :ref:`filtering-collections` to a QueryBuilder by +using ``addCriteria``: + +.. code-block:: php + + orderBy(['firstName', 'ASC']); + + // $qb instanceof QueryBuilder + $qb->addCriteria($criteria); + // then execute your query like normal Low Level API ^^^^^^^^^^^^^ -Now we have describe the low level (thought of as the -hardcore method) of creating queries. It may be useful to work at -this level for optimization purposes, but most of the time it is -preferred to work at a higher level of abstraction. +Now we will describe the low level method of creating queries. +It may be useful to work at this level for optimization purposes, +but most of the time it is preferred to work at a higher level of +abstraction. All helper methods in ``QueryBuilder`` actually rely on a single one: ``add()``. This method is responsible of building every piece @@ -559,7 +582,3 @@ same query of example 6 written using ->add('where', new Expr\Comparison('u.id', '=', '?1')) ->add('orderBy', new Expr\OrderBy('u.name', 'ASC')); -Of course this is the hardest way to build a DQL query in Doctrine. -To simplify some of these efforts, we introduce what we call as -``Expr`` helper class. - diff --git a/docs/en/reference/second-level-cache.rst b/docs/en/reference/second-level-cache.rst index e89beba310a..8a0b4c23102 100644 --- a/docs/en/reference/second-level-cache.rst +++ b/docs/en/reference/second-level-cache.rst @@ -97,7 +97,7 @@ Defines a contract for accessing a particular region. Defines a contract for accessing a particular cache region. -`See API Doc `_. +`See API Doc `_. Concurrent cache region ~~~~~~~~~~~~~~~~~~~~~~~ @@ -111,7 +111,7 @@ If you want to use an ``READ_WRITE`` cache, you should consider providing your o Defines contract for concurrently managed data region. -`See API Doc `_. +`See API Doc `_. Timestamp region ~~~~~~~~~~~~~~~~ @@ -120,7 +120,7 @@ Timestamp region Tracks the timestamps of the most recent updates to particular entity. -`See API Doc `_. +`See API Doc `_. .. _reference-second-level-cache-mode: @@ -153,21 +153,21 @@ Built-in cached persisters Cached persisters are responsible to access cache regions. - +-----------------------+-------------------------------------------------------------------------------+ - | Cache Usage | Persister | - +=======================+===============================================================================+ - | READ_ONLY | Doctrine\\ORM\\Cache\\Persister\\ReadOnlyCachedEntityPersister | - +-----------------------+-------------------------------------------------------------------------------+ - | READ_WRITE | Doctrine\\ORM\\Cache\\Persister\\ReadWriteCachedEntityPersister | - +-----------------------+-------------------------------------------------------------------------------+ - | NONSTRICT_READ_WRITE | Doctrine\\ORM\\Cache\\Persister\\NonStrictReadWriteCachedEntityPersister | - +-----------------------+-------------------------------------------------------------------------------+ - | READ_ONLY | Doctrine\\ORM\\Cache\\Persister\\ReadOnlyCachedCollectionPersister | - +-----------------------+-------------------------------------------------------------------------------+ - | READ_WRITE | Doctrine\\ORM\\Cache\\Persister\\ReadWriteCachedCollectionPersister | - +-----------------------+-------------------------------------------------------------------------------+ - | NONSTRICT_READ_WRITE | Doctrine\\ORM\\Cache\\Persister\\NonStrictReadWriteCacheCollectionPersister | - +-----------------------+-------------------------------------------------------------------------------+ + +-----------------------+-------------------------------------------------------------------------------------------+ + | Cache Usage | Persister | + +=======================+===========================================================================================+ + | READ_ONLY | Doctrine\\ORM\\Cache\\Persister\\Entity\\ReadOnlyCachedEntityPersister | + +-----------------------+-------------------------------------------------------------------------------------------+ + | READ_WRITE | Doctrine\\ORM\\Cache\\Persister\\Entity\\ReadWriteCachedEntityPersister | + +-----------------------+-------------------------------------------------------------------------------------------+ + | NONSTRICT_READ_WRITE | Doctrine\\ORM\\Cache\\Persister\\Entity\\NonStrictReadWriteCachedEntityPersister | + +-----------------------+-------------------------------------------------------------------------------------------+ + | READ_ONLY | Doctrine\\ORM\\Cache\\Persister\\Collection\\ReadOnlyCachedCollectionPersister | + +-----------------------+-------------------------------------------------------------------------------------------+ + | READ_WRITE | Doctrine\\ORM\\Cache\\Persister\\Collection\\ReadWriteCachedCollectionPersister | + +-----------------------+-------------------------------------------------------------------------------------------+ + | NONSTRICT_READ_WRITE | Doctrine\\ORM\\Cache\\Persister\\Collection\\NonStrictReadWriteCachedCollectionPersister | + +-----------------------+-------------------------------------------------------------------------------------------+ Configuration ------------- @@ -209,7 +209,7 @@ It allows you to provide a specific implementation of the following components : * ``EntityHydrator`` Transform an entity into a cache entry and cache entry into entities * ``CollectionHydrator`` Transform a collection into a cache entry and cache entry into collection -`See API Doc `_. +`See API Doc `_. Region Lifetime ~~~~~~~~~~~~~~~ @@ -220,7 +220,7 @@ To specify a default lifetime for all regions or specify a different lifetime fo getSecondLevelCacheConfiguration(); $regionConfig = $cacheConfig->getRegionsConfiguration(); @@ -270,7 +270,7 @@ By providing a cache logger you should be able to get information about all cach If you want to get more information you should implement ``\Doctrine\ORM\Cache\Logging\CacheLogger``. and collect all information you want. -`See API Doc `_. +`See API Doc `_. Entity cache definition @@ -310,7 +310,7 @@ Entity cache definition .. code-block:: xml - + @@ -386,7 +386,7 @@ It caches the primary keys of association and cache each element will be cached .. code-block:: xml - + diff --git a/docs/en/reference/security.rst b/docs/en/reference/security.rst index bb5f0f8767c..0101e860f8f 100644 --- a/docs/en/reference/security.rst +++ b/docs/en/reference/security.rst @@ -10,7 +10,7 @@ we cannot protect you from SQL injection. Please also read the documentation chapter on Security in Doctrine DBAL. This page only handles Security issues in the ORM. -- [DBAL Security Page](https://github.com/doctrine/dbal/blob/master/docs/en/reference/security.rst) +- `DBAL Security Page ` If you find a Security bug in Doctrine, please report it on Jira and change the Security Level to "Security Issues". It will be visible to Doctrine Core @@ -119,7 +119,7 @@ entity might look like this: } Now the possiblity of mass-asignment exists on this entity and can -be exploitet by attackers to set the "isAdmin" flag to true on any +be exploited by attackers to set the "isAdmin" flag to true on any object when you pass the whole request data to this method like: .. code-block:: php diff --git a/docs/en/reference/tools.rst b/docs/en/reference/tools.rst index 51f4573000e..3b6cf334971 100644 --- a/docs/en/reference/tools.rst +++ b/docs/en/reference/tools.rst @@ -205,7 +205,7 @@ tables of the current model to clean up with orphaned tables. You can also use database introspection to update your schema easily with the ``updateSchema()`` method. It will compare your existing database schema to the passed array of -``ClassMetdataInfo`` instances. +``ClassMetadataInfo`` instances. .. code-block:: php @@ -252,15 +252,6 @@ will output the SQL for the ran operation. Before using the orm:schema-tool commands, remember to configure your cli-config.php properly. -.. note:: - - When using the Annotation Mapping Driver you have to either setup - your autoloader in the cli-config.php correctly to find all the - entities, or you can use the second argument of the - ``EntityManagerHelper`` to specify all the paths of your entities - (or mapping files), i.e. - ``new \Doctrine\ORM\Tools\Console\Helper\EntityManagerHelper($em, $mappingPaths);`` - Entity Generation ----------------- @@ -385,7 +376,7 @@ First you need to retrieve the metadata instances with the ) ); - $cmf = new DisconnectedClassMetadataFactory(); + $cmf = new \Doctrine\ORM\Tools\DisconnectedClassMetadataFactory(); $cmf->setEntityManager($em); $metadata = $cmf->getAllMetadata(); @@ -395,6 +386,7 @@ to yml: .. code-block:: php getExporter('yml', '/path/to/export/yml'); $exporter->setMetadata($metadata); $exporter->export(); @@ -476,7 +468,7 @@ To include a new command on Doctrine Console, you need to do modify the + + + + + + .. code-block:: yaml + + User: + type: entity + fields: + version: + type: integer + version: true Alternatively a datetime type can be used (which maps to a SQL timestamp or datetime): -.. code-block:: php +.. configuration-block:: - + + + + + + .. code-block:: yaml + + User: + type: entity + fields: + version: + type: datetime + version: true Version numbers (not timestamps) should however be preferred as they can not potentially conflict in a highly concurrent diff --git a/docs/en/reference/unitofwork-associations.rst b/docs/en/reference/unitofwork-associations.rst index da3cc9dc88b..c9ccf73fc8a 100644 --- a/docs/en/reference/unitofwork-associations.rst +++ b/docs/en/reference/unitofwork-associations.rst @@ -15,10 +15,10 @@ Bidirectional Associations The following rules apply to **bidirectional** associations: -- The inverse side has to use the ``mappedBy`` attribute of the OneToOne, +- The inverse side has to have the ``mappedBy`` attribute of the OneToOne, OneToMany, or ManyToMany mapping declaration. The mappedBy attribute contains the name of the association-field on the owning side. -- The owning side has to use the ``inversedBy`` attribute of the +- The owning side has to have the ``inversedBy`` attribute of the OneToOne, ManyToOne, or ManyToMany mapping declaration. The inversedBy attribute contains the name of the association-field on the inverse-side. diff --git a/docs/en/reference/unitofwork.rst b/docs/en/reference/unitofwork.rst index cdfb6e0be4a..b060c464a17 100644 --- a/docs/en/reference/unitofwork.rst +++ b/docs/en/reference/unitofwork.rst @@ -156,7 +156,7 @@ wishes to be hydrated. Default result-types include: - SQL to simple scalar result arrays - SQL to a single result variable -Hydration to entities and arrays is one of most complex parts of Doctrine +Hydration to entities and arrays is one of the most complex parts of Doctrine algorithm-wise. It can build results with for example: - Single table selects diff --git a/docs/en/reference/working-with-associations.rst b/docs/en/reference/working-with-associations.rst index 85ffaee3a2f..ab588e4efb0 100644 --- a/docs/en/reference/working-with-associations.rst +++ b/docs/en/reference/working-with-associations.rst @@ -15,7 +15,7 @@ with associations in Doctrine: removed, not the entity itself. A collection of entities always only represents the association to the containing entities, not the entity itself. -- When a bidirectional assocation is updated, Doctrine only checks +- When a bidirectional association is updated, Doctrine only checks on one of both sides for these changes. This is called the :doc:`owning side ` of the association. - A property with a reference to many entities has to be instances of the @@ -238,14 +238,14 @@ the database permanently. Notice how both sides of the bidirectional association are always updated. Unidirectional associations are consequently simpler to -handle. Also note that if you use type-hinting in your methods, i.e. -``setAddress(Address $address)``, PHP will only allow null -values if ``null`` is set as default value. Otherwise -setAddress(null) will fail for removing the association. If you -insist on type-hinting a typical way to deal with this is to -provide a special method, like ``removeAddress()``. This can also -provide better encapsulation as it hides the internal meaning of -not having an address. +handle. + +Also note that if you use type-hinting in your methods, you will +have to specify a nullable type, i.e. ``setAddress(?Address $address)``, +otherwise ``setAddress(null)`` will fail to remove the association. +Another way to deal with this is to provide a special method, like +``removeAddress()``. This can also provide better encapsulation as +it hides the internal meaning of not having an address. When working with collections, keep in mind that a Collection is essentially an ordered map (just like a PHP array). That is why the @@ -396,54 +396,25 @@ There are two approaches to handle this problem in your code: 1. Ignore updating the inverse side of bidirectional collections, BUT never read from them in requests that changed their state. In - the next Request Doctrine hydrates the consistent collection state + the next request Doctrine hydrates the consistent collection state again. 2. Always keep the bidirectional collections in sync through association management methods. Reads of the Collections directly after changes are consistent then. +.. _transitive-persistence: + Transitive persistence / Cascade Operations ------------------------------------------- -Persisting, removing, detaching, refreshing and merging individual entities can -become pretty cumbersome, especially when a highly interweaved object graph -is involved. Therefore Doctrine 2 provides a -mechanism for transitive persistence through cascading of these -operations. Each association to another entity or a collection of -entities can be configured to automatically cascade certain -operations. By default, no operations are cascaded. - -The following cascade options exist: - +Doctrine 2 provides a mechanism for transitive persistence through cascading of certain operations. +Each association to another entity or a collection of +entities can be configured to automatically cascade the following operations to the associated entities: +``persist``, ``remove``, ``merge``, ``detach``, ``refresh`` or ``all``. -- persist : Cascades persist operations to the associated - entities. -- remove : Cascades remove operations to the associated entities. -- merge : Cascades merge operations to the associated entities. -- detach : Cascades detach operations to the associated entities. -- refresh : Cascades refresh operations to the associated entities. -- all : Cascades persist, remove, merge, refresh and detach operations to - associated entities. - -.. note:: - - Cascade operations are performed in memory. That means collections and related entities - are fetched into memory, even if they are still marked as lazy when - the cascade operation is about to be performed. However this approach allows - entity lifecycle events to be performed for each of these operations. - - However, pulling objects graph into memory on cascade can cause considerable performance - overhead, especially when cascading collections are large. Makes sure - to weigh the benefits and downsides of each cascade operation that you define. - - To rely on the database level cascade operations for the delete operation instead, you can - configure each join column with the **onDelete** option. See the respective - mapping driver chapters for more information. - -The following example is an extension to the User-Comment example -of this chapter. Suppose in our application a user is created -whenever he writes his first comment. In this case we would use the -following code: +The main use case for ``cascade: persist`` is to avoid "exposing" associated entities to your PHP application. +Continuing with the User-Comment example of this chapter, this is how the creation of a new user and a new +comment might look like in your controller (without ``cascade: persist``): .. code-block:: php @@ -453,37 +424,39 @@ following code: $user->addComment($myFirstComment); $em->persist($user); - $em->persist($myFirstComment); + $em->persist($myFirstComment); // required, if `cascade: persist` is not set $em->flush(); -Even if you *persist* a new User that contains our new Comment this -code would fail if you removed the call to -``EntityManager#persist($myFirstComment)``. Doctrine 2 does not -cascade the persist operation to all nested entities that are new -as well. - -More complicated is the deletion of all of a user's comments when he is -removed from the system: +Note that the Comment entity is instantiated right here in the controller. +To avoid this, ``cascade: persist`` allows you to "hide" the Comment entity from the controller, +only accessing it through the User entity: .. code-block:: php find('User', $deleteUserId); - - foreach ($user->getAuthoredComments() as $comment) { - $em->remove($comment); - } - $em->remove($user); - $em->flush(); + // User entity + class User + { + private $id; + private $comments; -Without the loop over all the authored comments Doctrine would use -an UPDATE statement only to set the foreign key to NULL and only -the User would be deleted from the database during the -flush()-Operation. + public function __construct() + { + $this->id = User::new(); + $this->comments = new ArrayCollection(); + } + + public function comment(string $text, DateTimeInterface $time) : void + { + $newComment = Comment::create($text, $time); + $newComment->setUser($this); + $this->comments->add($newComment); + } + + // ... + } -To have Doctrine handle both cases automatically we can change the -``User#commentsAuthored`` property to cascade both the "persist" -and the "remove" operation. +If you then set up the cascading to the ``User#commentsAuthored`` property... .. code-block:: php @@ -500,10 +473,51 @@ and the "remove" operation. //... } -Even though automatic cascading is convenient it should be used -with care. Do not blindly apply cascade=all to all associations as +...you can now create a user and an associated comment like this: + +.. code-block:: php + + comment('Lorem ipsum', new DateTime()); + + $em->persist($user); + $em->flush(); + +.. note:: + + The idea of ``cascade: persist`` is not to save you any lines of code in the controller. + If you instantiate the comment object in the controller (i.e. don't set up the user entity as shown above), + even with ``cascade: persist`` you still have to call ``$myFirstComment->setUser($user);``. + +Thanks to ``cascade: remove``, you can easily delete a user and all linked comments without having to loop through them: + +.. code-block:: php + + find('User', $deleteUserId); + + $em->remove($user); + $em->flush(); + +.. note:: + + Cascade operations are performed in memory. That means collections and related entities + are fetched into memory (even if they are marked as lazy) when + the cascade operation is about to be performed. This approach allows + entity lifecycle events to be performed for each of these operations. + + However, pulling object graphs into memory on cascade can cause considerable performance + overhead, especially when the cascaded collections are large. Make sure + to weigh the benefits and downsides of each cascade operation that you define. + + To rely on the database level cascade operations for the delete operation instead, you can + configure each join column with :doc:`the onDelete option `. + +Even though automatic cascading is convenient, it should be used +with care. Do not blindly apply ``cascade=all`` to all associations as it will unnecessarily degrade the performance of your application. -For each cascade operation that gets activated Doctrine also +For each cascade operation that gets activated, Doctrine also applies that operation to the association, be it single or collection valued. @@ -511,21 +525,20 @@ Persistence by Reachability: Cascade Persist ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ There are additional semantics that apply to the Cascade Persist -operation. During each flush() operation Doctrine detects if there +operation. During each ``flush()`` operation Doctrine detects if there are new entities in any collection and three possible cases can happen: -1. New entities in a collection marked as cascade persist will be +1. New entities in a collection marked as ``cascade: persist`` will be directly persisted by Doctrine. -2. New entities in a collection not marked as cascade persist will - produce an Exception and rollback the flush() operation. +2. New entities in a collection not marked as ``cascade: persist`` will + produce an Exception and rollback the ``flush()`` operation. 3. Collections without new entities are skipped. This concept is called Persistence by Reachability: New entities that are found on already managed entities are automatically -persisted as long as the association is defined as cascade -persist. +persisted as long as the association is defined as ``cascade: persist``. Orphan Removal -------------- @@ -603,11 +616,11 @@ address reference. When flush is called not only are the references removed but both the old standing data and the one address entity are also deleted from the database. +.. _filtering-collections: + Filtering Collections --------------------- -.. filtering-collections: - Collections have a filtering API that allows to slice parts of data from a collection. If the collection has not been loaded from the database yet, the filtering API can work on the SQL level to make optimized access to @@ -703,6 +716,9 @@ methods: * ``in($field, array $values)`` * ``notIn($field, array $values)`` * ``contains($field, $value)`` +* ``memberOf($value, $field)`` +* ``startsWith($field, $value)`` +* ``endsWith($field, $value)`` .. note:: diff --git a/docs/en/reference/working-with-objects.rst b/docs/en/reference/working-with-objects.rst index 8368c9f1309..4b16fc3579d 100644 --- a/docs/en/reference/working-with-objects.rst +++ b/docs/en/reference/working-with-objects.rst @@ -25,6 +25,13 @@ Work that have not yet been persisted are lost. Not calling ``EntityManager#flush()`` will lead to all changes during that request being lost. +.. note:: + + Doctrine does NEVER touch the public API of methods in your entity + classes (like getters and setters) nor the constructor method. + Instead, it uses reflection to get/set data from/to your entity objects. + When Doctrine fetches data from DB and saves it back, + any code put in your get/set methods won't be implicitly taken into account. Entities and the Identity Map ----------------------------- @@ -238,7 +245,7 @@ as follows: persist operation. However, the persist operation is cascaded to entities referenced by X, if the relationships from X to these other entities are mapped with cascade=PERSIST or cascade=ALL (see - "Transitive Persistence"). + ":ref:`transitive-persistence`"). - If X is a removed entity, it becomes managed. - If X is a detached entity, an exception will be thrown on flush. @@ -279,12 +286,12 @@ as follows: - If X is a new entity, it is ignored by the remove operation. However, the remove operation is cascaded to entities referenced by X, if the relationship from X to these other entities is mapped - with cascade=REMOVE or cascade=ALL (see "Transitive Persistence"). + with cascade=REMOVE or cascade=ALL (see ":ref:`transitive-persistence`"). - If X is a managed entity, the remove operation causes it to become removed. The remove operation is cascaded to entities referenced by X, if the relationships from X to these other entities is mapped with cascade=REMOVE or cascade=ALL (see - "Transitive Persistence"). + ":ref:`transitive-persistence`"). - If X is a detached entity, an InvalidArgumentException will be thrown. - If X is a removed entity, it is ignored by the remove operation. @@ -350,14 +357,14 @@ as follows: become detached. The detach operation is cascaded to entities referenced by X, if the relationships from X to these other entities is mapped with cascade=DETACH or cascade=ALL (see - "Transitive Persistence"). Entities which previously referenced X + ":ref:`transitive-persistence`"). Entities which previously referenced X will continue to reference X. - If X is a new or detached entity, it is ignored by the detach operation. - If X is a removed entity, the detach operation is cascaded to entities referenced by X, if the relationships from X to these other entities is mapped with cascade=DETACH or cascade=ALL (see - "Transitive Persistence"). Entities which previously referenced X + ":ref:`transitive-persistence`"). Entities which previously referenced X will continue to reference X. There are several situations in which an entity is detached @@ -416,8 +423,7 @@ as follows: - If X is a managed entity, it is ignored by the merge operation, however, the merge operation is cascaded to entities referenced by relationships from X if these relationships have been mapped with - the cascade element value MERGE or ALL (see "Transitive - Persistence"). + the cascade element value MERGE or ALL (see ":ref:`transitive-persistence`"). - For all entities Y referenced by relationships from X having the cascade element value MERGE or ALL, Y is merged recursively as Y'. For all such Y referenced by X, X' is set to reference Y'. (Note @@ -727,6 +733,14 @@ examples are equivalent: // A single user by its nickname (__call magic) $user = $em->getRepository('MyProject\Domain\User')->findOneByNickname('romanb'); +Additionally, you can just count the result of the provided conditions when you don't really need the data: + +.. code-block:: php + + getRepository('MyProject\Domain\User')->count(['nickname' => 'nonexistent']); + By Criteria ~~~~~~~~~~~ @@ -736,8 +750,7 @@ The Repository implement the ``Doctrine\Common\Collections\Selectable`` interface. That means you can build ``Doctrine\Common\Collections\Criteria`` and pass them to the ``matching($criteria)`` method. -See the :ref:`Working with Associations: Filtering collections -`. +See section `Filtering collections` of chapter :doc:`Working with Associations ` By Eager Loading ~~~~~~~~~~~~~~~~ @@ -787,7 +800,9 @@ DQL and its syntax as well as the Doctrine class can be found in :doc:`the dedicated chapter `. For programmatically building up queries based on conditions that are only known at runtime, Doctrine provides the special -``Doctrine\ORM\QueryBuilder`` class. More information on +``Doctrine\ORM\QueryBuilder`` class. While this a powerful tool, +it also brings more complexity to your code compared to plain DQL, +so you should only use it when you need it. More information on constructing queries with a QueryBuilder can be found :doc:`in Query Builder chapter `. diff --git a/docs/en/reference/xml-mapping.rst b/docs/en/reference/xml-mapping.rst index dbf97dc0ad1..f57ee461bbb 100644 --- a/docs/en/reference/xml-mapping.rst +++ b/docs/en/reference/xml-mapping.rst @@ -7,7 +7,7 @@ form of XML documents. The XML driver is backed by an XML Schema document that describes the structure of a mapping document. The most recent version of the XML Schema document is available online at -`http://www.doctrine-project.org/schemas/orm/doctrine-mapping.xsd `_. +`https://www.doctrine-project.org/schemas/orm/doctrine-mapping.xsd `_. In order to point to the latest version of the document of a particular stable release branch, just append the release number, i.e.: doctrine-mapping-2.0.xsd The most convenient way to work with @@ -21,7 +21,7 @@ setup for the latest code in trunk. + https://www.doctrine-project.org/schemas/orm/doctrine-mapping.xsd"> ... @@ -107,7 +107,7 @@ of several common elements: + https://www.doctrine-project.org/schemas/orm/doctrine-mapping.xsd"> @@ -321,12 +321,12 @@ Using the simplified definition above Doctrine will use no identifier strategy for this entity. That means you have to manually set the identifier before calling ``EntityManager#persist($entity)``. This is the so called -``ASSIGNED`` strategy. +``NONE`` strategy. If you want to switch the identifier generation strategy you have to nest a ```` element inside the id-element. This of course only works for surrogate keys. For composite keys you always -have to use the ``ASSIGNED`` strategy. +have to use the ``NONE`` strategy. .. code-block:: xml @@ -768,7 +768,7 @@ entity relationship. You can define this in XML with the "association-key" attri + https://www.doctrine-project.org/schemas/orm/doctrine-mapping.xsd"> diff --git a/docs/en/reference/yaml-mapping.rst b/docs/en/reference/yaml-mapping.rst index ea54e277ae9..8199406ebe7 100644 --- a/docs/en/reference/yaml-mapping.rst +++ b/docs/en/reference/yaml-mapping.rst @@ -1,6 +1,10 @@ YAML Mapping ============ +.. note:: + The YAML driver is deprecated and will be removed in version 3.0. + It is strongly recommended to switch to one of the other mappings. + The YAML mapping driver enables you to provide the ORM metadata in form of YAML documents. diff --git a/docs/en/sidebar.rst b/docs/en/sidebar.rst new file mode 100644 index 00000000000..03d130cc10e --- /dev/null +++ b/docs/en/sidebar.rst @@ -0,0 +1,83 @@ +.. toc:: + + .. tocheader:: Tutorials + + .. toctree:: + :depth: 3 + + tutorials/getting-started + tutorials/getting-started-database + tutorials/getting-started-models + tutorials/working-with-indexed-associations + tutorials/extra-lazy-associations + tutorials/composite-primary-keys + tutorials/ordered-associations + tutorials/override-field-association-mappings-in-subclasses + tutorials/pagination + tutorials/embeddables + +.. toc:: + + .. tocheader:: Reference + + .. toctree:: + :depth: 3 + + reference/architecture + reference/configuration + reference/faq + reference/basic-mapping + reference/association-mapping + reference/inheritance-mapping + reference/working-with-objects + reference/working-with-associations + reference/events + reference/unitofwork + reference/unitofwork-associations + reference/transactions-and-concurrency + reference/batch-processing + reference/dql-doctrine-query-language + reference/query-builder + reference/native-sql + reference/change-tracking-policies + reference/partial-objects + reference/xml-mapping + reference/yaml-mapping + reference/annotations-reference + reference/php-mapping + reference/caching + reference/improving-performance + reference/tools + reference/metadata-drivers + reference/best-practices + reference/limitations-and-known-issues + tutorials/pagination + reference/filters + reference/namingstrategy + reference/advanced-configuration + reference/second-level-cache + reference/security + +.. toc:: + + .. tocheader:: Cookbook + + .. toctree:: + :depth: 3 + + cookbook/aggregate-fields + cookbook/custom-mapping-types + cookbook/decorator-pattern + cookbook/dql-custom-walkers + cookbook/dql-user-defined-functions + cookbook/implementing-arrayaccess-for-domain-objects + cookbook/implementing-the-notify-changetracking-policy + cookbook/implementing-wakeup-or-clone + cookbook/resolve-target-entity-listener + cookbook/sql-table-prefixes + cookbook/strategy-cookbook-introduction + cookbook/validation-of-entities + cookbook/working-with-datetime + cookbook/mysql-enums + cookbook/advanced-field-value-conversion-using-custom-mapping-types + cookbook/entities-in-session diff --git a/docs/en/toc.rst b/docs/en/toc.rst index 0df70414f68..2309d569712 100644 --- a/docs/en/toc.rst +++ b/docs/en/toc.rst @@ -75,7 +75,6 @@ Cookbook cookbook/implementing-arrayaccess-for-domain-objects cookbook/implementing-the-notify-changetracking-policy cookbook/implementing-wakeup-or-clone - cookbook/integrating-with-codeigniter cookbook/resolve-target-entity-listener cookbook/sql-table-prefixes cookbook/strategy-cookbook-introduction diff --git a/docs/en/tutorials/composite-primary-keys.rst b/docs/en/tutorials/composite-primary-keys.rst index dd4e49e04aa..ef164c9db1f 100644 --- a/docs/en/tutorials/composite-primary-keys.rst +++ b/docs/en/tutorials/composite-primary-keys.rst @@ -13,7 +13,7 @@ This tutorial shows how the semantics of composite primary keys work and how the General Considerations ~~~~~~~~~~~~~~~~~~~~~~ -Every entity with a composite key cannot use an id generator other than "ASSIGNED". That means +Every entity with a composite key cannot use an id generator other than "NONE". That means the ID fields have to have their values set before you call ``EntityManager#persist($entity)``. Primitive Types only @@ -38,7 +38,7 @@ and year of production as primary keys: /** @Id @Column(type="string") */ private $name; /** @Id @Column(type="integer") */ - private $year + private $year; public function __construct($name, $year) { @@ -63,7 +63,7 @@ and year of production as primary keys: + https://www.doctrine-project.org/schemas/orm/doctrine-mapping.xsd"> @@ -203,7 +203,7 @@ We keep up the example of an Article with arbitrary attributes, the mapping look + https://www.doctrine-project.org/schemas/orm/doctrine-mapping.xsd"> diff --git a/docs/en/tutorials/embeddables.rst b/docs/en/tutorials/embeddables.rst index 681aa75366d..483e58d9da6 100644 --- a/docs/en/tutorials/embeddables.rst +++ b/docs/en/tutorials/embeddables.rst @@ -1,11 +1,14 @@ Separating Concerns using Embeddables ------------------------------------- -Embeddables are classes which are not entities themself, but are embedded +Embeddables are classes which are not entities themselves, but are embedded in entities and can also be queried in DQL. You'll mostly want to use them to reduce duplication or separating concerns. Value objects such as date range -or address are the primary use case for this feature. Embeddables can only -contain properties with basic ``@Column`` mapping. +or address are the primary use case for this feature. + +.. note:: + + Embeddables can only contain properties with basic ``@Column`` mapping. For the purposes of this tutorial, we will assume that you have a ``User`` class in your application and you would like to store an address in diff --git a/docs/en/tutorials/extra-lazy-associations.rst b/docs/en/tutorials/extra-lazy-associations.rst index 456c8c1c5ff..4452d6890a1 100644 --- a/docs/en/tutorials/extra-lazy-associations.rst +++ b/docs/en/tutorials/extra-lazy-associations.rst @@ -65,7 +65,7 @@ switch to extra lazy as shown in these examples: + https://www.doctrine-project.org/schemas/orm/doctrine-mapping.xsd"> diff --git a/docs/en/tutorials/getting-started-database.rst b/docs/en/tutorials/getting-started-database.rst index c625193aeb5..5a4883fae63 100644 --- a/docs/en/tutorials/getting-started-database.rst +++ b/docs/en/tutorials/getting-started-database.rst @@ -7,7 +7,7 @@ Getting Started: Database First start with developing Objects and then map them onto your database. When you :doc:`Model First `, you are modelling your application using tools (for example UML) and generate database schema and PHP code from this model. - When you have a :doc:`Database First `, you already have a database schema + When you have a Database First, you already have a database schema and generate the corresponding PHP code from it. .. note:: diff --git a/docs/en/tutorials/getting-started-models.rst b/docs/en/tutorials/getting-started-models.rst index e844b4d6865..01b71876299 100644 --- a/docs/en/tutorials/getting-started-models.rst +++ b/docs/en/tutorials/getting-started-models.rst @@ -5,7 +5,7 @@ Getting Started: Model First When you :doc:`Code First `, you start with developing Objects and then map them onto your database. When - you :doc:`Model First `, you are modelling your application using tools (for + you Model First, you are modelling your application using tools (for example UML) and generate database schema and PHP code from this model. When you have a :doc:`Database First `, then you already have a database schema and generate the corresponding PHP code from it. diff --git a/docs/en/tutorials/getting-started.rst b/docs/en/tutorials/getting-started.rst index 6b5cb72942e..52190e57099 100644 --- a/docs/en/tutorials/getting-started.rst +++ b/docs/en/tutorials/getting-started.rst @@ -14,26 +14,25 @@ Guide Assumptions ----------------- This guide is designed for beginners that haven't worked with Doctrine ORM -before. There are some prerequesites for the tutorial that have to be +before. There are some prerequisites for the tutorial that have to be installed: - PHP (latest stable version) - Composer Package Manager (`Install Composer - `_) + `_) The code of this tutorial is `available on Github `_. .. note:: - This tutorial assumes you work with **Doctrine 2.4** and above. + This tutorial assumes you work with **Doctrine 2.6** and above. Some of the code will not work with lower versions. What is Doctrine? ----------------- -Doctrine 2 is an `object-relational mapper (ORM) -`_ for PHP 5.4+ that -provides transparent persistence for PHP objects. It uses the Data Mapper +Doctrine 2 is an `object-relational mapper (ORM) `_ +for PHP 7.1+ that provides transparent persistence for PHP objects. It uses the Data Mapper pattern at the heart, aiming for a complete separation of your domain/business logic from the persistence in a relational database management system. @@ -62,7 +61,7 @@ An Example Model: Bug Tracker For this Getting Started Guide for Doctrine we will implement the Bug Tracker domain model from the -`Zend\_Db\_Table `_ +`Zend_Db_Table `_ documentation. Reading their documentation we can extract the requirements: @@ -80,14 +79,14 @@ Project Setup ------------- Create a new empty folder for this tutorial project, for example -``doctrine2-tutorial`` and create a new file ``composer.json`` with -the following contents: +``doctrine2-tutorial`` and create a new file ``composer.json`` inside +that directory with the following contents: :: { "require": { - "doctrine/orm": "2.4.*", + "doctrine/orm": "^2.6.2", "symfony/yaml": "2.*" }, "autoload": { @@ -103,23 +102,26 @@ Install Doctrine using the Composer Dependency Management tool, by calling: $ composer install This will install the packages Doctrine Common, Doctrine DBAL, Doctrine ORM, -Symfony YAML and Symfony Console into the `vendor` directory. The Symfony -dependencies are not required by Doctrine but will be used in this tutorial. +into the ``vendor`` directory. Add the following directories: :: doctrine2-tutorial |-- config - | |-- xml + | `-- xml | `-- yaml `-- src +.. note:: + The YAML driver is deprecated and will be removed in version 3.0. + It is strongly recommended to switch to one of the other mappings. + Obtaining the EntityManager --------------------------- -Doctrine's public interface is the EntityManager, it provides the -access point to the complete lifecycle management of your entities +Doctrine's public interface is through the ``EntityManager``. This class +provides access points to the complete lifecycle management for your entities, and transforms entities from and back to persistence. You have to configure and create it to use your entities with Doctrine 2. I will show the configuration steps and then discuss them step by @@ -136,7 +138,10 @@ step: // Create a simple "default" Doctrine ORM configuration for Annotations $isDevMode = true; - $config = Setup::createAnnotationMetadataConfiguration(array(__DIR__."/src"), $isDevMode); + $proxyDir = null; + $cache = null; + $useSimpleAnnotationReader = false; + $config = Setup::createAnnotationMetadataConfiguration(array(__DIR__."/src"), $isDevMode, $proxyDir, $cache, $useSimpleAnnotationReader); // or if you prefer yaml or XML //$config = Setup::createXMLMetadataConfiguration(array(__DIR__."/config/xml"), $isDevMode); //$config = Setup::createYAMLMetadataConfiguration(array(__DIR__."/config/yaml"), $isDevMode); @@ -150,8 +155,16 @@ step: // obtaining the entity manager $entityManager = EntityManager::create($conn, $config); -The first require statement sets up the autoloading capabilities of Doctrine -using the Composer autoload. +.. note:: + The YAML driver is deprecated and will be removed in version 3.0. + It is strongly recommended to switch to one of the other mappings. + +.. note:: + It is recommended not to use the SimpleAnnotationReader because its + usage will be removed for version 3.0. + +The ``require_once`` statement sets up the class autoloading for Doctrine and +its dependencies using Composer's autoloader. The second block consists of the instantiation of the ORM ``Configuration`` object using the Setup helper. It assumes a bunch @@ -159,10 +172,10 @@ of defaults that you don't have to bother about for now. You can read up on the configuration details in the :doc:`reference chapter on configuration <../reference/configuration>`. -The third block shows the configuration options required to connect -to a database, in my case a file-based sqlite database. All the +The third block shows the configuration options required to connect to +a database. In this case, we'll use a file-based SQLite database. All the configuration options for all the shipped drivers are given in the -`DBAL Configuration section of the manual `_. +`DBAL Configuration section of the manual `_. The last block shows how the ``EntityManager`` is obtained from a factory method. @@ -170,15 +183,10 @@ factory method. Generating the Database Schema ------------------------------ -Now that we have defined the Metadata mappings and bootstrapped the -EntityManager we want to generate the relational database schema -from it. Doctrine has a Command-Line Interface that allows you to -access the SchemaTool, a component that generates the required -tables to work with the metadata. - -For the command-line tool to work a cli-config.php file has to be -present in the project root directory, where you will execute the -doctrine command. Its a fairly simple file: +Doctrine has a command-line interface that allows you to access the SchemaTool, +a component that can generate a relational database schema based entirely on the +defined entity classes and their metadata. For this tool to work, a +``cli-config.php`` file must exist in the project root directory: .. code-block:: php @@ -188,40 +196,37 @@ doctrine command. Its a fairly simple file: return \Doctrine\ORM\Tools\Console\ConsoleRunner::createHelperSet($entityManager); -You can then change into your project directory and call the -Doctrine command-line tool: +Now call the Doctrine command-line tool: :: - $ cd project/ $ vendor/bin/doctrine orm:schema-tool:create -At this point no entity metadata exists in `src` so you will see a message like -"No Metadata Classes to process." Don't worry, we'll create a Product entity and -corresponding metadata in the next section. +Since we haven't added any entity metadata in ``src`` yet, you'll see a message +stating "No Metadata Classes to process." In the next section, we'll create a +Product entity along with the corresponding metadata, and run this command again. -You should be aware that during the development process you'll periodically need -to update your database schema to be in sync with your Entities metadata. - -You can easily recreate the database: +Note that as you modify your entities' metadata during the development process, +you'll need to update your database schema to stay in sync with the metadata. +You can easily recreate the database using the following commands: :: $ vendor/bin/doctrine orm:schema-tool:drop --force $ vendor/bin/doctrine orm:schema-tool:create -Or use the update functionality: +Or you can use the update functionality: :: $ vendor/bin/doctrine orm:schema-tool:update --force -The updating of databases uses a Diff Algorithm for a given -Database Schema, a cornerstone of the ``Doctrine\DBAL`` package, +The updating of databases uses a diff algorithm for a given +database schema. This is a cornerstone of the ``Doctrine\DBAL`` package, which can even be used without the Doctrine ORM package. -Starting with the Product -------------------------- +Starting with the Product Entity +-------------------------------- We start with the simplest entity, the Product. Create a ``src/Product.php`` file to contain the ``Product`` entity definition: @@ -257,16 +262,16 @@ entity definition: } } -Note that all fields are set to protected (not public) with a -mutator (getter and setter) defined for every field except $id. -The use of mutators allows Doctrine to hook into calls which -manipulate the entities in ways that it could not if you just +When creating entity classes, all of the fields should be ``protected`` or ``private`` +(not ``public``), with getter and setter methods for each one (except ``$id``). +The use of mutators allows Doctrine to hook into calls which +manipulate the entities in ways that it could not if you just directly set the values with ``entity#field = foo;`` -The id field has no setter since, generally speaking, your code -should not set this value since it represents a database id value. -(Note that Doctrine itself can still set the value using the -Reflection API instead of a defined setter function) +The id field has no setter since, generally speaking, your code +should not set this value since it represents a database id value. +(Note that Doctrine itself can still set the value using the +Reflection API instead of a defined setter function.) The next step for persistence with Doctrine is to describe the structure of the ``Product`` entity to Doctrine using a metadata @@ -274,9 +279,10 @@ language. The metadata language describes how entities, their properties and references should be persisted and what constraints should be applied to them. -Metadata for entities are configured using a XML, YAML or Docblock Annotations. -This Getting Started Guide will show the mappings for all Mapping Drivers. -References in the text will be made to the XML mapping. +Metadata for an Entity can be configured using DocBlock annotations directly +in the Entity class itself, or in an external XML or YAML file. This Getting +Started guide will demonstrate metadata mappings using all three methods, +but you only need to choose one. .. configuration-block:: @@ -284,14 +290,24 @@ References in the text will be made to the XML mapping. + https://www.doctrine-project.org/schemas/orm/doctrine-mapping.xsd"> @@ -314,6 +330,10 @@ References in the text will be made to the XML mapping. +.. note:: + The YAML driver is deprecated and will be removed in version 3.0. + It is strongly recommended to switch to one of the other mappings. + .. code-block:: yaml # config/yaml/Product.dcm.yml @@ -329,30 +349,31 @@ References in the text will be made to the XML mapping. name: type: string -The top-level ``entity`` definition tag specifies information about -the class and table-name. The primitive type ``Product#name`` is +The top-level ``entity`` definition specifies information about +the class and table name. The primitive type ``Product#name`` is defined as a ``field`` attribute. The ``id`` property is defined with -the ``id`` tag, this has a ``generator`` tag nested inside which -defines that the primary key generation mechanism automatically -uses the database platforms native id generation strategy (for -example AUTO INCREMENT in the case of MySql or Sequences in the +the ``id`` tag. It has a ``generator`` tag nested inside, which +specifies that the primary key generation mechanism should automatically +use the database platform's native id generation strategy (for +example, AUTO INCREMENT in the case of MySql, or Sequences in the case of PostgreSql and Oracle). -Now that we have defined our first entity, let's update the database: +Now that we have defined our first entity and its metadata, +let's update the database schema: :: $ vendor/bin/doctrine orm:schema-tool:update --force --dump-sql -Specifying both flags ``--force`` and ``--dump-sql`` prints and executes the DDL -statements. +Specifying both flags ``--force`` and ``--dump-sql`` will cause the DDL +statements to be executed and then printed to the screen. -Now create a new script that will insert products into the database: +Now, we'll create a new script to insert products into the database: .. code-block:: php require_once "bootstrap.php"; $newProductName = $argv[1]; @@ -372,22 +393,19 @@ Call this script from the command-line to see how new products are created: $ php create_product.php ORM $ php create_product.php DBAL -What is happening here? Using the ``Product`` is pretty standard OOP. +What is happening here? Using the ``Product`` class is pretty standard OOP. The interesting bits are the use of the ``EntityManager`` service. To -notify the EntityManager that a new entity should be inserted into the database -you have to call ``persist()``. To initiate a transaction to actually perform -the insertion, You have to explicitly call ``flush()`` on the ``EntityManager``. - -This distinction between persist and flush is allows to aggregate all writes -(INSERT, UPDATE, DELETE) into one single transaction, which is executed when -flush is called. Using this approach the write-performance is significantly -better than in a scenario where updates are done for each entity in isolation. +notify the EntityManager that a new entity should be inserted into the database, +you have to call ``persist()``. To initiate a transaction to actually *perform* +the insertion, you have to explicitly call ``flush()`` on the ``EntityManager``. -Doctrine follows the UnitOfWork pattern which additionally detects all entities -that were fetched and have changed during the request. You don't have to keep track of -entities yourself, when Doctrine already knows about them. +This distinction between persist and flush is what allows the aggregation of +all database writes (INSERT, UPDATE, DELETE) into one single transaction, which +is executed when ``flush()`` is called. Using this approach, the write-performance +is significantly better than in a scenario in which writes are performed on +each entity in isolation. -As a next step we want to fetch a list of all the Products. Let's create a +Next, we'll fetch a list of all the Products in the database. Let's create a new script for this: .. code-block:: php @@ -404,10 +422,10 @@ new script for this: } The ``EntityManager#getRepository()`` method can create a finder object (called -a repository) for every entity. It is provided by Doctrine and contains some -finder methods such as ``findAll()``. +a repository) for every type of entity. It is provided by Doctrine and contains +some finder methods like ``findAll()``. -Let's continue with displaying the name of a product based on its ID: +Let's continue by creating a script to display the name of a product based on its ID: .. code-block:: php @@ -425,9 +443,13 @@ Let's continue with displaying the name of a product based on its ID: echo sprintf("-%s\n", $product->getName()); -Updating a product name demonstrates the functionality UnitOfWork of pattern -discussed before. We only need to find a product entity and all changes to its -properties are written to the database: +Next we'll update a product's name, given its id. This simple example will +help demonstrate Doctrine's implementation of the UnitOfWork pattern. Doctrine +keeps track of all the entities that were retrieved from the Entity Manager, +and can detect when any of those entities' properties have been modified. +As a result, rather than needing to call ``persist($entity)`` for each individual +entity whose properties were changed, a single call to ``flush()`` at the end of a +request is sufficient to update the database for all of the modified entities. .. code-block:: php @@ -455,36 +477,44 @@ product name changed by calling the ``show_product.php`` script. Adding Bug and User Entities ---------------------------- -We continue with the bug tracker domain, by creating the missing classes -``Bug`` and ``User`` and putting them into ``src/Bug.php`` and -``src/User.php`` respectively. +We continue with the bug tracker example by creating the ``Bug`` and ``User`` +classes. We'll store them in ``src/Bug.php`` and ``src/User.php``, respectively. .. code-block:: php assignedToBug($this); $this->engineer = $engineer; } - public function setReporter($reporter) + public function setReporter(User $reporter) { $reporter->addReportedBug($this); $this->reporter = $reporter; @@ -717,15 +755,15 @@ the bi-directional reference: { // ... (previous code) - private $reportedBugs = null; - private $assignedBugs = null; + protected $reportedBugs; + protected $assignedBugs; - public function addReportedBug($bug) + public function addReportedBug(Bug $bug) { $this->reportedBugs[] = $bug; } - public function assignedToBug($bug) + public function assignedToBug(Bug $bug) { $this->assignedBugs[] = $bug; } @@ -741,7 +779,7 @@ You can see from ``User#addReportedBug()`` and ``User#assignedToBug()`` that using this method in userland alone would not add the Bug to the collection of the owning side in ``Bug#reporter`` or ``Bug#engineer``. Using these methods and -calling Doctrine for persistence would not update the collections +calling Doctrine for persistence would not update the Collections' representation in the database. Only using ``Bug#setEngineer()`` or ``Bug#setReporter()`` @@ -749,7 +787,7 @@ correctly saves the relation information. The ``Bug#reporter`` and ``Bug#engineer`` properties are Many-To-One relations, which point to a User. In a normalized -relational model the foreign key is saved on the Bug's table, hence +relational model, the foreign key is saved on the Bug's table, hence in our object-relation model the Bug is at the owning side of the relation. You should always make sure that the use-cases of your domain model should drive which side is an inverse or owning one in @@ -758,7 +796,7 @@ or an engineer is assigned to the bug, we don't want to update the User to persist the reference, but the Bug. This is the case with the Bug being at the owning side of the relation. -Bugs reference Products by an uni-directional ManyToMany relation in +Bugs reference Products by a uni-directional ManyToMany relation in the database that points from Bugs to Products. .. code-block:: php @@ -769,9 +807,9 @@ the database that points from Bugs to Products. { // ... (previous code) - protected $products = null; + protected $products; - public function assignToProduct($product) + public function assignToProduct(Product $product) { $this->products[] = $product; } @@ -783,7 +821,7 @@ the database that points from Bugs to Products. } We are now finished with the domain model given the requirements. -Lets add metadata mappings for the ``User`` and ``Bug`` as we did for +Lets add metadata mappings for the ``Bug`` entity, as we did for the ``Product`` before: .. configuration-block:: @@ -791,41 +829,50 @@ the ``Product`` before: + https://www.doctrine-project.org/schemas/orm/doctrine-mapping.xsd"> @@ -855,6 +902,10 @@ the ``Product`` before: +.. note:: + The YAML driver is deprecated and will be removed in version 3.0. + It is strongly recommended to switch to one of the other mappings. + .. code-block:: yaml # config/yaml/Bug.dcm.yml @@ -890,13 +941,13 @@ For the "created" field we have used the ``datetime`` type, which translates the YYYY-mm-dd HH:mm:ss database format into a PHP DateTime instance and back. -After the field definitions the two qualified references to the +After the field definitions, the two qualified references to the user entity are defined. They are created by the ``many-to-one`` tag. The class name of the related entity has to be specified with the ``target-entity`` attribute, which is enough information for the database mapper to access the foreign-table. Since ``reporter`` and ``engineer`` are on the owning side of a -bi-directional relation we also have to specify the ``inversed-by`` +bi-directional relation, we also have to specify the ``inversed-by`` attribute. They have to point to the field names on the inverse side of the relationship. We will see in the next example that the ``inversed-by`` attribute has a counterpart ``mapped-by`` which makes that @@ -907,7 +958,7 @@ holds all products where the specific bug occurs. Again you have to define the ``target-entity`` and ``field`` attributes on the ``many-to-many`` tag. -The last missing definition is that of the User entity: +Finally, we'll add metadata mappings for the ``User`` entity. .. configuration-block:: @@ -915,34 +966,40 @@ The last missing definition is that of the User entity: + https://www.doctrine-project.org/schemas/orm/doctrine-mapping.xsd"> @@ -967,9 +1024,13 @@ The last missing definition is that of the User entity: +.. note:: + The YAML driver is deprecated and will be removed in version 3.0. + It is strongly recommended to switch to one of the other mappings. + .. code-block:: yaml - # config/xml/User.dcm.yml + # config/yaml/User.dcm.yml User: type: entity table: users @@ -996,10 +1057,7 @@ means the join details have already been defined on the owning side. Therefore we only have to specify the property on the Bug class that holds the owning sides. -This example has a fair overview of the most basic features of the -metadata definition language. - -Update your database running: +Update your database schema by running: :: $ vendor/bin/doctrine orm:schema-tool:update --force @@ -1008,7 +1066,8 @@ Update your database running: Implementing more Requirements ------------------------------ -For starters we need a create user entities: +So far, we've seen the most basic features of the metadata definition language. +To explore additional functionality, let's first create new ``User`` entities: .. code-block:: php @@ -1032,23 +1091,22 @@ Now call: $ php create_user.php beberlei -We now have the data to create a bug and the code for this scenario may look -like this: +We now have the necessary data to create a new Bug entity: .. code-block:: php require_once "bootstrap.php"; - $theReporterId = $argv[1]; - $theDefaultEngineerId = $argv[2]; + $reporterId = $argv[1]; + $engineerId = $argv[2]; $productIds = explode(",", $argv[3]); - $reporter = $entityManager->find("User", $theReporterId); - $engineer = $entityManager->find("User", $theDefaultEngineerId); + $reporter = $entityManager->find("User", $reporterId); + $engineer = $entityManager->find("User", $engineerId); if (!$reporter || !$engineer) { - echo "No reporter and/or engineer found for the input.\n"; + echo "No reporter and/or engineer found for the given id(s).\n"; exit(1); } @@ -1070,22 +1128,17 @@ like this: echo "Your new Bug Id: ".$bug->getId()."\n"; -Since we only have one user and product, probably with the ID of 1, we can call this script with: +Since we only have one user and product, probably with the ID of 1, we can +call this script as follows: :: php create_bug.php 1 1 1 -This is the first contact with the read API of the EntityManager, -showing that a call to ``EntityManager#find($name, $id)`` returns a -single instance of an entity queried by primary key. Besides this -we see the persist + flush pattern again to save the Bug into the -database. - -See how simple relating Bug, Reporter, Engineer and Products is -done by using the discussed methods in the "A first prototype" -section. The UnitOfWork will detect this relations when flush is -called and relate them in the database appropriately. +See how simple it is to relate a Bug, Reporter, Engineer and Products? +Also recall that thanks to the UnitOfWork pattern, Doctrine will detect +these relations and update all of the modified entities in the database +automatically when ``flush()`` is called. Queries for Application Use-Cases --------------------------------- @@ -1094,7 +1147,7 @@ List of Bugs ~~~~~~~~~~~~ Using the previous examples we can fill up the database quite a -bit, however we now need to discuss how to query the underlying +bit. However, we now need to discuss how to query the underlying mapper for the required view representations. When opening the application, bugs can be paginated through a list-view, which is the first read-only use-case: @@ -1150,15 +1203,14 @@ The console output of this script is then: An important reason why DQL is favourable to the Query API of most ORMs is its similarity to SQL. The DQL language allows query - constructs that most ORMs don't, GROUP BY even with HAVING, + constructs that most ORMs don't: GROUP BY even with HAVING, Sub-selects, Fetch-Joins of nested classes, mixed results with entities and scalar data such as COUNT() results and much more. Using DQL you should seldom come to the point where you want to throw your ORM into the dumpster, because it doesn't support some the more powerful SQL concepts. - - Instead of handwriting DQL you can use the ``QueryBuilder`` retrieved + If you need to build your query dynamically, you can use the ``QueryBuilder`` retrieved by calling ``$entityManager->createQueryBuilder()``. There are more details about this in the relevant part of the documentation. @@ -1225,7 +1277,7 @@ write scenarios: .. code-block:: php require_once "bootstrap.php"; $theBugId = $argv[1]; @@ -1300,7 +1352,7 @@ and usage of bound parameters: .. code-block:: php require_once "bootstrap.php"; $theUserId = $argv[1]; @@ -1366,7 +1418,7 @@ should be able to close a bug. This looks like: .. code-block:: php require_once "bootstrap.php"; $theBugId = $argv[1]; @@ -1484,9 +1536,12 @@ we have to adjust the metadata slightly. .. code-block:: php + https://www.doctrine-project.org/schemas/orm/doctrine-mapping.xsd"> +.. note:: + The YAML driver is deprecated and will be removed in version 3.0. + It is strongly recommended to switch to one of the other mappings. + .. code-block:: yaml Bug: @@ -1535,6 +1594,16 @@ As an example here is the code of the first use case "List of Bugs": Using EntityRepositories you can avoid coupling your model with specific query logic. You can also re-use query logic easily throughout your application. +The method ``count()`` takes an array of fields or association keys and the values to match against. +This provides you with a convenient and lightweight way to count a resultset when you don't need to +deal with it: + +.. code-block:: php + + getRepository(Product::class) + ->count(['name' => $productName]); + Conclusion ---------- diff --git a/docs/en/tutorials/ordered-associations.rst b/docs/en/tutorials/ordered-associations.rst index 121bd145d57..cb0e64a498a 100644 --- a/docs/en/tutorials/ordered-associations.rst +++ b/docs/en/tutorials/ordered-associations.rst @@ -5,8 +5,8 @@ There are use-cases when you'll want to sort collections when they are retrieved from the database. In userland you do this as long as you haven't initially saved an entity with its associations into the database. To retrieve a sorted collection from the database you can -use the ``@OrderBy`` annotation with an collection that specifies -an DQL snippet that is appended to all queries with this +use the ``@OrderBy`` annotation with a collection that specifies +a DQL snippet that is appended to all queries with this collection. Additional to any ``@OneToMany`` or ``@ManyToMany`` annotation you @@ -64,7 +64,7 @@ positional statement. Multiple Fields are separated by a comma (,). The referenced field names have to exist on the ``targetEntity`` class of the ``@ManyToMany`` or ``@OneToMany`` annotation. -The semantics of this feature can be described as follows. +The semantics of this feature can be described as follows: - ``@OrderBy`` acts as an implicit ORDER BY clause for the given @@ -73,7 +73,7 @@ The semantics of this feature can be described as follows. - All collections of the ordered type are always retrieved in an ordered fashion. - To keep the database impact low, these implicit ORDER BY items - are only added to an DQL Query if the collection is fetch joined in + are only added to a DQL Query if the collection is fetch joined in the DQL query. Given our previously defined example, the following would not add diff --git a/docs/en/tutorials/working-with-indexed-associations.rst b/docs/en/tutorials/working-with-indexed-associations.rst index 3536a34f8ee..0381764bee9 100644 --- a/docs/en/tutorials/working-with-indexed-associations.rst +++ b/docs/en/tutorials/working-with-indexed-associations.rst @@ -3,7 +3,7 @@ Working with Indexed Associations .. note:: - This feature is scheduled for version 2.1 of Doctrine and not included in the 2.0.x series. + This feature is available from version 2.1 of Doctrine. Doctrine 2 collections are modelled after PHPs native arrays. PHP arrays are an ordered hashmap, but in the first version of Doctrine keys retrieved from the database were always numerical unless ``INDEX BY`` @@ -13,8 +13,8 @@ The feature works like an implicit ``INDEX BY`` for the selected association but downsides also: - You have to manage both the key and field if you want to change the index by field value. -- On each request the keys are regenerated from the field value not from the previous collection key. -- Values of the Index-By keys are never considered during persistence, it only exists for accessing purposes. +- On each request the keys are regenerated from the field value, and not from the previous collection key. +- Values of the Index-By keys are never considered during persistence. They only exist for accessing purposes. - Fields that are used for the index by feature **HAVE** to be unique in the database. The behavior for multiple entities with the same index-by field value is undefined. @@ -107,7 +107,7 @@ The code and mappings for the Market entity looks like this: + https://www.doctrine-project.org/schemas/orm/doctrine-mapping.xsd"> @@ -164,8 +164,6 @@ here are the code and mappings for it: private $id; /** - * For real this column would have to be unique=true. But I want to test behavior of non-unique overrides. - * * @Column(type="string", unique=true) */ private $symbol; @@ -195,7 +193,7 @@ here are the code and mappings for it: + https://www.doctrine-project.org/schemas/orm/doctrine-mapping.xsd"> @@ -227,7 +225,7 @@ here are the code and mappings for it: Querying indexed associations ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -Now that we defined the stocks collection to be indexed by symbol we can take a look at some code, +Now that we defined the stocks collection to be indexed by symbol, we can take a look at some code that makes use of the indexing. First we will populate our database with two example stocks traded on a single market: @@ -263,7 +261,7 @@ now query for the market: echo $stock->getSymbol(); // will print "AAPL" -The implementation ``Market::addStock()`` in combination with ``indexBy`` allows to access the collection +The implementation of ``Market::addStock()``, in combination with ``indexBy``, allows us to access the collection consistently by the Stock symbol. It does not matter if Stock is managed by Doctrine or not. The same applies to DQL queries: The ``indexBy`` configuration acts as implicit "INDEX BY" to a join association. @@ -285,8 +283,8 @@ The same applies to DQL queries: The ``indexBy`` configuration acts as implicit echo $stock->getSymbol(); // will print "AAPL" -If you want to use ``INDEX BY`` explicitly on an indexed association you are free to do so. Additionally -indexed associations also work with the ``Collection::slice()`` functionality, no matter if marked as +If you want to use ``INDEX BY`` explicitly on an indexed association you are free to do so. Additionally, +indexed associations also work with the ``Collection::slice()`` functionality, even if the association's fetch mode is LAZY or EXTRA_LAZY. Outlook into the Future @@ -294,5 +292,5 @@ Outlook into the Future For the inverse side of a many-to-many associations there will be a way to persist the keys and the order as a third and fourth parameter into the join table. This feature is discussed in `DDC-213 `_ -This feature cannot be implemented for One-To-Many associations, because they are never the owning side. +This feature cannot be implemented for one-to-many associations, because they are never the owning side. diff --git a/doctrine-mapping.xsd b/doctrine-mapping.xsd index aef47b2a66a..561b0624edb 100644 --- a/doctrine-mapping.xsd +++ b/doctrine-mapping.xsd @@ -101,7 +101,7 @@ - + @@ -117,7 +117,7 @@ - + @@ -139,7 +139,7 @@ - + @@ -167,7 +167,7 @@ - + @@ -189,17 +189,24 @@ - + - + - + + + + + + + + @@ -302,7 +309,7 @@ - + @@ -361,7 +368,7 @@ - + @@ -412,9 +419,16 @@ - + + + + + + + + @@ -487,11 +501,11 @@ - + - + @@ -504,12 +518,12 @@ + - - + @@ -524,11 +538,10 @@ - - - + + @@ -547,8 +560,8 @@ - + @@ -567,6 +580,7 @@ + diff --git a/lib/Doctrine/ORM/AbstractQuery.php b/lib/Doctrine/ORM/AbstractQuery.php index 0b2b0663c09..22403668675 100644 --- a/lib/Doctrine/ORM/AbstractQuery.php +++ b/lib/Doctrine/ORM/AbstractQuery.php @@ -19,16 +19,16 @@ namespace Doctrine\ORM; +use Doctrine\Common\Persistence\Mapping\MappingException; use Doctrine\Common\Util\ClassUtils; use Doctrine\Common\Collections\Collection; use Doctrine\Common\Collections\ArrayCollection; +use Doctrine\ORM\Mapping\MappingException as ORMMappingException; use Doctrine\ORM\Query\Parameter; use Doctrine\ORM\Cache\QueryCacheKey; use Doctrine\DBAL\Cache\QueryCacheProfile; -use Doctrine\ORM\Cache; - /** * Base contract for ORM queries. Base class for Query and NativeQuery. * @@ -72,7 +72,7 @@ abstract class AbstractQuery /** * The parameter map of this query. * - * @var \Doctrine\Common\Collections\ArrayCollection + * @var ArrayCollection|Parameter[] */ protected $parameters; @@ -95,17 +95,17 @@ abstract class AbstractQuery * * @var array */ - protected $_hints = array(); + protected $_hints = []; /** * The hydration mode. * - * @var integer + * @var string|int */ protected $_hydrationMode = self::HYDRATE_OBJECT; /** - * @param \Doctrine\DBAL\Cache\QueryCacheProfile + * @var \Doctrine\DBAL\Cache\QueryCacheProfile */ protected $_queryCacheProfile; @@ -117,7 +117,7 @@ abstract class AbstractQuery protected $_expireResultCache = false; /** - * @param \Doctrine\DBAL\Cache\QueryCacheProfile + * @var \Doctrine\DBAL\Cache\QueryCacheProfile */ protected $_hydrationCacheProfile; @@ -306,7 +306,7 @@ public function free() /** * Get all defined parameters. * - * @return \Doctrine\Common\Collections\ArrayCollection The defined query parameters. + * @return ArrayCollection The defined query parameters. */ public function getParameters() { @@ -323,20 +323,20 @@ public function getParameters() public function getParameter($key) { $filteredParameters = $this->parameters->filter( - function ($parameter) use ($key) - { - // Must not be identical because of string to integer conversion - return ($key == $parameter->getName()); + function (Query\Parameter $parameter) use ($key) : bool { + $parameterName = $parameter->getName(); + + return $key === $parameterName || (string) $key === (string) $parameterName; } ); - return count($filteredParameters) ? $filteredParameters->first() : null; + return ! $filteredParameters->isEmpty() ? $filteredParameters->first() : null; } /** * Sets a collection of query parameters. * - * @param \Doctrine\Common\Collections\ArrayCollection|array $parameters + * @param ArrayCollection|mixed[] $parameters * * @return static This query instance. */ @@ -371,17 +371,10 @@ public function setParameters($parameters) */ public function setParameter($key, $value, $type = null) { - $filteredParameters = $this->parameters->filter( - function ($parameter) use ($key) - { - // Must not be identical because of string to integer conversion - return ($key == $parameter->getName()); - } - ); + $existingParameter = $this->getParameter($key); - if (count($filteredParameters)) { - $parameter = $filteredParameters->first(); - $parameter->setValue($value, $type); + if ($existingParameter !== null) { + $existingParameter->setValue($value, $type); return $this; } @@ -419,16 +412,24 @@ public function processParameterValue($value) return $value; } - if (is_object($value) && $this->_em->getMetadataFactory()->hasMetadataFor(ClassUtils::getClass($value))) { + if ($value instanceof Mapping\ClassMetadata) { + return $value->name; + } + + if (! is_object($value)) { + return $value; + } + + try { $value = $this->_em->getUnitOfWork()->getSingleIdentifierValue($value); if ($value === null) { throw ORMInvalidArgumentException::invalidIdentifierBindingEntity(); } - } - - if ($value instanceof Mapping\ClassMetadata) { - return $value->name; + } catch (MappingException | ORMMappingException $e) { + // Silence any mapping exceptions. These can occur if the object in + // question is not a mapped entity, in which case we just don't do + // any preparation on the value. } return $value; @@ -530,7 +531,7 @@ public function getHydrationCacheProfile() */ public function setResultCacheProfile(QueryCacheProfile $profile = null) { - if ( ! $profile->getResultCacheDriver()) { + if ($profile !== null && ! $profile->getResultCacheDriver()) { $resultCacheDriver = $this->_em->getConfiguration()->getResultCacheImpl(); $profile = $profile->setResultCacheDriver($resultCacheDriver); } @@ -582,21 +583,45 @@ public function getResultCacheDriver() * Set whether or not to cache the results of this query and if so, for * how long and which ID to use for the cache entry. * - * @param boolean $bool - * @param integer $lifetime - * @param string $resultCacheId + * @deprecated 2.7 Use {@see enableResultCache} and {@see disableResultCache} instead. + * + * @param bool $useCache + * @param int $lifetime + * @param string $resultCacheId * * @return static This query instance. */ - public function useResultCache($bool, $lifetime = null, $resultCacheId = null) + public function useResultCache($useCache, $lifetime = null, $resultCacheId = null) { - if ($bool) { - $this->setResultCacheLifetime($lifetime); - $this->setResultCacheId($resultCacheId); + return $useCache + ? $this->enableResultCache($lifetime, $resultCacheId) + : $this->disableResultCache(); + } - return $this; - } + /** + * Enables caching of the results of this query, for given or default amount of seconds + * and optionally specifies which ID to use for the cache entry. + * + * @param int|null $lifetime How long the cache entry is valid, in seconds. + * @param string|null $resultCacheId ID to use for the cache entry. + * + * @return static This query instance. + */ + public function enableResultCache(?int $lifetime = null, ?string $resultCacheId = null) : self + { + $this->setResultCacheLifetime($lifetime); + $this->setResultCacheId($resultCacheId); + + return $this; + } + /** + * Disables caching of the results of this query. + * + * @return static This query instance. + */ + public function disableResultCache() : self + { $this->_queryCacheProfile = null; return $this; @@ -689,8 +714,8 @@ public function setFetchMode($class, $assocName, $fetchMode) /** * Defines the processing mode to be used during hydration / result set transformation. * - * @param integer $hydrationMode Doctrine processing mode to be used during hydration process. - * One of the Query::HYDRATE_* constants. + * @param string|int $hydrationMode Doctrine processing mode to be used during hydration process. + * One of the Query::HYDRATE_* constants. * * @return static This query instance. */ @@ -704,7 +729,7 @@ public function setHydrationMode($hydrationMode) /** * Gets the hydration mode currently used by the query. * - * @return integer + * @return string|int */ public function getHydrationMode() { @@ -716,9 +741,9 @@ public function getHydrationMode() * * Alias for execute(null, $hydrationMode = HYDRATE_OBJECT). * - * @param int $hydrationMode + * @param string|int $hydrationMode * - * @return array + * @return mixed */ public function getResult($hydrationMode = self::HYDRATE_OBJECT) { @@ -752,7 +777,7 @@ public function getScalarResult() /** * Get exactly one result or null. * - * @param int $hydrationMode + * @param string|int $hydrationMode * * @return mixed * @@ -790,12 +815,12 @@ public function getOneOrNullResult($hydrationMode = null) * If the result is not unique, a NonUniqueResultException is thrown. * If there is no result, a NoResultException is thrown. * - * @param integer $hydrationMode + * @param string|int $hydrationMode * * @return mixed * * @throws NonUniqueResultException If the query result is not unique. - * @throws NoResultException If the query returned no result. + * @throws NoResultException If the query returned no result and hydration mode is not HYDRATE_SINGLE_SCALAR. */ public function getSingleResult($hydrationMode = null) { @@ -821,10 +846,10 @@ public function getSingleResult($hydrationMode = null) * * Alias for getSingleResult(HYDRATE_SINGLE_SCALAR). * - * @return mixed + * @return mixed The scalar result. * - * @throws NonUniqueResultException If the query result is not unique. * @throws NoResultException If the query returned no result. + * @throws NonUniqueResultException If the query result is not unique. */ public function getSingleScalarResult() { @@ -885,7 +910,7 @@ public function getHints() * iterate over the result. * * @param ArrayCollection|array|null $parameters The query parameters. - * @param integer|null $hydrationMode The hydration mode to use. + * @param string|int|null $hydrationMode The hydration mode to use. * * @return \Doctrine\ORM\Internal\Hydration\IterableResult */ @@ -909,7 +934,7 @@ public function iterate($parameters = null, $hydrationMode = null) * Executes the query. * * @param ArrayCollection|array|null $parameters Query parameters. - * @param integer|null $hydrationMode Processing mode to be used during the hydration process. + * @param string|int|null $hydrationMode Processing mode to be used during the hydration process. * * @return mixed */ @@ -926,7 +951,7 @@ public function execute($parameters = null, $hydrationMode = null) * Execute query ignoring second level cache. * * @param ArrayCollection|array|null $parameters - * @param integer|null $hydrationMode + * @param string|int|null $hydrationMode * * @return mixed */ @@ -954,7 +979,7 @@ private function executeIgnoreQueryCache($parameters = null, $hydrationMode = nu } if ( ! $result) { - $result = array(); + $result = []; } $setCacheEntry = function($data) use ($cache, $result, $cacheKey, $realCacheKey, $queryCacheProfile) { @@ -984,39 +1009,61 @@ private function executeIgnoreQueryCache($parameters = null, $hydrationMode = nu * Load from second level cache or executes the query and put into cache. * * @param ArrayCollection|array|null $parameters - * @param integer|null $hydrationMode + * @param string|int|null $hydrationMode * * @return mixed */ private function executeUsingQueryCache($parameters = null, $hydrationMode = null) { $rsm = $this->getResultSetMapping(); - $querykey = new QueryCacheKey($this->getHash(), $this->lifetime, $this->cacheMode ?: Cache::MODE_NORMAL); $queryCache = $this->_em->getCache()->getQueryCache($this->cacheRegion); - $result = $queryCache->get($querykey, $rsm, $this->_hints); + $queryKey = new QueryCacheKey( + $this->getHash(), + $this->lifetime, + $this->cacheMode ?: Cache::MODE_NORMAL, + $this->getTimestampKey() + ); + + $result = $queryCache->get($queryKey, $rsm, $this->_hints); if ($result !== null) { if ($this->cacheLogger) { - $this->cacheLogger->queryCacheHit($queryCache->getRegion()->getName(), $querykey); + $this->cacheLogger->queryCacheHit($queryCache->getRegion()->getName(), $queryKey); } return $result; } $result = $this->executeIgnoreQueryCache($parameters, $hydrationMode); - $cached = $queryCache->put($querykey, $rsm, $result, $this->_hints); + $cached = $queryCache->put($queryKey, $rsm, $result, $this->_hints); if ($this->cacheLogger) { - $this->cacheLogger->queryCacheMiss($queryCache->getRegion()->getName(), $querykey); + $this->cacheLogger->queryCacheMiss($queryCache->getRegion()->getName(), $queryKey); if ($cached) { - $this->cacheLogger->queryCachePut($queryCache->getRegion()->getName(), $querykey); + $this->cacheLogger->queryCachePut($queryCache->getRegion()->getName(), $queryKey); } } return $result; } + /** + * @return \Doctrine\ORM\Cache\TimestampCacheKey|null + */ + private function getTimestampKey() + { + $entityName = reset($this->_resultSetMapping->aliasMap); + + if (empty($entityName)) { + return null; + } + + $metadata = $this->_em->getClassMetadata($entityName); + + return new Cache\TimestampCacheKey($metadata->rootEntityName); + } + /** * Get the result cache id to use to store the result set cache entry. * Will return the configured id if it exists otherwise a hash will be @@ -1026,7 +1073,7 @@ private function executeUsingQueryCache($parameters = null, $hydrationMode = nul */ protected function getHydrationCacheId() { - $parameters = array(); + $parameters = []; foreach ($this->getParameters() as $parameter) { $parameters[$parameter->getName()] = $this->processParameterValue($parameter->getValue()); @@ -1088,7 +1135,7 @@ public function __clone() { $this->parameters = new ArrayCollection(); - $this->_hints = array(); + $this->_hints = []; $this->_hints = $this->_em->getConfiguration()->getDefaultQueryHints(); } diff --git a/lib/Doctrine/ORM/Cache/CacheConfiguration.php b/lib/Doctrine/ORM/Cache/CacheConfiguration.php index 4891cac4909..eb3ec428df3 100644 --- a/lib/Doctrine/ORM/Cache/CacheConfiguration.php +++ b/lib/Doctrine/ORM/Cache/CacheConfiguration.php @@ -110,7 +110,9 @@ public function setRegionsConfiguration(RegionsConfiguration $regionsConfig) public function getQueryValidator() { if ($this->queryValidator === null) { - $this->queryValidator = new TimestampQueryCacheValidator(); + $this->queryValidator = new TimestampQueryCacheValidator( + $this->cacheFactory->getTimestampRegion() + ); } return $this->queryValidator; diff --git a/lib/Doctrine/ORM/Cache/DefaultCache.php b/lib/Doctrine/ORM/Cache/DefaultCache.php index 78a22a80f1d..80fbd814388 100644 --- a/lib/Doctrine/ORM/Cache/DefaultCache.php +++ b/lib/Doctrine/ORM/Cache/DefaultCache.php @@ -53,7 +53,7 @@ class DefaultCache implements Cache /** * @var \Doctrine\ORM\Cache\QueryCache[] */ - private $queryCaches = array(); + private $queryCaches = []; /** * @var \Doctrine\ORM\Cache\QueryCache @@ -314,7 +314,7 @@ private function buildEntityCacheKey(ClassMetadata $metadata, $identifier) private function buildCollectionCacheKey(ClassMetadata $metadata, $association, $ownerIdentifier) { if ( ! is_array($ownerIdentifier)) { - $ownerIdentifier = $this->toIdentifierArray($metadata, $ownerIdentifier);; + $ownerIdentifier = $this->toIdentifierArray($metadata, $ownerIdentifier); } return new CollectionCacheKey($metadata->rootEntityName, $association, $ownerIdentifier); @@ -336,7 +336,7 @@ private function toIdentifierArray(ClassMetadata $metadata, $identifier) } } - return array($metadata->identifier[0] => $identifier); + return [$metadata->identifier[0] => $identifier]; } } diff --git a/lib/Doctrine/ORM/Cache/DefaultCacheFactory.php b/lib/Doctrine/ORM/Cache/DefaultCacheFactory.php index 98ece43c719..bfc6aa29ab1 100644 --- a/lib/Doctrine/ORM/Cache/DefaultCacheFactory.php +++ b/lib/Doctrine/ORM/Cache/DefaultCacheFactory.php @@ -30,7 +30,6 @@ use Doctrine\ORM\Cache\Persister\Entity\NonStrictReadWriteCachedEntityPersister; use Doctrine\ORM\Cache\Persister\Entity\ReadOnlyCachedEntityPersister; use Doctrine\ORM\Cache\Persister\Entity\ReadWriteCachedEntityPersister; -use Doctrine\ORM\Cache\Region; use Doctrine\ORM\Cache\Region\DefaultMultiGetRegion; use Doctrine\ORM\Cache\Region\DefaultRegion; use Doctrine\ORM\Cache\Region\FileLockRegion; @@ -64,7 +63,7 @@ class DefaultCacheFactory implements CacheFactory /** * @var \Doctrine\ORM\Cache\Region[] */ - private $regions = array(); + private $regions = []; /** * @var string|null @@ -167,10 +166,10 @@ public function buildQueryCache(EntityManagerInterface $em, $regionName = null) return new DefaultQueryCache( $em, $this->getRegion( - array( + [ 'region' => $regionName ?: Cache::DEFAULT_QUERY_REGION_NAME, 'usage' => ClassMetadata::CACHE_USAGE_NONSTRICT_READ_WRITE - ) + ] ) ); } @@ -200,14 +199,9 @@ public function getRegion(array $cache) return $this->regions[$cache['region']]; } - $cacheAdapter = clone $this->cache; - - if ($cacheAdapter instanceof CacheProvider) { - $cacheAdapter->setNamespace($cache['region']); - } - - $name = $cache['region']; - $lifetime = $this->regionsConfig->getLifetime($cache['region']); + $name = $cache['region']; + $cacheAdapter = $this->createRegionCache($name); + $lifetime = $this->regionsConfig->getLifetime($cache['region']); $region = ($cacheAdapter instanceof MultiGetCache) ? new DefaultMultiGetRegion($name, $cacheAdapter, $lifetime) @@ -215,7 +209,10 @@ public function getRegion(array $cache) if ($cache['usage'] === ClassMetadata::CACHE_USAGE_READ_WRITE) { - if ( ! $this->fileLockRegionDirectory) { + if ( + '' === $this->fileLockRegionDirectory || + null === $this->fileLockRegionDirectory + ) { throw new \LogicException( 'If you want to use a "READ_WRITE" cache an implementation of "Doctrine\ORM\Cache\ConcurrentRegion" is required, ' . 'The default implementation provided by doctrine is "Doctrine\ORM\Cache\Region\FileLockRegion" if you want to use it please provide a valid directory, DefaultCacheFactory#setFileLockRegionDirectory(). ' @@ -229,6 +226,30 @@ public function getRegion(array $cache) return $this->regions[$cache['region']] = $region; } + /** + * @param string $name + * + * @return CacheAdapter + */ + private function createRegionCache($name) + { + $cacheAdapter = clone $this->cache; + + if (!$cacheAdapter instanceof CacheProvider) { + return $cacheAdapter; + } + + $namespace = $cacheAdapter->getNamespace(); + + if ('' !== $namespace) { + $namespace .= ':'; + } + + $cacheAdapter->setNamespace($namespace . $name); + + return $cacheAdapter; + } + /** * {@inheritdoc} */ diff --git a/lib/Doctrine/ORM/Cache/DefaultCollectionHydrator.php b/lib/Doctrine/ORM/Cache/DefaultCollectionHydrator.php index f6583cbd2ca..f12ccf50a78 100644 --- a/lib/Doctrine/ORM/Cache/DefaultCollectionHydrator.php +++ b/lib/Doctrine/ORM/Cache/DefaultCollectionHydrator.php @@ -46,7 +46,7 @@ class DefaultCollectionHydrator implements CollectionHydrator /** * @var array */ - private static $hints = array(Query::HINT_CACHE_ENABLED => true); + private static $hints = [Query::HINT_CACHE_ENABLED => true]; /** * @param \Doctrine\ORM\EntityManagerInterface $em The entity manager. @@ -62,11 +62,12 @@ public function __construct(EntityManagerInterface $em) */ public function buildCacheEntry(ClassMetadata $metadata, CollectionCacheKey $key, $collection) { - $data = array(); + $data = []; foreach ($collection as $index => $entity) { - $data[$index] = new EntityCacheKey($metadata->name, $this->uow->getEntityIdentifier($entity)); + $data[$index] = new EntityCacheKey($metadata->rootEntityName, $this->uow->getEntityIdentifier($entity)); } + return new CollectionCacheEntry($data); } @@ -79,7 +80,7 @@ public function loadCacheEntry(ClassMetadata $metadata, CollectionCacheKey $key, /* @var $targetPersister \Doctrine\ORM\Cache\Persister\CachedPersister */ $targetPersister = $this->uow->getEntityPersister($assoc['targetEntity']); $targetRegion = $targetPersister->getCacheRegion(); - $list = array(); + $list = []; $entityEntries = $targetRegion->getMultiple($entry); diff --git a/lib/Doctrine/ORM/Cache/DefaultEntityHydrator.php b/lib/Doctrine/ORM/Cache/DefaultEntityHydrator.php index 9ecb18e9298..62f76205ed3 100644 --- a/lib/Doctrine/ORM/Cache/DefaultEntityHydrator.php +++ b/lib/Doctrine/ORM/Cache/DefaultEntityHydrator.php @@ -36,7 +36,7 @@ class DefaultEntityHydrator implements EntityHydrator { /** - * @var \Doctrine\ORM\EntityManager + * @var \Doctrine\ORM\EntityManagerInterface */ private $em; @@ -55,7 +55,7 @@ class DefaultEntityHydrator implements EntityHydrator /** * @var array */ - private static $hints = array(Query::HINT_CACHE_ENABLED => true); + private static $hints = [Query::HINT_CACHE_ENABLED => true]; /** * @param \Doctrine\ORM\EntityManagerInterface $em The entity manager. @@ -75,6 +75,10 @@ public function buildCacheEntry(ClassMetadata $metadata, EntityCacheKey $key, $e $data = $this->uow->getOriginalEntityData($entity); $data = array_merge($data, $metadata->getIdentifierValues($entity)); // why update has no identifier values ? + if ($metadata->isVersioned) { + $data[$metadata->versionField] = $metadata->getFieldValue($entity, $metadata->versionField); + } + foreach ($metadata->associationMappings as $name => $assoc) { if ( ! isset($data[$name])) { continue; @@ -138,7 +142,7 @@ public function buildCacheEntry(ClassMetadata $metadata, EntityCacheKey $key, $e $data[reset($assoc['joinColumnFieldNames'])] = $targetId; $targetEntity = $this->em->getClassMetadata($assoc['targetEntity']); - $targetId = array($targetEntity->identifier[0] => $targetId); + $targetId = [$targetEntity->identifier[0] => $targetId]; } $data[$name] = new AssociationCacheEntry($assoc['targetEntity'], $targetId); @@ -175,7 +179,8 @@ public function loadCacheEntry(ClassMetadata $metadata, EntityCacheKey $key, Ent continue; } - $assocKey = new EntityCacheKey($assoc['targetEntity'], $assocId); + $assocMetadata = $this->em->getClassMetadata($assoc['targetEntity']); + $assocKey = new EntityCacheKey($assocMetadata->rootEntityName, $assocId); $assocPersister = $this->uow->getEntityPersister($assoc['targetEntity']); $assocRegion = $assocPersister->getCacheRegion(); $assocEntry = $assocRegion->get($assocKey); diff --git a/lib/Doctrine/ORM/Cache/DefaultQueryCache.php b/lib/Doctrine/ORM/Cache/DefaultQueryCache.php index dabf1721e0e..866ea0db257 100644 --- a/lib/Doctrine/ORM/Cache/DefaultQueryCache.php +++ b/lib/Doctrine/ORM/Cache/DefaultQueryCache.php @@ -22,6 +22,7 @@ use Doctrine\Common\Collections\ArrayCollection; use Doctrine\ORM\Cache\Persister\CachedPersister; +use Doctrine\ORM\Cache\Persister\Entity\CachedEntityPersister; use Doctrine\ORM\EntityManagerInterface; use Doctrine\ORM\Query\ResultSetMapping; use Doctrine\ORM\Mapping\ClassMetadata; @@ -29,6 +30,7 @@ use Doctrine\Common\Proxy\Proxy; use Doctrine\ORM\Cache; use Doctrine\ORM\Query; +use function assert; /** * Default query cache implementation. @@ -66,7 +68,7 @@ class DefaultQueryCache implements QueryCache /** * @var array */ - private static $hints = array(Query::HINT_CACHE_ENABLED => true); + private static $hints = [Query::HINT_CACHE_ENABLED => true]; /** * @param \Doctrine\ORM\EntityManagerInterface $em The entity manager. @@ -86,50 +88,59 @@ public function __construct(EntityManagerInterface $em, Region $region) /** * {@inheritdoc} */ - public function get(QueryCacheKey $key, ResultSetMapping $rsm, array $hints = array()) + public function get(QueryCacheKey $key, ResultSetMapping $rsm, array $hints = []) { if ( ! ($key->cacheMode & Cache::MODE_GET)) { return null; } - $entry = $this->region->get($key); + $cacheEntry = $this->region->get($key); - if ( ! $entry instanceof QueryCacheEntry) { + if ( ! $cacheEntry instanceof QueryCacheEntry) { return null; } - if ( ! $this->validator->isValid($key, $entry)) { + if ( ! $this->validator->isValid($key, $cacheEntry)) { $this->region->evict($key); return null; } - $result = array(); + $result = []; $entityName = reset($rsm->aliasMap); - $hasRelation = ( ! empty($rsm->relationMap)); + $hasRelation = ! empty($rsm->relationMap); $persister = $this->uow->getEntityPersister($entityName); - $region = $persister->getCacheRegion(); - $regionName = $region->getName(); + assert($persister instanceof CachedEntityPersister); + + $region = $persister->getCacheRegion(); + $regionName = $region->getName(); $cm = $this->em->getClassMetadata($entityName); - // @TODO - move to cache hydration component - foreach ($entry->result as $index => $entry) { - if (($entityEntry = $region->get($entityKey = new EntityCacheKey($cm->rootEntityName, $entry['identifier']))) === null) { + $generateKeys = static function (array $entry) use ($cm) : EntityCacheKey { + return new EntityCacheKey($cm->rootEntityName, $entry['identifier']); + }; + + $cacheKeys = new CollectionCacheEntry(array_map($generateKeys, $cacheEntry->result)); + $entries = $region->getMultiple($cacheKeys) ?? []; + + // @TODO - move to cache hydration component + foreach ($cacheEntry->result as $index => $entry) { + $entityEntry = $entries[$index] ?? null; + if (! $entityEntry instanceof EntityCacheEntry) { if ($this->cacheLogger !== null) { - $this->cacheLogger->entityCacheMiss($regionName, $entityKey); + $this->cacheLogger->entityCacheMiss($regionName, $cacheKeys->identifiers[$index]); } return null; } if ($this->cacheLogger !== null) { - $this->cacheLogger->entityCacheHit($regionName, $entityKey); + $this->cacheLogger->entityCacheHit($regionName, $cacheKeys->identifiers[$index]); } if ( ! $hasRelation) { - $result[$index] = $this->uow->createEntity($entityEntry->class, $entityEntry->resolveAssociationEntries($this->em), self::$hints); continue; @@ -138,13 +149,15 @@ public function get(QueryCacheKey $key, ResultSetMapping $rsm, array $hints = ar $data = $entityEntry->data; foreach ($entry['associations'] as $name => $assoc) { + $assocPersister = $this->uow->getEntityPersister($assoc['targetEntity']); + assert($assocPersister instanceof CachedEntityPersister); - $assocPersister = $this->uow->getEntityPersister($assoc['targetEntity']); - $assocRegion = $assocPersister->getCacheRegion(); + $assocRegion = $assocPersister->getCacheRegion(); + $assocMetadata = $this->em->getClassMetadata($assoc['targetEntity']); if ($assoc['type'] & ClassMetadata::TO_ONE) { - if (($assocEntry = $assocRegion->get($assocKey = new EntityCacheKey($assoc['targetEntity'], $assoc['identifier']))) === null) { + if (($assocEntry = $assocRegion->get($assocKey = new EntityCacheKey($assocMetadata->rootEntityName, $assoc['identifier']))) === null) { if ($this->cacheLogger !== null) { $this->cacheLogger->entityCacheMiss($assocRegion->getName(), $assocKey); @@ -168,15 +181,20 @@ public function get(QueryCacheKey $key, ResultSetMapping $rsm, array $hints = ar continue; } - $targetClass = $this->em->getClassMetadata($assoc['targetEntity']); - $collection = new PersistentCollection($this->em, $targetClass, new ArrayCollection()); + $generateKeys = function ($id) use ($assocMetadata): EntityCacheKey { + return new EntityCacheKey($assocMetadata->rootEntityName, $id); + }; - foreach ($assoc['list'] as $assocIndex => $assocId) { + $collection = new PersistentCollection($this->em, $assocMetadata, new ArrayCollection()); + $assocKeys = new CollectionCacheEntry(array_map($generateKeys, $assoc['list'])); + $assocEntries = $assocRegion->getMultiple($assocKeys); - if (($assocEntry = $assocRegion->get($assocKey = new EntityCacheKey($assoc['targetEntity'], $assocId))) === null) { + foreach ($assoc['list'] as $assocIndex => $assocId) { + $assocEntry = is_array($assocEntries) && array_key_exists($assocIndex, $assocEntries) ? $assocEntries[$assocIndex] : null; + if ($assocEntry === null) { if ($this->cacheLogger !== null) { - $this->cacheLogger->entityCacheMiss($assocRegion->getName(), $assocKey); + $this->cacheLogger->entityCacheMiss($assocRegion->getName(), $assocKeys->identifiers[$assocIndex]); } $this->uow->hydrationComplete(); @@ -189,7 +207,7 @@ public function get(QueryCacheKey $key, ResultSetMapping $rsm, array $hints = ar $collection->hydrateSet($assocIndex, $element); if ($this->cacheLogger !== null) { - $this->cacheLogger->entityCacheHit($assocRegion->getName(), $assocKey); + $this->cacheLogger->entityCacheHit($assocRegion->getName(), $assocKeys->identifiers[$assocIndex]); } } @@ -198,6 +216,25 @@ public function get(QueryCacheKey $key, ResultSetMapping $rsm, array $hints = ar $collection->setInitialized(true); } + foreach ($data as $fieldName => $unCachedAssociationData) { + // In some scenarios, such as EAGER+ASSOCIATION+ID+CACHE, the + // cache key information in `$cacheEntry` will not contain details + // for fields that are associations. + // + // This means that `$data` keys for some associations that may + // actually not be cached will not be converted to actual association + // data, yet they contain L2 cache AssociationCacheEntry objects. + // + // We need to unwrap those associations into proxy references, + // since we don't have actual data for them except for identifiers. + if ($unCachedAssociationData instanceof AssociationCacheEntry) { + $data[$fieldName] = $this->em->getReference( + $unCachedAssociationData->class, + $unCachedAssociationData->identifier + ); + } + } + $result[$index] = $this->uow->createEntity($entityEntry->class, $data, self::$hints); } @@ -209,7 +246,7 @@ public function get(QueryCacheKey $key, ResultSetMapping $rsm, array $hints = ar /** * {@inheritdoc} */ - public function put(QueryCacheKey $key, ResultSetMapping $rsm, $result, array $hints = array()) + public function put(QueryCacheKey $key, ResultSetMapping $rsm, $result, array $hints = []) { if ($rsm->scalarMappings) { throw new CacheException("Second level cache does not support scalar results."); @@ -231,13 +268,12 @@ public function put(QueryCacheKey $key, ResultSetMapping $rsm, $result, array $h return false; } - $data = array(); + $data = []; $entityName = reset($rsm->aliasMap); $rootAlias = key($rsm->aliasMap); - $hasRelation = ( ! empty($rsm->relationMap)); $persister = $this->uow->getEntityPersister($entityName); - if ( ! ($persister instanceof CachedPersister)) { + if (! $persister instanceof CachedEntityPersister) { throw CacheException::nonCacheableEntity($entityName); } @@ -246,8 +282,6 @@ public function put(QueryCacheKey $key, ResultSetMapping $rsm, $result, array $h foreach ($result as $index => $entity) { $identifier = $this->uow->getEntityIdentifier($entity); $entityKey = new EntityCacheKey($entityName, $identifier); - $data[$index]['identifier'] = $identifier; - $data[$index]['associations'] = array(); if (($key->cacheMode & Cache::MODE_REFRESH) || ! $region->contains($entityKey)) { // Cancel put result if entity put fail @@ -256,9 +290,8 @@ public function put(QueryCacheKey $key, ResultSetMapping $rsm, $result, array $h } } - if ( ! $hasRelation) { - continue; - } + $data[$index]['identifier'] = $identifier; + $data[$index]['associations'] = []; // @TODO - move to cache hydration components foreach ($rsm->relationMap as $alias => $name) { @@ -332,15 +365,15 @@ private function storeAssociationCache(QueryCacheKey $key, array $assoc, $assocV } } - return array( + return [ 'targetEntity' => $assocMetadata->rootEntityName, 'identifier' => $assocIdentifier, 'type' => $assoc['type'] - ); + ]; } // Handle *-to-many associations - $list = array(); + $list = []; foreach ($assocValue as $assocItemIndex => $assocItem) { $assocIdentifier = $this->uow->getEntityIdentifier($assocItem); @@ -356,11 +389,11 @@ private function storeAssociationCache(QueryCacheKey $key, array $assoc, $assocV $list[$assocItemIndex] = $assocIdentifier; } - return array( + return [ 'targetEntity' => $assocMetadata->rootEntityName, 'type' => $assoc['type'], 'list' => $list, - ); + ]; } /** @@ -372,7 +405,7 @@ private function storeAssociationCache(QueryCacheKey $key, array $assoc, $assocV */ private function getAssociationValue(ResultSetMapping $rsm, $assocAlias, $entity) { - $path = array(); + $path = []; $alias = $assocAlias; while (isset($rsm->parentAliasMap[$alias])) { @@ -380,10 +413,11 @@ private function getAssociationValue(ResultSetMapping $rsm, $assocAlias, $entity $field = $rsm->relationMap[$alias]; $class = $rsm->aliasMap[$parent]; - array_unshift($path, array( + array_unshift($path, [ 'field' => $field, 'class' => $class - )); + ] + ); $alias = $parent; } @@ -417,7 +451,7 @@ private function getAssociationPathValue($value, array $path) return $this->getAssociationPathValue($value, $path); } - $values = array(); + $values = []; foreach ($value as $item) { $values[] = $this->getAssociationPathValue($item, $path); diff --git a/lib/Doctrine/ORM/Cache/Lock.php b/lib/Doctrine/ORM/Cache/Lock.php index 5346aa32371..60f7d6c9d7d 100644 --- a/lib/Doctrine/ORM/Cache/Lock.php +++ b/lib/Doctrine/ORM/Cache/Lock.php @@ -53,6 +53,6 @@ public function __construct($value, $time = null) */ public static function createLockRead() { - return new self(uniqid(time())); + return new self(uniqid(time(), true)); } } diff --git a/lib/Doctrine/ORM/Cache/Logging/CacheLoggerChain.php b/lib/Doctrine/ORM/Cache/Logging/CacheLoggerChain.php index 694b35ca5eb..28a8125c972 100644 --- a/lib/Doctrine/ORM/Cache/Logging/CacheLoggerChain.php +++ b/lib/Doctrine/ORM/Cache/Logging/CacheLoggerChain.php @@ -35,7 +35,7 @@ class CacheLoggerChain implements CacheLogger /** * @var array<\Doctrine\ORM\Cache\Logging\CacheLogger> */ - private $loggers = array(); + private $loggers = []; /** * @param string $name diff --git a/lib/Doctrine/ORM/Cache/Logging/StatisticsCacheLogger.php b/lib/Doctrine/ORM/Cache/Logging/StatisticsCacheLogger.php index 2fbba40bef1..122e3534ac7 100644 --- a/lib/Doctrine/ORM/Cache/Logging/StatisticsCacheLogger.php +++ b/lib/Doctrine/ORM/Cache/Logging/StatisticsCacheLogger.php @@ -35,17 +35,17 @@ class StatisticsCacheLogger implements CacheLogger /** * @var array */ - private $cacheMissCountMap = array(); + private $cacheMissCountMap = []; /** * @var array */ - private $cacheHitCountMap = array(); + private $cacheHitCountMap = []; /** * @var array */ - private $cachePutCountMap = array(); + private $cachePutCountMap = []; /** * {@inheritdoc} @@ -214,9 +214,9 @@ public function clearRegionStats($regionName) */ public function clearStats() { - $this->cachePutCountMap = array(); - $this->cacheHitCountMap = array(); - $this->cacheMissCountMap = array(); + $this->cachePutCountMap = []; + $this->cacheHitCountMap = []; + $this->cacheMissCountMap = []; } /** diff --git a/lib/Doctrine/ORM/Cache/Persister/Collection/AbstractCollectionPersister.php b/lib/Doctrine/ORM/Cache/Persister/Collection/AbstractCollectionPersister.php index abaef17a680..7a10d17d932 100644 --- a/lib/Doctrine/ORM/Cache/Persister/Collection/AbstractCollectionPersister.php +++ b/lib/Doctrine/ORM/Cache/Persister/Collection/AbstractCollectionPersister.php @@ -70,7 +70,7 @@ abstract class AbstractCollectionPersister implements CachedCollectionPersister /** * @var array */ - protected $queuedCache = array(); + protected $queuedCache = []; /** * @var \Doctrine\ORM\Cache\Region diff --git a/lib/Doctrine/ORM/Cache/Persister/Collection/NonStrictReadWriteCachedCollectionPersister.php b/lib/Doctrine/ORM/Cache/Persister/Collection/NonStrictReadWriteCachedCollectionPersister.php index 86e5c8f9ffd..fbd46f6eafe 100644 --- a/lib/Doctrine/ORM/Cache/Persister/Collection/NonStrictReadWriteCachedCollectionPersister.php +++ b/lib/Doctrine/ORM/Cache/Persister/Collection/NonStrictReadWriteCachedCollectionPersister.php @@ -46,7 +46,7 @@ public function afterTransactionComplete() } } - $this->queuedCache = array(); + $this->queuedCache = []; } /** @@ -54,7 +54,7 @@ public function afterTransactionComplete() */ public function afterTransactionRolledBack() { - $this->queuedCache = array(); + $this->queuedCache = []; } /** @@ -96,9 +96,9 @@ public function update(PersistentCollection $collection) $this->persister->update($collection); - $this->queuedCache['update'][spl_object_hash($collection)] = array( + $this->queuedCache['update'][spl_object_hash($collection)] = [ 'key' => $key, 'list' => $collection - ); + ]; } } diff --git a/lib/Doctrine/ORM/Cache/Persister/Collection/ReadOnlyCachedCollectionPersister.php b/lib/Doctrine/ORM/Cache/Persister/Collection/ReadOnlyCachedCollectionPersister.php index 4f35ceb10dc..dfc816c5ab9 100644 --- a/lib/Doctrine/ORM/Cache/Persister/Collection/ReadOnlyCachedCollectionPersister.php +++ b/lib/Doctrine/ORM/Cache/Persister/Collection/ReadOnlyCachedCollectionPersister.php @@ -35,7 +35,7 @@ class ReadOnlyCachedCollectionPersister extends NonStrictReadWriteCachedCollecti */ public function update(PersistentCollection $collection) { - if ($collection->isDirty() && count($collection->getSnapshot()) > 0) { + if ($collection->isDirty() && $collection->getSnapshot()) { throw CacheException::updateReadOnlyCollection(ClassUtils::getClass($collection->getOwner()), $this->association['fieldName']); } diff --git a/lib/Doctrine/ORM/Cache/Persister/Collection/ReadWriteCachedCollectionPersister.php b/lib/Doctrine/ORM/Cache/Persister/Collection/ReadWriteCachedCollectionPersister.php index a92ed20d302..74bb044451b 100644 --- a/lib/Doctrine/ORM/Cache/Persister/Collection/ReadWriteCachedCollectionPersister.php +++ b/lib/Doctrine/ORM/Cache/Persister/Collection/ReadWriteCachedCollectionPersister.php @@ -60,7 +60,7 @@ public function afterTransactionComplete() } } - $this->queuedCache = array(); + $this->queuedCache = []; } /** @@ -80,7 +80,7 @@ public function afterTransactionRolledBack() } } - $this->queuedCache = array(); + $this->queuedCache = []; } /** @@ -98,10 +98,10 @@ public function delete(PersistentCollection $collection) return; } - $this->queuedCache['delete'][spl_object_hash($collection)] = array( + $this->queuedCache['delete'][spl_object_hash($collection)] = [ 'key' => $key, 'lock' => $lock - ); + ]; } /** @@ -126,9 +126,9 @@ public function update(PersistentCollection $collection) return; } - $this->queuedCache['update'][spl_object_hash($collection)] = array( + $this->queuedCache['update'][spl_object_hash($collection)] = [ 'key' => $key, 'lock' => $lock - ); + ]; } } diff --git a/lib/Doctrine/ORM/Cache/Persister/Entity/AbstractEntityPersister.php b/lib/Doctrine/ORM/Cache/Persister/Entity/AbstractEntityPersister.php index 5690f9169c2..05484120ec4 100644 --- a/lib/Doctrine/ORM/Cache/Persister/Entity/AbstractEntityPersister.php +++ b/lib/Doctrine/ORM/Cache/Persister/Entity/AbstractEntityPersister.php @@ -64,7 +64,7 @@ abstract class AbstractEntityPersister implements CachedEntityPersister /** * @var array */ - protected $queuedCache = array(); + protected $queuedCache = []; /** * @var \Doctrine\ORM\Cache\Region @@ -104,7 +104,7 @@ abstract class AbstractEntityPersister implements CachedEntityPersister /** * Associations configured as FETCH_EAGER, as well as all inverse one-to-one associations. * - * @var array + * @var array|null */ protected $joinedAssociations; @@ -130,7 +130,7 @@ public function __construct(EntityPersister $persister, Region $region, EntityMa $this->cacheLogger = $cacheConfig->getCacheLogger(); $this->timestampRegion = $cacheFactory->getTimestampRegion(); $this->hydrator = $cacheFactory->buildEntityHydrator($em, $class); - $this->timestampKey = new TimestampCacheKey($this->class->getTableName()); + $this->timestampKey = new TimestampCacheKey($this->class->rootEntityName); } /** @@ -160,7 +160,7 @@ public function getSelectSQL($criteria, $assoc = null, $lockMode = null, $limit /** * {@inheritDoc} */ - public function getCountSQL($criteria = array()) + public function getCountSQL($criteria = []) { return $this->persister->getCountSQL($criteria); } @@ -249,7 +249,7 @@ public function storeEntityCache($entity, EntityCacheKey $key) private function storeJoinedAssociations($entity) { if ($this->joinedAssociations === null) { - $associations = array(); + $associations = []; foreach ($this->class->associationMappings as $name => $assoc) { if (isset($assoc['cache']) && @@ -272,7 +272,8 @@ private function storeJoinedAssociations($entity) } $assocId = $this->uow->getEntityIdentifier($assocEntity); - $assocKey = new EntityCacheKey($assoc['targetEntity'], $assocId); + $assocMetadata = $this->metadataFactory->getMetadataFor($assoc['targetEntity']); + $assocKey = new EntityCacheKey($assocMetadata->rootEntityName, $assocId); $assocPersister = $this->uow->getEntityPersister($assoc['targetEntity']); $assocPersister->storeEntityCache($assocEntity, $assocKey); @@ -287,17 +288,16 @@ private function storeJoinedAssociations($entity) * @param array $orderBy * @param integer $limit * @param integer $offset - * @param integer $timestamp * * @return string */ - protected function getHash($query, $criteria, array $orderBy = null, $limit = null, $offset = null, $timestamp = null) + protected function getHash($query, $criteria, array $orderBy = null, $limit = null, $offset = null) { list($params) = ($criteria instanceof Criteria) ? $this->persister->expandCriteriaParameters($criteria) : $this->persister->expandParameters($criteria); - return sha1($query . serialize($params) . serialize($orderBy) . $limit . $offset . $timestamp); + return sha1($query . serialize($params) . serialize($orderBy) . $limit . $offset); } /** @@ -361,24 +361,23 @@ public function executeInserts() /** * {@inheritdoc} */ - public function load(array $criteria, $entity = null, $assoc = null, array $hints = array(), $lockMode = null, $limit = null, array $orderBy = null) + public function load(array $criteria, $entity = null, $assoc = null, array $hints = [], $lockMode = null, $limit = null, array $orderBy = null) { if ($entity !== null || $assoc !== null || ! empty($hints) || $lockMode !== null) { return $this->persister->load($criteria, $entity, $assoc, $hints, $lockMode, $limit, $orderBy); } //handle only EntityRepository#findOneBy - $timestamp = $this->timestampRegion->get($this->timestampKey); $query = $this->persister->getSelectSQL($criteria, null, null, $limit, null, $orderBy); - $hash = $this->getHash($query, $criteria, null, null, null, $timestamp ? $timestamp->time : null); + $hash = $this->getHash($query, $criteria, null, null, null); $rsm = $this->getResultSetMapping(); - $querykey = new QueryCacheKey($hash, 0, Cache::MODE_NORMAL); + $queryKey = new QueryCacheKey($hash, 0, Cache::MODE_NORMAL, $this->timestampKey); $queryCache = $this->cache->getQueryCache($this->regionName); - $result = $queryCache->get($querykey, $rsm); + $result = $queryCache->get($queryKey, $rsm); if ($result !== null) { if ($this->cacheLogger) { - $this->cacheLogger->queryCacheHit($this->regionName, $querykey); + $this->cacheLogger->queryCacheHit($this->regionName, $queryKey); } return $result[0]; @@ -388,15 +387,15 @@ public function load(array $criteria, $entity = null, $assoc = null, array $hint return null; } - $cached = $queryCache->put($querykey, $rsm, array($result)); + $cached = $queryCache->put($queryKey, $rsm, [$result]); if ($this->cacheLogger) { if ($result) { - $this->cacheLogger->queryCacheMiss($this->regionName, $querykey); + $this->cacheLogger->queryCacheMiss($this->regionName, $queryKey); } if ($cached) { - $this->cacheLogger->queryCachePut($this->regionName, $querykey); + $this->cacheLogger->queryCachePut($this->regionName, $queryKey); } } @@ -406,34 +405,33 @@ public function load(array $criteria, $entity = null, $assoc = null, array $hint /** * {@inheritdoc} */ - public function loadAll(array $criteria = array(), array $orderBy = null, $limit = null, $offset = null) + public function loadAll(array $criteria = [], array $orderBy = null, $limit = null, $offset = null) { - $timestamp = $this->timestampRegion->get($this->timestampKey); $query = $this->persister->getSelectSQL($criteria, null, null, $limit, $offset, $orderBy); - $hash = $this->getHash($query, $criteria, null, null, null, $timestamp ? $timestamp->time : null); + $hash = $this->getHash($query, $criteria, null, null, null); $rsm = $this->getResultSetMapping(); - $querykey = new QueryCacheKey($hash, 0, Cache::MODE_NORMAL); + $queryKey = new QueryCacheKey($hash, 0, Cache::MODE_NORMAL, $this->timestampKey); $queryCache = $this->cache->getQueryCache($this->regionName); - $result = $queryCache->get($querykey, $rsm); + $result = $queryCache->get($queryKey, $rsm); if ($result !== null) { if ($this->cacheLogger) { - $this->cacheLogger->queryCacheHit($this->regionName, $querykey); + $this->cacheLogger->queryCacheHit($this->regionName, $queryKey); } return $result; } $result = $this->persister->loadAll($criteria, $orderBy, $limit, $offset); - $cached = $queryCache->put($querykey, $rsm, $result); + $cached = $queryCache->put($queryKey, $rsm, $result); if ($this->cacheLogger) { if ($result) { - $this->cacheLogger->queryCacheMiss($this->regionName, $querykey); + $this->cacheLogger->queryCacheMiss($this->regionName, $queryKey); } if ($cached) { - $this->cacheLogger->queryCachePut($this->regionName, $querykey); + $this->cacheLogger->queryCachePut($this->regionName, $queryKey); } } @@ -454,12 +452,14 @@ public function loadById(array $identifier, $entity = null) $class = $this->metadataFactory->getMetadataFor($cacheEntry->class); } - if (($entity = $this->hydrator->loadCacheEntry($class, $cacheKey, $cacheEntry, $entity)) !== null) { + $cachedEntity = $this->hydrator->loadCacheEntry($class, $cacheKey, $cacheEntry, $entity); + + if ($cachedEntity !== null) { if ($this->cacheLogger) { $this->cacheLogger->entityCacheHit($this->regionName, $cacheKey); } - return $entity; + return $cachedEntity; } } @@ -479,7 +479,7 @@ public function loadById(array $identifier, $entity = null) $cacheEntry = $this->hydrator->buildCacheEntry($class, $cacheKey, $entity); $cached = $this->region->put($cacheKey, $cacheEntry); - if ($cached && ($this->joinedAssociations === null || count($this->joinedAssociations) > 0)) { + if ($cached && (null === $this->joinedAssociations || $this->joinedAssociations)) { $this->storeJoinedAssociations($entity); } @@ -497,7 +497,7 @@ public function loadById(array $identifier, $entity = null) /** * {@inheritDoc} */ - public function count($criteria = array()) + public function count($criteria = []) { return $this->persister->count($criteria); } @@ -511,31 +511,30 @@ public function loadCriteria(Criteria $criteria) $limit = $criteria->getMaxResults(); $offset = $criteria->getFirstResult(); $query = $this->persister->getSelectSQL($criteria); - $timestamp = $this->timestampRegion->get($this->timestampKey); - $hash = $this->getHash($query, $criteria, $orderBy, $limit, $offset, $timestamp ? $timestamp->time : null); + $hash = $this->getHash($query, $criteria, $orderBy, $limit, $offset); $rsm = $this->getResultSetMapping(); - $querykey = new QueryCacheKey($hash, 0, Cache::MODE_NORMAL); + $queryKey = new QueryCacheKey($hash, 0, Cache::MODE_NORMAL, $this->timestampKey); $queryCache = $this->cache->getQueryCache($this->regionName); - $cacheResult = $queryCache->get($querykey, $rsm); + $cacheResult = $queryCache->get($queryKey, $rsm); if ($cacheResult !== null) { if ($this->cacheLogger) { - $this->cacheLogger->queryCacheHit($this->regionName, $querykey); + $this->cacheLogger->queryCacheHit($this->regionName, $queryKey); } return $cacheResult; } $result = $this->persister->loadCriteria($criteria); - $cached = $queryCache->put($querykey, $rsm, $result); + $cached = $queryCache->put($queryKey, $rsm, $result); if ($this->cacheLogger) { if ($result) { - $this->cacheLogger->queryCacheMiss($this->regionName, $querykey); + $this->cacheLogger->queryCacheMiss($this->regionName, $queryKey); } if ($cached) { - $this->cacheLogger->queryCachePut($this->regionName, $querykey); + $this->cacheLogger->queryCachePut($this->regionName, $queryKey); } } @@ -551,28 +550,28 @@ public function loadManyToManyCollection(array $assoc, $sourceEntity, Persistent $hasCache = ($persister instanceof CachedPersister); $key = null; - if ($hasCache) { - $ownerId = $this->uow->getEntityIdentifier($coll->getOwner()); - $key = $this->buildCollectionCacheKey($assoc, $ownerId); - $list = $persister->loadCollectionCache($coll, $key); + if ( ! $hasCache) { + return $this->persister->loadManyToManyCollection($assoc, $sourceEntity, $coll); + } - if ($list !== null) { - if ($this->cacheLogger) { - $this->cacheLogger->collectionCacheHit($persister->getCacheRegion()->getName(), $key); - } + $ownerId = $this->uow->getEntityIdentifier($coll->getOwner()); + $key = $this->buildCollectionCacheKey($assoc, $ownerId); + $list = $persister->loadCollectionCache($coll, $key); - return $list; + if ($list !== null) { + if ($this->cacheLogger) { + $this->cacheLogger->collectionCacheHit($persister->getCacheRegion()->getName(), $key); } + + return $list; } $list = $this->persister->loadManyToManyCollection($assoc, $sourceEntity, $coll); - if ($hasCache) { - $persister->storeCollectionCache($key, $list); + $persister->storeCollectionCache($key, $list); - if ($this->cacheLogger) { - $this->cacheLogger->collectionCacheMiss($persister->getCacheRegion()->getName(), $key); - } + if ($this->cacheLogger) { + $this->cacheLogger->collectionCacheMiss($persister->getCacheRegion()->getName(), $key); } return $list; @@ -586,28 +585,28 @@ public function loadOneToManyCollection(array $assoc, $sourceEntity, PersistentC $persister = $this->uow->getCollectionPersister($assoc); $hasCache = ($persister instanceof CachedPersister); - if ($hasCache) { - $ownerId = $this->uow->getEntityIdentifier($coll->getOwner()); - $key = $this->buildCollectionCacheKey($assoc, $ownerId); - $list = $persister->loadCollectionCache($coll, $key); + if ( ! $hasCache) { + return $this->persister->loadOneToManyCollection($assoc, $sourceEntity, $coll); + } - if ($list !== null) { - if ($this->cacheLogger) { - $this->cacheLogger->collectionCacheHit($persister->getCacheRegion()->getName(), $key); - } + $ownerId = $this->uow->getEntityIdentifier($coll->getOwner()); + $key = $this->buildCollectionCacheKey($assoc, $ownerId); + $list = $persister->loadCollectionCache($coll, $key); - return $list; + if ($list !== null) { + if ($this->cacheLogger) { + $this->cacheLogger->collectionCacheHit($persister->getCacheRegion()->getName(), $key); } + + return $list; } $list = $this->persister->loadOneToManyCollection($assoc, $sourceEntity, $coll); - if ($hasCache) { - $persister->storeCollectionCache($key, $list); + $persister->storeCollectionCache($key, $list); - if ($this->cacheLogger) { - $this->cacheLogger->collectionCacheMiss($persister->getCacheRegion()->getName(), $key); - } + if ($this->cacheLogger) { + $this->cacheLogger->collectionCacheMiss($persister->getCacheRegion()->getName(), $key); } return $list; @@ -616,7 +615,7 @@ public function loadOneToManyCollection(array $assoc, $sourceEntity, PersistentC /** * {@inheritdoc} */ - public function loadOneToOneEntity(array $assoc, $sourceEntity, array $identifier = array()) + public function loadOneToOneEntity(array $assoc, $sourceEntity, array $identifier = []) { return $this->persister->loadOneToOneEntity($assoc, $sourceEntity, $identifier); } diff --git a/lib/Doctrine/ORM/Cache/Persister/Entity/NonStrictReadWriteCachedEntityPersister.php b/lib/Doctrine/ORM/Cache/Persister/Entity/NonStrictReadWriteCachedEntityPersister.php index 54c814a9a22..a2844673bee 100644 --- a/lib/Doctrine/ORM/Cache/Persister/Entity/NonStrictReadWriteCachedEntityPersister.php +++ b/lib/Doctrine/ORM/Cache/Persister/Entity/NonStrictReadWriteCachedEntityPersister.php @@ -62,7 +62,7 @@ public function afterTransactionComplete() $this->timestampRegion->update($this->timestampKey); } - $this->queuedCache = array(); + $this->queuedCache = []; } /** @@ -70,7 +70,7 @@ public function afterTransactionComplete() */ public function afterTransactionRolledBack() { - $this->queuedCache = array(); + $this->queuedCache = []; } /** diff --git a/lib/Doctrine/ORM/Cache/Persister/Entity/ReadWriteCachedEntityPersister.php b/lib/Doctrine/ORM/Cache/Persister/Entity/ReadWriteCachedEntityPersister.php index 07cac510d4c..79a4c8c3dad 100644 --- a/lib/Doctrine/ORM/Cache/Persister/Entity/ReadWriteCachedEntityPersister.php +++ b/lib/Doctrine/ORM/Cache/Persister/Entity/ReadWriteCachedEntityPersister.php @@ -73,7 +73,7 @@ public function afterTransactionComplete() $this->timestampRegion->update($this->timestampKey); } - $this->queuedCache = array(); + $this->queuedCache = []; } /** @@ -93,7 +93,7 @@ public function afterTransactionRolledBack() } } - $this->queuedCache = array(); + $this->queuedCache = []; } /** @@ -113,10 +113,10 @@ public function delete($entity) return $deleted; } - $this->queuedCache['delete'][] = array( + $this->queuedCache['delete'][] = [ 'lock' => $lock, 'key' => $key - ); + ]; return $deleted; } @@ -135,9 +135,9 @@ public function update($entity) return; } - $this->queuedCache['update'][] = array( + $this->queuedCache['update'][] = [ 'lock' => $lock, 'key' => $key - ); + ]; } } diff --git a/lib/Doctrine/ORM/Cache/QueryCache.php b/lib/Doctrine/ORM/Cache/QueryCache.php index dd5ef3bf539..de2496253b3 100644 --- a/lib/Doctrine/ORM/Cache/QueryCache.php +++ b/lib/Doctrine/ORM/Cache/QueryCache.php @@ -44,7 +44,7 @@ public function clear(); * * @return boolean */ - public function put(QueryCacheKey $key, ResultSetMapping $rsm, $result, array $hints = array()); + public function put(QueryCacheKey $key, ResultSetMapping $rsm, $result, array $hints = []); /** * @param \Doctrine\ORM\Cache\QueryCacheKey $key @@ -53,7 +53,7 @@ public function put(QueryCacheKey $key, ResultSetMapping $rsm, $result, array $h * * @return array|null */ - public function get(QueryCacheKey $key, ResultSetMapping $rsm, array $hints = array()); + public function get(QueryCacheKey $key, ResultSetMapping $rsm, array $hints = []); /** * @return \Doctrine\ORM\Cache\Region diff --git a/lib/Doctrine/ORM/Cache/QueryCacheEntry.php b/lib/Doctrine/ORM/Cache/QueryCacheEntry.php index 74e4cdda561..b6af393fde1 100644 --- a/lib/Doctrine/ORM/Cache/QueryCacheEntry.php +++ b/lib/Doctrine/ORM/Cache/QueryCacheEntry.php @@ -38,18 +38,18 @@ class QueryCacheEntry implements CacheEntry /** * READ-ONLY: Public only for performance reasons, it should be considered immutable. * - * @var integer Time creation of this cache entry + * @var float Time creation of this cache entry */ public $time; /** - * @param array $result - * @param integer $time + * @param array $result + * @param float $time */ public function __construct($result, $time = null) { $this->result = $result; - $this->time = $time ?: time(); + $this->time = $time ?: microtime(true); } /** diff --git a/lib/Doctrine/ORM/Cache/QueryCacheKey.php b/lib/Doctrine/ORM/Cache/QueryCacheKey.php index 9a7d2b7bcc8..0e072a36fc0 100644 --- a/lib/Doctrine/ORM/Cache/QueryCacheKey.php +++ b/lib/Doctrine/ORM/Cache/QueryCacheKey.php @@ -45,14 +45,27 @@ class QueryCacheKey extends CacheKey public $cacheMode; /** - * @param string $hash Result cache id - * @param integer $lifetime Query lifetime - * @param integer $cacheMode Query cache mode + * READ-ONLY: Public only for performance reasons, it should be considered immutable. + * + * @var TimestampCacheKey|null + */ + public $timestampKey; + + /** + * @param string $hash Result cache id + * @param integer $lifetime Query lifetime + * @param int $cacheMode Query cache mode + * @param TimestampCacheKey|null $timestampKey */ - public function __construct($hash, $lifetime = 0, $cacheMode = Cache::MODE_NORMAL) - { - $this->hash = $hash; - $this->lifetime = $lifetime; - $this->cacheMode = $cacheMode; + public function __construct( + $hash, + $lifetime = 0, + $cacheMode = Cache::MODE_NORMAL, + TimestampCacheKey $timestampKey = null + ) { + $this->hash = $hash; + $this->lifetime = $lifetime; + $this->cacheMode = $cacheMode; + $this->timestampKey = $timestampKey; } } diff --git a/lib/Doctrine/ORM/Cache/Region/DefaultMultiGetRegion.php b/lib/Doctrine/ORM/Cache/Region/DefaultMultiGetRegion.php index 7ecf7331116..7b5f28ecf33 100644 --- a/lib/Doctrine/ORM/Cache/Region/DefaultMultiGetRegion.php +++ b/lib/Doctrine/ORM/Cache/Region/DefaultMultiGetRegion.php @@ -21,7 +21,7 @@ namespace Doctrine\ORM\Cache\Region; use Doctrine\Common\Cache\MultiGetCache; -use Doctrine\ORM\Cache\Region; +use Doctrine\ORM\Cache\CacheEntry; use Doctrine\ORM\Cache\CollectionCacheEntry; /** @@ -56,7 +56,7 @@ public function __construct($name, MultiGetCache $cache, $lifetime = 0) */ public function getMultiple(CollectionCacheEntry $collection) { - $keysToRetrieve = array(); + $keysToRetrieve = []; foreach ($collection->identifiers as $index => $key) { $keysToRetrieve[$index] = $this->getCacheEntryKey($key); @@ -67,8 +67,13 @@ public function getMultiple(CollectionCacheEntry $collection) return null; } - $returnableItems = array(); + $returnableItems = []; + foreach ($keysToRetrieve as $index => $key) { + if (! $items[$key] instanceof CacheEntry) { + return null; + } + $returnableItems[$index] = $items[$key]; } diff --git a/lib/Doctrine/ORM/Cache/Region/DefaultRegion.php b/lib/Doctrine/ORM/Cache/Region/DefaultRegion.php index 3f214d0b0e9..ab069cefb52 100644 --- a/lib/Doctrine/ORM/Cache/Region/DefaultRegion.php +++ b/lib/Doctrine/ORM/Cache/Region/DefaultRegion.php @@ -94,7 +94,13 @@ public function contains(CacheKey $key) */ public function get(CacheKey $key) { - return $this->cache->fetch($this->getCacheEntryKey($key)) ?: null; + $entry = $this->cache->fetch($this->getCacheEntryKey($key)); + + if (! $entry instanceof CacheEntry) { + return null; + } + + return $entry; } /** @@ -102,13 +108,13 @@ public function get(CacheKey $key) */ public function getMultiple(CollectionCacheEntry $collection) { - $result = array(); + $result = []; foreach ($collection->identifiers as $key) { $entryKey = $this->getCacheEntryKey($key); $entryValue = $this->cache->fetch($entryKey); - if ($entryValue === false) { + if (! $entryValue instanceof CacheEntry) { return null; } diff --git a/lib/Doctrine/ORM/Cache/RegionsConfiguration.php b/lib/Doctrine/ORM/Cache/RegionsConfiguration.php index 0d060636cf1..d79c5b1af28 100644 --- a/lib/Doctrine/ORM/Cache/RegionsConfiguration.php +++ b/lib/Doctrine/ORM/Cache/RegionsConfiguration.php @@ -31,12 +31,12 @@ class RegionsConfiguration /** * @var array */ - private $lifetimes = array(); + private $lifetimes = []; /** * @var array */ - private $lockLifetimes = array(); + private $lockLifetimes = []; /** * @var integer diff --git a/lib/Doctrine/ORM/Cache/TimestampQueryCacheValidator.php b/lib/Doctrine/ORM/Cache/TimestampQueryCacheValidator.php index 4e504e4f8da..c6404d3b25d 100644 --- a/lib/Doctrine/ORM/Cache/TimestampQueryCacheValidator.php +++ b/lib/Doctrine/ORM/Cache/TimestampQueryCacheValidator.php @@ -26,15 +26,49 @@ */ class TimestampQueryCacheValidator implements QueryCacheValidator { + /** + * @var TimestampRegion + */ + private $timestampRegion; + + /** + * @param TimestampRegion $timestampRegion + */ + public function __construct(TimestampRegion $timestampRegion) + { + $this->timestampRegion = $timestampRegion; + } + /** * {@inheritdoc} */ public function isValid(QueryCacheKey $key, QueryCacheEntry $entry) { + if ($this->regionUpdated($key, $entry)) { + return false; + } + if ($key->lifetime == 0) { return true; } - return ($entry->time + $key->lifetime) > time(); + return ($entry->time + $key->lifetime) > microtime(true); + } + + /** + * @param QueryCacheKey $key + * @param QueryCacheEntry $entry + * + * @return bool + */ + private function regionUpdated(QueryCacheKey $key, QueryCacheEntry $entry) + { + if ($key->timestampKey === null) { + return false; + } + + $timestamp = $this->timestampRegion->get($key->timestampKey); + + return $timestamp && $timestamp->time > $entry->time; } } diff --git a/lib/Doctrine/ORM/Configuration.php b/lib/Doctrine/ORM/Configuration.php index 872050cb084..c036d67fa5f 100644 --- a/lib/Doctrine/ORM/Configuration.php +++ b/lib/Doctrine/ORM/Configuration.php @@ -25,9 +25,11 @@ use Doctrine\Common\Annotations\SimpleAnnotationReader; use Doctrine\Common\Cache\ArrayCache; use Doctrine\Common\Cache\Cache as CacheDriver; +use Doctrine\Common\Persistence\Mapping\Driver\MappingDriver; +use Doctrine\Common\Persistence\ObjectRepository; use Doctrine\Common\Proxy\AbstractProxyFactory; use Doctrine\ORM\Cache\CacheConfiguration; -use Doctrine\Common\Persistence\Mapping\Driver\MappingDriver; +use Doctrine\ORM\Mapping\ClassMetadataFactory; use Doctrine\ORM\Mapping\DefaultEntityListenerResolver; use Doctrine\ORM\Mapping\DefaultNamingStrategy; use Doctrine\ORM\Mapping\DefaultQuoteStrategy; @@ -68,6 +70,9 @@ public function setProxyDir($dir) * Gets the directory where Doctrine generates any necessary proxy class files. * * @return string|null + * + * @deprecated 2.7 We're switch to `ocramius/proxy-manager` and this method isn't applicable any longer + * @see https://github.com/Ocramius/ProxyManager */ public function getProxyDir() { @@ -80,6 +85,9 @@ public function getProxyDir() * Gets the strategy for automatically generating proxy classes. * * @return int Possible values are constants of Doctrine\Common\Proxy\AbstractProxyFactory. + * + * @deprecated 2.7 We're switch to `ocramius/proxy-manager` and this method isn't applicable any longer + * @see https://github.com/Ocramius/ProxyManager */ public function getAutoGenerateProxyClasses() { @@ -105,6 +113,9 @@ public function setAutoGenerateProxyClasses($autoGenerate) * Gets the namespace where proxy classes reside. * * @return string|null + * + * @deprecated 2.7 We're switch to `ocramius/proxy-manager` and this method isn't applicable any longer + * @see https://github.com/Ocramius/ProxyManager */ public function getProxyNamespace() { @@ -149,7 +160,7 @@ public function setMetadataDriverImpl(MappingDriver $driverImpl) * * @return AnnotationDriver */ - public function newDefaultAnnotationDriver($paths = array(), $useSimpleAnnotationReader = true) + public function newDefaultAnnotationDriver($paths = [], $useSimpleAnnotationReader = true) { AnnotationRegistry::registerFile(__DIR__ . '/Mapping/Driver/DoctrineAnnotations.php'); @@ -349,7 +360,7 @@ public function getNamedQuery($name) */ public function addNamedNativeQuery($name, $sql, Query\ResultSetMapping $rsm) { - $this->_attributes['namedNativeQueries'][$name] = array($sql, $rsm); + $this->_attributes['namedNativeQueries'][$name] = [$sql, $rsm]; } /** @@ -418,15 +429,9 @@ public function ensureProductionSettings() * @param string|callable $className Class name or a callable that returns the function. * * @return void - * - * @throws ORMException */ public function addCustomStringFunction($name, $className) { - if (Query\Parser::isInternalFunction($name)) { - throw ORMException::overwriteInternalDQLFunctionNotAllowed($name); - } - $this->_attributes['customStringFunctions'][strtolower($name)] = $className; } @@ -476,15 +481,9 @@ public function setCustomStringFunctions(array $functions) * @param string|callable $className Class name or a callable that returns the function. * * @return void - * - * @throws ORMException */ public function addCustomNumericFunction($name, $className) { - if (Query\Parser::isInternalFunction($name)) { - throw ORMException::overwriteInternalDQLFunctionNotAllowed($name); - } - $this->_attributes['customNumericFunctions'][strtolower($name)] = $className; } @@ -534,15 +533,9 @@ public function setCustomNumericFunctions(array $functions) * @param string|callable $className Class name or a callable that returns the function. * * @return void - * - * @throws ORMException */ public function addCustomDatetimeFunction($name, $className) { - if (Query\Parser::isInternalFunction($name)) { - throw ORMException::overwriteInternalDQLFunctionNotAllowed($name); - } - $this->_attributes['customDatetimeFunctions'][strtolower($name)] = $className; } @@ -590,7 +583,7 @@ public function setCustomDatetimeFunctions(array $functions) */ public function setCustomHydrationModes($modes) { - $this->_attributes['customHydrationModes'] = array(); + $this->_attributes['customHydrationModes'] = []; foreach ($modes as $modeName => $hydrator) { $this->addCustomHydrationMode($modeName, $hydrator); @@ -642,7 +635,7 @@ public function setClassMetadataFactoryName($cmfName) public function getClassMetadataFactoryName() { if ( ! isset($this->_attributes['classMetadataFactoryName'])) { - $this->_attributes['classMetadataFactoryName'] = 'Doctrine\ORM\Mapping\ClassMetadataFactory'; + $this->_attributes['classMetadataFactoryName'] = ClassMetadataFactory::class; } return $this->_attributes['classMetadataFactoryName']; @@ -689,7 +682,7 @@ public function setDefaultRepositoryClassName($className) { $reflectionClass = new \ReflectionClass($className); - if ( ! $reflectionClass->implementsInterface('Doctrine\Common\Persistence\ObjectRepository')) { + if ( ! $reflectionClass->implementsInterface(ObjectRepository::class)) { throw ORMException::invalidEntityRepository($className); } @@ -707,7 +700,7 @@ public function getDefaultRepositoryClassName() { return isset($this->_attributes['defaultRepositoryClassName']) ? $this->_attributes['defaultRepositoryClassName'] - : 'Doctrine\ORM\EntityRepository'; + : EntityRepository::class; } /** @@ -881,7 +874,7 @@ public function getSecondLevelCacheConfiguration() */ public function getDefaultQueryHints() { - return isset($this->_attributes['defaultQueryHints']) ? $this->_attributes['defaultQueryHints'] : array(); + return isset($this->_attributes['defaultQueryHints']) ? $this->_attributes['defaultQueryHints'] : []; } /** diff --git a/lib/Doctrine/ORM/EntityManager.php b/lib/Doctrine/ORM/EntityManager.php index 4de4932bcfc..0752f0e897e 100644 --- a/lib/Doctrine/ORM/EntityManager.php +++ b/lib/Doctrine/ORM/EntityManager.php @@ -19,15 +19,18 @@ namespace Doctrine\ORM; -use Exception; use Doctrine\Common\EventManager; use Doctrine\DBAL\Connection; use Doctrine\DBAL\DriverManager; use Doctrine\DBAL\LockMode; +use Doctrine\ORM\Mapping\ClassMetadata; use Doctrine\ORM\Query\ResultSetMapping; use Doctrine\ORM\Proxy\ProxyFactory; use Doctrine\ORM\Query\FilterCollection; use Doctrine\Common\Util\ClassUtils; +use Throwable; +use const E_USER_DEPRECATED; +use function trigger_error; /** * The EntityManager is the central access point to ORM functionality. @@ -237,7 +240,7 @@ public function transactional($func) $this->conn->commit(); return $return ?: true; - } catch (Exception $e) { + } catch (Throwable $e) { $this->close(); $this->conn->rollBack(); @@ -353,6 +356,13 @@ public function createQueryBuilder() */ public function flush($entity = null) { + if ($entity !== null) { + @trigger_error( + 'Calling ' . __METHOD__ . '() with any arguments to flush specific entities is deprecated and will not be supported in Doctrine ORM 3.0.', + E_USER_DEPRECATED + ); + } + $this->errorIfClosed(); $this->unitOfWork->commit($entity); @@ -380,12 +390,16 @@ public function find($entityName, $id, $lockMode = null, $lockVersion = null) { $class = $this->metadataFactory->getMetadataFor(ltrim($entityName, '\\')); + if ($lockMode !== null) { + $this->checkLockRequirements($lockMode, $class); + } + if ( ! is_array($id)) { if ($class->isIdentifierComposite) { throw ORMInvalidArgumentException::invalidCompositeIdentifier(); } - $id = array($class->identifier[0] => $id); + $id = [$class->identifier[0] => $id]; } foreach ($id as $i => $value) { @@ -398,7 +412,7 @@ public function find($entityName, $id, $lockMode = null, $lockVersion = null) } } - $sortedId = array(); + $sortedId = []; foreach ($class->identifier as $identifier) { if ( ! isset($id[$identifier])) { @@ -441,10 +455,6 @@ public function find($entityName, $id, $lockMode = null, $lockVersion = null) switch (true) { case LockMode::OPTIMISTIC === $lockMode: - if ( ! $class->isVersioned) { - throw OptimisticLockException::notVersioned($class->name); - } - $entity = $persister->load($sortedId); $unitOfWork->lock($entity, $lockMode, $lockVersion); @@ -453,11 +463,7 @@ public function find($entityName, $id, $lockMode = null, $lockVersion = null) case LockMode::PESSIMISTIC_READ === $lockMode: case LockMode::PESSIMISTIC_WRITE === $lockMode: - if ( ! $this->getConnection()->isTransactionActive()) { - throw TransactionRequiredException::transactionRequired(); - } - - return $persister->load($sortedId, null, null, array(), $lockMode); + return $persister->load($sortedId, null, null, [], $lockMode); default: return $persister->loadById($sortedId); @@ -472,10 +478,10 @@ public function getReference($entityName, $id) $class = $this->metadataFactory->getMetadataFor(ltrim($entityName, '\\')); if ( ! is_array($id)) { - $id = array($class->identifier[0] => $id); + $id = [$class->identifier[0] => $id]; } - $sortedId = array(); + $sortedId = []; foreach ($class->identifier as $identifier) { if ( ! isset($id[$identifier])) { @@ -501,7 +507,7 @@ public function getReference($entityName, $id) $entity = $this->proxyFactory->getProxy($class->name, $sortedId); - $this->unitOfWork->registerManaged($entity, $sortedId, array()); + $this->unitOfWork->registerManaged($entity, $sortedId, []); return $entity; } @@ -519,14 +525,14 @@ public function getPartialReference($entityName, $identifier) } if ( ! is_array($identifier)) { - $identifier = array($class->identifier[0] => $identifier); + $identifier = [$class->identifier[0] => $identifier]; } $entity = $class->newInstance(); $class->setIdentifierValues($entity, $identifier); - $this->unitOfWork->registerManaged($entity, $identifier, array()); + $this->unitOfWork->registerManaged($entity, $identifier, []); $this->unitOfWork->markReadOnly($entity); return $entity; @@ -539,10 +545,29 @@ public function getPartialReference($entityName, $identifier) * @param string|null $entityName if given, only entities of this type will get detached * * @return void + * + * @throws ORMInvalidArgumentException if a non-null non-string value is given + * @throws \Doctrine\Common\Persistence\Mapping\MappingException if a $entityName is given, but that entity is not + * found in the mappings */ public function clear($entityName = null) { - $this->unitOfWork->clear($entityName); + if (null !== $entityName && ! is_string($entityName)) { + throw ORMInvalidArgumentException::invalidEntityName($entityName); + } + + if ($entityName !== null) { + @trigger_error( + 'Calling ' . __METHOD__ . '() with any arguments to clear specific entities is deprecated and will not be supported in Doctrine ORM 3.0.', + E_USER_DEPRECATED + ); + } + + $this->unitOfWork->clear( + null === $entityName + ? null + : $this->metadataFactory->getMetadataFor($entityName)->getName() + ); } /** @@ -640,9 +665,13 @@ public function refresh($entity) * @return void * * @throws ORMInvalidArgumentException + * + * @deprecated 2.7 This method is being removed from the ORM and won't have any replacement */ public function detach($entity) { + @trigger_error('Method ' . __METHOD__ . '() is deprecated and will be removed in Doctrine ORM 3.0.', E_USER_DEPRECATED); + if ( ! is_object($entity)) { throw ORMInvalidArgumentException::invalidObject('EntityManager#detach()', $entity); } @@ -661,9 +690,13 @@ public function detach($entity) * * @throws ORMInvalidArgumentException * @throws ORMException + * + * @deprecated 2.7 This method is being removed from the ORM and won't have any replacement */ public function merge($entity) { + @trigger_error('Method ' . __METHOD__ . '() is deprecated and will be removed in Doctrine ORM 3.0.', E_USER_DEPRECATED); + if ( ! is_object($entity)) { throw ORMInvalidArgumentException::invalidObject('EntityManager#merge()', $entity); } @@ -675,12 +708,11 @@ public function merge($entity) /** * {@inheritDoc} - * - * @todo Implementation need. This is necessary since $e2 = clone $e1; throws an E_FATAL when access anything on $e: - * Fatal error: Maximum function nesting level of '100' reached, aborting! */ public function copy($entity, $deep = false) { + @trigger_error('Method ' . __METHOD__ . '() is deprecated and will be removed in Doctrine ORM 3.0.', E_USER_DEPRECATED); + throw new \BadMethodCallException("Not implemented."); } @@ -697,7 +729,7 @@ public function lock($entity, $lockMode, $lockVersion = null) * * @param string $entityName The name of the entity. * - * @return \Doctrine\ORM\EntityRepository The repository class. + * @return \Doctrine\Common\Persistence\ObjectRepository|\Doctrine\ORM\EntityRepository The repository class. */ public function getRepository($entityName) { @@ -860,7 +892,13 @@ protected static function createConnection($connection, Configuration $config, E } if ( ! $connection instanceof Connection) { - throw new \InvalidArgumentException("Invalid argument: " . $connection); + throw new \InvalidArgumentException( + sprintf( + 'Invalid $connection argument of type %s given%s.', + is_object($connection) ? get_class($connection) : gettype($connection), + is_object($connection) ? '' : ': "' . $connection . '"' + ) + ); } if ($eventManager !== null && $connection->getEventManager() !== $eventManager) { @@ -897,4 +935,26 @@ public function hasFilters() { return null !== $this->filterCollection; } + + /** + * @param int $lockMode + * @param ClassMetadata $class + * @throws OptimisticLockException + * @throws TransactionRequiredException + */ + private function checkLockRequirements(int $lockMode, ClassMetadata $class): void + { + switch ($lockMode) { + case LockMode::OPTIMISTIC: + if (!$class->isVersioned) { + throw OptimisticLockException::notVersioned($class->name); + } + break; + case LockMode::PESSIMISTIC_READ: + case LockMode::PESSIMISTIC_WRITE: + if (!$this->getConnection()->isTransactionActive()) { + throw TransactionRequiredException::transactionRequired(); + } + } + } } diff --git a/lib/Doctrine/ORM/EntityManagerInterface.php b/lib/Doctrine/ORM/EntityManagerInterface.php index 016cfd4ec8b..c96aa6720fe 100644 --- a/lib/Doctrine/ORM/EntityManagerInterface.php +++ b/lib/Doctrine/ORM/EntityManagerInterface.php @@ -7,9 +7,9 @@ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION); HOWEVER CAUSED AND ON ANY + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE); ARISING IN ANY WAY OUT OF THE USE + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * This software consists of voluntary contributions made by many individuals @@ -150,7 +150,7 @@ public function createQueryBuilder(); * @param string $entityName The name of the entity type. * @param mixed $id The entity identifier. * - * @return object The entity reference. + * @return object|null The entity reference. * * @throws ORMException */ @@ -174,7 +174,7 @@ public function getReference($entityName, $id); * @param string $entityName The name of the entity type. * @param mixed $identifier The entity identifier. * - * @return object The (partial) entity reference. + * @return object|null The (partial) entity reference. */ public function getPartialReference($entityName, $identifier); @@ -190,6 +190,8 @@ public function close(); /** * Creates a copy of the given entity. Can create a shallow or a deep copy. * + * @deprecated 2.7 This method is being removed from the ORM and won't have any replacement + * * @param object $entity The entity to copy. * @param boolean $deep FALSE for a shallow copy, TRUE for a deep copy. * @@ -249,7 +251,7 @@ public function getUnitOfWork(); * * @deprecated * - * @param int $hydrationMode + * @param string|int $hydrationMode * * @return \Doctrine\ORM\Internal\Hydration\AbstractHydrator */ @@ -258,7 +260,7 @@ public function getHydrator($hydrationMode); /** * Create a new instance for the given hydration mode. * - * @param int $hydrationMode + * @param string|int $hydrationMode * * @return \Doctrine\ORM\Internal\Hydration\AbstractHydrator * diff --git a/lib/Doctrine/ORM/EntityNotFoundException.php b/lib/Doctrine/ORM/EntityNotFoundException.php index afe2f22426d..5b21e15c276 100644 --- a/lib/Doctrine/ORM/EntityNotFoundException.php +++ b/lib/Doctrine/ORM/EntityNotFoundException.php @@ -37,7 +37,7 @@ class EntityNotFoundException extends ORMException */ public static function fromClassNameAndIdentifier($className, array $id) { - $ids = array(); + $ids = []; foreach ($id as $key => $value) { $ids[] = $key . '(' . $value . ')'; diff --git a/lib/Doctrine/ORM/EntityRepository.php b/lib/Doctrine/ORM/EntityRepository.php index 08b2ff19344..8a7c8143337 100644 --- a/lib/Doctrine/ORM/EntityRepository.php +++ b/lib/Doctrine/ORM/EntityRepository.php @@ -19,6 +19,7 @@ namespace Doctrine\ORM; +use Doctrine\Common\Inflector\Inflector; use Doctrine\ORM\Query\ResultSetMappingBuilder; use Doctrine\Common\Persistence\ObjectRepository; use Doctrine\Common\Collections\Selectable; @@ -56,9 +57,6 @@ class EntityRepository implements ObjectRepository, Selectable /** * Initializes a new EntityRepository. - * - * @param EntityManager $em The EntityManager to use. - * @param Mapping\ClassMetadata $class The class descriptor. */ public function __construct(EntityManagerInterface $em, Mapping\ClassMetadata $class) { @@ -160,7 +158,7 @@ public function find($id, $lockMode = null, $lockVersion = null) */ public function findAll() { - return $this->findBy(array()); + return $this->findBy([]); } /** @@ -192,68 +190,52 @@ public function findOneBy(array $criteria, array $orderBy = null) { $persister = $this->_em->getUnitOfWork()->getEntityPersister($this->_entityName); - return $persister->load($criteria, null, null, array(), null, 1, $orderBy); + return $persister->load($criteria, null, null, [], null, 1, $orderBy); } /** - * Adds support for magic finders. + * Counts entities by a set of criteria. + * + * @todo Add this method to `ObjectRepository` interface in the next major release + * + * @param array $criteria + * + * @return int The cardinality of the objects that match the given criteria. + */ + public function count(array $criteria) + { + return $this->_em->getUnitOfWork()->getEntityPersister($this->_entityName)->count($criteria); + } + + /** + * Adds support for magic method calls. * * @param string $method * @param array $arguments * - * @return array|object The found entity/entities. + * @return mixed The returned value from the resolved method. * * @throws ORMException - * @throws \BadMethodCallException If the method called is an invalid find* method - * or no find* method at all and therefore an invalid - * method call. + * @throws \BadMethodCallException If the method called is invalid */ public function __call($method, $arguments) { - switch (true) { - case (0 === strpos($method, 'findBy')): - $by = substr($method, 6); - $method = 'findBy'; - break; - - case (0 === strpos($method, 'findOneBy')): - $by = substr($method, 9); - $method = 'findOneBy'; - break; - - default: - throw new \BadMethodCallException( - "Undefined method '$method'. The method name must start with ". - "either findBy or findOneBy!" - ); + if (0 === strpos($method, 'findBy')) { + return $this->resolveMagicCall('findBy', substr($method, 6), $arguments); } - if (empty($arguments)) { - throw ORMException::findByRequiresParameter($method . $by); + if (0 === strpos($method, 'findOneBy')) { + return $this->resolveMagicCall('findOneBy', substr($method, 9), $arguments); } - $fieldName = lcfirst(\Doctrine\Common\Util\Inflector::classify($by)); - - if ($this->_class->hasField($fieldName) || $this->_class->hasAssociation($fieldName)) { - switch (count($arguments)) { - case 1: - return $this->$method(array($fieldName => $arguments[0])); - - case 2: - return $this->$method(array($fieldName => $arguments[0]), $arguments[1]); - - case 3: - return $this->$method(array($fieldName => $arguments[0]), $arguments[1], $arguments[2]); - - case 4: - return $this->$method(array($fieldName => $arguments[0]), $arguments[1], $arguments[2], $arguments[3]); - - default: - // Do nothing - } + if (0 === strpos($method, 'countBy')) { + return $this->resolveMagicCall('count', substr($method, 7), $arguments); } - throw ORMException::invalidFindByCall($this->_entityName, $fieldName, $method.$by); + throw new \BadMethodCallException( + "Undefined method '$method'. The method name must start with ". + "either findBy, findOneBy or countBy!" + ); } /** @@ -302,4 +284,30 @@ public function matching(Criteria $criteria) return new LazyCriteriaCollection($persister, $criteria); } + + /** + * Resolves a magic method call to the proper existent method at `EntityRepository`. + * + * @param string $method The method to call + * @param string $by The property name used as condition + * @param array $arguments The arguments to pass at method call + * + * @throws ORMException If the method called is invalid or the requested field/association does not exist + * + * @return mixed + */ + private function resolveMagicCall($method, $by, array $arguments) + { + if (! $arguments) { + throw ORMException::findByRequiresParameter($method . $by); + } + + $fieldName = lcfirst(Inflector::classify($by)); + + if (! ($this->_class->hasField($fieldName) || $this->_class->hasAssociation($fieldName))) { + throw ORMException::invalidMagicCall($this->_entityName, $fieldName, $method . $by); + } + + return $this->$method([$fieldName => $arguments[0]], ...array_slice($arguments, 1)); + } } diff --git a/lib/Doctrine/ORM/Event/LifecycleEventArgs.php b/lib/Doctrine/ORM/Event/LifecycleEventArgs.php index 9a5c8cf0624..c7eb80bf61f 100644 --- a/lib/Doctrine/ORM/Event/LifecycleEventArgs.php +++ b/lib/Doctrine/ORM/Event/LifecycleEventArgs.php @@ -15,7 +15,7 @@ * This software consists of voluntary contributions made by many individuals * and is licensed under the MIT license. For more information, see * . -*/ + */ namespace Doctrine\ORM\Event; diff --git a/lib/Doctrine/ORM/Id/AbstractIdGenerator.php b/lib/Doctrine/ORM/Id/AbstractIdGenerator.php index dada71e43ad..9e2e2262514 100644 --- a/lib/Doctrine/ORM/Id/AbstractIdGenerator.php +++ b/lib/Doctrine/ORM/Id/AbstractIdGenerator.php @@ -27,7 +27,7 @@ abstract class AbstractIdGenerator * Generates an identifier for an entity. * * @param EntityManager $em - * @param \Doctrine\ORM\Mapping\Entity $entity + * @param object|null $entity * @return mixed */ abstract public function generate(EntityManager $em, $entity); diff --git a/lib/Doctrine/ORM/Id/AssignedGenerator.php b/lib/Doctrine/ORM/Id/AssignedGenerator.php index 447dbd6d597..691eaee4221 100644 --- a/lib/Doctrine/ORM/Id/AssignedGenerator.php +++ b/lib/Doctrine/ORM/Id/AssignedGenerator.php @@ -44,7 +44,7 @@ public function generate(EntityManager $em, $entity) { $class = $em->getClassMetadata(get_class($entity)); $idFields = $class->getIdentifierFieldNames(); - $identifier = array(); + $identifier = []; foreach ($idFields as $idField) { $value = $class->getFieldValue($entity, $idField); diff --git a/lib/Doctrine/ORM/Id/SequenceGenerator.php b/lib/Doctrine/ORM/Id/SequenceGenerator.php index 1f3c9541b6c..9d8e9eb75aa 100644 --- a/lib/Doctrine/ORM/Id/SequenceGenerator.php +++ b/lib/Doctrine/ORM/Id/SequenceGenerator.php @@ -76,7 +76,8 @@ public function generate(EntityManager $em, $entity) $conn = $em->getConnection(); $sql = $conn->getDatabasePlatform()->getSequenceNextValSQL($this->_sequenceName); - $this->_nextValue = (int) $conn->fetchColumn($sql); + // Using `query` to force usage of the master server in MasterSlaveConnection + $this->_nextValue = (int) $conn->query($sql)->fetchColumn(); $this->_maxValue = $this->_nextValue + $this->_allocationSize; } @@ -108,10 +109,12 @@ public function getNextValue() */ public function serialize() { - return serialize(array( + return serialize( + [ 'allocationSize' => $this->_allocationSize, 'sequenceName' => $this->_sequenceName - )); + ] + ); } /** diff --git a/lib/Doctrine/ORM/Id/TableGenerator.php b/lib/Doctrine/ORM/Id/TableGenerator.php index abf3ab8acd3..02385f51158 100644 --- a/lib/Doctrine/ORM/Id/TableGenerator.php +++ b/lib/Doctrine/ORM/Id/TableGenerator.php @@ -92,7 +92,7 @@ public function generate( $this->_tableName, $this->_sequenceName, $this->_allocationSize ); - if ($conn->executeUpdate($updateSql, array(1 => $currentLevel, 2 => $currentLevel+1)) !== 1) { + if ($conn->executeUpdate($updateSql, [1 => $currentLevel, 2 => $currentLevel+1]) !== 1) { // no affected rows, concurrency issue, throw exception } } else { diff --git a/lib/Doctrine/ORM/Internal/CommitOrderCalculator.php b/lib/Doctrine/ORM/Internal/CommitOrderCalculator.php index e1331da4750..30b9caa8206 100644 --- a/lib/Doctrine/ORM/Internal/CommitOrderCalculator.php +++ b/lib/Doctrine/ORM/Internal/CommitOrderCalculator.php @@ -52,16 +52,16 @@ class CommitOrderCalculator * - dependencyList (array) * Map of node dependencies defined as hashes. * - * @var array + * @var array<\stdClass> */ - private $nodeList = array(); + private $nodeList = []; /** * Volatile variable holding calculated nodes during sorting process. * * @var array */ - private $sortedNodeList = array(); + private $sortedNodeList = []; /** * Checks for node (vertex) existence in graph. @@ -90,7 +90,7 @@ public function addNode($hash, $node) $vertex->hash = $hash; $vertex->state = self::NOT_VISITED; $vertex->value = $node; - $vertex->dependencyList = array(); + $vertex->dependencyList = []; $this->nodeList[$hash] = $vertex; } @@ -136,8 +136,8 @@ public function sort() $sortedList = $this->sortedNodeList; - $this->nodeList = array(); - $this->sortedNodeList = array(); + $this->nodeList = []; + $this->sortedNodeList = []; return array_reverse($sortedList); } @@ -162,8 +162,19 @@ private function visit($vertex) break; case self::IN_PROGRESS: - if (isset($adjacentVertex->dependencyList[$vertex->hash]) && + if (isset($adjacentVertex->dependencyList[$vertex->hash]) && $adjacentVertex->dependencyList[$vertex->hash]->weight < $edge->weight) { + + // If we have some non-visited dependencies in the in-progress dependency, we + // need to visit them before adding the node. + foreach ($adjacentVertex->dependencyList as $adjacentEdge) { + $adjacentEdgeVertex = $this->nodeList[$adjacentEdge->to]; + + if ($adjacentEdgeVertex->state === self::NOT_VISITED) { + $this->visit($adjacentEdgeVertex); + } + } + $adjacentVertex->state = self::VISITED; $this->sortedNodeList[] = $adjacentVertex->value; diff --git a/lib/Doctrine/ORM/Internal/Hydration/AbstractHydrator.php b/lib/Doctrine/ORM/Internal/Hydration/AbstractHydrator.php index ff142fc3589..8a9c0f4d7e4 100644 --- a/lib/Doctrine/ORM/Internal/Hydration/AbstractHydrator.php +++ b/lib/Doctrine/ORM/Internal/Hydration/AbstractHydrator.php @@ -23,7 +23,10 @@ use Doctrine\ORM\EntityManagerInterface; use Doctrine\ORM\Events; use Doctrine\ORM\Mapping\ClassMetadata; +use Doctrine\ORM\Tools\Pagination\LimitSubqueryWalker; use PDO; +use function array_map; +use function in_array; /** * Base class for all hydrators. A hydrator is a class that provides some form @@ -69,14 +72,14 @@ abstract class AbstractHydrator * * @var array */ - protected $_metadataCache = array(); + protected $_metadataCache = []; /** * The cache used during row-by-row hydration. * * @var array */ - protected $_cache = array(); + protected $_cache = []; /** * The statement that provides the data to hydrate. @@ -113,7 +116,7 @@ public function __construct(EntityManagerInterface $em) * * @return IterableResult */ - public function iterate($stmt, $resultSetMapping, array $hints = array()) + public function iterate($stmt, $resultSetMapping, array $hints = []) { $this->_stmt = $stmt; $this->_rsm = $resultSetMapping; @@ -121,7 +124,7 @@ public function iterate($stmt, $resultSetMapping, array $hints = array()) $evm = $this->_em->getEventManager(); - $evm->addEventListener(array(Events::onClear), $this); + $evm->addEventListener([Events::onClear], $this); $this->prepare(); @@ -137,12 +140,14 @@ public function iterate($stmt, $resultSetMapping, array $hints = array()) * * @return array */ - public function hydrateAll($stmt, $resultSetMapping, array $hints = array()) + public function hydrateAll($stmt, $resultSetMapping, array $hints = []) { $this->_stmt = $stmt; $this->_rsm = $resultSetMapping; $this->_hints = $hints; + $this->_em->getEventManager()->addEventListener([Events::onClear], $this); + $this->prepare(); $result = $this->hydrateAllData(); @@ -168,7 +173,7 @@ public function hydrateRow() return false; } - $result = array(); + $result = []; $this->hydrateRowData($row, $result); @@ -209,8 +214,13 @@ protected function cleanup() $this->_stmt = null; $this->_rsm = null; - $this->_cache = array(); - $this->_metadataCache = array(); + $this->_cache = []; + $this->_metadataCache = []; + + $this + ->_em + ->getEventManager() + ->removeEventListener([Events::onClear], $this); } /** @@ -255,7 +265,7 @@ abstract protected function hydrateAllData(); */ protected function gatherRowData(array $data, array &$id, array &$nonemptyComponents) { - $rowData = array('data' => array()); + $rowData = ['data' => []]; foreach ($data as $key => $value) { if (($cacheKeyInfo = $this->hydrateColumnInfo($key)) === null) { @@ -287,6 +297,14 @@ protected function gatherRowData(array $data, array &$id, array &$nonemptyCompon $dqlAlias = $cacheKeyInfo['dqlAlias']; $type = $cacheKeyInfo['type']; + // If there are field name collisions in the child class, then we need + // to only hydrate if we are looking at the correct discriminator value + if (isset($cacheKeyInfo['discriminatorColumn'], $data[$cacheKeyInfo['discriminatorColumn']]) + && ! in_array((string) $data[$cacheKeyInfo['discriminatorColumn']], $cacheKeyInfo['discriminatorValues'], true) + ) { + break; + } + // in an inheritance hierarchy the same field could be defined several times. // We overwrite this value so long we don't have a non-null value, that value we keep. // Per definition it cannot be that a field is defined several times and has several values. @@ -323,7 +341,7 @@ protected function gatherRowData(array $data, array &$id, array &$nonemptyCompon */ protected function gatherScalarRowData(&$data) { - $rowData = array(); + $rowData = []; foreach ($data as $key => $value) { if (($cacheKeyInfo = $this->hydrateColumnInfo($key)) === null) { @@ -334,13 +352,11 @@ protected function gatherScalarRowData(&$data) // WARNING: BC break! We know this is the desired behavior to type convert values, but this // erroneous behavior exists since 2.0 and we're forced to keep compatibility. - if ( ! isset($cacheKeyInfo['isScalar'])) { - $dqlAlias = $cacheKeyInfo['dqlAlias']; - $type = $cacheKeyInfo['type']; - $fieldName = $dqlAlias . '_' . $fieldName; - $value = $type - ? $type->convertToPHPValue($value, $this->_platform) - : $value; + if (! isset($cacheKeyInfo['isScalar'])) { + $type = $cacheKeyInfo['type']; + $value = $type ? $type->convertToPHPValue($value, $this->_platform) : $value; + + $fieldName = $cacheKeyInfo['dqlAlias'] . '_' . $fieldName; } $rowData[$fieldName] = $value; @@ -368,19 +384,34 @@ protected function hydrateColumnInfo($key) $classMetadata = $this->getClassMetadata($this->_rsm->declaringClasses[$key]); $fieldName = $this->_rsm->fieldMappings[$key]; $fieldMapping = $classMetadata->fieldMappings[$fieldName]; - - return $this->_cache[$key] = array( - 'isIdentifier' => in_array($fieldName, $classMetadata->identifier), + $ownerMap = $this->_rsm->columnOwnerMap[$key]; + $columnInfo = [ + 'isIdentifier' => \in_array($fieldName, $classMetadata->identifier, true), 'fieldName' => $fieldName, 'type' => Type::getType($fieldMapping['type']), - 'dqlAlias' => $this->_rsm->columnOwnerMap[$key], - ); + 'dqlAlias' => $ownerMap, + ]; + + // the current discriminator value must be saved in order to disambiguate fields hydration, + // should there be field name collisions + if ($classMetadata->parentClasses && isset($this->_rsm->discriminatorColumns[$ownerMap])) { + return $this->_cache[$key] = \array_merge( + $columnInfo, + [ + 'discriminatorColumn' => $this->_rsm->discriminatorColumns[$ownerMap], + 'discriminatorValue' => $classMetadata->discriminatorValue, + 'discriminatorValues' => $this->getDiscriminatorValues($classMetadata), + ] + ); + } + + return $this->_cache[$key] = $columnInfo; case (isset($this->_rsm->newObjectMappings[$key])): // WARNING: A NEW object is also a scalar, so it must be declared before! $mapping = $this->_rsm->newObjectMappings[$key]; - return $this->_cache[$key] = array( + return $this->_cache[$key] = [ 'isScalar' => true, 'isNewObjectParameter' => true, 'fieldName' => $this->_rsm->scalarMappings[$key], @@ -388,14 +419,20 @@ protected function hydrateColumnInfo($key) 'argIndex' => $mapping['argIndex'], 'objIndex' => $mapping['objIndex'], 'class' => new \ReflectionClass($mapping['className']), - ); + ]; + case isset($this->_rsm->scalarMappings[$key], $this->_hints[LimitSubqueryWalker::FORCE_DBAL_TYPE_CONVERSION]): + return $this->_cache[$key] = [ + 'fieldName' => $this->_rsm->scalarMappings[$key], + 'type' => Type::getType($this->_rsm->typeMappings[$key]), + 'dqlAlias' => '', + ]; case (isset($this->_rsm->scalarMappings[$key])): - return $this->_cache[$key] = array( + return $this->_cache[$key] = [ 'isScalar' => true, 'fieldName' => $this->_rsm->scalarMappings[$key], 'type' => Type::getType($this->_rsm->typeMappings[$key]), - ); + ]; case (isset($this->_rsm->metaMappings[$key])): // Meta column (has meaning in relational schema only, i.e. foreign keys or discriminator columns). @@ -408,13 +445,13 @@ protected function hydrateColumnInfo($key) // Cache metadata fetch $this->getClassMetadata($this->_rsm->aliasMap[$dqlAlias]); - return $this->_cache[$key] = array( + return $this->_cache[$key] = [ 'isIdentifier' => isset($this->_rsm->isIdentifierColumn[$dqlAlias][$key]), 'isMetaColumn' => true, 'fieldName' => $fieldName, 'type' => $type, 'dqlAlias' => $dqlAlias, - ); + ]; } // this column is a left over, maybe from a LIMIT query hack for example in Oracle or DB2 @@ -422,6 +459,23 @@ protected function hydrateColumnInfo($key) return null; } + /** + * @return string[] + */ + private function getDiscriminatorValues(ClassMetadata $classMetadata) : array + { + $values = array_map( + function (string $subClass) : string { + return (string) $this->getClassMetadata($subClass)->discriminatorValue; + }, + $classMetadata->subClasses + ); + + $values[] = (string) $classMetadata->discriminatorValue; + + return $values; + } + /** * Retrieve ClassMetadata associated to entity class name. * @@ -452,7 +506,7 @@ protected function getClassMetadata($className) protected function registerManaged(ClassMetadata $class, $entity, array $data) { if ($class->isIdentifierComposite) { - $id = array(); + $id = []; foreach ($class->identifier as $fieldName) { $id[$fieldName] = isset($class->associationMappings[$fieldName]) @@ -461,11 +515,11 @@ protected function registerManaged(ClassMetadata $class, $entity, array $data) } } else { $fieldName = $class->identifier[0]; - $id = array( + $id = [ $fieldName => isset($class->associationMappings[$fieldName]) ? $data[$class->associationMappings[$fieldName]['joinColumns'][0]['name']] : $data[$fieldName] - ); + ]; } $this->_em->getUnitOfWork()->registerManaged($entity, $id, $data); diff --git a/lib/Doctrine/ORM/Internal/Hydration/ArrayHydrator.php b/lib/Doctrine/ORM/Internal/Hydration/ArrayHydrator.php index f3e4376f757..c26b99be38c 100644 --- a/lib/Doctrine/ORM/Internal/Hydration/ArrayHydrator.php +++ b/lib/Doctrine/ORM/Internal/Hydration/ArrayHydrator.php @@ -35,7 +35,7 @@ class ArrayHydrator extends AbstractHydrator /** * @var array */ - private $_rootAliases = array(); + private $_rootAliases = []; /** * @var bool @@ -45,17 +45,17 @@ class ArrayHydrator extends AbstractHydrator /** * @var array */ - private $_identifierMap = array(); + private $_identifierMap = []; /** * @var array */ - private $_resultPointers = array(); + private $_resultPointers = []; /** * @var array */ - private $_idTemplate = array(); + private $_idTemplate = []; /** * @var int @@ -70,8 +70,8 @@ protected function prepare() $this->_isSimpleQuery = count($this->_rsm->aliasMap) <= 1; foreach ($this->_rsm->aliasMap as $dqlAlias => $className) { - $this->_identifierMap[$dqlAlias] = array(); - $this->_resultPointers[$dqlAlias] = array(); + $this->_identifierMap[$dqlAlias] = []; + $this->_resultPointers[$dqlAlias] = []; $this->_idTemplate[$dqlAlias] = ''; } } @@ -81,7 +81,7 @@ protected function prepare() */ protected function hydrateAllData() { - $result = array(); + $result = []; while ($data = $this->_stmt->fetch(PDO::FETCH_ASSOC)) { $this->hydrateRowData($data, $result); @@ -97,7 +97,7 @@ protected function hydrateRowData(array $row, array &$result) { // 1) Initialize $id = $this->_idTemplate; // initialize the id-memory - $nonemptyComponents = array(); + $nonemptyComponents = []; $rowData = $this->gatherRowData($row, $id, $nonemptyComponents); // 2) Now hydrate the data found in the current row. @@ -138,7 +138,7 @@ protected function hydrateRowData(array $row, array &$result) $oneToOne = false; if ( ! isset($baseElement[$relationAlias])) { - $baseElement[$relationAlias] = array(); + $baseElement[$relationAlias] = []; } if (isset($nonemptyComponents[$dqlAlias])) { @@ -187,7 +187,7 @@ protected function hydrateRowData(array $row, array &$result) // if this row has a NULL value for the root result id then make it a null result. if ( ! isset($nonemptyComponents[$dqlAlias]) ) { $result[] = $this->_rsm->isMixed - ? array($entityKey => null) + ? [$entityKey => null] : null; $resultKey = $this->_resultCounter; @@ -199,7 +199,7 @@ protected function hydrateRowData(array $row, array &$result) // Check for an existing element if ($this->_isSimpleQuery || ! isset($this->_identifierMap[$dqlAlias][$id[$dqlAlias]])) { $element = $this->_rsm->isMixed - ? array($entityKey => $data) + ? [$entityKey => $data] : $data; if (isset($this->_rsm->indexByMap[$dqlAlias])) { diff --git a/lib/Doctrine/ORM/Internal/Hydration/ObjectHydrator.php b/lib/Doctrine/ORM/Internal/Hydration/ObjectHydrator.php index 70d47655dab..5048216cf7b 100644 --- a/lib/Doctrine/ORM/Internal/Hydration/ObjectHydrator.php +++ b/lib/Doctrine/ORM/Internal/Hydration/ObjectHydrator.php @@ -42,17 +42,17 @@ class ObjectHydrator extends AbstractHydrator /** * @var array */ - private $identifierMap = array(); + private $identifierMap = []; /** * @var array */ - private $resultPointers = array(); + private $resultPointers = []; /** * @var array */ - private $idTemplate = array(); + private $idTemplate = []; /** * @var integer @@ -62,17 +62,17 @@ class ObjectHydrator extends AbstractHydrator /** * @var array */ - private $rootAliases = array(); + private $rootAliases = []; /** * @var array */ - private $initializedCollections = array(); + private $initializedCollections = []; /** * @var array */ - private $existingCollections = array(); + private $existingCollections = []; /** * {@inheritdoc} @@ -84,7 +84,7 @@ protected function prepare() } foreach ($this->_rsm->aliasMap as $dqlAlias => $className) { - $this->identifierMap[$dqlAlias] = array(); + $this->identifierMap[$dqlAlias] = []; $this->idTemplate[$dqlAlias] = ''; // Remember which associations are "fetch joined", so that we know where to inject @@ -142,7 +142,7 @@ protected function cleanup() $this->identifierMap = $this->initializedCollections = $this->existingCollections = - $this->resultPointers = array(); + $this->resultPointers = []; if ($eagerLoad) { $this->_uow->triggerEagerLoads(); @@ -156,7 +156,7 @@ protected function cleanup() */ protected function hydrateAllData() { - $result = array(); + $result = []; while ($row = $this->_stmt->fetch(PDO::FETCH_ASSOC)) { $this->hydrateRowData($row, $result); @@ -251,12 +251,13 @@ private function getEntity(array $data, $dqlAlias) } $discrMap = $this->_metadataCache[$className]->discriminatorMap; + $discriminatorValue = (string) $data[$discrColumn]; - if ( ! isset($discrMap[$data[$discrColumn]])) { - throw HydrationException::invalidDiscriminatorValue($data[$discrColumn], array_keys($discrMap)); + if ( ! isset($discrMap[$discriminatorValue])) { + throw HydrationException::invalidDiscriminatorValue($discriminatorValue, array_keys($discrMap)); } - $className = $discrMap[$data[$discrColumn]]; + $className = $discrMap[$discriminatorValue]; unset($data[$discrColumn]); } @@ -325,10 +326,13 @@ protected function hydrateRowData(array $row, array &$result) { // Initialize $id = $this->idTemplate; // initialize the id-memory - $nonemptyComponents = array(); + $nonemptyComponents = []; // Split the row data into chunks of class data. $rowData = $this->gatherRowData($row, $id, $nonemptyComponents); + // reset result pointers for each data row + $this->resultPointers = []; + // Hydrate the data chunks foreach ($rowData['data'] as $dqlAlias => $data) { $entityName = $this->_rsm->aliasMap[$dqlAlias]; @@ -354,8 +358,8 @@ protected function hydrateRowData(array $row, array &$result) // Get a reference to the parent object to which the joined element belongs. if ($this->_rsm->isMixed && isset($this->rootAliases[$parentAlias])) { - $first = reset($this->resultPointers); - $parentObject = $first[key($first)]; + $objectClass = $this->resultPointers[$parentAlias]; + $parentObject = $objectClass[key($objectClass)]; } else if (isset($this->resultPointers[$parentAlias])) { $parentObject = $this->resultPointers[$parentAlias]; } else { @@ -418,7 +422,7 @@ protected function hydrateRowData(array $row, array &$result) $this->resultPointers[$dqlAlias] = $reflFieldValue[$index]; } } else if ( ! $reflFieldValue) { - $reflFieldValue = $this->initRelatedCollection($parentObject, $parentClass, $relationField, $parentAlias); + $this->initRelatedCollection($parentObject, $parentClass, $relationField, $parentAlias); } else if ($reflFieldValue instanceof PersistentCollection && $reflFieldValue->isInitialized() === false) { $reflFieldValue->setInitialized(true); } @@ -429,7 +433,7 @@ protected function hydrateRowData(array $row, array &$result) if ( ! $reflFieldValue || isset($this->_hints[Query::HINT_REFRESH]) || ($reflFieldValue instanceof Proxy && !$reflFieldValue->__isInitialized__)) { // we only need to take action if this value is null, - // we refresh the entity or its an unitialized proxy. + // we refresh the entity or its an uninitialized proxy. if (isset($nonemptyComponents[$dqlAlias])) { $element = $this->getEntity($data, $dqlAlias); $reflField->setValue($parentObject, $element); @@ -474,7 +478,7 @@ protected function hydrateRowData(array $row, array &$result) // if this row has a NULL value for the root result id then make it a null result. if ( ! isset($nonemptyComponents[$dqlAlias]) ) { if ($this->_rsm->isMixed) { - $result[] = array($entityKey => null); + $result[] = [$entityKey => null]; } else { $result[] = null; } @@ -488,7 +492,7 @@ protected function hydrateRowData(array $row, array &$result) $element = $this->getEntity($data, $dqlAlias); if ($this->_rsm->isMixed) { - $element = array($entityKey => $element); + $element = [$entityKey => $element]; } if (isset($this->_rsm->indexByMap[$dqlAlias])) { diff --git a/lib/Doctrine/ORM/Internal/Hydration/ScalarHydrator.php b/lib/Doctrine/ORM/Internal/Hydration/ScalarHydrator.php index 024ee3b6692..093e89c4e13 100644 --- a/lib/Doctrine/ORM/Internal/Hydration/ScalarHydrator.php +++ b/lib/Doctrine/ORM/Internal/Hydration/ScalarHydrator.php @@ -35,7 +35,7 @@ class ScalarHydrator extends AbstractHydrator */ protected function hydrateAllData() { - $result = array(); + $result = []; while ($data = $this->_stmt->fetch(\PDO::FETCH_ASSOC)) { $this->hydrateRowData($data, $result); diff --git a/lib/Doctrine/ORM/Internal/Hydration/SimpleObjectHydrator.php b/lib/Doctrine/ORM/Internal/Hydration/SimpleObjectHydrator.php index 92c77ddd3f3..bf2beaba347 100644 --- a/lib/Doctrine/ORM/Internal/Hydration/SimpleObjectHydrator.php +++ b/lib/Doctrine/ORM/Internal/Hydration/SimpleObjectHydrator.php @@ -62,7 +62,7 @@ protected function cleanup() */ protected function hydrateAllData() { - $result = array(); + $result = []; while ($row = $this->_stmt->fetch(PDO::FETCH_ASSOC)) { $this->hydrateRowData($row, $result); @@ -79,7 +79,7 @@ protected function hydrateAllData() protected function hydrateRowData(array $sqlResult, array &$result) { $entityName = $this->class->name; - $data = array(); + $data = []; // We need to find the correct entity class name if we have inheritance in resultset if ($this->class->inheritanceType !== ClassMetadata::INHERITANCE_TYPE_NONE) { @@ -121,6 +121,9 @@ protected function hydrateRowData(array $sqlResult, array &$result) continue; } + // Check if value is null before conversion (because some types convert null to something else) + $valueIsNull = null === $value; + // Convert field to a valid PHP value if (isset($cacheKeyInfo['type'])) { $type = $cacheKeyInfo['type']; @@ -130,7 +133,7 @@ protected function hydrateRowData(array $sqlResult, array &$result) $fieldName = $cacheKeyInfo['fieldName']; // Prevent overwrite in case of inherit classes using same property name (See AbstractHydrator) - if ( ! isset($data[$fieldName]) || $value !== null) { + if ( ! isset($data[$fieldName]) || ! $valueIsNull) { $data[$fieldName] = $value; } } diff --git a/lib/Doctrine/ORM/Internal/HydrationCompleteHandler.php b/lib/Doctrine/ORM/Internal/HydrationCompleteHandler.php index 4da71cefaf2..72a0c70348e 100644 --- a/lib/Doctrine/ORM/Internal/HydrationCompleteHandler.php +++ b/lib/Doctrine/ORM/Internal/HydrationCompleteHandler.php @@ -47,7 +47,7 @@ final class HydrationCompleteHandler /** * @var array[] */ - private $deferredPostLoadInvocations = array(); + private $deferredPostLoadInvocations = []; /** * Constructor for this object @@ -75,7 +75,7 @@ public function deferPostLoadInvoking(ClassMetadata $class, $entity) return; } - $this->deferredPostLoadInvocations[] = array($class, $invoke, $entity); + $this->deferredPostLoadInvocations[] = [$class, $invoke, $entity]; } /** @@ -86,7 +86,7 @@ public function deferPostLoadInvoking(ClassMetadata $class, $entity) public function hydrationComplete() { $toInvoke = $this->deferredPostLoadInvocations; - $this->deferredPostLoadInvocations = array(); + $this->deferredPostLoadInvocations = []; foreach ($toInvoke as $classAndEntity) { list($class, $invoke, $entity) = $classAndEntity; diff --git a/lib/Doctrine/ORM/Mapping/AssociationOverride.php b/lib/Doctrine/ORM/Mapping/AssociationOverride.php index 83cff417914..e208b16228a 100644 --- a/lib/Doctrine/ORM/Mapping/AssociationOverride.php +++ b/lib/Doctrine/ORM/Mapping/AssociationOverride.php @@ -57,4 +57,13 @@ final class AssociationOverride implements Annotation * @var string */ public $inversedBy; + + /** + * The fetching strategy to use for the association. + * + * @var string + * + * @Enum({"LAZY", "EAGER", "EXTRA_LAZY"}) + */ + public $fetch; } diff --git a/lib/Doctrine/ORM/Mapping/Builder/AssociationBuilder.php b/lib/Doctrine/ORM/Mapping/Builder/AssociationBuilder.php index 5abfe21bba1..7f4fddc96ba 100644 --- a/lib/Doctrine/ORM/Mapping/Builder/AssociationBuilder.php +++ b/lib/Doctrine/ORM/Mapping/Builder/AssociationBuilder.php @@ -84,7 +84,7 @@ public function inversedBy($fieldName) */ public function cascadeAll() { - $this->mapping['cascade'] = array("ALL"); + $this->mapping['cascade'] = ["ALL"]; return $this; } @@ -183,14 +183,14 @@ public function fetchLazy() */ public function addJoinColumn($columnName, $referencedColumnName, $nullable = true, $unique = false, $onDelete = null, $columnDef = null) { - $this->joinColumns[] = array( + $this->joinColumns[] = [ 'name' => $columnName, 'referencedColumnName' => $referencedColumnName, 'nullable' => $nullable, 'unique' => $unique, 'onDelete' => $onDelete, 'columnDefinition' => $columnDef, - ); + ]; return $this; } diff --git a/lib/Doctrine/ORM/Mapping/Builder/ClassMetadataBuilder.php b/lib/Doctrine/ORM/Mapping/Builder/ClassMetadataBuilder.php index 7d771d3f95a..c08b374feeb 100644 --- a/lib/Doctrine/ORM/Mapping/Builder/ClassMetadataBuilder.php +++ b/lib/Doctrine/ORM/Mapping/Builder/ClassMetadataBuilder.php @@ -91,11 +91,13 @@ public function setEmbeddable() */ public function addEmbedded($fieldName, $class, $columnPrefix = null) { - $this->cm->mapEmbedded(array( - 'fieldName' => $fieldName, - 'class' => $class, - 'columnPrefix' => $columnPrefix - )); + $this->cm->mapEmbedded( + [ + 'fieldName' => $fieldName, + 'class' => $class, + 'columnPrefix' => $columnPrefix + ] + ); return $this; } @@ -135,7 +137,7 @@ public function setReadOnly() */ public function setTable($name) { - $this->cm->setPrimaryTable(array('name' => $name)); + $this->cm->setPrimaryTable(['name' => $name]); return $this; } @@ -151,10 +153,10 @@ public function setTable($name) public function addIndex(array $columns, $name) { if (!isset($this->cm->table['indexes'])) { - $this->cm->table['indexes'] = array(); + $this->cm->table['indexes'] = []; } - $this->cm->table['indexes'][$name] = array('columns' => $columns); + $this->cm->table['indexes'][$name] = ['columns' => $columns]; return $this; } @@ -170,10 +172,10 @@ public function addIndex(array $columns, $name) public function addUniqueConstraint(array $columns, $name) { if ( ! isset($this->cm->table['uniqueConstraints'])) { - $this->cm->table['uniqueConstraints'] = array(); + $this->cm->table['uniqueConstraints'] = []; } - $this->cm->table['uniqueConstraints'][$name] = array('columns' => $columns); + $this->cm->table['uniqueConstraints'][$name] = ['columns' => $columns]; return $this; } @@ -188,10 +190,12 @@ public function addUniqueConstraint(array $columns, $name) */ public function addNamedQuery($name, $dqlQuery) { - $this->cm->addNamedQuery(array( - 'name' => $name, - 'query' => $dqlQuery, - )); + $this->cm->addNamedQuery( + [ + 'name' => $name, + 'query' => $dqlQuery, + ] + ); return $this; } @@ -231,11 +235,13 @@ public function setSingleTableInheritance() */ public function setDiscriminatorColumn($name, $type = 'string', $length = 255) { - $this->cm->setDiscriminatorColumn(array( - 'name' => $name, - 'type' => $type, - 'length' => $length, - )); + $this->cm->setDiscriminatorColumn( + [ + 'name' => $name, + 'type' => $type, + 'length' => $length, + ] + ); return $this; } @@ -303,7 +309,7 @@ public function addLifecycleEvent($methodName, $event) * * @return ClassMetadataBuilder */ - public function addField($name, $type, array $mapping = array()) + public function addField($name, $type, array $mapping = []) { $mapping['fieldName'] = $name; $mapping['type'] = $type; @@ -325,10 +331,10 @@ public function createField($name, $type) { return new FieldBuilder( $this, - array( + [ 'fieldName' => $name, 'type' => $type - ) + ] ); } @@ -344,11 +350,11 @@ public function createEmbedded($fieldName, $class) { return new EmbeddedBuilder( $this, - array( + [ 'fieldName' => $fieldName, 'class' => $class, 'columnPrefix' => null - ) + ] ); } @@ -386,10 +392,10 @@ public function createManyToOne($name, $targetEntity) { return new AssociationBuilder( $this, - array( + [ 'fieldName' => $name, 'targetEntity' => $targetEntity - ), + ], ClassMetadata::MANY_TO_ONE ); } @@ -406,10 +412,10 @@ public function createOneToOne($name, $targetEntity) { return new AssociationBuilder( $this, - array( + [ 'fieldName' => $name, 'targetEntity' => $targetEntity - ), + ], ClassMetadata::ONE_TO_ONE ); } @@ -463,10 +469,10 @@ public function createManyToMany($name, $targetEntity) { return new ManyToManyAssociationBuilder( $this, - array( + [ 'fieldName' => $name, 'targetEntity' => $targetEntity - ), + ], ClassMetadata::MANY_TO_MANY ); } @@ -520,10 +526,10 @@ public function createOneToMany($name, $targetEntity) { return new OneToManyAssociationBuilder( $this, - array( + [ 'fieldName' => $name, 'targetEntity' => $targetEntity - ), + ], ClassMetadata::ONE_TO_MANY ); } diff --git a/lib/Doctrine/ORM/Mapping/Builder/EntityListenerBuilder.php b/lib/Doctrine/ORM/Mapping/Builder/EntityListenerBuilder.php index d17abeac52c..e962726091c 100644 --- a/lib/Doctrine/ORM/Mapping/Builder/EntityListenerBuilder.php +++ b/lib/Doctrine/ORM/Mapping/Builder/EntityListenerBuilder.php @@ -34,7 +34,7 @@ class EntityListenerBuilder /** * @var array Hash-map to handle event names. */ - static private $events = array( + static private $events = [ Events::preRemove => true, Events::postRemove => true, Events::prePersist => true, @@ -43,7 +43,7 @@ class EntityListenerBuilder Events::postUpdate => true, Events::postLoad => true, Events::preFlush => true - ); + ]; /** * Lookup the entity class to find methods that match to event lifecycle names @@ -69,4 +69,4 @@ static public function bindEntityListener(ClassMetadata $metadata, $className) $metadata->addEntityListener($method, $class, $method); } } -} \ No newline at end of file +} diff --git a/lib/Doctrine/ORM/Mapping/Builder/FieldBuilder.php b/lib/Doctrine/ORM/Mapping/Builder/FieldBuilder.php index 5a896678117..d0128d4a933 100644 --- a/lib/Doctrine/ORM/Mapping/Builder/FieldBuilder.php +++ b/lib/Doctrine/ORM/Mapping/Builder/FieldBuilder.php @@ -226,11 +226,11 @@ public function isVersionField() */ public function setSequenceGenerator($sequenceName, $allocationSize = 1, $initialValue = 1) { - $this->sequenceDef = array( + $this->sequenceDef = [ 'sequenceName' => $sequenceName, 'allocationSize' => $allocationSize, 'initialValue' => $initialValue, - ); + ]; return $this; } diff --git a/lib/Doctrine/ORM/Mapping/Builder/ManyToManyAssociationBuilder.php b/lib/Doctrine/ORM/Mapping/Builder/ManyToManyAssociationBuilder.php index 8b167d9964a..a71859dfd38 100644 --- a/lib/Doctrine/ORM/Mapping/Builder/ManyToManyAssociationBuilder.php +++ b/lib/Doctrine/ORM/Mapping/Builder/ManyToManyAssociationBuilder.php @@ -37,7 +37,7 @@ class ManyToManyAssociationBuilder extends OneToManyAssociationBuilder /** * @var array */ - private $inverseJoinColumns = array(); + private $inverseJoinColumns = []; /** * @param string $name @@ -65,14 +65,14 @@ public function setJoinTable($name) */ public function addInverseJoinColumn($columnName, $referencedColumnName, $nullable = true, $unique = false, $onDelete = null, $columnDef = null) { - $this->inverseJoinColumns[] = array( + $this->inverseJoinColumns[] = [ 'name' => $columnName, 'referencedColumnName' => $referencedColumnName, 'nullable' => $nullable, 'unique' => $unique, 'onDelete' => $onDelete, 'columnDefinition' => $columnDef, - ); + ]; return $this; } @@ -83,7 +83,7 @@ public function addInverseJoinColumn($columnName, $referencedColumnName, $nullab public function build() { $mapping = $this->mapping; - $mapping['joinTable'] = array(); + $mapping['joinTable'] = []; if ($this->joinColumns) { $mapping['joinTable']['joinColumns'] = $this->joinColumns; } diff --git a/lib/Doctrine/ORM/Mapping/ClassMetadataFactory.php b/lib/Doctrine/ORM/Mapping/ClassMetadataFactory.php index b42b8b5673d..8410ce5b0de 100644 --- a/lib/Doctrine/ORM/Mapping/ClassMetadataFactory.php +++ b/lib/Doctrine/ORM/Mapping/ClassMetadataFactory.php @@ -68,7 +68,7 @@ class ClassMetadataFactory extends AbstractClassMetadataFactory /** * @var array */ - private $embeddablesActiveNesting = array(); + private $embeddablesActiveNesting = []; /** * {@inheritDoc} @@ -350,9 +350,9 @@ private function addDefaultDiscriminatorMap(ClassMetadata $class) { $allClasses = $this->driver->getAllClassNames(); $fqcn = $class->getName(); - $map = array($this->getShortName($class->name) => $fqcn); + $map = [$this->getShortName($class->name) => $fqcn]; - $duplicates = array(); + $duplicates = []; foreach ($allClasses as $subClassCandidate) { if (is_subclass_of($subClassCandidate, $fqcn)) { $shortName = $this->getShortName($subClassCandidate); @@ -475,15 +475,17 @@ private function addNestedEmbeddedClasses(ClassMetadata $subClass, ClassMetadata $embeddableMetadata = $this->getMetadataFor($embeddableClass['class']); - $parentClass->mapEmbedded(array( - 'fieldName' => $prefix . '.' . $property, - 'class' => $embeddableMetadata->name, - 'columnPrefix' => $embeddableClass['columnPrefix'], - 'declaredField' => $embeddableClass['declaredField'] - ? $prefix . '.' . $embeddableClass['declaredField'] - : $prefix, - 'originalField' => $embeddableClass['originalField'] ?: $property, - )); + $parentClass->mapEmbedded( + [ + 'fieldName' => $prefix . '.' . $property, + 'class' => $embeddableMetadata->name, + 'columnPrefix' => $embeddableClass['columnPrefix'], + 'declaredField' => $embeddableClass['declaredField'] + ? $prefix . '.' . $embeddableClass['declaredField'] + : $prefix, + 'originalField' => $embeddableClass['originalField'] ?: $property, + ] + ); } } @@ -501,7 +503,7 @@ private function addInheritedIndexes(ClassMetadata $subClass, ClassMetadata $par return; } - foreach (array('uniqueConstraints', 'indexes') as $indexType) { + foreach (['uniqueConstraints', 'indexes'] as $indexType) { if (isset($parentClass->table[$indexType])) { foreach ($parentClass->table[$indexType] as $indexName => $index) { if (isset($subClass->table[$indexType][$indexName])) { @@ -528,10 +530,12 @@ private function addInheritedNamedQueries(ClassMetadata $subClass, ClassMetadata { foreach ($parentClass->namedQueries as $name => $query) { if ( ! isset ($subClass->namedQueries[$name])) { - $subClass->addNamedQuery(array( - 'name' => $query['name'], - 'query' => $query['query'] - )); + $subClass->addNamedQuery( + [ + 'name' => $query['name'], + 'query' => $query['query'] + ] + ); } } } @@ -550,13 +554,15 @@ private function addInheritedNamedNativeQueries(ClassMetadata $subClass, ClassMe { foreach ($parentClass->namedNativeQueries as $name => $query) { if ( ! isset ($subClass->namedNativeQueries[$name])) { - $subClass->addNamedNativeQuery(array( - 'name' => $query['name'], - 'query' => $query['query'], - 'isSelfClass' => $query['isSelfClass'], - 'resultSetMapping' => $query['resultSetMapping'], - 'resultClass' => $query['isSelfClass'] ? $subClass->name : $query['resultClass'], - )); + $subClass->addNamedNativeQuery( + [ + 'name' => $query['name'], + 'query' => $query['query'], + 'isSelfClass' => $query['isSelfClass'], + 'resultSetMapping' => $query['resultSetMapping'], + 'resultClass' => $query['isSelfClass'] ? $subClass->name : $query['resultClass'], + ] + ); } } } @@ -575,21 +581,23 @@ private function addInheritedSqlResultSetMappings(ClassMetadata $subClass, Class { foreach ($parentClass->sqlResultSetMappings as $name => $mapping) { if ( ! isset ($subClass->sqlResultSetMappings[$name])) { - $entities = array(); + $entities = []; foreach ($mapping['entities'] as $entity) { - $entities[] = array( + $entities[] = [ 'fields' => $entity['fields'], 'isSelfClass' => $entity['isSelfClass'], 'discriminatorColumn' => $entity['discriminatorColumn'], 'entityClass' => $entity['isSelfClass'] ? $subClass->name : $entity['entityClass'], - ); + ]; } - $subClass->addSqlResultSetMapping(array( - 'name' => $mapping['name'], - 'columns' => $mapping['columns'], - 'entities' => $entities, - )); + $subClass->addSqlResultSetMapping( + [ + 'name' => $mapping['name'], + 'columns' => $mapping['columns'], + 'entities' => $entities, + ] + ); } } } @@ -629,9 +637,9 @@ private function completeIdGeneratorMapping(ClassMetadataInfo $class) $quoted = isset($class->fieldMappings[$fieldName]['quoted']) || isset($class->table['quoted']); $sequencePrefix = $class->getSequencePrefix($this->getTargetPlatform()); $sequenceName = $this->getTargetPlatform()->getIdentitySequenceName($sequencePrefix, $columnName); - $definition = array( + $definition = [ 'sequenceName' => $this->getTargetPlatform()->fixSchemaElementName($sequenceName) - ); + ]; if ($quoted) { $definition['quoted'] = true; @@ -661,11 +669,11 @@ private function completeIdGeneratorMapping(ClassMetadataInfo $class) $sequenceName = $class->getSequenceName($this->getTargetPlatform()); $quoted = isset($class->fieldMappings[$fieldName]['quoted']) || isset($class->table['quoted']); - $definition = array( + $definition = [ 'sequenceName' => $this->getTargetPlatform()->fixSchemaElementName($sequenceName), 'allocationSize' => 1, 'initialValue' => 1, - ); + ]; if ($quoted) { $definition['quoted'] = true; @@ -695,6 +703,9 @@ private function completeIdGeneratorMapping(ClassMetadataInfo $class) case ClassMetadata::GENERATOR_TYPE_CUSTOM: $definition = $class->customGeneratorDefinition; + if ($definition === null) { + throw new ORMException("Can't instantiate custom generator : no custom generator definition"); + } if ( ! class_exists($definition['class'])) { throw new ORMException("Can't instantiate custom generator : " . $definition['class']); diff --git a/lib/Doctrine/ORM/Mapping/ClassMetadataInfo.php b/lib/Doctrine/ORM/Mapping/ClassMetadataInfo.php index bf83caa3643..f6768838c52 100644 --- a/lib/Doctrine/ORM/Mapping/ClassMetadataInfo.php +++ b/lib/Doctrine/ORM/Mapping/ClassMetadataInfo.php @@ -27,7 +27,6 @@ use Doctrine\DBAL\Platforms\AbstractPlatform; use ReflectionClass; use Doctrine\Common\Persistence\Mapping\ClassMetadata; -use Doctrine\Common\ClassLoader; use Doctrine\ORM\Cache\CacheException; /** @@ -242,9 +241,9 @@ class ClassMetadataInfo implements ClassMetadata * ) * * - * @var array - * * @todo Merge with tableGeneratorDefinition into generic generatorDefinition + * + * @var array|null */ public $customGeneratorDefinition; @@ -275,28 +274,28 @@ class ClassMetadataInfo implements ClassMetadata * * @var array */ - public $parentClasses = array(); + public $parentClasses = []; /** * READ-ONLY: The names of all subclasses (descendants). * * @var array */ - public $subClasses = array(); + public $subClasses = []; /** * READ-ONLY: The names of all embedded classes based on properties. * * @var array */ - public $embeddedClasses = array(); + public $embeddedClasses = []; /** * READ-ONLY: The named queries allowed to be called directly from Repository. * * @var array */ - public $namedQueries = array(); + public $namedQueries = []; /** * READ-ONLY: The named native queries allowed to be called directly from Repository. @@ -313,7 +312,7 @@ class ClassMetadataInfo implements ClassMetadata * * @var array */ - public $namedNativeQueries = array(); + public $namedNativeQueries = []; /** * READ-ONLY: The mappings of the results of native SQL queries. @@ -329,7 +328,7 @@ class ClassMetadataInfo implements ClassMetadata * * @var array */ - public $sqlResultSetMappings = array(); + public $sqlResultSetMappings = []; /** * READ-ONLY: The field names of all fields that are part of the identifier/primary key @@ -337,7 +336,7 @@ class ClassMetadataInfo implements ClassMetadata * * @var array */ - public $identifier = array(); + public $identifier = []; /** * READ-ONLY: The inheritance mapping type used by the class. @@ -394,7 +393,7 @@ class ClassMetadataInfo implements ClassMetadata * * @var array */ - public $fieldMappings = array(); + public $fieldMappings = []; /** * READ-ONLY: An array of field names. Used to look up field names from column names. @@ -402,7 +401,7 @@ class ClassMetadataInfo implements ClassMetadata * * @var array */ - public $fieldNames = array(); + public $fieldNames = []; /** * READ-ONLY: A map of field names to column names. Keys are field names and values column names. @@ -413,7 +412,7 @@ class ClassMetadataInfo implements ClassMetadata * * @deprecated 3.0 Remove this. */ - public $columnNames = array(); + public $columnNames = []; /** * READ-ONLY: The discriminator value of this class. @@ -437,7 +436,7 @@ class ClassMetadataInfo implements ClassMetadata * * @see discriminatorColumn */ - public $discriminatorMap = array(); + public $discriminatorMap = []; /** * READ-ONLY: The definition of the discriminator column used in JOINED and SINGLE_TABLE @@ -463,16 +462,16 @@ class ClassMetadataInfo implements ClassMetadata /** * READ-ONLY: The registered lifecycle callbacks for entities of this class. * - * @var array + * @var array[] */ - public $lifecycleCallbacks = array(); + public $lifecycleCallbacks = []; /** * READ-ONLY: The registered entity listeners. * * @var array */ - public $entityListeners = array(); + public $entityListeners = []; /** * READ-ONLY: The association mappings of this class. @@ -529,7 +528,7 @@ class ClassMetadataInfo implements ClassMetadata * * @var array */ - public $associationMappings = array(); + public $associationMappings = []; /** * READ-ONLY: Flag indicating whether the identifier/primary key of the class is composite. @@ -642,7 +641,7 @@ class ClassMetadataInfo implements ClassMetadata * * @var \ReflectionProperty[] */ - public $reflFields = array(); + public $reflFields = []; /** * @var \Doctrine\Instantiator\InstantiatorInterface|null @@ -715,12 +714,12 @@ public function getSingleIdReflectionProperty() public function getIdentifierValues($entity) { if ($this->isIdentifierComposite) { - $id = array(); + $id = []; foreach ($this->identifier as $idField) { $value = $this->reflFields[$idField]->getValue($entity); - if ($value !== null) { + if (null !== $value) { $id[$idField] = $value; } } @@ -732,10 +731,10 @@ public function getIdentifierValues($entity) $value = $this->reflFields[$id]->getValue($entity); if (null === $value) { - return array(); + return []; } - return array($id => $value); + return [$id => $value]; } /** @@ -810,7 +809,7 @@ public function __toString() public function __sleep() { // This metadata is always serialized/cached. - $serialized = array( + $serialized = [ 'associationMappings', 'columnNames', //TODO: 3.0 Remove this. Can use fieldMappings[$fieldName]['columnName'] 'fieldMappings', @@ -823,7 +822,7 @@ public function __sleep() 'table', 'rootEntityName', 'idGenerator', //TODO: Does not really need to be serialized. Could be moved to runtime. - ); + ]; // The rest of the metadata is only serialized if necessary. if ($this->changeTrackingPolicy != self::CHANGETRACKING_DEFERRED_IMPLICIT) { @@ -925,7 +924,7 @@ public function wakeupReflection($reflService) $this->reflClass = $reflService->getClass($this->name); $this->instantiator = $this->instantiator ?: new Instantiator(); - $parentReflFields = array(); + $parentReflFields = []; foreach ($this->embeddedClasses as $property => $embeddedClass) { if (isset($embeddedClass['declaredField'])) { @@ -942,7 +941,7 @@ public function wakeupReflection($reflService) } $fieldRefl = $reflService->getAccessibleProperty( - isset($embeddedClass['declared']) ? $embeddedClass['declared'] : $this->name, + $embeddedClass['declared'] ?? $this->name, $property ); @@ -1025,7 +1024,11 @@ public function validateIdentifier() public function validateAssociations() { foreach ($this->associationMappings as $mapping) { - if ( ! ClassLoader::classExists($mapping['targetEntity']) ) { + if ( + ! class_exists($mapping['targetEntity']) + && ! interface_exists($mapping['targetEntity']) + && ! trait_exists($mapping['targetEntity']) + ) { throw MappingException::invalidTargetEntityClass($mapping['targetEntity'], $this->name, $mapping['fieldName']); } } @@ -1085,7 +1088,7 @@ public function enableCache(array $cache) */ public function enableAssociationCache($fieldName, array $cache) { - $this->associationMappings[$fieldName]['cache'] = $this->getAssociationCacheDefaults ($fieldName, $cache); + $this->associationMappings[$fieldName]['cache'] = $this->getAssociationCacheDefaults($fieldName, $cache); } /** @@ -1128,7 +1131,7 @@ public function setChangeTrackingPolicy($policy) */ public function isChangeTrackingDeferredExplicit() { - return $this->changeTrackingPolicy == self::CHANGETRACKING_DEFERRED_EXPLICIT; + return self::CHANGETRACKING_DEFERRED_EXPLICIT === $this->changeTrackingPolicy; } /** @@ -1138,7 +1141,7 @@ public function isChangeTrackingDeferredExplicit() */ public function isChangeTrackingDeferredImplicit() { - return $this->changeTrackingPolicy == self::CHANGETRACKING_DEFERRED_IMPLICIT; + return self::CHANGETRACKING_DEFERRED_IMPLICIT === $this->changeTrackingPolicy; } /** @@ -1148,7 +1151,7 @@ public function isChangeTrackingDeferredImplicit() */ public function isChangeTrackingNotify() { - return $this->changeTrackingPolicy == self::CHANGETRACKING_NOTIFY; + return self::CHANGETRACKING_NOTIFY === $this->changeTrackingPolicy; } /** @@ -1169,7 +1172,7 @@ public function isIdentifier($fieldName) return $fieldName === $this->identifier[0]; } - return in_array($fieldName, $this->identifier); + return in_array($fieldName, $this->identifier, true); } /** @@ -1183,11 +1186,7 @@ public function isUniqueField($fieldName) { $mapping = $this->getFieldMapping($fieldName); - if ($mapping !== false) { - return isset($mapping['unique']) && $mapping['unique'] == true; - } - - return false; + return false !== $mapping && isset($mapping['unique']) && $mapping['unique']; } /** @@ -1201,11 +1200,7 @@ public function isNullable($fieldName) { $mapping = $this->getFieldMapping($fieldName); - if ($mapping !== false) { - return isset($mapping['nullable']) && $mapping['nullable'] == true; - } - - return false; + return false !== $mapping && isset($mapping['nullable']) && $mapping['nullable']; } /** @@ -1384,14 +1379,14 @@ public function getSqlResultSetMappings() * * @param array $mapping The field mapping to validate & complete. * - * @return array The validated and completed field mapping. + * @return void * * @throws MappingException */ protected function _validateAndCompleteFieldMapping(array &$mapping) { // Check mandatory fields - if ( ! isset($mapping['fieldName']) || strlen($mapping['fieldName']) == 0) { + if ( ! isset($mapping['fieldName']) || !$mapping['fieldName']) { throw MappingException::missingFieldName($this->name); } @@ -1405,21 +1400,21 @@ protected function _validateAndCompleteFieldMapping(array &$mapping) $mapping['columnName'] = $this->namingStrategy->propertyToColumnName($mapping['fieldName'], $this->name); } - if ($mapping['columnName'][0] === '`') { + if ('`' === $mapping['columnName'][0]) { $mapping['columnName'] = trim($mapping['columnName'], '`'); $mapping['quoted'] = true; } $this->columnNames[$mapping['fieldName']] = $mapping['columnName']; - if (isset($this->fieldNames[$mapping['columnName']]) || ($this->discriminatorColumn != null && $this->discriminatorColumn['name'] == $mapping['columnName'])) { + if (isset($this->fieldNames[$mapping['columnName']]) || ($this->discriminatorColumn && $this->discriminatorColumn['name'] === $mapping['columnName'])) { throw MappingException::duplicateColumnName($this->name, $mapping['columnName']); } $this->fieldNames[$mapping['columnName']] = $mapping['fieldName']; // Complete id mapping - if (isset($mapping['id']) && $mapping['id'] === true) { + if (isset($mapping['id']) && true === $mapping['id']) { if ($this->versionField == $mapping['fieldName']) { throw MappingException::cannotVersionIdField($this->name, $mapping['fieldName']); } @@ -1474,13 +1469,13 @@ protected function _validateAndCompleteAssociationMapping(array $mapping) $mapping['targetEntity'] = ltrim($mapping['targetEntity'], '\\'); } - if (($mapping['type'] & self::MANY_TO_ONE) > 0 && isset($mapping['orphanRemoval']) && $mapping['orphanRemoval'] == true) { + if (($mapping['type'] & self::MANY_TO_ONE) > 0 && isset($mapping['orphanRemoval']) && $mapping['orphanRemoval']) { throw MappingException::illegalOrphanRemoval($this->name, $mapping['fieldName']); } // Complete id mapping - if (isset($mapping['id']) && $mapping['id'] === true) { - if (isset($mapping['orphanRemoval']) && $mapping['orphanRemoval'] == true) { + if (isset($mapping['id']) && true === $mapping['id']) { + if (isset($mapping['orphanRemoval']) && $mapping['orphanRemoval']) { throw MappingException::illegalOrphanRemovalOnIdentifierAssociation($this->name, $mapping['fieldName']); } @@ -1507,7 +1502,7 @@ protected function _validateAndCompleteAssociationMapping(array $mapping) // Mandatory attributes for both sides // Mandatory: fieldName, targetEntity - if ( ! isset($mapping['fieldName']) || strlen($mapping['fieldName']) == 0) { + if ( ! isset($mapping['fieldName']) || !$mapping['fieldName']) { throw MappingException::missingFieldName($this->name); } @@ -1527,7 +1522,7 @@ protected function _validateAndCompleteAssociationMapping(array $mapping) $mapping['isOwningSide'] = false; } - if (isset($mapping['id']) && $mapping['id'] === true && $mapping['type'] & self::TO_MANY) { + if (isset($mapping['id']) && true === $mapping['id'] && $mapping['type'] & self::TO_MANY) { throw MappingException::illegalToManyIdentifierAssociation($this->name, $mapping['fieldName']); } @@ -1537,9 +1532,9 @@ protected function _validateAndCompleteAssociationMapping(array $mapping) } // Cascades - $cascades = isset($mapping['cascade']) ? array_map('strtolower', $mapping['cascade']) : array(); + $cascades = isset($mapping['cascade']) ? array_map('strtolower', $mapping['cascade']) : []; - $allCascades = array('remove', 'persist', 'refresh', 'merge', 'detach'); + $allCascades = ['remove', 'persist', 'refresh', 'merge', 'detach']; if (in_array('all', $cascades)) { $cascades = $allCascades; } elseif (count($cascades) !== count(array_intersect($cascades, $allCascades))) { @@ -1551,11 +1546,11 @@ protected function _validateAndCompleteAssociationMapping(array $mapping) } $mapping['cascade'] = $cascades; - $mapping['isCascadeRemove'] = in_array('remove', $cascades); + $mapping['isCascadeRemove'] = in_array('remove', $cascades); $mapping['isCascadePersist'] = in_array('persist', $cascades); $mapping['isCascadeRefresh'] = in_array('refresh', $cascades); - $mapping['isCascadeMerge'] = in_array('merge', $cascades); - $mapping['isCascadeDetach'] = in_array('detach', $cascades); + $mapping['isCascadeMerge'] = in_array('merge', $cascades); + $mapping['isCascadeDetach'] = in_array('detach', $cascades); return $mapping; } @@ -1581,15 +1576,15 @@ protected function _validateAndCompleteOneToOneMapping(array $mapping) if ($mapping['isOwningSide']) { if (empty($mapping['joinColumns'])) { // Apply default join column - $mapping['joinColumns'] = array( - array( + $mapping['joinColumns'] = [ + [ 'name' => $this->namingStrategy->joinColumnName($mapping['fieldName'], $this->name), 'referencedColumnName' => $this->namingStrategy->referenceColumnName() - ) - ); + ] + ]; } - $uniqueConstraintColumns = array(); + $uniqueConstraintColumns = []; foreach ($mapping['joinColumns'] as &$joinColumn) { if ($mapping['type'] === self::ONE_TO_ONE && ! $this->isInheritanceTypeSingleTable()) { @@ -1621,9 +1616,7 @@ protected function _validateAndCompleteOneToOneMapping(array $mapping) } $mapping['sourceToTargetKeyColumns'][$joinColumn['name']] = $joinColumn['referencedColumnName']; - $mapping['joinColumnFieldNames'][$joinColumn['name']] = isset($joinColumn['fieldName']) - ? $joinColumn['fieldName'] - : $joinColumn['name']; + $mapping['joinColumnFieldNames'][$joinColumn['name']] = $joinColumn['fieldName'] ?? $joinColumn['name']; } if ($uniqueConstraintColumns) { @@ -1631,9 +1624,9 @@ protected function _validateAndCompleteOneToOneMapping(array $mapping) throw new RuntimeException("ClassMetadataInfo::setTable() has to be called before defining a one to one relationship."); } - $this->table['uniqueConstraints'][$mapping['fieldName'] . "_uniq"] = array( + $this->table['uniqueConstraints'][$mapping['fieldName'] . "_uniq"] = [ 'columns' => $uniqueConstraintColumns - ); + ]; } $mapping['targetToSourceKeyColumns'] = array_flip($mapping['sourceToTargetKeyColumns']); @@ -1703,26 +1696,26 @@ protected function _validateAndCompleteManyToManyMapping(array $mapping) && (! (isset($mapping['joinTable']['joinColumns']) || isset($mapping['joinTable']['inverseJoinColumns']))); if ( ! isset($mapping['joinTable']['joinColumns'])) { - $mapping['joinTable']['joinColumns'] = array( - array( + $mapping['joinTable']['joinColumns'] = [ + [ 'name' => $this->namingStrategy->joinKeyColumnName($mapping['sourceEntity'], $selfReferencingEntityWithoutJoinColumns ? 'source' : null), 'referencedColumnName' => $this->namingStrategy->referenceColumnName(), 'onDelete' => 'CASCADE' - ) - ); + ] + ]; } if ( ! isset($mapping['joinTable']['inverseJoinColumns'])) { - $mapping['joinTable']['inverseJoinColumns'] = array( - array( + $mapping['joinTable']['inverseJoinColumns'] = [ + [ 'name' => $this->namingStrategy->joinKeyColumnName($mapping['targetEntity'], $selfReferencingEntityWithoutJoinColumns ? 'target' : null), 'referencedColumnName' => $this->namingStrategy->referenceColumnName(), 'onDelete' => 'CASCADE' - ) - ); + ] + ]; } - $mapping['joinTableColumns'] = array(); + $mapping['joinTableColumns'] = []; foreach ($mapping['joinTable']['joinColumns'] as &$joinColumn) { if (empty($joinColumn['name'])) { @@ -1800,7 +1793,7 @@ public function getIdentifierFieldNames() * * @return string * - * @throws MappingException If the class has a composite primary key. + * @throws MappingException If the class doesn't have an identifier or it has a composite primary key. */ public function getSingleIdentifierFieldName() { @@ -1808,6 +1801,10 @@ public function getSingleIdentifierFieldName() throw MappingException::singleIdNotAllowedOnCompositePrimaryKey($this->name); } + if ( ! isset($this->identifier[0])) { + throw MappingException::noIdDefined($this->name); + } + return $this->identifier[0]; } @@ -1817,7 +1814,7 @@ public function getSingleIdentifierFieldName() * * @return string * - * @throws MappingException If the class has a composite primary key. + * @throws MappingException If the class doesn't have an identifier or it has a composite primary key. */ public function getSingleIdentifierColumnName() { @@ -1852,7 +1849,7 @@ public function getIdentifier() */ public function hasField($fieldName) { - return isset($this->fieldMappings[$fieldName]); + return isset($this->fieldMappings[$fieldName]) || isset($this->embeddedClasses[$fieldName]); } /** @@ -1878,7 +1875,7 @@ public function getColumnNames(array $fieldNames = null) */ public function getIdentifierColumnNames() { - $columnNames = array(); + $columnNames = []; foreach ($this->identifier as $idProperty) { if (isset($this->fieldMappings[$idProperty])) { @@ -2016,7 +2013,7 @@ public function isIdentifierUuid() * * @param string $fieldName * - * @return \Doctrine\DBAL\Types\Type|string|null + * @return string|null * * @todo 3.0 Remove this. PersisterHelper should fix it somehow */ @@ -2032,9 +2029,9 @@ public function getTypeOfField($fieldName) * * @param string $columnName * - * @return \Doctrine\DBAL\Types\Type|string|null + * @return string|null * - * @deprecated 3.0 remove this. this method is bogous and unreliable, since it cannot resolve the type of a column + * @deprecated 3.0 remove this. this method is bogus and unreliable, since it cannot resolve the type of a column * that is derived by a referenced field on a different entity. */ public function getTypeOfColumn($columnName) @@ -2153,6 +2150,10 @@ public function setAssociationOverride($fieldName, array $overrideMapping) $mapping['joinTable'] = $overrideMapping['joinTable']; } + if (isset($overrideMapping['fetch'])) { + $mapping['fetch'] = $overrideMapping['fetch']; + } + $mapping['joinColumnFieldNames'] = null; $mapping['joinTableColumns'] = null; $mapping['sourceToTargetKeyColumns'] = null; @@ -2303,6 +2304,10 @@ public function setPrimaryTable(array $table) $this->table['name'] = $table['name']; } + if (isset($table['quoted'])) { + $this->table['quoted'] = $table['quoted']; + } + if (isset($table['schema'])) { $this->table['schema'] = $table['schema']; } @@ -2415,11 +2420,11 @@ public function addNamedQuery(array $queryMapping) $query = $queryMapping['query']; $dql = str_replace('__CLASS__', $this->name, $query); - $this->namedQueries[$name] = array( + $this->namedQueries[$name] = [ 'name' => $name, 'query' => $query, 'dql' => $dql, - ); + ]; } /** @@ -2661,7 +2666,7 @@ public function hasLifecycleCallbacks($lifecycleEvent) */ public function getLifecycleCallbacks($event) { - return isset($this->lifecycleCallbacks[$event]) ? $this->lifecycleCallbacks[$event] : array(); + return isset($this->lifecycleCallbacks[$event]) ? $this->lifecycleCallbacks[$event] : []; } /** @@ -2707,10 +2712,10 @@ public function addEntityListener($eventName, $class, $method) { $class = $this->fullyQualifiedClassName($class); - $listener = array( + $listener = [ 'class' => $class, 'method' => $method, - ); + ]; if ( ! class_exists($class)) { throw MappingException::entityListenerClassNotFound($class, $this->name); @@ -2757,7 +2762,7 @@ public function setDiscriminatorColumn($columnDef) $columnDef['type'] = "string"; } - if (in_array($columnDef['type'], array("boolean", "array", "object", "datetime", "time", "date"))) { + if (in_array($columnDef['type'], ["boolean", "array", "object", "datetime", "time", "date"])) { throw MappingException::invalidDiscriminatorColumnType($this->name, $columnDef['type']); } @@ -2997,7 +3002,7 @@ public function setCustomGeneratorDefinition(array $definition) */ public function setSequenceGeneratorDefinition(array $definition) { - if ( ! isset($definition['sequenceName'])) { + if ( ! isset($definition['sequenceName']) || trim($definition['sequenceName']) === '') { throw MappingException::missingSequenceName($this->name); } @@ -3006,6 +3011,14 @@ public function setSequenceGeneratorDefinition(array $definition) $definition['quoted'] = true; } + if ( ! isset($definition['allocationSize']) || trim($definition['allocationSize']) === '') { + $definition['allocationSize'] = '1'; + } + + if ( ! isset($definition['initialValue']) || trim($definition['initialValue']) === '') { + $definition['initialValue'] = '1'; + } + $this->sequenceGeneratorDefinition = $definition; } @@ -3025,7 +3038,7 @@ public function setVersionMapping(array &$mapping) $this->versionField = $mapping['fieldName']; if ( ! isset($mapping['default'])) { - if (in_array($mapping['type'], array('integer', 'bigint', 'smallint'))) { + if (in_array($mapping['type'], ['integer', 'bigint', 'smallint'])) { $mapping['default'] = 1; } else if ($mapping['type'] == 'datetime') { $mapping['default'] = 'CURRENT_TIMESTAMP'; @@ -3119,7 +3132,7 @@ public function getName() */ public function getQuotedIdentifierColumnNames($platform) { - $quotedColumnNames = array(); + $quotedColumnNames = []; foreach ($this->identifier as $idProperty) { if (isset($this->fieldMappings[$idProperty])) { @@ -3221,7 +3234,7 @@ public function getAssociationMappedByTargetField($fieldName) */ public function getAssociationsByTargetClass($targetClass) { - $relations = array(); + $relations = []; foreach ($this->associationMappings as $mapping) { if ($mapping['targetEntity'] == $targetClass) { @@ -3243,7 +3256,7 @@ public function fullyQualifiedClassName($className) return $className; } - if ($className !== null && strpos($className, '\\') === false && strlen($this->namespace) > 0) { + if ($className !== null && strpos($className, '\\') === false && $this->namespace) { return $this->namespace . '\\' . $className; } @@ -3277,12 +3290,12 @@ public function mapEmbedded(array $mapping) { $this->assertFieldNotMapped($mapping['fieldName']); - $this->embeddedClasses[$mapping['fieldName']] = array( + $this->embeddedClasses[$mapping['fieldName']] = [ 'class' => $this->fullyQualifiedClassName($mapping['class']), 'columnPrefix' => $mapping['columnPrefix'], - 'declaredField' => isset($mapping['declaredField']) ? $mapping['declaredField'] : null, - 'originalField' => isset($mapping['originalField']) ? $mapping['originalField'] : null, - ); + 'declaredField' => $mapping['declaredField'] ?? null, + 'originalField' => $mapping['originalField'] ?? null, + ]; } /** @@ -3294,15 +3307,11 @@ public function mapEmbedded(array $mapping) public function inlineEmbeddable($property, ClassMetadataInfo $embeddable) { foreach ($embeddable->fieldMappings as $fieldMapping) { - $fieldMapping['originalClass'] = isset($fieldMapping['originalClass']) - ? $fieldMapping['originalClass'] - : $embeddable->name; + $fieldMapping['originalClass'] = $fieldMapping['originalClass'] ?? $embeddable->name; $fieldMapping['declaredField'] = isset($fieldMapping['declaredField']) ? $property . '.' . $fieldMapping['declaredField'] : $property; - $fieldMapping['originalField'] = isset($fieldMapping['originalField']) - ? $fieldMapping['originalField'] - : $fieldMapping['fieldName']; + $fieldMapping['originalField'] = $fieldMapping['originalField'] ?? $fieldMapping['fieldName']; $fieldMapping['fieldName'] = $property . "." . $fieldMapping['fieldName']; if (! empty($this->embeddedClasses[$property]['columnPrefix'])) { diff --git a/lib/Doctrine/ORM/Mapping/Column.php b/lib/Doctrine/ORM/Mapping/Column.php index 70337323f6f..711590be672 100644 --- a/lib/Doctrine/ORM/Mapping/Column.php +++ b/lib/Doctrine/ORM/Mapping/Column.php @@ -67,7 +67,7 @@ final class Column implements Annotation /** * @var array */ - public $options = array(); + public $options = []; /** * @var string diff --git a/lib/Doctrine/ORM/Mapping/DefaultEntityListenerResolver.php b/lib/Doctrine/ORM/Mapping/DefaultEntityListenerResolver.php index 75658547e17..a8ee2dc783d 100644 --- a/lib/Doctrine/ORM/Mapping/DefaultEntityListenerResolver.php +++ b/lib/Doctrine/ORM/Mapping/DefaultEntityListenerResolver.php @@ -31,7 +31,7 @@ class DefaultEntityListenerResolver implements EntityListenerResolver /** * @var array Map to store entity listener instances. */ - private $instances = array(); + private $instances = []; /** * {@inheritdoc} @@ -39,7 +39,7 @@ class DefaultEntityListenerResolver implements EntityListenerResolver public function clear($className = null) { if ($className === null) { - $this->instances = array(); + $this->instances = []; return; } @@ -72,4 +72,4 @@ public function resolve($className) return $this->instances[$className] = new $className(); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/ORM/Mapping/DefaultQuoteStrategy.php b/lib/Doctrine/ORM/Mapping/DefaultQuoteStrategy.php index dfbded8a4a9..ade44a0624c 100644 --- a/lib/Doctrine/ORM/Mapping/DefaultQuoteStrategy.php +++ b/lib/Doctrine/ORM/Mapping/DefaultQuoteStrategy.php @@ -99,7 +99,8 @@ public function getJoinTableName(array $association, ClassMetadata $class, Abstr $schema = ''; if (isset($association['joinTable']['schema'])) { - $schema = $association['joinTable']['schema'] . '.'; + $schema = $association['joinTable']['schema']; + $schema .= ! $platform->supportsSchemas() && $platform->canEmulateSchemas() ? '__' : '.'; } $tableName = $association['joinTable']['name']; @@ -116,7 +117,7 @@ public function getJoinTableName(array $association, ClassMetadata $class, Abstr */ public function getIdentifierColumnNames(ClassMetadata $class, AbstractPlatform $platform) { - $quotedColumnNames = array(); + $quotedColumnNames = []; foreach ($class->identifier as $fieldName) { if (isset($class->fieldMappings[$fieldName])) { diff --git a/lib/Doctrine/ORM/Mapping/Driver/AnnotationDriver.php b/lib/Doctrine/ORM/Mapping/Driver/AnnotationDriver.php index 9dd64bbd33a..d59fd3bb773 100644 --- a/lib/Doctrine/ORM/Mapping/Driver/AnnotationDriver.php +++ b/lib/Doctrine/ORM/Mapping/Driver/AnnotationDriver.php @@ -20,13 +20,12 @@ namespace Doctrine\ORM\Mapping\Driver; use Doctrine\Common\Annotations\AnnotationReader; -use Doctrine\ORM\Mapping\MappingException; -use Doctrine\ORM\Mapping\JoinColumn; -use Doctrine\ORM\Mapping\Column; -use Doctrine\ORM\Mapping\Builder\EntityListenerBuilder; use Doctrine\Common\Persistence\Mapping\ClassMetadata; use Doctrine\Common\Persistence\Mapping\Driver\AnnotationDriver as AbstractAnnotationDriver; use Doctrine\ORM\Events; +use Doctrine\ORM\Mapping; +use Doctrine\ORM\Mapping\Builder\EntityListenerBuilder; +use Doctrine\ORM\Mapping\MappingException; /** * The AnnotationDriver reads the mapping metadata from docblock annotations. @@ -42,10 +41,10 @@ class AnnotationDriver extends AbstractAnnotationDriver /** * {@inheritDoc} */ - protected $entityAnnotationClasses = array( - 'Doctrine\ORM\Mapping\Entity' => 1, - 'Doctrine\ORM\Mapping\MappedSuperclass' => 2, - ); + protected $entityAnnotationClasses = [ + Mapping\Entity::class => 1, + Mapping\MappedSuperclass::class => 2, + ]; /** * {@inheritDoc} @@ -74,8 +73,8 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) } // Evaluate Entity annotation - if (isset($classAnnotations['Doctrine\ORM\Mapping\Entity'])) { - $entityAnnot = $classAnnotations['Doctrine\ORM\Mapping\Entity']; + if (isset($classAnnotations[Mapping\Entity::class])) { + $entityAnnot = $classAnnotations[Mapping\Entity::class]; if ($entityAnnot->repositoryClass !== null) { $metadata->setCustomRepositoryClass($entityAnnot->repositoryClass); } @@ -83,28 +82,28 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) if ($entityAnnot->readOnly) { $metadata->markReadOnly(); } - } else if (isset($classAnnotations['Doctrine\ORM\Mapping\MappedSuperclass'])) { - $mappedSuperclassAnnot = $classAnnotations['Doctrine\ORM\Mapping\MappedSuperclass']; + } else if (isset($classAnnotations[Mapping\MappedSuperclass::class])) { + $mappedSuperclassAnnot = $classAnnotations[Mapping\MappedSuperclass::class]; $metadata->setCustomRepositoryClass($mappedSuperclassAnnot->repositoryClass); $metadata->isMappedSuperclass = true; - } else if (isset($classAnnotations['Doctrine\ORM\Mapping\Embeddable'])) { + } else if (isset($classAnnotations[Mapping\Embeddable::class])) { $metadata->isEmbeddedClass = true; } else { throw MappingException::classIsNotAValidEntityOrMappedSuperClass($className); } // Evaluate Table annotation - if (isset($classAnnotations['Doctrine\ORM\Mapping\Table'])) { - $tableAnnot = $classAnnotations['Doctrine\ORM\Mapping\Table']; - $primaryTable = array( + if (isset($classAnnotations[Mapping\Table::class])) { + $tableAnnot = $classAnnotations[Mapping\Table::class]; + $primaryTable = [ 'name' => $tableAnnot->name, 'schema' => $tableAnnot->schema - ); + ]; if ($tableAnnot->indexes !== null) { foreach ($tableAnnot->indexes as $indexAnnot) { - $index = array('columns' => $indexAnnot->columns); + $index = ['columns' => $indexAnnot->columns]; if ( ! empty($indexAnnot->flags)) { $index['flags'] = $indexAnnot->flags; @@ -124,7 +123,7 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) if ($tableAnnot->uniqueConstraints !== null) { foreach ($tableAnnot->uniqueConstraints as $uniqueConstraintAnnot) { - $uniqueConstraint = array('columns' => $uniqueConstraintAnnot->columns); + $uniqueConstraint = ['columns' => $uniqueConstraintAnnot->columns]; if ( ! empty($uniqueConstraintAnnot->options)) { $uniqueConstraint['options'] = $uniqueConstraintAnnot->options; @@ -146,113 +145,121 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) } // Evaluate @Cache annotation - if (isset($classAnnotations['Doctrine\ORM\Mapping\Cache'])) { - $cacheAnnot = $classAnnotations['Doctrine\ORM\Mapping\Cache']; - $cacheMap = array( + if (isset($classAnnotations[Mapping\Cache::class])) { + $cacheAnnot = $classAnnotations[Mapping\Cache::class]; + $cacheMap = [ 'region' => $cacheAnnot->region, 'usage' => constant('Doctrine\ORM\Mapping\ClassMetadata::CACHE_USAGE_' . $cacheAnnot->usage), - ); + ]; $metadata->enableCache($cacheMap); } // Evaluate NamedNativeQueries annotation - if (isset($classAnnotations['Doctrine\ORM\Mapping\NamedNativeQueries'])) { - $namedNativeQueriesAnnot = $classAnnotations['Doctrine\ORM\Mapping\NamedNativeQueries']; + if (isset($classAnnotations[Mapping\NamedNativeQueries::class])) { + $namedNativeQueriesAnnot = $classAnnotations[Mapping\NamedNativeQueries::class]; foreach ($namedNativeQueriesAnnot->value as $namedNativeQuery) { - $metadata->addNamedNativeQuery(array( - 'name' => $namedNativeQuery->name, - 'query' => $namedNativeQuery->query, - 'resultClass' => $namedNativeQuery->resultClass, - 'resultSetMapping' => $namedNativeQuery->resultSetMapping, - )); + $metadata->addNamedNativeQuery( + [ + 'name' => $namedNativeQuery->name, + 'query' => $namedNativeQuery->query, + 'resultClass' => $namedNativeQuery->resultClass, + 'resultSetMapping' => $namedNativeQuery->resultSetMapping, + ] + ); } } // Evaluate SqlResultSetMappings annotation - if (isset($classAnnotations['Doctrine\ORM\Mapping\SqlResultSetMappings'])) { - $sqlResultSetMappingsAnnot = $classAnnotations['Doctrine\ORM\Mapping\SqlResultSetMappings']; + if (isset($classAnnotations[Mapping\SqlResultSetMappings::class])) { + $sqlResultSetMappingsAnnot = $classAnnotations[Mapping\SqlResultSetMappings::class]; foreach ($sqlResultSetMappingsAnnot->value as $resultSetMapping) { - $entities = array(); - $columns = array(); + $entities = []; + $columns = []; foreach ($resultSetMapping->entities as $entityResultAnnot) { - $entityResult = array( - 'fields' => array(), + $entityResult = [ + 'fields' => [], 'entityClass' => $entityResultAnnot->entityClass, 'discriminatorColumn' => $entityResultAnnot->discriminatorColumn, - ); + ]; foreach ($entityResultAnnot->fields as $fieldResultAnnot) { - $entityResult['fields'][] = array( + $entityResult['fields'][] = [ 'name' => $fieldResultAnnot->name, 'column' => $fieldResultAnnot->column - ); + ]; } $entities[] = $entityResult; } foreach ($resultSetMapping->columns as $columnResultAnnot) { - $columns[] = array( + $columns[] = [ 'name' => $columnResultAnnot->name, - ); + ]; } - $metadata->addSqlResultSetMapping(array( - 'name' => $resultSetMapping->name, - 'entities' => $entities, - 'columns' => $columns - )); + $metadata->addSqlResultSetMapping( + [ + 'name' => $resultSetMapping->name, + 'entities' => $entities, + 'columns' => $columns + ] + ); } } // Evaluate NamedQueries annotation - if (isset($classAnnotations['Doctrine\ORM\Mapping\NamedQueries'])) { - $namedQueriesAnnot = $classAnnotations['Doctrine\ORM\Mapping\NamedQueries']; + if (isset($classAnnotations[Mapping\NamedQueries::class])) { + $namedQueriesAnnot = $classAnnotations[Mapping\NamedQueries::class]; if ( ! is_array($namedQueriesAnnot->value)) { throw new \UnexpectedValueException("@NamedQueries should contain an array of @NamedQuery annotations."); } foreach ($namedQueriesAnnot->value as $namedQuery) { - if ( ! ($namedQuery instanceof \Doctrine\ORM\Mapping\NamedQuery)) { + if ( ! ($namedQuery instanceof Mapping\NamedQuery)) { throw new \UnexpectedValueException("@NamedQueries should contain an array of @NamedQuery annotations."); } - $metadata->addNamedQuery(array( - 'name' => $namedQuery->name, - 'query' => $namedQuery->query - )); + $metadata->addNamedQuery( + [ + 'name' => $namedQuery->name, + 'query' => $namedQuery->query + ] + ); } } // Evaluate InheritanceType annotation - if (isset($classAnnotations['Doctrine\ORM\Mapping\InheritanceType'])) { - $inheritanceTypeAnnot = $classAnnotations['Doctrine\ORM\Mapping\InheritanceType']; + if (isset($classAnnotations[Mapping\InheritanceType::class])) { + $inheritanceTypeAnnot = $classAnnotations[Mapping\InheritanceType::class]; $metadata->setInheritanceType( constant('Doctrine\ORM\Mapping\ClassMetadata::INHERITANCE_TYPE_' . $inheritanceTypeAnnot->value) ); - if ($metadata->inheritanceType != \Doctrine\ORM\Mapping\ClassMetadata::INHERITANCE_TYPE_NONE) { + if ($metadata->inheritanceType != Mapping\ClassMetadata::INHERITANCE_TYPE_NONE) { // Evaluate DiscriminatorColumn annotation - if (isset($classAnnotations['Doctrine\ORM\Mapping\DiscriminatorColumn'])) { - $discrColumnAnnot = $classAnnotations['Doctrine\ORM\Mapping\DiscriminatorColumn']; - - $metadata->setDiscriminatorColumn(array( - 'name' => $discrColumnAnnot->name, - 'type' => $discrColumnAnnot->type ?: 'string', - 'length' => $discrColumnAnnot->length ?: 255, - 'columnDefinition' => $discrColumnAnnot->columnDefinition, - )); + if (isset($classAnnotations[Mapping\DiscriminatorColumn::class])) { + $discrColumnAnnot = $classAnnotations[Mapping\DiscriminatorColumn::class]; + + $metadata->setDiscriminatorColumn( + [ + 'name' => $discrColumnAnnot->name, + 'type' => $discrColumnAnnot->type ?: 'string', + 'length' => $discrColumnAnnot->length ?: 255, + 'columnDefinition' => $discrColumnAnnot->columnDefinition, + ] + ); } else { - $metadata->setDiscriminatorColumn(array('name' => 'dtype', 'type' => 'string', 'length' => 255)); + $metadata->setDiscriminatorColumn(['name' => 'dtype', 'type' => 'string', 'length' => 255]); } // Evaluate DiscriminatorMap annotation - if (isset($classAnnotations['Doctrine\ORM\Mapping\DiscriminatorMap'])) { - $discrMapAnnot = $classAnnotations['Doctrine\ORM\Mapping\DiscriminatorMap']; + if (isset($classAnnotations[Mapping\DiscriminatorMap::class])) { + $discrMapAnnot = $classAnnotations[Mapping\DiscriminatorMap::class]; $metadata->setDiscriminatorMap($discrMapAnnot->value); } } @@ -260,8 +267,8 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) // Evaluate DoctrineChangeTrackingPolicy annotation - if (isset($classAnnotations['Doctrine\ORM\Mapping\ChangeTrackingPolicy'])) { - $changeTrackingAnnot = $classAnnotations['Doctrine\ORM\Mapping\ChangeTrackingPolicy']; + if (isset($classAnnotations[Mapping\ChangeTrackingPolicy::class])) { + $changeTrackingAnnot = $classAnnotations[Mapping\ChangeTrackingPolicy::class]; $metadata->setChangeTrackingPolicy(constant('Doctrine\ORM\Mapping\ClassMetadata::CHANGETRACKING_' . $changeTrackingAnnot->value)); } @@ -278,22 +285,25 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) continue; } - $mapping = array(); + $mapping = []; $mapping['fieldName'] = $property->getName(); // Evaluate @Cache annotation - if (($cacheAnnot = $this->reader->getPropertyAnnotation($property, 'Doctrine\ORM\Mapping\Cache')) !== null) { - $mapping['cache'] = $metadata->getAssociationCacheDefaults($mapping['fieldName'], array( - 'usage' => constant('Doctrine\ORM\Mapping\ClassMetadata::CACHE_USAGE_' . $cacheAnnot->usage), - 'region' => $cacheAnnot->region, - )); + if (($cacheAnnot = $this->reader->getPropertyAnnotation($property, Mapping\Cache::class)) !== null) { + $mapping['cache'] = $metadata->getAssociationCacheDefaults( + $mapping['fieldName'], + [ + 'usage' => constant('Doctrine\ORM\Mapping\ClassMetadata::CACHE_USAGE_' . $cacheAnnot->usage), + 'region' => $cacheAnnot->region, + ] + ); } // Check for JoinColumn/JoinColumns annotations - $joinColumns = array(); + $joinColumns = []; - if ($joinColumnAnnot = $this->reader->getPropertyAnnotation($property, 'Doctrine\ORM\Mapping\JoinColumn')) { + if ($joinColumnAnnot = $this->reader->getPropertyAnnotation($property, Mapping\JoinColumn::class)) { $joinColumns[] = $this->joinColumnToArray($joinColumnAnnot); - } else if ($joinColumnsAnnot = $this->reader->getPropertyAnnotation($property, 'Doctrine\ORM\Mapping\JoinColumns')) { + } else if ($joinColumnsAnnot = $this->reader->getPropertyAnnotation($property, Mapping\JoinColumns::class)) { foreach ($joinColumnsAnnot->value as $joinColumn) { $joinColumns[] = $this->joinColumnToArray($joinColumn); } @@ -301,43 +311,47 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) // Field can only be annotated with one of: // @Column, @OneToOne, @OneToMany, @ManyToOne, @ManyToMany - if ($columnAnnot = $this->reader->getPropertyAnnotation($property, 'Doctrine\ORM\Mapping\Column')) { + if ($columnAnnot = $this->reader->getPropertyAnnotation($property, Mapping\Column::class)) { if ($columnAnnot->type == null) { throw MappingException::propertyTypeIsRequired($className, $property->getName()); } $mapping = $this->columnToArray($property->getName(), $columnAnnot); - if ($idAnnot = $this->reader->getPropertyAnnotation($property, 'Doctrine\ORM\Mapping\Id')) { + if ($idAnnot = $this->reader->getPropertyAnnotation($property, Mapping\Id::class)) { $mapping['id'] = true; } - if ($generatedValueAnnot = $this->reader->getPropertyAnnotation($property, 'Doctrine\ORM\Mapping\GeneratedValue')) { + if ($generatedValueAnnot = $this->reader->getPropertyAnnotation($property, Mapping\GeneratedValue::class)) { $metadata->setIdGeneratorType(constant('Doctrine\ORM\Mapping\ClassMetadata::GENERATOR_TYPE_' . $generatedValueAnnot->strategy)); } - if ($this->reader->getPropertyAnnotation($property, 'Doctrine\ORM\Mapping\Version')) { + if ($this->reader->getPropertyAnnotation($property, Mapping\Version::class)) { $metadata->setVersionMapping($mapping); } $metadata->mapField($mapping); // Check for SequenceGenerator/TableGenerator definition - if ($seqGeneratorAnnot = $this->reader->getPropertyAnnotation($property, 'Doctrine\ORM\Mapping\SequenceGenerator')) { - $metadata->setSequenceGeneratorDefinition(array( - 'sequenceName' => $seqGeneratorAnnot->sequenceName, - 'allocationSize' => $seqGeneratorAnnot->allocationSize, - 'initialValue' => $seqGeneratorAnnot->initialValue - )); + if ($seqGeneratorAnnot = $this->reader->getPropertyAnnotation($property, Mapping\SequenceGenerator::class)) { + $metadata->setSequenceGeneratorDefinition( + [ + 'sequenceName' => $seqGeneratorAnnot->sequenceName, + 'allocationSize' => $seqGeneratorAnnot->allocationSize, + 'initialValue' => $seqGeneratorAnnot->initialValue + ] + ); } else if ($this->reader->getPropertyAnnotation($property, 'Doctrine\ORM\Mapping\TableGenerator')) { throw MappingException::tableIdGeneratorNotImplemented($className); - } else if ($customGeneratorAnnot = $this->reader->getPropertyAnnotation($property, 'Doctrine\ORM\Mapping\CustomIdGenerator')) { - $metadata->setCustomGeneratorDefinition(array( - 'class' => $customGeneratorAnnot->class - )); + } else if ($customGeneratorAnnot = $this->reader->getPropertyAnnotation($property, Mapping\CustomIdGenerator::class)) { + $metadata->setCustomGeneratorDefinition( + [ + 'class' => $customGeneratorAnnot->class + ] + ); } - } else if ($oneToOneAnnot = $this->reader->getPropertyAnnotation($property, 'Doctrine\ORM\Mapping\OneToOne')) { - if ($idAnnot = $this->reader->getPropertyAnnotation($property, 'Doctrine\ORM\Mapping\Id')) { + } else if ($oneToOneAnnot = $this->reader->getPropertyAnnotation($property, Mapping\OneToOne::class)) { + if ($idAnnot = $this->reader->getPropertyAnnotation($property, Mapping\Id::class)) { $mapping['id'] = true; } @@ -349,7 +363,7 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) $mapping['orphanRemoval'] = $oneToOneAnnot->orphanRemoval; $mapping['fetch'] = $this->getFetchMode($className, $oneToOneAnnot->fetch); $metadata->mapOneToOne($mapping); - } else if ($oneToManyAnnot = $this->reader->getPropertyAnnotation($property, 'Doctrine\ORM\Mapping\OneToMany')) { + } else if ($oneToManyAnnot = $this->reader->getPropertyAnnotation($property, Mapping\OneToMany::class)) { $mapping['mappedBy'] = $oneToManyAnnot->mappedBy; $mapping['targetEntity'] = $oneToManyAnnot->targetEntity; $mapping['cascade'] = $oneToManyAnnot->cascade; @@ -357,13 +371,13 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) $mapping['orphanRemoval'] = $oneToManyAnnot->orphanRemoval; $mapping['fetch'] = $this->getFetchMode($className, $oneToManyAnnot->fetch); - if ($orderByAnnot = $this->reader->getPropertyAnnotation($property, 'Doctrine\ORM\Mapping\OrderBy')) { + if ($orderByAnnot = $this->reader->getPropertyAnnotation($property, Mapping\OrderBy::class)) { $mapping['orderBy'] = $orderByAnnot->value; } $metadata->mapOneToMany($mapping); - } else if ($manyToOneAnnot = $this->reader->getPropertyAnnotation($property, 'Doctrine\ORM\Mapping\ManyToOne')) { - if ($idAnnot = $this->reader->getPropertyAnnotation($property, 'Doctrine\ORM\Mapping\Id')) { + } else if ($manyToOneAnnot = $this->reader->getPropertyAnnotation($property, Mapping\ManyToOne::class)) { + if ($idAnnot = $this->reader->getPropertyAnnotation($property, Mapping\Id::class)) { $mapping['id'] = true; } @@ -373,14 +387,14 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) $mapping['targetEntity'] = $manyToOneAnnot->targetEntity; $mapping['fetch'] = $this->getFetchMode($className, $manyToOneAnnot->fetch); $metadata->mapManyToOne($mapping); - } else if ($manyToManyAnnot = $this->reader->getPropertyAnnotation($property, 'Doctrine\ORM\Mapping\ManyToMany')) { - $joinTable = array(); + } else if ($manyToManyAnnot = $this->reader->getPropertyAnnotation($property, Mapping\ManyToMany::class)) { + $joinTable = []; - if ($joinTableAnnot = $this->reader->getPropertyAnnotation($property, 'Doctrine\ORM\Mapping\JoinTable')) { - $joinTable = array( + if ($joinTableAnnot = $this->reader->getPropertyAnnotation($property, Mapping\JoinTable::class)) { + $joinTable = [ 'name' => $joinTableAnnot->name, 'schema' => $joinTableAnnot->schema - ); + ]; foreach ($joinTableAnnot->joinColumns as $joinColumn) { $joinTable['joinColumns'][] = $this->joinColumnToArray($joinColumn); @@ -400,12 +414,12 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) $mapping['orphanRemoval'] = $manyToManyAnnot->orphanRemoval; $mapping['fetch'] = $this->getFetchMode($className, $manyToManyAnnot->fetch); - if ($orderByAnnot = $this->reader->getPropertyAnnotation($property, 'Doctrine\ORM\Mapping\OrderBy')) { + if ($orderByAnnot = $this->reader->getPropertyAnnotation($property, Mapping\OrderBy::class)) { $mapping['orderBy'] = $orderByAnnot->value; } $metadata->mapManyToMany($mapping); - } else if ($embeddedAnnot = $this->reader->getPropertyAnnotation($property, 'Doctrine\ORM\Mapping\Embedded')) { + } else if ($embeddedAnnot = $this->reader->getPropertyAnnotation($property, Mapping\Embedded::class)) { $mapping['class'] = $embeddedAnnot->class; $mapping['columnPrefix'] = $embeddedAnnot->columnPrefix; @@ -414,16 +428,16 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) } // Evaluate AssociationOverrides annotation - if (isset($classAnnotations['Doctrine\ORM\Mapping\AssociationOverrides'])) { - $associationOverridesAnnot = $classAnnotations['Doctrine\ORM\Mapping\AssociationOverrides']; + if (isset($classAnnotations[Mapping\AssociationOverrides::class])) { + $associationOverridesAnnot = $classAnnotations[Mapping\AssociationOverrides::class]; foreach ($associationOverridesAnnot->value as $associationOverride) { - $override = array(); + $override = []; $fieldName = $associationOverride->name; // Check for JoinColumn/JoinColumns annotations if ($associationOverride->joinColumns) { - $joinColumns = array(); + $joinColumns = []; foreach ($associationOverride->joinColumns as $joinColumn) { $joinColumns[] = $this->joinColumnToArray($joinColumn); @@ -435,10 +449,10 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) // Check for JoinTable annotations if ($associationOverride->joinTable) { $joinTableAnnot = $associationOverride->joinTable; - $joinTable = array( + $joinTable = [ 'name' => $joinTableAnnot->name, 'schema' => $joinTableAnnot->schema - ); + ]; foreach ($joinTableAnnot->joinColumns as $joinColumn) { $joinTable['joinColumns'][] = $this->joinColumnToArray($joinColumn); @@ -456,13 +470,18 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) $override['inversedBy'] = $associationOverride->inversedBy; } + // Check for `fetch` + if ($associationOverride->fetch) { + $override['fetch'] = constant(Mapping\ClassMetadata::class . '::FETCH_' . $associationOverride->fetch); + } + $metadata->setAssociationOverride($fieldName, $override); } } // Evaluate AttributeOverrides annotation - if (isset($classAnnotations['Doctrine\ORM\Mapping\AttributeOverrides'])) { - $attributeOverridesAnnot = $classAnnotations['Doctrine\ORM\Mapping\AttributeOverrides']; + if (isset($classAnnotations[Mapping\AttributeOverrides::class])) { + $attributeOverridesAnnot = $classAnnotations[Mapping\AttributeOverrides::class]; foreach ($attributeOverridesAnnot->value as $attributeOverrideAnnot) { $attributeOverride = $this->columnToArray($attributeOverrideAnnot->name, $attributeOverrideAnnot->column); @@ -472,8 +491,8 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) } // Evaluate EntityListeners annotation - if (isset($classAnnotations['Doctrine\ORM\Mapping\EntityListeners'])) { - $entityListenersAnnot = $classAnnotations['Doctrine\ORM\Mapping\EntityListeners']; + if (isset($classAnnotations[Mapping\EntityListeners::class])) { + $entityListenersAnnot = $classAnnotations[Mapping\EntityListeners::class]; foreach ($entityListenersAnnot->value as $item) { $listenerClassName = $metadata->fullyQualifiedClassName($item); @@ -504,7 +523,7 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) } // Evaluate @HasLifecycleCallbacks annotation - if (isset($classAnnotations['Doctrine\ORM\Mapping\HasLifecycleCallbacks'])) { + if (isset($classAnnotations[Mapping\HasLifecycleCallbacks::class])) { /* @var $method \ReflectionMethod */ foreach ($class->getMethods(\ReflectionMethod::IS_PUBLIC) as $method) { foreach ($this->getMethodCallbacks($method) as $value) { @@ -542,40 +561,40 @@ private function getFetchMode($className, $fetchMode) */ private function getMethodCallbacks(\ReflectionMethod $method) { - $callbacks = array(); + $callbacks = []; $annotations = $this->reader->getMethodAnnotations($method); foreach ($annotations as $annot) { - if ($annot instanceof \Doctrine\ORM\Mapping\PrePersist) { - $callbacks[] = array($method->name, Events::prePersist); + if ($annot instanceof Mapping\PrePersist) { + $callbacks[] = [$method->name, Events::prePersist]; } - if ($annot instanceof \Doctrine\ORM\Mapping\PostPersist) { - $callbacks[] = array($method->name, Events::postPersist); + if ($annot instanceof Mapping\PostPersist) { + $callbacks[] = [$method->name, Events::postPersist]; } - if ($annot instanceof \Doctrine\ORM\Mapping\PreUpdate) { - $callbacks[] = array($method->name, Events::preUpdate); + if ($annot instanceof Mapping\PreUpdate) { + $callbacks[] = [$method->name, Events::preUpdate]; } - if ($annot instanceof \Doctrine\ORM\Mapping\PostUpdate) { - $callbacks[] = array($method->name, Events::postUpdate); + if ($annot instanceof Mapping\PostUpdate) { + $callbacks[] = [$method->name, Events::postUpdate]; } - if ($annot instanceof \Doctrine\ORM\Mapping\PreRemove) { - $callbacks[] = array($method->name, Events::preRemove); + if ($annot instanceof Mapping\PreRemove) { + $callbacks[] = [$method->name, Events::preRemove]; } - if ($annot instanceof \Doctrine\ORM\Mapping\PostRemove) { - $callbacks[] = array($method->name, Events::postRemove); + if ($annot instanceof Mapping\PostRemove) { + $callbacks[] = [$method->name, Events::postRemove]; } - if ($annot instanceof \Doctrine\ORM\Mapping\PostLoad) { - $callbacks[] = array($method->name, Events::postLoad); + if ($annot instanceof Mapping\PostLoad) { + $callbacks[] = [$method->name, Events::postLoad]; } - if ($annot instanceof \Doctrine\ORM\Mapping\PreFlush) { - $callbacks[] = array($method->name, Events::preFlush); + if ($annot instanceof Mapping\PreFlush) { + $callbacks[] = [$method->name, Events::preFlush]; } } @@ -585,32 +604,32 @@ private function getMethodCallbacks(\ReflectionMethod $method) /** * Parse the given JoinColumn as array * - * @param JoinColumn $joinColumn + * @param Mapping\JoinColumn $joinColumn * @return array */ - private function joinColumnToArray(JoinColumn $joinColumn) + private function joinColumnToArray(Mapping\JoinColumn $joinColumn) { - return array( + return [ 'name' => $joinColumn->name, 'unique' => $joinColumn->unique, 'nullable' => $joinColumn->nullable, 'onDelete' => $joinColumn->onDelete, 'columnDefinition' => $joinColumn->columnDefinition, 'referencedColumnName' => $joinColumn->referencedColumnName, - ); + ]; } /** * Parse the given Column as array * * @param string $fieldName - * @param Column $column + * @param Mapping\Column $column * * @return array */ - private function columnToArray($fieldName, Column $column) + private function columnToArray($fieldName, Mapping\Column $column) { - $mapping = array( + $mapping = [ 'fieldName' => $fieldName, 'type' => $column->type, 'scale' => $column->scale, @@ -618,7 +637,7 @@ private function columnToArray($fieldName, Column $column) 'unique' => $column->unique, 'nullable' => $column->nullable, 'precision' => $column->precision - ); + ]; if ($column->options) { $mapping['options'] = $column->options; @@ -643,7 +662,7 @@ private function columnToArray($fieldName, Column $column) * * @return AnnotationDriver */ - static public function create($paths = array(), AnnotationReader $reader = null) + static public function create($paths = [], AnnotationReader $reader = null) { if ($reader == null) { $reader = new AnnotationReader(); diff --git a/lib/Doctrine/ORM/Mapping/Driver/DatabaseDriver.php b/lib/Doctrine/ORM/Mapping/Driver/DatabaseDriver.php index ac3b309fd7e..83798e16e21 100644 --- a/lib/Doctrine/ORM/Mapping/Driver/DatabaseDriver.php +++ b/lib/Doctrine/ORM/Mapping/Driver/DatabaseDriver.php @@ -19,9 +19,9 @@ namespace Doctrine\ORM\Mapping\Driver; +use Doctrine\Common\Inflector\Inflector; use Doctrine\Common\Persistence\Mapping\Driver\MappingDriver; use Doctrine\Common\Persistence\Mapping\ClassMetadata; -use Doctrine\Common\Util\Inflector; use Doctrine\DBAL\Schema\AbstractSchemaManager; use Doctrine\DBAL\Schema\SchemaException; use Doctrine\DBAL\Schema\Table; @@ -29,6 +29,7 @@ use Doctrine\DBAL\Types\Type; use Doctrine\ORM\Mapping\ClassMetadataInfo; use Doctrine\ORM\Mapping\MappingException; +use function preg_replace; /** * The DatabaseDriver reverse engineers the mapping metadata from a database. @@ -54,22 +55,22 @@ class DatabaseDriver implements MappingDriver /** * @var array */ - private $classToTableNames = array(); + private $classToTableNames = []; /** * @var array */ - private $manyToManyTables = array(); + private $manyToManyTables = []; /** * @var array */ - private $classNamesForTables = array(); + private $classNamesForTables = []; /** * @var array */ - private $fieldNamesForColumns = array(); + private $fieldNamesForColumns = []; /** * The namespace for the generated entities. @@ -153,7 +154,7 @@ public function setFieldNameForColumn($tableName, $columnName, $fieldName) */ public function setTables($entityTables, $manyToManyTables) { - $this->tables = $this->manyToManyTables = $this->classToTableNames = array(); + $this->tables = $this->manyToManyTables = $this->classToTableNames = []; foreach ($entityTables as $table) { $className = $this->getClassNameForTable($table->getName()); @@ -212,36 +213,36 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) $localColumn = current($myFk->getColumns()); - $associationMapping = array(); + $associationMapping = []; $associationMapping['fieldName'] = $this->getFieldNameForColumn($manyTable->getName(), current($otherFk->getColumns()), true); $associationMapping['targetEntity'] = $this->getClassNameForTable($otherFk->getForeignTableName()); if (current($manyTable->getColumns())->getName() == $localColumn) { $associationMapping['inversedBy'] = $this->getFieldNameForColumn($manyTable->getName(), current($myFk->getColumns()), true); - $associationMapping['joinTable'] = array( + $associationMapping['joinTable'] = [ 'name' => strtolower($manyTable->getName()), - 'joinColumns' => array(), - 'inverseJoinColumns' => array(), - ); + 'joinColumns' => [], + 'inverseJoinColumns' => [], + ]; $fkCols = $myFk->getForeignColumns(); $cols = $myFk->getColumns(); - for ($i = 0; $i < count($cols); $i++) { - $associationMapping['joinTable']['joinColumns'][] = array( + for ($i = 0, $colsCount = count($cols); $i < $colsCount; $i++) { + $associationMapping['joinTable']['joinColumns'][] = [ 'name' => $cols[$i], 'referencedColumnName' => $fkCols[$i], - ); + ]; } $fkCols = $otherFk->getForeignColumns(); $cols = $otherFk->getColumns(); - for ($i = 0; $i < count($cols); $i++) { - $associationMapping['joinTable']['inverseJoinColumns'][] = array( + for ($i = 0, $colsCount = count($cols); $i < $colsCount; $i++) { + $associationMapping['joinTable']['inverseJoinColumns'][] = [ 'name' => $cols[$i], 'referencedColumnName' => $fkCols[$i], - ); + ]; } } else { $associationMapping['mappedBy'] = $this->getFieldNameForColumn($manyTable->getName(), current($myFk->getColumns()), true); @@ -265,20 +266,20 @@ private function reverseEngineerMappingFromDatabase() return; } - $tables = array(); + $tables = []; foreach ($this->_sm->listTableNames() as $tableName) { $tables[$tableName] = $this->_sm->listTableDetails($tableName); } - $this->tables = $this->manyToManyTables = $this->classToTableNames = array(); + $this->tables = $this->manyToManyTables = $this->classToTableNames = []; foreach ($tables as $tableName => $table) { $foreignKeys = ($this->_sm->getDatabasePlatform()->supportsForeignKeyConstraints()) ? $table->getForeignKeys() - : array(); + : []; - $allForeignKeyColumns = array(); + $allForeignKeyColumns = []; foreach ($foreignKeys as $foreignKey) { $allForeignKeyColumns = array_merge($allForeignKeyColumns, $foreignKey->getLocalColumns()); @@ -345,14 +346,14 @@ private function buildFieldMappings(ClassMetadataInfo $metadata) $columns = $this->tables[$tableName]->getColumns(); $primaryKeys = $this->getTablePrimaryKeys($this->tables[$tableName]); $foreignKeys = $this->getTableForeignKeys($this->tables[$tableName]); - $allForeignKeys = array(); + $allForeignKeys = []; foreach ($foreignKeys as $foreignKey) { $allForeignKeys = array_merge($allForeignKeys, $foreignKey->getLocalColumns()); } - $ids = array(); - $fieldMappings = array(); + $ids = []; + $fieldMappings = []; foreach ($columns as $column) { if (in_array($column->getName(), $allForeignKeys)) { @@ -389,12 +390,12 @@ private function buildFieldMappings(ClassMetadataInfo $metadata) */ private function buildFieldMapping($tableName, Column $column) { - $fieldMapping = array( + $fieldMapping = [ 'fieldName' => $this->getFieldNameForColumn($tableName, $column->getName(), false), 'columnName' => $column->getName(), 'type' => $column->getType()->getName(), - 'nullable' => ( ! $column->getNotNull()), - ); + 'nullable' => ( ! $column->getNotnull()), + ]; // Type specific elements switch ($fieldMapping['type']) { @@ -452,10 +453,10 @@ private function buildToOneAssociationMappings(ClassMetadataInfo $metadata) $fkColumns = $foreignKey->getColumns(); $fkForeignColumns = $foreignKey->getForeignColumns(); $localColumn = current($fkColumns); - $associationMapping = array( + $associationMapping = [ 'fieldName' => $this->getFieldNameForColumn($tableName, $localColumn, true), 'targetEntity' => $this->getClassNameForTable($foreignTableName), - ); + ]; if (isset($metadata->fieldMappings[$associationMapping['fieldName']])) { $associationMapping['fieldName'] .= '2'; // "foo" => "foo2" @@ -465,11 +466,11 @@ private function buildToOneAssociationMappings(ClassMetadataInfo $metadata) $associationMapping['id'] = true; } - for ($i = 0; $i < count($fkColumns); $i++) { - $associationMapping['joinColumns'][] = array( + for ($i = 0, $fkColumnsCount = count($fkColumns); $i < $fkColumnsCount; $i++) { + $associationMapping['joinColumns'][] = [ 'name' => $fkColumns[$i], 'referencedColumnName' => $fkForeignColumns[$i], - ); + ]; } // Here we need to check if $fkColumns are the same as $primaryKeys @@ -482,7 +483,7 @@ private function buildToOneAssociationMappings(ClassMetadataInfo $metadata) } /** - * Retreive schema table definition foreign keys. + * Retrieve schema table definition foreign keys. * * @param \Doctrine\DBAL\Schema\Table $table * @@ -492,11 +493,11 @@ private function getTableForeignKeys(Table $table) { return ($this->_sm->getDatabasePlatform()->supportsForeignKeyConstraints()) ? $table->getForeignKeys() - : array(); + : []; } /** - * Retreive schema table definition primary keys. + * Retrieve schema table definition primary keys. * * @param \Doctrine\DBAL\Schema\Table $table * @@ -510,7 +511,7 @@ private function getTablePrimaryKeys(Table $table) // Do nothing } - return array(); + return []; } /** @@ -548,7 +549,7 @@ private function getFieldNameForColumn($tableName, $columnName, $fk = false) // Replace _id if it is a foreignkey column if ($fk) { - $columnName = str_replace('_id', '', $columnName); + $columnName = preg_replace('/_id$/', '', $columnName); } return Inflector::camelize($columnName); diff --git a/lib/Doctrine/ORM/Mapping/Driver/SimplifiedXmlDriver.php b/lib/Doctrine/ORM/Mapping/Driver/SimplifiedXmlDriver.php index 85221f3a2bc..9bfd84cae38 100644 --- a/lib/Doctrine/ORM/Mapping/Driver/SimplifiedXmlDriver.php +++ b/lib/Doctrine/ORM/Mapping/Driver/SimplifiedXmlDriver.php @@ -15,7 +15,7 @@ * This software consists of voluntary contributions made by many individuals * and is licensed under the MIT license. For more information, see * . -*/ + */ namespace Doctrine\ORM\Mapping\Driver; diff --git a/lib/Doctrine/ORM/Mapping/Driver/SimplifiedYamlDriver.php b/lib/Doctrine/ORM/Mapping/Driver/SimplifiedYamlDriver.php index d2b8c0fcf03..8f38784f4e6 100644 --- a/lib/Doctrine/ORM/Mapping/Driver/SimplifiedYamlDriver.php +++ b/lib/Doctrine/ORM/Mapping/Driver/SimplifiedYamlDriver.php @@ -15,7 +15,7 @@ * This software consists of voluntary contributions made by many individuals * and is licensed under the MIT license. For more information, see * . -*/ + */ namespace Doctrine\ORM\Mapping\Driver; diff --git a/lib/Doctrine/ORM/Mapping/Driver/XmlDriver.php b/lib/Doctrine/ORM/Mapping/Driver/XmlDriver.php index 00de4f2ea11..93b697caef6 100644 --- a/lib/Doctrine/ORM/Mapping/Driver/XmlDriver.php +++ b/lib/Doctrine/ORM/Mapping/Driver/XmlDriver.php @@ -19,11 +19,13 @@ namespace Doctrine\ORM\Mapping\Driver; +use Doctrine\Common\Collections\Criteria; use SimpleXMLElement; use Doctrine\Common\Persistence\Mapping\Driver\FileDriver; use Doctrine\ORM\Mapping\Builder\EntityListenerBuilder; use Doctrine\Common\Persistence\Mapping\ClassMetadata; use Doctrine\ORM\Mapping\MappingException; +use Doctrine\ORM\Mapping\ClassMetadata as Metadata; /** * XmlDriver is a metadata driver that enables mapping through XML files. @@ -76,7 +78,7 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) } // Evaluate attributes - $primaryTable = array(); + $primaryTable = []; if (isset($xmlRoot['table'])) { $primaryTable['name'] = (string) $xmlRoot['table']; @@ -96,44 +98,48 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) // Evaluate named queries if (isset($xmlRoot->{'named-queries'})) { foreach ($xmlRoot->{'named-queries'}->{'named-query'} as $namedQueryElement) { - $metadata->addNamedQuery(array( - 'name' => (string) $namedQueryElement['name'], - 'query' => (string) $namedQueryElement['query'] - )); + $metadata->addNamedQuery( + [ + 'name' => (string) $namedQueryElement['name'], + 'query' => (string) $namedQueryElement['query'] + ] + ); } } // Evaluate native named queries if (isset($xmlRoot->{'named-native-queries'})) { foreach ($xmlRoot->{'named-native-queries'}->{'named-native-query'} as $nativeQueryElement) { - $metadata->addNamedNativeQuery(array( - 'name' => isset($nativeQueryElement['name']) ? (string) $nativeQueryElement['name'] : null, - 'query' => isset($nativeQueryElement->query) ? (string) $nativeQueryElement->query : null, - 'resultClass' => isset($nativeQueryElement['result-class']) ? (string) $nativeQueryElement['result-class'] : null, - 'resultSetMapping' => isset($nativeQueryElement['result-set-mapping']) ? (string) $nativeQueryElement['result-set-mapping'] : null, - )); + $metadata->addNamedNativeQuery( + [ + 'name' => isset($nativeQueryElement['name']) ? (string) $nativeQueryElement['name'] : null, + 'query' => isset($nativeQueryElement->query) ? (string) $nativeQueryElement->query : null, + 'resultClass' => isset($nativeQueryElement['result-class']) ? (string) $nativeQueryElement['result-class'] : null, + 'resultSetMapping' => isset($nativeQueryElement['result-set-mapping']) ? (string) $nativeQueryElement['result-set-mapping'] : null, + ] + ); } } // Evaluate sql result set mapping if (isset($xmlRoot->{'sql-result-set-mappings'})) { foreach ($xmlRoot->{'sql-result-set-mappings'}->{'sql-result-set-mapping'} as $rsmElement) { - $entities = array(); - $columns = array(); + $entities = []; + $columns = []; foreach ($rsmElement as $entityElement) { // if (isset($entityElement['entity-class'])) { - $entityResult = array( - 'fields' => array(), + $entityResult = [ + 'fields' => [], 'entityClass' => (string) $entityElement['entity-class'], 'discriminatorColumn' => isset($entityElement['discriminator-column']) ? (string) $entityElement['discriminator-column'] : null, - ); + ]; foreach ($entityElement as $fieldElement) { - $entityResult['fields'][] = array( + $entityResult['fields'][] = [ 'name' => isset($fieldElement['name']) ? (string) $fieldElement['name'] : null, 'column' => isset($fieldElement['column']) ? (string) $fieldElement['column'] : null, - ); + ]; } $entities[] = $entityResult; @@ -141,17 +147,19 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) // if (isset($entityElement['name'])) { - $columns[] = array( + $columns[] = [ 'name' => (string) $entityElement['name'], - ); + ]; } } - $metadata->addSqlResultSetMapping(array( - 'name' => (string) $rsmElement['name'], - 'entities' => $entities, - 'columns' => $columns - )); + $metadata->addSqlResultSetMapping( + [ + 'name' => (string) $rsmElement['name'], + 'entities' => $entities, + 'columns' => $columns + ] + ); } } @@ -159,23 +167,25 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) $inheritanceType = (string) $xmlRoot['inheritance-type']; $metadata->setInheritanceType(constant('Doctrine\ORM\Mapping\ClassMetadata::INHERITANCE_TYPE_' . $inheritanceType)); - if ($metadata->inheritanceType != \Doctrine\ORM\Mapping\ClassMetadata::INHERITANCE_TYPE_NONE) { + if ($metadata->inheritanceType != Metadata::INHERITANCE_TYPE_NONE) { // Evaluate if (isset($xmlRoot->{'discriminator-column'})) { $discrColumn = $xmlRoot->{'discriminator-column'}; - $metadata->setDiscriminatorColumn(array( - 'name' => isset($discrColumn['name']) ? (string) $discrColumn['name'] : null, - 'type' => isset($discrColumn['type']) ? (string) $discrColumn['type'] : 'string', - 'length' => isset($discrColumn['length']) ? (string) $discrColumn['length'] : 255, - 'columnDefinition' => isset($discrColumn['column-definition']) ? (string) $discrColumn['column-definition'] : null - )); + $metadata->setDiscriminatorColumn( + [ + 'name' => isset($discrColumn['name']) ? (string) $discrColumn['name'] : null, + 'type' => isset($discrColumn['type']) ? (string) $discrColumn['type'] : 'string', + 'length' => isset($discrColumn['length']) ? (string) $discrColumn['length'] : 255, + 'columnDefinition' => isset($discrColumn['column-definition']) ? (string) $discrColumn['column-definition'] : null + ] + ); } else { - $metadata->setDiscriminatorColumn(array('name' => 'dtype', 'type' => 'string', 'length' => 255)); + $metadata->setDiscriminatorColumn(['name' => 'dtype', 'type' => 'string', 'length' => 255]); } // Evaluate if (isset($xmlRoot->{'discriminator-map'})) { - $map = array(); + $map = []; foreach ($xmlRoot->{'discriminator-map'}->{'discriminator-mapping'} as $discrMapElement) { $map[(string) $discrMapElement['value']] = (string) $discrMapElement['class']; } @@ -193,9 +203,9 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) // Evaluate if (isset($xmlRoot->indexes)) { - $metadata->table['indexes'] = array(); + $metadata->table['indexes'] = []; foreach ($xmlRoot->indexes->index as $indexXml) { - $index = array('columns' => explode(',', (string) $indexXml['columns'])); + $index = ['columns' => explode(',', (string) $indexXml['columns'])]; if (isset($indexXml['flags'])) { $index['flags'] = explode(',', (string) $indexXml['flags']); @@ -215,10 +225,9 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) // Evaluate if (isset($xmlRoot->{'unique-constraints'})) { - $metadata->table['uniqueConstraints'] = array(); + $metadata->table['uniqueConstraints'] = []; foreach ($xmlRoot->{'unique-constraints'}->{'unique-constraint'} as $uniqueXml) { - $unique = array('columns' => explode(',', (string) $uniqueXml['columns'])); - + $unique = ['columns' => explode(',', (string) $uniqueXml['columns'])]; if (isset($uniqueXml->options)) { $unique['options'] = $this->_parseOptions($uniqueXml->options->children()); @@ -238,7 +247,7 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) // The mapping assignment is done in 2 times as a bug might occurs on some php/xml lib versions // The internal SimpleXmlIterator get resetted, to this generate a duplicate field exception - $mappings = array(); + $mappings = []; // Evaluate mappings if (isset($xmlRoot->field)) { foreach ($xmlRoot->field as $fieldMapping) { @@ -263,11 +272,11 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) ? $this->evaluateBoolean($embeddedMapping['use-column-prefix']) : true; - $mapping = array( + $mapping = [ 'fieldName' => (string) $embeddedMapping['name'], 'class' => (string) $embeddedMapping['class'], 'columnPrefix' => $useColumnPrefix ? $columnPrefix : false - ); + ]; $metadata->mapEmbedded($mapping); } @@ -282,17 +291,17 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) } // Evaluate mappings - $associationIds = array(); + $associationIds = []; foreach ($xmlRoot->id as $idElement) { if (isset($idElement['association-key']) && $this->evaluateBoolean($idElement['association-key'])) { $associationIds[(string) $idElement['name']] = true; continue; } - $mapping = array( + $mapping = [ 'id' => true, 'fieldName' => (string) $idElement['name'] - ); + ]; if (isset($idElement['type'])) { $mapping['type'] = (string) $idElement['type']; @@ -326,16 +335,20 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) // Check for SequenceGenerator/TableGenerator definition if (isset($idElement->{'sequence-generator'})) { $seqGenerator = $idElement->{'sequence-generator'}; - $metadata->setSequenceGeneratorDefinition(array( - 'sequenceName' => (string) $seqGenerator['sequence-name'], - 'allocationSize' => (string) $seqGenerator['allocation-size'], - 'initialValue' => (string) $seqGenerator['initial-value'] - )); + $metadata->setSequenceGeneratorDefinition( + [ + 'sequenceName' => (string) $seqGenerator['sequence-name'], + 'allocationSize' => (string) $seqGenerator['allocation-size'], + 'initialValue' => (string) $seqGenerator['initial-value'] + ] + ); } else if (isset($idElement->{'custom-id-generator'})) { $customGenerator = $idElement->{'custom-id-generator'}; - $metadata->setCustomGeneratorDefinition(array( - 'class' => (string) $customGenerator['class'] - )); + $metadata->setCustomGeneratorDefinition( + [ + 'class' => (string) $customGenerator['class'] + ] + ); } else if (isset($idElement->{'table-generator'})) { throw MappingException::tableIdGeneratorNotImplemented($className); } @@ -344,10 +357,10 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) // Evaluate mappings if (isset($xmlRoot->{'one-to-one'})) { foreach ($xmlRoot->{'one-to-one'} as $oneToOneElement) { - $mapping = array( + $mapping = [ 'fieldName' => (string) $oneToOneElement['field'], 'targetEntity' => (string) $oneToOneElement['target-entity'] - ); + ]; if (isset($associationIds[$mapping['fieldName']])) { $mapping['id'] = true; @@ -363,7 +376,7 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) if (isset($oneToOneElement['inversed-by'])) { $mapping['inversedBy'] = (string) $oneToOneElement['inversed-by']; } - $joinColumns = array(); + $joinColumns = []; if (isset($oneToOneElement->{'join-column'})) { $joinColumns[] = $this->joinColumnToArray($oneToOneElement->{'join-column'}); @@ -396,11 +409,11 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) // Evaluate mappings if (isset($xmlRoot->{'one-to-many'})) { foreach ($xmlRoot->{'one-to-many'} as $oneToManyElement) { - $mapping = array( + $mapping = [ 'fieldName' => (string) $oneToManyElement['field'], 'targetEntity' => (string) $oneToManyElement['target-entity'], 'mappedBy' => (string) $oneToManyElement['mapped-by'] - ); + ]; if (isset($oneToManyElement['fetch'])) { $mapping['fetch'] = constant('Doctrine\ORM\Mapping\ClassMetadata::FETCH_' . (string) $oneToManyElement['fetch']); @@ -415,9 +428,12 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) } if (isset($oneToManyElement->{'order-by'})) { - $orderBy = array(); + $orderBy = []; foreach ($oneToManyElement->{'order-by'}->{'order-by-field'} as $orderByField) { - $orderBy[(string) $orderByField['name']] = (string) $orderByField['direction']; + $orderBy[(string) $orderByField['name']] = isset($orderByField['direction']) + ? (string) $orderByField['direction'] + : Criteria::ASC + ; } $mapping['orderBy'] = $orderBy; } @@ -440,10 +456,10 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) // Evaluate mappings if (isset($xmlRoot->{'many-to-one'})) { foreach ($xmlRoot->{'many-to-one'} as $manyToOneElement) { - $mapping = array( + $mapping = [ 'fieldName' => (string) $manyToOneElement['field'], 'targetEntity' => (string) $manyToOneElement['target-entity'] - ); + ]; if (isset($associationIds[$mapping['fieldName']])) { $mapping['id'] = true; @@ -457,7 +473,7 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) $mapping['inversedBy'] = (string) $manyToOneElement['inversed-by']; } - $joinColumns = array(); + $joinColumns = []; if (isset($manyToOneElement->{'join-column'})) { $joinColumns[] = $this->joinColumnToArray($manyToOneElement->{'join-column'}); @@ -486,10 +502,10 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) // Evaluate mappings if (isset($xmlRoot->{'many-to-many'})) { foreach ($xmlRoot->{'many-to-many'} as $manyToManyElement) { - $mapping = array( + $mapping = [ 'fieldName' => (string) $manyToManyElement['field'], 'targetEntity' => (string) $manyToManyElement['target-entity'] - ); + ]; if (isset($manyToManyElement['fetch'])) { $mapping['fetch'] = constant('Doctrine\ORM\Mapping\ClassMetadata::FETCH_' . (string) $manyToManyElement['fetch']); @@ -507,9 +523,9 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) } $joinTableElement = $manyToManyElement->{'join-table'}; - $joinTable = array( + $joinTable = [ 'name' => (string) $joinTableElement['name'] - ); + ]; if (isset($joinTableElement['schema'])) { $joinTable['schema'] = (string) $joinTableElement['schema']; @@ -531,9 +547,11 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) } if (isset($manyToManyElement->{'order-by'})) { - $orderBy = array(); + $orderBy = []; foreach ($manyToManyElement->{'order-by'}->{'order-by-field'} as $orderByField) { - $orderBy[(string) $orderByField['name']] = (string) $orderByField['direction']; + $orderBy[(string) $orderByField['name']] = isset($orderByField['direction']) + ? (string) $orderByField['direction'] + : Criteria::ASC; } $mapping['orderBy'] = $orderBy; } @@ -569,11 +587,11 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) if (isset($xmlRoot->{'association-overrides'})) { foreach ($xmlRoot->{'association-overrides'}->{'association-override'} as $overrideElement) { $fieldName = (string) $overrideElement['name']; - $override = array(); + $override = []; // Check for join-columns if (isset($overrideElement->{'join-columns'})) { - $joinColumns = array(); + $joinColumns = []; foreach ($overrideElement->{'join-columns'}->{'join-column'} as $joinColumnElement) { $joinColumns[] = $this->joinColumnToArray($joinColumnElement); } @@ -585,10 +603,10 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) $joinTable = null; $joinTableElement = $overrideElement->{'join-table'}; - $joinTable = array( + $joinTable = [ 'name' => (string) $joinTableElement['name'], 'schema' => (string) $joinTableElement['schema'] - ); + ]; if (isset($joinTableElement->{'join-columns'})) { foreach ($joinTableElement->{'join-columns'}->{'join-column'} as $joinColumnElement) { @@ -610,6 +628,11 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) $override['inversedBy'] = (string) $overrideElement->{'inversed-by'}['name']; } + // Check for `fetch` + if (isset($overrideElement['fetch'])) { + $override['fetch'] = constant(Metadata::class . '::FETCH_' . (string) $overrideElement['fetch']); + } + $metadata->setAssociationOverride($fieldName, $override); } } @@ -651,7 +674,7 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) */ private function _parseOptions(SimpleXMLElement $options) { - $array = array(); + $array = []; /* @var $option SimpleXMLElement */ foreach ($options as $option) { @@ -661,10 +684,13 @@ private function _parseOptions(SimpleXMLElement $options) $value = (string) $option; } - $attr = $option->attributes(); + $attributes = $option->attributes(); - if (isset($attr->name)) { - $array[(string) $attr->name] = $value; + if (isset($attributes->name)) { + $nameAttribute = (string) $attributes->name; + $array[$nameAttribute] = in_array($nameAttribute, ['unsigned', 'fixed']) + ? $this->evaluateBoolean($value) + : $value; } else { $array[] = $value; } @@ -683,10 +709,10 @@ private function _parseOptions(SimpleXMLElement $options) */ private function joinColumnToArray(SimpleXMLElement $joinColumnElement) { - $joinColumn = array( + $joinColumn = [ 'name' => (string) $joinColumnElement['name'], 'referencedColumnName' => (string) $joinColumnElement['referenced-column-name'] - ); + ]; if (isset($joinColumnElement['unique'])) { $joinColumn['unique'] = $this->evaluateBoolean($joinColumnElement['unique']); @@ -716,9 +742,9 @@ private function joinColumnToArray(SimpleXMLElement $joinColumnElement) */ private function columnToArray(SimpleXMLElement $fieldMapping) { - $mapping = array( + $mapping = [ 'fieldName' => (string) $fieldMapping['name'], - ); + ]; if (isset($fieldMapping['type'])) { $mapping['type'] = (string) $fieldMapping['type']; @@ -783,10 +809,10 @@ private function cacheToArray(SimpleXMLElement $cacheMapping) $usage = constant('Doctrine\ORM\Mapping\ClassMetadata::CACHE_USAGE_' . $usage); } - return array( + return [ 'usage' => $usage, 'region' => $region, - ); + ]; } /** @@ -798,7 +824,7 @@ private function cacheToArray(SimpleXMLElement $cacheMapping) */ private function _getCascadeMappings(SimpleXMLElement $cascadeElement) { - $cascades = array(); + $cascades = []; /* @var $action SimpleXmlElement */ foreach ($cascadeElement->children() as $action) { // According to the JPA specifications, XML uses "cascade-persist" @@ -817,8 +843,9 @@ private function _getCascadeMappings(SimpleXMLElement $cascadeElement) */ protected function loadMappingFile($file) { - $result = array(); - $xmlElement = simplexml_load_file($file); + $result = []; + // Note: we do not use `simplexml_load_file()` because of https://bugs.php.net/bug.php?id=62577 + $xmlElement = simplexml_load_string(file_get_contents($file)); if (isset($xmlElement->entity)) { foreach ($xmlElement->entity as $entityElement) { diff --git a/lib/Doctrine/ORM/Mapping/Driver/YamlDriver.php b/lib/Doctrine/ORM/Mapping/Driver/YamlDriver.php index fe406785f58..05339ec4f69 100644 --- a/lib/Doctrine/ORM/Mapping/Driver/YamlDriver.php +++ b/lib/Doctrine/ORM/Mapping/Driver/YamlDriver.php @@ -22,8 +22,10 @@ use Doctrine\Common\Persistence\Mapping\ClassMetadata; use Doctrine\ORM\Mapping\Builder\EntityListenerBuilder; use Doctrine\Common\Persistence\Mapping\Driver\FileDriver; +use Doctrine\ORM\Mapping\ClassMetadata as Metadata; use Doctrine\ORM\Mapping\MappingException; use Symfony\Component\Yaml\Yaml; +use function trigger_error; /** * The YamlDriver reads the mapping metadata from yaml schema files. @@ -33,6 +35,8 @@ * @author Guilherme Blanco * @author Jonathan H. Wage * @author Roman Borschel + * + * @deprecated 2.7 This class is being removed from the ORM and won't have any replacement */ class YamlDriver extends FileDriver { @@ -43,6 +47,11 @@ class YamlDriver extends FileDriver */ public function __construct($locator, $fileExtension = self::DEFAULT_FILE_EXTENSION) { + @trigger_error( + 'YAML mapping driver is deprecated and will be removed in Doctrine ORM 3.0, please migrate to annotation or XML driver.', + E_USER_DEPRECATED + ); + parent::__construct($locator, $fileExtension); } @@ -63,7 +72,7 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) } } else if ($element['type'] == 'mappedSuperclass') { $metadata->setCustomRepositoryClass( - isset($element['repositoryClass']) ? $element['repositoryClass'] : null + $element['repositoryClass'] ?? null ); $metadata->isMappedSuperclass = true; } else if ($element['type'] == 'embeddable') { @@ -73,7 +82,7 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) } // Evaluate root level properties - $primaryTable = array(); + $primaryTable = []; if (isset($element['table'])) { $primaryTable['name'] = $element['table']; @@ -94,7 +103,7 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) if (isset($element['namedQueries'])) { foreach ($element['namedQueries'] as $name => $queryMapping) { if (is_string($queryMapping)) { - $queryMapping = array('query' => $queryMapping); + $queryMapping = ['query' => $queryMapping]; } if ( ! isset($queryMapping['name'])) { @@ -111,12 +120,14 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) if (!isset($mappingElement['name'])) { $mappingElement['name'] = $name; } - $metadata->addNamedNativeQuery(array( - 'name' => $mappingElement['name'], - 'query' => isset($mappingElement['query']) ? $mappingElement['query'] : null, - 'resultClass' => isset($mappingElement['resultClass']) ? $mappingElement['resultClass'] : null, - 'resultSetMapping' => isset($mappingElement['resultSetMapping']) ? $mappingElement['resultSetMapping'] : null, - )); + $metadata->addNamedNativeQuery( + [ + 'name' => $mappingElement['name'], + 'query' => $mappingElement['query'] ?? null, + 'resultClass' => $mappingElement['resultClass'] ?? null, + 'resultSetMapping' => $mappingElement['resultSetMapping'] ?? null, + ] + ); } } @@ -127,22 +138,22 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) $resultSetMapping['name'] = $name; } - $entities = array(); - $columns = array(); + $entities = []; + $columns = []; if (isset($resultSetMapping['entityResult'])) { foreach ($resultSetMapping['entityResult'] as $entityResultElement) { - $entityResult = array( - 'fields' => array(), - 'entityClass' => isset($entityResultElement['entityClass']) ? $entityResultElement['entityClass'] : null, - 'discriminatorColumn' => isset($entityResultElement['discriminatorColumn']) ? $entityResultElement['discriminatorColumn'] : null, - ); + $entityResult = [ + 'fields' => [], + 'entityClass' => $entityResultElement['entityClass'] ?? null, + 'discriminatorColumn' => $entityResultElement['discriminatorColumn'] ?? null, + ]; if (isset($entityResultElement['fieldResult'])) { foreach ($entityResultElement['fieldResult'] as $fieldResultElement) { - $entityResult['fields'][] = array( - 'name' => isset($fieldResultElement['name']) ? $fieldResultElement['name'] : null, - 'column' => isset($fieldResultElement['column']) ? $fieldResultElement['column'] : null, - ); + $entityResult['fields'][] = [ + 'name' => $fieldResultElement['name'] ?? null, + 'column' => $fieldResultElement['column'] ?? null, + ]; } } @@ -153,35 +164,39 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) if (isset($resultSetMapping['columnResult'])) { foreach ($resultSetMapping['columnResult'] as $columnResultAnnot) { - $columns[] = array( - 'name' => isset($columnResultAnnot['name']) ? $columnResultAnnot['name'] : null, - ); + $columns[] = [ + 'name' => $columnResultAnnot['name'] ?? null, + ]; } } - $metadata->addSqlResultSetMapping(array( - 'name' => $resultSetMapping['name'], - 'entities' => $entities, - 'columns' => $columns - )); + $metadata->addSqlResultSetMapping( + [ + 'name' => $resultSetMapping['name'], + 'entities' => $entities, + 'columns' => $columns + ] + ); } } if (isset($element['inheritanceType'])) { $metadata->setInheritanceType(constant('Doctrine\ORM\Mapping\ClassMetadata::INHERITANCE_TYPE_' . strtoupper($element['inheritanceType']))); - if ($metadata->inheritanceType != \Doctrine\ORM\Mapping\ClassMetadata::INHERITANCE_TYPE_NONE) { + if ($metadata->inheritanceType != Metadata::INHERITANCE_TYPE_NONE) { // Evaluate discriminatorColumn if (isset($element['discriminatorColumn'])) { $discrColumn = $element['discriminatorColumn']; - $metadata->setDiscriminatorColumn(array( - 'name' => isset($discrColumn['name']) ? (string) $discrColumn['name'] : null, - 'type' => isset($discrColumn['type']) ? (string) $discrColumn['type'] : 'string', - 'length' => isset($discrColumn['length']) ? (string) $discrColumn['length'] : 255, - 'columnDefinition' => isset($discrColumn['columnDefinition']) ? (string) $discrColumn['columnDefinition'] : null - )); + $metadata->setDiscriminatorColumn( + [ + 'name' => isset($discrColumn['name']) ? (string) $discrColumn['name'] : null, + 'type' => isset($discrColumn['type']) ? (string) $discrColumn['type'] : 'string', + 'length' => isset($discrColumn['length']) ? (string) $discrColumn['length'] : 255, + 'columnDefinition' => isset($discrColumn['columnDefinition']) ? (string) $discrColumn['columnDefinition'] : null + ] + ); } else { - $metadata->setDiscriminatorColumn(array('name' => 'dtype', 'type' => 'string', 'length' => 255)); + $metadata->setDiscriminatorColumn(['name' => 'dtype', 'type' => 'string', 'length' => 255]); } // Evaluate discriminatorMap @@ -206,9 +221,9 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) } if (is_string($indexYml['columns'])) { - $index = array('columns' => array_map('trim', explode(',', $indexYml['columns']))); + $index = ['columns' => array_map('trim', explode(',', $indexYml['columns']))]; } else { - $index = array('columns' => $indexYml['columns']); + $index = ['columns' => $indexYml['columns']]; } if (isset($indexYml['flags'])) { @@ -235,9 +250,9 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) } if (is_string($uniqueYml['columns'])) { - $unique = array('columns' => array_map('trim', explode(',', $uniqueYml['columns']))); + $unique = ['columns' => array_map('trim', explode(',', $uniqueYml['columns']))]; } else { - $unique = array('columns' => $uniqueYml['columns']); + $unique = ['columns' => $uniqueYml['columns']]; } if (isset($uniqueYml['options'])) { @@ -252,7 +267,7 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) $metadata->table['options'] = $element['options']; } - $associationIds = array(); + $associationIds = []; if (isset($element['id'])) { // Evaluate identifier settings foreach ($element['id'] as $name => $idElement) { @@ -261,10 +276,10 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) continue; } - $mapping = array( + $mapping = [ 'id' => true, 'fieldName' => $name - ); + ]; if (isset($idElement['type'])) { $mapping['type'] = $idElement['type']; @@ -297,9 +312,11 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) $metadata->setSequenceGeneratorDefinition($idElement['sequenceGenerator']); } else if (isset($idElement['customIdGenerator'])) { $customGenerator = $idElement['customIdGenerator']; - $metadata->setCustomGeneratorDefinition(array( - 'class' => (string) $customGenerator['class'] - )); + $metadata->setCustomGeneratorDefinition( + [ + 'class' => (string) $customGenerator['class'] + ] + ); } else if (isset($idElement['tableGenerator'])) { throw MappingException::tableIdGeneratorNotImplemented($className); } @@ -331,11 +348,11 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) if (isset($element['embedded'])) { foreach ($element['embedded'] as $name => $embeddedMapping) { - $mapping = array( + $mapping = [ 'fieldName' => $name, 'class' => $embeddedMapping['class'], - 'columnPrefix' => isset($embeddedMapping['columnPrefix']) ? $embeddedMapping['columnPrefix'] : null, - ); + 'columnPrefix' => $embeddedMapping['columnPrefix'] ?? null, + ]; $metadata->mapEmbedded($mapping); } } @@ -343,10 +360,10 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) // Evaluate oneToOne relationships if (isset($element['oneToOne'])) { foreach ($element['oneToOne'] as $name => $oneToOneElement) { - $mapping = array( + $mapping = [ 'fieldName' => $name, 'targetEntity' => $oneToOneElement['targetEntity'] - ); + ]; if (isset($associationIds[$mapping['fieldName']])) { $mapping['id'] = true; @@ -363,7 +380,7 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) $mapping['inversedBy'] = $oneToOneElement['inversedBy']; } - $joinColumns = array(); + $joinColumns = []; if (isset($oneToOneElement['joinColumn'])) { $joinColumns[] = $this->joinColumnToArray($oneToOneElement['joinColumn']); @@ -400,11 +417,11 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) // Evaluate oneToMany relationships if (isset($element['oneToMany'])) { foreach ($element['oneToMany'] as $name => $oneToManyElement) { - $mapping = array( + $mapping = [ 'fieldName' => $name, 'targetEntity' => $oneToManyElement['targetEntity'], 'mappedBy' => $oneToManyElement['mappedBy'] - ); + ]; if (isset($oneToManyElement['fetch'])) { $mapping['fetch'] = constant('Doctrine\ORM\Mapping\ClassMetadata::FETCH_' . $oneToManyElement['fetch']); @@ -439,10 +456,10 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) // Evaluate manyToOne relationships if (isset($element['manyToOne'])) { foreach ($element['manyToOne'] as $name => $manyToOneElement) { - $mapping = array( + $mapping = [ 'fieldName' => $name, 'targetEntity' => $manyToOneElement['targetEntity'] - ); + ]; if (isset($associationIds[$mapping['fieldName']])) { $mapping['id'] = true; @@ -456,7 +473,7 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) $mapping['inversedBy'] = $manyToOneElement['inversedBy']; } - $joinColumns = array(); + $joinColumns = []; if (isset($manyToOneElement['joinColumn'])) { $joinColumns[] = $this->joinColumnToArray($manyToOneElement['joinColumn']); @@ -488,10 +505,10 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) // Evaluate manyToMany relationships if (isset($element['manyToMany'])) { foreach ($element['manyToMany'] as $name => $manyToManyElement) { - $mapping = array( + $mapping = [ 'fieldName' => $name, 'targetEntity' => $manyToManyElement['targetEntity'] - ); + ]; if (isset($manyToManyElement['fetch'])) { $mapping['fetch'] = constant('Doctrine\ORM\Mapping\ClassMetadata::FETCH_' . $manyToManyElement['fetch']); @@ -502,9 +519,9 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) } else if (isset($manyToManyElement['joinTable'])) { $joinTableElement = $manyToManyElement['joinTable']; - $joinTable = array( + $joinTable = [ 'name' => $joinTableElement['name'] - ); + ]; if (isset($joinTableElement['schema'])) { $joinTable['schema'] = $joinTableElement['schema']; @@ -564,11 +581,11 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) if (isset($element['associationOverride']) && is_array($element['associationOverride'])) { foreach ($element['associationOverride'] as $fieldName => $associationOverrideElement) { - $override = array(); + $override = []; // Check for joinColumn if (isset($associationOverrideElement['joinColumn'])) { - $joinColumns = array(); + $joinColumns = []; foreach ($associationOverrideElement['joinColumn'] as $name => $joinColumnElement) { if ( ! isset($joinColumnElement['name'])) { $joinColumnElement['name'] = $name; @@ -582,9 +599,9 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) if (isset($associationOverrideElement['joinTable'])) { $joinTableElement = $associationOverrideElement['joinTable']; - $joinTable = array( + $joinTable = [ 'name' => $joinTableElement['name'] - ); + ]; if (isset($joinTableElement['schema'])) { $joinTable['schema'] = $joinTableElement['schema']; @@ -614,6 +631,11 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) $override['inversedBy'] = (string) $associationOverrideElement['inversedBy']; } + // Check for `fetch` + if (isset($associationOverrideElement['fetch'])) { + $override['fetch'] = constant(Metadata::class . '::FETCH_' . $associationOverrideElement['fetch']); + } + $metadata->setAssociationOverride($fieldName, $override); } } @@ -665,7 +687,7 @@ public function loadMetadataForClass($className, ClassMetadata $metadata) */ private function joinColumnToArray($joinColumnElement) { - $joinColumn = array(); + $joinColumn = []; if (isset($joinColumnElement['referencedColumnName'])) { $joinColumn['referencedColumnName'] = (string) $joinColumnElement['referencedColumnName']; } @@ -707,9 +729,9 @@ private function joinColumnToArray($joinColumnElement) */ private function columnToArray($fieldName, $column) { - $mapping = array( + $mapping = [ 'fieldName' => $fieldName - ); + ]; if (isset($column['type'])) { $params = explode('(', $column['type']); @@ -781,10 +803,10 @@ private function cacheToArray($cacheMapping) $usage = constant('Doctrine\ORM\Mapping\ClassMetadata::CACHE_USAGE_' . $usage); } - return array( + return [ 'usage' => $usage, 'region' => $region, - ); + ]; } /** diff --git a/lib/Doctrine/ORM/Mapping/EntityListeners.php b/lib/Doctrine/ORM/Mapping/EntityListeners.php index d9478a4979e..ae6c9126bd7 100644 --- a/lib/Doctrine/ORM/Mapping/EntityListeners.php +++ b/lib/Doctrine/ORM/Mapping/EntityListeners.php @@ -37,5 +37,5 @@ final class EntityListeners implements Annotation * * @var array */ - public $value = array(); -} \ No newline at end of file + public $value = []; +} diff --git a/lib/Doctrine/ORM/Mapping/EntityResult.php b/lib/Doctrine/ORM/Mapping/EntityResult.php index 63bbed22fac..d8b05730ae5 100644 --- a/lib/Doctrine/ORM/Mapping/EntityResult.php +++ b/lib/Doctrine/ORM/Mapping/EntityResult.php @@ -45,7 +45,7 @@ final class EntityResult implements Annotation * * @var array<\Doctrine\ORM\Mapping\FieldResult> */ - public $fields = array(); + public $fields = []; /** * Specifies the column name of the column in the SELECT list that is used to determine the type of the entity instance. diff --git a/lib/Doctrine/ORM/Mapping/JoinTable.php b/lib/Doctrine/ORM/Mapping/JoinTable.php index 8a440c6143d..879316a2874 100644 --- a/lib/Doctrine/ORM/Mapping/JoinTable.php +++ b/lib/Doctrine/ORM/Mapping/JoinTable.php @@ -38,10 +38,10 @@ final class JoinTable implements Annotation /** * @var array<\Doctrine\ORM\Mapping\JoinColumn> */ - public $joinColumns = array(); + public $joinColumns = []; /** * @var array<\Doctrine\ORM\Mapping\JoinColumn> */ - public $inverseJoinColumns = array(); + public $inverseJoinColumns = []; } diff --git a/lib/Doctrine/ORM/Mapping/MappingException.php b/lib/Doctrine/ORM/Mapping/MappingException.php index ace42db2792..7dc4405159a 100644 --- a/lib/Doctrine/ORM/Mapping/MappingException.php +++ b/lib/Doctrine/ORM/Mapping/MappingException.php @@ -14,7 +14,7 @@ * * This software consists of voluntary contributions made by many individuals * and is licensed under the MIT license. For more information, see - * . + * . */ namespace Doctrine\ORM\Mapping; @@ -424,6 +424,16 @@ public static function singleIdNotAllowedOnCompositePrimaryKey($entity) return new self('Single id is not allowed on composite primary key in entity '.$entity); } + /** + * @param string $entity + * + * @return MappingException + */ + public static function noIdDefined($entity) + { + return new self('No ID defined for entity ' . $entity); + } + /** * @param string $entity * @param string $fieldName diff --git a/lib/Doctrine/ORM/Mapping/NamedNativeQueries.php b/lib/Doctrine/ORM/Mapping/NamedNativeQueries.php index 7f5460a81e9..2539107afcf 100644 --- a/lib/Doctrine/ORM/Mapping/NamedNativeQueries.php +++ b/lib/Doctrine/ORM/Mapping/NamedNativeQueries.php @@ -25,7 +25,7 @@ * * @author Fabio B. Silva * @since 2.3 - * + * * @Annotation * @Target("CLASS") */ @@ -36,5 +36,5 @@ final class NamedNativeQueries implements Annotation * * @var array<\Doctrine\ORM\Mapping\NamedNativeQuery> */ - public $value = array(); + public $value = []; } diff --git a/lib/Doctrine/ORM/Mapping/NamingStrategy.php b/lib/Doctrine/ORM/Mapping/NamingStrategy.php index 8845cb1ed5f..9960f949f16 100644 --- a/lib/Doctrine/ORM/Mapping/NamingStrategy.php +++ b/lib/Doctrine/ORM/Mapping/NamingStrategy.php @@ -52,8 +52,10 @@ function propertyToColumnName($propertyName, $className = null); /** * Returns a column name for an embedded property. * - * @param string $propertyName - * @param string $embeddedColumnName + * @param string $propertyName + * @param string $embeddedColumnName + * @param string $className + * @param string $embeddedClassName * * @return string */ @@ -70,12 +72,10 @@ function referenceColumnName(); * Returns a join column name for a property. * * @param string $propertyName A property name. - * @param string|null $className The fully-qualified class name. - * This parameter is omitted from the signature due to BC * * @return string A join column name. */ - function joinColumnName($propertyName/*, $className = null*/); + function joinColumnName($propertyName); /** * Returns a join table name. diff --git a/lib/Doctrine/ORM/Mapping/SqlResultSetMapping.php b/lib/Doctrine/ORM/Mapping/SqlResultSetMapping.php index f5ead7c0f22..cb78c9a40a5 100644 --- a/lib/Doctrine/ORM/Mapping/SqlResultSetMapping.php +++ b/lib/Doctrine/ORM/Mapping/SqlResultSetMapping.php @@ -33,22 +33,22 @@ final class SqlResultSetMapping implements Annotation { /** * The name given to the result set mapping, and used to refer to it in the methods of the Query API. - * + * * @var string */ public $name; /** * Specifies the result set mapping to entities. - * + * * @var array<\Doctrine\ORM\Mapping\EntityResult> */ - public $entities = array(); + public $entities = []; /** * Specifies the result set mapping to scalar values. * * @var array<\Doctrine\ORM\Mapping\ColumnResult> */ - public $columns = array(); + public $columns = []; } diff --git a/lib/Doctrine/ORM/Mapping/SqlResultSetMappings.php b/lib/Doctrine/ORM/Mapping/SqlResultSetMappings.php index c21b2ab820b..0b74f2d9598 100644 --- a/lib/Doctrine/ORM/Mapping/SqlResultSetMappings.php +++ b/lib/Doctrine/ORM/Mapping/SqlResultSetMappings.php @@ -25,7 +25,7 @@ * * @author Fabio B. Silva * @since 2.3 - * + * * @Annotation * @Target("CLASS") */ @@ -36,5 +36,5 @@ final class SqlResultSetMappings implements Annotation * * @var array<\Doctrine\ORM\Mapping\SqlResultSetMapping> */ - public $value = array(); + public $value = []; } diff --git a/lib/Doctrine/ORM/Mapping/Table.php b/lib/Doctrine/ORM/Mapping/Table.php index f9f8d4a656d..6ed703750be 100644 --- a/lib/Doctrine/ORM/Mapping/Table.php +++ b/lib/Doctrine/ORM/Mapping/Table.php @@ -48,5 +48,5 @@ final class Table implements Annotation /** * @var array */ - public $options = array(); + public $options = []; } diff --git a/lib/Doctrine/ORM/Mapping/UnderscoreNamingStrategy.php b/lib/Doctrine/ORM/Mapping/UnderscoreNamingStrategy.php index 543d92ba31c..177b390f4fe 100644 --- a/lib/Doctrine/ORM/Mapping/UnderscoreNamingStrategy.php +++ b/lib/Doctrine/ORM/Mapping/UnderscoreNamingStrategy.php @@ -20,30 +20,55 @@ namespace Doctrine\ORM\Mapping; +use const CASE_LOWER; +use const CASE_UPPER; +use const E_USER_DEPRECATED; +use function preg_replace; +use function strpos; +use function strrpos; +use function strtolower; +use function strtoupper; +use function substr; +use function trigger_error; + /** * Naming strategy implementing the underscore naming convention. * Converts 'MyEntity' to 'my_entity' or 'MY_ENTITY'. * - * + * * @link www.doctrine-project.org * @since 2.3 * @author Fabio B. Silva */ class UnderscoreNamingStrategy implements NamingStrategy { + private const DEFAULT_PATTERN = '/(?<=[a-z])([A-Z])/'; + private const NUMBER_AWARE_PATTERN = '/(?<=[a-z0-9])([A-Z])/'; + /** * @var integer */ private $case; + /** @var string */ + private $pattern; + /** * Underscore naming strategy construct. * - * @param integer $case CASE_LOWER | CASE_UPPER + * @param int $case CASE_LOWER | CASE_UPPER */ - public function __construct($case = CASE_LOWER) + public function __construct($case = CASE_LOWER, bool $numberAware = false) { - $this->case = $case; + if (! $numberAware) { + @trigger_error( + 'Creating ' . self::class . ' without making it number aware is deprecated and will be removed in Doctrine ORM 3.0.', + E_USER_DEPRECATED + ); + } + + $this->case = $case; + $this->pattern = $numberAware ? self::NUMBER_AWARE_PATTERN : self::DEFAULT_PATTERN; } /** @@ -57,7 +82,7 @@ public function getCase() /** * Sets string case CASE_LOWER | CASE_UPPER. * Alphabetic characters converted to lowercase or uppercase. - * + * * @param integer $case * * @return void @@ -118,7 +143,7 @@ public function joinTableName($sourceEntity, $targetEntity, $propertyName = null { return $this->classToTableName($sourceEntity) . '_' . $this->classToTableName($targetEntity); } - + /** * {@inheritdoc} */ @@ -127,15 +152,10 @@ public function joinKeyColumnName($entityName, $referencedColumnName = null) return $this->classToTableName($entityName) . '_' . ($referencedColumnName ?: $this->referenceColumnName()); } - - /** - * @param string $string - * - * @return string - */ - private function underscore($string) + + private function underscore(string $string) : string { - $string = preg_replace('/(?<=[a-z])([A-Z])/', '_$1', $string); + $string = preg_replace($this->pattern, '_$1', $string); if ($this->case === CASE_UPPER) { return strtoupper($string); diff --git a/lib/Doctrine/ORM/NativeQuery.php b/lib/Doctrine/ORM/NativeQuery.php index b19f8180564..ddc5418d672 100644 --- a/lib/Doctrine/ORM/NativeQuery.php +++ b/lib/Doctrine/ORM/NativeQuery.php @@ -63,8 +63,8 @@ public function getSQL() */ protected function _doExecute() { - $parameters = array(); - $types = array(); + $parameters = []; + $types = []; foreach ($this->getParameters() as $parameter) { $name = $parameter->getName(); diff --git a/lib/Doctrine/ORM/NonUniqueResultException.php b/lib/Doctrine/ORM/NonUniqueResultException.php index 55b71300058..78a58dd4990 100644 --- a/lib/Doctrine/ORM/NonUniqueResultException.php +++ b/lib/Doctrine/ORM/NonUniqueResultException.php @@ -27,4 +27,10 @@ */ class NonUniqueResultException extends UnexpectedResultException { + const DEFAULT_MESSAGE = 'More than one result was found for query although one row or none was expected.'; + + public function __construct(string $message = null) + { + parent::__construct($message ?? self::DEFAULT_MESSAGE); + } } diff --git a/lib/Doctrine/ORM/ORMException.php b/lib/Doctrine/ORM/ORMException.php index 6d8a6d631f4..3ce9ce9dc91 100644 --- a/lib/Doctrine/ORM/ORMException.php +++ b/lib/Doctrine/ORM/ORMException.php @@ -101,7 +101,7 @@ public static function unrecognizedField($field) return new self("Unrecognized field: $field"); } - /** + /** * * @param string $class * @param string $association @@ -187,6 +187,21 @@ public static function invalidFindByCall($entityName, $fieldName, $method) ); } + /** + * @param string $entityName + * @param string $fieldName + * @param string $method + * + * @return ORMException + */ + public static function invalidMagicCall($entityName, $fieldName, $method) + { + return new self( + "Entity '".$entityName."' has no field '".$fieldName."'. ". + "You can therefore not call '".$method."' on the entities' repository" + ); + } + /** * @param string $entityName * @param string $associationFieldName @@ -308,16 +323,6 @@ public static function unrecognizedIdentifierFields($className, $fieldNames) ); } - /** - * @param string $functionName - * - * @return ORMException - */ - public static function overwriteInternalDQLFunctionNotAllowed($functionName) - { - return new self("It is not allowed to overwrite internal function '$functionName' in the DQL parser through user-defined functions."); - } - /** * @return ORMException */ diff --git a/lib/Doctrine/ORM/ORMInvalidArgumentException.php b/lib/Doctrine/ORM/ORMInvalidArgumentException.php index 81466a0fed0..68bb6f91dff 100644 --- a/lib/Doctrine/ORM/ORMInvalidArgumentException.php +++ b/lib/Doctrine/ORM/ORMInvalidArgumentException.php @@ -82,21 +82,42 @@ static public function readOnlyRequiresManagedEntity($entity) } /** - * @param array $assoc + * @param array[][]|object[][] $newEntitiesWithAssociations non-empty an array + * of [array $associationMapping, object $entity] pairs + * + * @return ORMInvalidArgumentException + */ + static public function newEntitiesFoundThroughRelationships($newEntitiesWithAssociations) + { + $errorMessages = array_map( + function (array $newEntityWithAssociation) : string { + [$associationMapping, $entity] = $newEntityWithAssociation; + + return self::newEntityFoundThroughRelationshipMessage($associationMapping, $entity); + }, + $newEntitiesWithAssociations + ); + + if (1 === count($errorMessages)) { + return new self(reset($errorMessages)); + } + + return new self( + 'Multiple non-persisted new entities were found through the given association graph:' + . "\n\n * " + . implode("\n * ", $errorMessages) + ); + } + + /** + * @param array $associationMapping * @param object $entry * * @return ORMInvalidArgumentException */ - static public function newEntityFoundThroughRelationship(array $assoc, $entry) + static public function newEntityFoundThroughRelationship(array $associationMapping, $entry) { - return new self("A new entity was found through the relationship '" - . $assoc['sourceEntity'] . "#" . $assoc['fieldName'] . "' that was not" - . " configured to cascade persist operations for entity: " . self::objToStr($entry) . "." - . " To solve this issue: Either explicitly call EntityManager#persist()" - . " on this unknown entity or configure cascade persist " - . " this association in the mapping for example @ManyToOne(..,cascade={\"persist\"})." - . (method_exists($entry, '__toString') ? "": " If you cannot find out which entity causes the problem" - . " implement '" . $assoc['targetEntity'] . "#__toString()' to get a clue.")); + return new self(self::newEntityFoundThroughRelationshipMessage($associationMapping, $entry)); } /** @@ -195,11 +216,7 @@ public static function invalidIdentifierBindingEntity() */ public static function invalidAssociation(ClassMetadata $targetClass, $assoc, $actualValue) { - $expectedType = 'Doctrine\Common\Collections\Collection|array'; - - if (($assoc['type'] & ClassMetadata::TO_ONE) > 0) { - $expectedType = $targetClass->getName(); - } + $expectedType = $targetClass->getName(); return new self(sprintf( 'Expected value of type "%s" for association field "%s#$%s", got "%s" instead.', @@ -210,6 +227,18 @@ public static function invalidAssociation(ClassMetadata $targetClass, $assoc, $a )); } + /** + * Used when a given entityName hasn't the good type + * + * @param mixed $entityName The given entity (which shouldn't be a string) + * + * @return self + */ + public static function invalidEntityName($entityName) + { + return new self(sprintf('Entity name must be a string, %s given', gettype($entityName))); + } + /** * Helper method to show an object as string. * @@ -217,8 +246,27 @@ public static function invalidAssociation(ClassMetadata $targetClass, $assoc, $a * * @return string */ - private static function objToStr($obj) + private static function objToStr($obj) : string { return method_exists($obj, '__toString') ? (string) $obj : get_class($obj).'@'.spl_object_hash($obj); } + + /** + * @param array $associationMapping + * @param object $entity + */ + private static function newEntityFoundThroughRelationshipMessage(array $associationMapping, $entity) : string + { + return 'A new entity was found through the relationship \'' + . $associationMapping['sourceEntity'] . '#' . $associationMapping['fieldName'] . '\' that was not' + . ' configured to cascade persist operations for entity: ' . self::objToStr($entity) . '.' + . ' To solve this issue: Either explicitly call EntityManager#persist()' + . ' on this unknown entity or configure cascade persist' + . ' this association in the mapping for example @ManyToOne(..,cascade={"persist"}).' + . (method_exists($entity, '__toString') + ? '' + : ' If you cannot find out which entity causes the problem implement \'' + . $associationMapping['targetEntity'] . '#__toString()\' to get a clue.' + ); + } } diff --git a/lib/Doctrine/ORM/PersistentCollection.php b/lib/Doctrine/ORM/PersistentCollection.php index c1f3cf1b6c9..7d52d5392af 100644 --- a/lib/Doctrine/ORM/PersistentCollection.php +++ b/lib/Doctrine/ORM/PersistentCollection.php @@ -25,6 +25,7 @@ use Doctrine\Common\Collections\Selectable; use Doctrine\Common\Collections\Criteria; use Doctrine\ORM\Mapping\ClassMetadata; +use function get_class; /** * A PersistentCollection represents a collection of elements that have persistent state. @@ -49,7 +50,7 @@ final class PersistentCollection extends AbstractLazyCollection implements Selec * * @var array */ - private $snapshot = array(); + private $snapshot = []; /** * The entity that owns this collection. @@ -373,11 +374,7 @@ public function removeElement($element) $persister = $this->em->getUnitOfWork()->getCollectionPersister($this->association); - if ($persister->removeElement($this, $element)) { - return $element; - } - - return null; + return $persister->removeElement($this, $element); } $removed = parent::removeElement($element); @@ -451,7 +448,7 @@ public function get($key) */ public function count() { - if ( ! $this->initialized && $this->association['fetch'] === ClassMetadata::FETCH_EXTRA_LAZY) { + if (! $this->initialized && $this->association !== null && $this->association['fetch'] === ClassMetadata::FETCH_EXTRA_LAZY) { $persister = $this->em->getUnitOfWork()->getCollectionPersister($this->association); return $persister->count($this) + ($this->isDirty ? $this->collection->count() : 0); @@ -514,10 +511,11 @@ public function offsetGet($offset) public function offsetSet($offset, $value) { if ( ! isset($offset)) { - return $this->add($value); + $this->add($value); + return; } - return $this->set($offset, $value); + $this->set($offset, $value); } /** @@ -542,6 +540,8 @@ public function isEmpty() public function clear() { if ($this->initialized && $this->isEmpty()) { + $this->collection->clear(); + return; } @@ -583,7 +583,7 @@ public function clear() */ public function __sleep() { - return array('collection', 'initialized'); + return ['collection', 'initialized']; } /** @@ -631,7 +631,7 @@ public function __clone() $this->initialize(); $this->owner = null; - $this->snapshot = array(); + $this->snapshot = []; $this->changed(); } @@ -669,6 +669,7 @@ public function matching(Criteria $criteria) $criteria = clone $criteria; $criteria->where($expression); + $criteria->orderBy($criteria->getOrderings() ?: $this->association['orderBy'] ?? []); $persister = $this->em->getUnitOfWork()->getEntityPersister($this->association['targetEntity']); @@ -693,21 +694,39 @@ public function unwrap() protected function doInitialize() { // Has NEW objects added through add(). Remember them. - $newObjects = array(); + $newlyAddedDirtyObjects = []; if ($this->isDirty) { - $newObjects = $this->collection->toArray(); + $newlyAddedDirtyObjects = $this->collection->toArray(); } $this->collection->clear(); $this->em->getUnitOfWork()->loadCollection($this); $this->takeSnapshot(); - // Reattach NEW objects added through add(), if any. - if ($newObjects) { - foreach ($newObjects as $obj) { - $this->collection->add($obj); - } + if ($newlyAddedDirtyObjects) { + $this->restoreNewObjectsInDirtyCollection($newlyAddedDirtyObjects); + } + } + + /** + * @param object[] $newObjects + * + * Note: the only reason why this entire looping/complexity is performed via `spl_object_hash` + * is because we want to prevent using `array_udiff()`, which is likely to cause very + * high overhead (complexity of O(n^2)). `array_diff_key()` performs the operation in + * core, which is faster than using a callback for comparisons + */ + private function restoreNewObjectsInDirtyCollection(array $newObjects) : void + { + $loadedObjects = $this->collection->toArray(); + $newObjectsByOid = \array_combine(\array_map('spl_object_hash', $newObjects), $newObjects); + $loadedObjectsByOid = \array_combine(\array_map('spl_object_hash', $loadedObjects), $loadedObjects); + $newObjectsThatWereNotLoaded = \array_diff_key($newObjectsByOid, $loadedObjectsByOid); + + if ($newObjectsThatWereNotLoaded) { + // Reattach NEW objects added through add(), if any. + \array_walk($newObjectsThatWereNotLoaded, [$this->collection, 'add']); $this->isDirty = true; } diff --git a/lib/Doctrine/ORM/Persisters/Collection/ManyToManyPersister.php b/lib/Doctrine/ORM/Persisters/Collection/ManyToManyPersister.php index 525ab34b322..c817f609794 100644 --- a/lib/Doctrine/ORM/Persisters/Collection/ManyToManyPersister.php +++ b/lib/Doctrine/ORM/Persisters/Collection/ManyToManyPersister.php @@ -47,7 +47,7 @@ public function delete(PersistentCollection $collection) return; // ignore inverse side } - $types = array(); + $types = []; $class = $this->em->getClassMetadata($mapping['sourceEntity']); foreach ($mapping['joinTable']['joinColumns'] as $joinColumn) { @@ -104,7 +104,7 @@ public function get(PersistentCollection $collection, $index) ? $mapping['inversedBy'] : $mapping['mappedBy']; - return $persister->load(array($mappedKey => $collection->getOwner(), $mapping['indexBy'] => $index), null, $mapping, array(), 0, 1); + return $persister->load([$mappedKey => $collection->getOwner(), $mapping['indexBy'] => $index], null, $mapping, [], 0, 1); } /** @@ -112,9 +112,9 @@ public function get(PersistentCollection $collection, $index) */ public function count(PersistentCollection $collection) { - $conditions = array(); - $params = array(); - $types = array(); + $conditions = []; + $params = []; + $types = []; $mapping = $collection->getMapping(); $id = $this->uow->getEntityIdentifier($collection->getOwner()); $sourceClass = $this->em->getClassMetadata($mapping['sourceEntity']); @@ -238,7 +238,7 @@ public function loadCriteria(PersistentCollection $collection, Criteria $criteri $id = $this->uow->getEntityIdentifier($owner); $targetClass = $this->em->getClassMetadata($mapping['targetEntity']); $onConditions = $this->getOnConditionSQL($mapping); - $whereClauses = $params = array(); + $whereClauses = $params = []; if ( ! $mapping['isOwningSide']) { $associationSourceClass = $targetClass; @@ -259,10 +259,11 @@ public function loadCriteria(PersistentCollection $collection, Criteria $criteri $parameters = $this->expandCriteriaParameters($criteria); foreach ($parameters as $parameter) { - list($name, $value) = $parameter; - $field = $this->quoteStrategy->getColumnName($name, $targetClass, $this->platform); - $whereClauses[] = sprintf('te.%s = ?', $field); - $params[] = $value; + [$name, $value, $operator] = $parameter; + + $field = $this->quoteStrategy->getColumnName($name, $targetClass, $this->platform); + $whereClauses[] = sprintf('te.%s %s ?', $field, $operator); + $params[] = $value; } $tableName = $this->quoteStrategy->getTableName($targetClass, $this->platform); @@ -311,7 +312,7 @@ public function getFilterSql($mapping) $filterSql = $this->generateFilterConditionSQL($rootClass, 'te'); if ('' === $filterSql) { - return array('', ''); + return ['', '']; } // A join is needed if there is filtering on the target entity @@ -319,7 +320,7 @@ public function getFilterSql($mapping) $joinSql = ' JOIN ' . $tableName . ' te' . ' ON' . implode(' AND ', $this->getOnConditionSQL($mapping)); - return array($joinSql, $filterSql); + return [$joinSql, $filterSql]; } /** @@ -332,7 +333,7 @@ public function getFilterSql($mapping) */ protected function generateFilterConditionSQL(ClassMetadata $targetEntity, $targetTableAlias) { - $filterClauses = array(); + $filterClauses = []; foreach ($this->em->getFilters()->getEnabledFilters() as $filter) { if ($filterExpr = $filter->addFilterConstraint($targetEntity, $targetTableAlias)) { @@ -363,7 +364,7 @@ protected function getOnConditionSQL($mapping) ? $association['joinTable']['inverseJoinColumns'] : $association['joinTable']['joinColumns']; - $conditions = array(); + $conditions = []; foreach ($joinColumns as $joinColumn) { $joinColumnName = $this->quoteStrategy->getJoinColumnName($joinColumn, $targetClass, $this->platform); @@ -382,7 +383,7 @@ protected function getOnConditionSQL($mapping) */ protected function getDeleteSQL(PersistentCollection $collection) { - $columns = array(); + $columns = []; $mapping = $collection->getMapping(); $class = $this->em->getClassMetadata(get_class($collection->getOwner())); $joinTable = $this->quoteStrategy->getJoinTableName($mapping, $class, $this->platform); @@ -408,17 +409,17 @@ protected function getDeleteSQLParameters(PersistentCollection $collection) // Optimization for single column identifier if (count($mapping['relationToSourceKeyColumns']) === 1) { - return array(reset($identifier)); + return [reset($identifier)]; } // Composite identifier $sourceClass = $this->em->getClassMetadata($mapping['sourceEntity']); - $params = array(); + $params = []; foreach ($mapping['relationToSourceKeyColumns'] as $columnName => $refColumnName) { $params[] = isset($sourceClass->fieldNames[$refColumnName]) ? $identifier[$sourceClass->fieldNames[$refColumnName]] - : $identifier[$sourceClass->getFieldForColumn($columnName)]; + : $identifier[$sourceClass->getFieldForColumn($refColumnName)]; } return $params; @@ -437,8 +438,8 @@ protected function getDeleteRowSQL(PersistentCollection $collection) $mapping = $collection->getMapping(); $class = $this->em->getClassMetadata($mapping['sourceEntity']); $targetClass = $this->em->getClassMetadata($mapping['targetEntity']); - $columns = array(); - $types = array(); + $columns = []; + $types = []; foreach ($mapping['joinTable']['joinColumns'] as $joinColumn) { $columns[] = $this->quoteStrategy->getJoinColumnName($joinColumn, $class, $this->platform); @@ -450,11 +451,11 @@ protected function getDeleteRowSQL(PersistentCollection $collection) $types[] = PersisterHelper::getTypeOfColumn($joinColumn['referencedColumnName'], $targetClass, $this->em); } - return array( + return [ 'DELETE FROM ' . $this->quoteStrategy->getJoinTableName($mapping, $class, $this->platform) . ' WHERE ' . implode(' = ? AND ', $columns) . ' = ?', $types, - ); + ]; } /** @@ -483,8 +484,8 @@ protected function getDeleteRowSQLParameters(PersistentCollection $collection, $ */ protected function getInsertRowSQL(PersistentCollection $collection) { - $columns = array(); - $types = array(); + $columns = []; + $types = []; $mapping = $collection->getMapping(); $class = $this->em->getClassMetadata($mapping['sourceEntity']); $targetClass = $this->em->getClassMetadata($mapping['targetEntity']); @@ -499,13 +500,13 @@ protected function getInsertRowSQL(PersistentCollection $collection) $types[] = PersisterHelper::getTypeOfColumn($joinColumn['referencedColumnName'], $targetClass, $this->em); } - return array( + return [ 'INSERT INTO ' . $this->quoteStrategy->getJoinTableName($mapping, $class, $this->platform) . ' (' . implode(', ', $columns) . ')' . ' VALUES' . ' (' . implode(', ', array_fill(0, count($columns), '?')) . ')', $types, - ); + ]; } /** @@ -535,13 +536,14 @@ protected function getInsertRowSQLParameters(PersistentCollection $collection, $ */ private function collectJoinTableColumnParameters(PersistentCollection $collection, $element) { - $params = array(); + $params = []; $mapping = $collection->getMapping(); $isComposite = count($mapping['joinTableColumns']) > 2; $identifier1 = $this->uow->getEntityIdentifier($collection->getOwner()); $identifier2 = $this->uow->getEntityIdentifier($element); + $class1 = $class2 = null; if ($isComposite) { $class1 = $this->em->getClassMetadata(get_class($collection->getOwner())); $class2 = $collection->getTypeClass(); @@ -602,14 +604,14 @@ private function getJoinTableRestrictionsWithKey(PersistentCollection $collectio } $quotedJoinTable = $this->quoteStrategy->getJoinTableName($mapping, $associationSourceClass, $this->platform). ' t'; - $whereClauses = array(); - $params = array(); - $types = array(); + $whereClauses = []; + $params = []; + $types = []; $joinNeeded = ! in_array($indexBy, $targetClass->identifier); if ($joinNeeded) { // extra join needed if indexBy is not a @id - $joinConditions = array(); + $joinConditions = []; foreach ($joinColumns as $joinTableColumn) { $joinConditions[] = 't.' . $joinTableColumn['name'] . ' = tr.' . $joinTableColumn['referencedColumnName']; @@ -650,7 +652,7 @@ private function getJoinTableRestrictionsWithKey(PersistentCollection $collectio } } - return array($quotedJoinTable, $whereClauses, $params, $types); + return [$quotedJoinTable, $whereClauses, $params, $types]; } /** @@ -684,9 +686,9 @@ private function getJoinTableRestrictions(PersistentCollection $collection, $ele } $quotedJoinTable = $this->quoteStrategy->getJoinTableName($mapping, $sourceClass, $this->platform); - $whereClauses = array(); - $params = array(); - $types = array(); + $whereClauses = []; + $params = []; + $types = []; foreach ($mapping['joinTableColumns'] as $joinTableColumn) { $whereClauses[] = ($addFilters ? 't.' : '') . $joinTableColumn . ' = ?'; @@ -716,7 +718,7 @@ private function getJoinTableRestrictions(PersistentCollection $collection, $ele } } - return array($quotedJoinTable, $whereClauses, $params, $types); + return [$quotedJoinTable, $whereClauses, $params, $types]; } /** @@ -732,7 +734,7 @@ private function expandCriteriaParameters(Criteria $criteria) $expression = $criteria->getWhereExpression(); if ($expression === null) { - return array(); + return []; } $valueVisitor = new SqlValueVisitor(); diff --git a/lib/Doctrine/ORM/Persisters/Collection/OneToManyPersister.php b/lib/Doctrine/ORM/Persisters/Collection/OneToManyPersister.php index 0e2fda86815..82115071f35 100644 --- a/lib/Doctrine/ORM/Persisters/Collection/OneToManyPersister.php +++ b/lib/Doctrine/ORM/Persisters/Collection/OneToManyPersister.php @@ -83,13 +83,13 @@ public function get(PersistentCollection $collection, $index) $persister = $this->uow->getEntityPersister($mapping['targetEntity']); return $persister->load( - array( + [ $mapping['mappedBy'] => $collection->getOwner(), $mapping['indexBy'] => $index - ), + ], null, $mapping, - array(), + [], null, 1 ); @@ -249,10 +249,10 @@ private function deleteJoinedEntityCollection(PersistentCollection $collection) $columnDefinitions = []; foreach ($idColumnNames as $idColumnName) { - $columnDefinitions[$idColumnName] = array( + $columnDefinitions[$idColumnName] = [ 'notnull' => true, 'type' => Type::getType(PersisterHelper::getTypeOfColumn($idColumnName, $rootClass, $this->em)), - ); + ]; } $statement = $this->platform->getCreateTemporaryTableSnippetSQL() . ' ' . $tempTable @@ -271,7 +271,7 @@ private function deleteJoinedEntityCollection(PersistentCollection $collection) $numDeleted = $this->conn->executeUpdate($statement, $parameters); // 3) Delete records on each table in the hierarchy - $classNames = array_merge($targetClass->parentClasses, array($targetClass->name), $targetClass->subClasses); + $classNames = array_merge($targetClass->parentClasses, [$targetClass->name], $targetClass->subClasses); foreach (array_reverse($classNames) as $className) { $tableName = $this->quoteStrategy->getTableName($this->em->getClassMetadata($className), $this->platform); diff --git a/lib/Doctrine/ORM/Persisters/Entity/AbstractEntityInheritancePersister.php b/lib/Doctrine/ORM/Persisters/Entity/AbstractEntityInheritancePersister.php index aa2038ffcb8..79472b50c0e 100644 --- a/lib/Doctrine/ORM/Persisters/Entity/AbstractEntityInheritancePersister.php +++ b/lib/Doctrine/ORM/Persisters/Entity/AbstractEntityInheritancePersister.php @@ -82,17 +82,18 @@ protected function getSelectColumnSQL($field, ClassMetadata $class, $alias = 'r' /** * @param string $tableAlias * @param string $joinColumnName - * @param string $className + * @param string $quotedColumnName + * * @param string $type * * @return string */ - protected function getSelectJoinColumnSQL($tableAlias, $joinColumnName, $className, $type) + protected function getSelectJoinColumnSQL($tableAlias, $joinColumnName, $quotedColumnName, $type) { $columnAlias = $this->getSQLColumnAlias($joinColumnName); $this->currentPersisterContext->rsm->addMetaResult('r', $columnAlias, $joinColumnName, false, $type); - return $tableAlias . '.' . $joinColumnName . ' AS ' . $columnAlias; + return $tableAlias . '.' . $quotedColumnName . ' AS ' . $columnAlias; } } diff --git a/lib/Doctrine/ORM/Persisters/Entity/BasicEntityPersister.php b/lib/Doctrine/ORM/Persisters/Entity/BasicEntityPersister.php index 3b2faf878d7..ea1f2efee3c 100644 --- a/lib/Doctrine/ORM/Persisters/Entity/BasicEntityPersister.php +++ b/lib/Doctrine/ORM/Persisters/Entity/BasicEntityPersister.php @@ -37,6 +37,10 @@ use Doctrine\ORM\UnitOfWork; use Doctrine\ORM\Utility\IdentifierFlattener; use Doctrine\ORM\Utility\PersisterHelper; +use function array_map; +use function array_merge; +use function assert; +use function reset; /** * A BasicEntityPersister maps an entity to a single table in a relational database. @@ -86,18 +90,20 @@ class BasicEntityPersister implements EntityPersister /** * @var array */ - static private $comparisonMap = array( - Comparison::EQ => '= %s', - Comparison::IS => '= %s', - Comparison::NEQ => '!= %s', - Comparison::GT => '> %s', - Comparison::GTE => '>= %s', - Comparison::LT => '< %s', - Comparison::LTE => '<= %s', - Comparison::IN => 'IN (%s)', - Comparison::NIN => 'NOT IN (%s)', - Comparison::CONTAINS => 'LIKE %s', - ); + static private $comparisonMap = [ + Comparison::EQ => '= %s', + Comparison::IS => '= %s', + Comparison::NEQ => '!= %s', + Comparison::GT => '> %s', + Comparison::GTE => '>= %s', + Comparison::LT => '< %s', + Comparison::LTE => '<= %s', + Comparison::IN => 'IN (%s)', + Comparison::NIN => 'NOT IN (%s)', + Comparison::CONTAINS => 'LIKE %s', + Comparison::STARTS_WITH => 'LIKE %s', + Comparison::ENDS_WITH => 'LIKE %s', + ]; /** * Metadata object that describes the mapping of the mapped entity class. @@ -132,7 +138,7 @@ class BasicEntityPersister implements EntityPersister * * @var array */ - protected $queuedInserts = array(); + protected $queuedInserts = []; /** * The map of column names to DBAL mapping types of all prepared columns used @@ -143,7 +149,7 @@ class BasicEntityPersister implements EntityPersister * @see prepareInsertData($entity) * @see prepareUpdateData($entity) */ - protected $columnTypes = array(); + protected $columnTypes = []; /** * The map of quoted column names. @@ -153,7 +159,7 @@ class BasicEntityPersister implements EntityPersister * @see prepareInsertData($entity) * @see prepareUpdateData($entity) */ - protected $quotedColumns = array(); + protected $quotedColumns = []; /** * The INSERT SQL statement used for entities handled by this persister. @@ -257,10 +263,10 @@ public function getInserts() public function executeInserts() { if ( ! $this->queuedInserts) { - return array(); + return []; } - $postInsertIds = array(); + $postInsertIds = []; $idGenerator = $this->class->idGenerator; $isPostInsertId = $idGenerator->isPostInsertGenerator(); @@ -282,13 +288,13 @@ public function executeInserts() if ($isPostInsertId) { $generatedId = $idGenerator->generate($this->em, $entity); - $id = array( + $id = [ $this->class->identifier[0] => $generatedId - ); - $postInsertIds[] = array( + ]; + $postInsertIds[] = [ 'generatedId' => $generatedId, 'entity' => $entity, - ); + ]; } else { $id = $this->class->getIdentifierValues($entity); } @@ -299,7 +305,7 @@ public function executeInserts() } $stmt->closeCursor(); - $this->queuedInserts = array(); + $this->queuedInserts = []; return $postInsertIds; } @@ -342,13 +348,30 @@ protected function fetchVersionValue($versionedClass, array $id) . ' FROM ' . $tableName . ' WHERE ' . implode(' = ? AND ', $identifier) . ' = ?'; + $flatId = $this->identifierFlattener->flattenIdentifier($versionedClass, $id); - $value = $this->conn->fetchColumn($sql, array_values($flatId)); + $value = $this->conn->fetchColumn( + $sql, + array_values($flatId), + 0, + $this->extractIdentifierTypes($id, $versionedClass) + ); return Type::getType($fieldMapping['type'])->convertToPHPValue($value, $this->platform); } + private function extractIdentifierTypes(array $id, ClassMetadata $versionedClass) : array + { + $types = []; + + foreach ($id as $field => $value) { + $types = array_merge($types, $this->getTypes($field, $value, $versionedClass)); + } + + return $types; + } + /** * {@inheritdoc} */ @@ -389,9 +412,9 @@ public function update($entity) */ protected final function updateTable($entity, $quotedTableName, array $updateData, $versioned = false) { - $set = array(); - $types = array(); - $params = array(); + $set = []; + $types = []; + $params = []; foreach ($updateData as $columnName => $value) { $placeholder = '?'; @@ -420,7 +443,7 @@ protected final function updateTable($entity, $quotedTableName, array $updateDat $types[] = $this->columnTypes[$columnName]; } - $where = array(); + $where = []; $identifier = $this->em->getUnitOfWork()->getEntityIdentifier($entity); foreach ($this->class->identifier as $idField) { @@ -432,23 +455,21 @@ protected final function updateTable($entity, $quotedTableName, array $updateDat continue; } - $params[] = $identifier[$idField]; - $where[] = $this->class->associationMappings[$idField]['joinColumns'][0]['name']; - $targetMapping = $this->em->getClassMetadata($this->class->associationMappings[$idField]['targetEntity']); - - switch (true) { - case (isset($targetMapping->fieldMappings[$targetMapping->identifier[0]])): - $types[] = $targetMapping->fieldMappings[$targetMapping->identifier[0]]['type']; - break; + $params[] = $identifier[$idField]; + $where[] = $this->quoteStrategy->getJoinColumnName( + $this->class->associationMappings[$idField]['joinColumns'][0], + $this->class, + $this->platform + ); - case (isset($targetMapping->associationMappings[$targetMapping->identifier[0]])): - $types[] = $targetMapping->associationMappings[$targetMapping->identifier[0]]['type']; - break; + $targetMapping = $this->em->getClassMetadata($this->class->associationMappings[$idField]['targetEntity']); + $targetType = PersisterHelper::getTypeOfField($targetMapping->identifier[0], $targetMapping, $this->em); - default: - throw ORMException::unrecognizedField($targetMapping->identifier[0]); + if ($targetType === []) { + throw ORMException::unrecognizedField($targetMapping->identifier[0]); } + $types[] = reset($targetType); } if ($versioned) { @@ -503,9 +524,9 @@ protected function deleteJoinTableRecords($identifier) $selfReferential = ($mapping['targetEntity'] == $mapping['sourceEntity']); $class = $this->class; $association = $mapping; - $otherColumns = array(); - $otherKeys = array(); - $keys = array(); + $otherColumns = []; + $otherKeys = []; + $keys = []; if ( ! $mapping['isOwningSide']) { $class = $this->em->getClassMetadata($mapping['targetEntity']); @@ -550,29 +571,12 @@ protected function deleteJoinTableRecords($identifier) */ public function delete($entity) { - $self = $this; $class = $this->class; $identifier = $this->em->getUnitOfWork()->getEntityIdentifier($entity); $tableName = $this->quoteStrategy->getTableName($class, $this->platform); $idColumns = $this->quoteStrategy->getIdentifierColumnNames($class, $this->platform); $id = array_combine($idColumns, $identifier); - $types = array_map(function ($identifier) use ($class, $self) { - if (isset($class->fieldMappings[$identifier])) { - return $class->fieldMappings[$identifier]['type']; - } - - $targetMapping = $self->em->getClassMetadata($class->associationMappings[$identifier]['targetEntity']); - - if (isset($targetMapping->fieldMappings[$targetMapping->identifier[0]])) { - return $targetMapping->fieldMappings[$targetMapping->identifier[0]]['type']; - } - - if (isset($targetMapping->associationMappings[$targetMapping->identifier[0]])) { - return $targetMapping->associationMappings[$targetMapping->identifier[0]]['type']; - } - - throw ORMException::unrecognizedField($targetMapping->identifier[0]); - }, $class->identifier); + $types = $this->getClassIdentifiersTypes($class); $this->deleteJoinTableRecords($identifier); @@ -603,7 +607,7 @@ public function delete($entity) protected function prepareUpdateData($entity) { $versionField = null; - $result = array(); + $result = []; $uow = $this->em->getUnitOfWork(); if (($versioned = $this->class->isVersioned) != false) { @@ -646,7 +650,7 @@ protected function prepareUpdateData($entity) // The associated entity $newVal is not yet persisted, so we must // set $newVal = null, in order to insert a null value and schedule an // extra update on the UnitOfWork. - $uow->scheduleExtraUpdate($entity, array($field => array(null, $newVal))); + $uow->scheduleExtraUpdate($entity, [$field => [null, $newVal]]); $newVal = null; } @@ -705,7 +709,7 @@ public function getOwningTable($fieldName) /** * {@inheritdoc} */ - public function load(array $criteria, $entity = null, $assoc = null, array $hints = array(), $lockMode = null, $limit = null, array $orderBy = null) + public function load(array $criteria, $entity = null, $assoc = null, array $hints = [], $lockMode = null, $limit = null, array $orderBy = null) { $this->switchPersisterContext(null, $limit); @@ -735,7 +739,7 @@ public function loadById(array $identifier, $entity = null) /** * {@inheritdoc} */ - public function loadOneToOneEntity(array $assoc, $sourceEntity, array $identifier = array()) + public function loadOneToOneEntity(array $assoc, $sourceEntity, array $identifier = []) { if (($foundEntity = $this->em->getUnitOfWork()->tryGetById($identifier, $assoc['targetEntity'])) != false) { return $foundEntity; @@ -748,7 +752,7 @@ public function loadOneToOneEntity(array $assoc, $sourceEntity, array $identifie // Mark inverse side as fetched in the hints, otherwise the UoW would // try to load it in a separate query (remember: to-one inverse sides can not be lazy). - $hints = array(); + $hints = []; if ($isInverseSingleValued) { $hints['fetched']["r"][$assoc['inversedBy']] = true; @@ -773,6 +777,8 @@ public function loadOneToOneEntity(array $assoc, $sourceEntity, array $identifie $sourceClass = $this->em->getClassMetadata($assoc['sourceEntity']); $owningAssoc = $targetClass->getAssociationMapping($assoc['mappedBy']); + $computedIdentifier = []; + // TRICKY: since the association is specular source and target are flipped foreach ($owningAssoc['targetToSourceKeyColumns'] as $sourceKeyColumn => $targetKeyColumn) { if ( ! isset($sourceClass->fieldNames[$sourceKeyColumn])) { @@ -781,15 +787,11 @@ public function loadOneToOneEntity(array $assoc, $sourceEntity, array $identifie ); } - // unset the old value and set the new sql aliased value here. By definition - // unset($identifier[$targetKeyColumn] works here with how UnitOfWork::createEntity() calls this method. - $identifier[$this->getSQLTableAlias($targetClass->name) . "." . $targetKeyColumn] = + $computedIdentifier[$targetClass->getFieldForColumn($targetKeyColumn)] = $sourceClass->reflFields[$sourceClass->fieldNames[$sourceKeyColumn]]->getValue($sourceEntity); - - unset($identifier[$targetKeyColumn]); } - $targetEntity = $this->load($identifier, null, $assoc); + $targetEntity = $this->load($computedIdentifier, null, $assoc); if ($targetEntity !== null) { $targetClass->setFieldValue($targetEntity, $assoc['mappedBy'], $sourceEntity); @@ -808,13 +810,13 @@ public function refresh(array $id, $entity, $lockMode = null) $stmt = $this->conn->executeQuery($sql, $params, $types); $hydrator = $this->em->newHydrator(Query::HYDRATE_OBJECT); - $hydrator->hydrateAll($stmt, $this->currentPersisterContext->rsm, array(Query::HINT_REFRESH => true)); + $hydrator->hydrateAll($stmt, $this->currentPersisterContext->rsm, [Query::HINT_REFRESH => true]); } /** * {@inheritDoc} */ - public function count($criteria = array()) + public function count($criteria = []) { $sql = $this->getCountSQL($criteria); @@ -822,7 +824,7 @@ public function count($criteria = array()) ? $this->expandCriteriaParameters($criteria) : $this->expandParameters($criteria); - return $this->conn->executeQuery($sql, $params, $types)->fetchColumn(); + return (int) $this->conn->executeQuery($sql, $params, $types)->fetchColumn(); } /** @@ -840,7 +842,8 @@ public function loadCriteria(Criteria $criteria) $stmt = $this->conn->executeQuery($query, $params, $types); $hydrator = $this->em->newHydrator(($this->currentPersisterContext->selectJoinSql) ? Query::HYDRATE_OBJECT : Query::HYDRATE_SIMPLEOBJECT); - return $hydrator->hydrateAll($stmt, $this->currentPersisterContext->rsm, array(UnitOfWork::HINT_DEFEREAGERLOAD => true)); + return $hydrator->hydrateAll($stmt, $this->currentPersisterContext->rsm, [UnitOfWork::HINT_DEFEREAGERLOAD => true] + ); } /** @@ -849,11 +852,11 @@ public function loadCriteria(Criteria $criteria) public function expandCriteriaParameters(Criteria $criteria) { $expression = $criteria->getWhereExpression(); - $sqlParams = array(); - $sqlTypes = array(); + $sqlParams = []; + $sqlTypes = []; if ($expression === null) { - return array($sqlParams, $sqlTypes); + return [$sqlParams, $sqlTypes]; } $valueVisitor = new SqlValueVisitor(); @@ -871,13 +874,13 @@ public function expandCriteriaParameters(Criteria $criteria) $sqlTypes = array_merge($sqlTypes, $this->getTypes($field, $value, $this->class)); } - return array($sqlParams, $sqlTypes); + return [$sqlParams, $sqlTypes]; } /** * {@inheritdoc} */ - public function loadAll(array $criteria = array(), array $orderBy = null, $limit = null, $offset = null) + public function loadAll(array $criteria = [], array $orderBy = null, $limit = null, $offset = null) { $this->switchPersisterContext($offset, $limit); @@ -887,7 +890,8 @@ public function loadAll(array $criteria = array(), array $orderBy = null, $limit $hydrator = $this->em->newHydrator(($this->currentPersisterContext->selectJoinSql) ? Query::HYDRATE_OBJECT : Query::HYDRATE_SIMPLEOBJECT); - return $hydrator->hydrateAll($stmt, $this->currentPersisterContext->rsm, array(UnitOfWork::HINT_DEFEREAGERLOAD => true)); + return $hydrator->hydrateAll($stmt, $this->currentPersisterContext->rsm, [UnitOfWork::HINT_DEFEREAGERLOAD => true] + ); } /** @@ -913,7 +917,7 @@ public function getManyToManyCollection(array $assoc, $sourceEntity, $offset = n private function loadArrayFromStatement($assoc, $stmt) { $rsm = $this->currentPersisterContext->rsm; - $hints = array(UnitOfWork::HINT_DEFEREAGERLOAD => true); + $hints = [UnitOfWork::HINT_DEFEREAGERLOAD => true]; if (isset($assoc['indexBy'])) { $rsm = clone ($this->currentPersisterContext->rsm); // this is necessary because the "default rsm" should be changed. @@ -935,10 +939,10 @@ private function loadArrayFromStatement($assoc, $stmt) private function loadCollectionFromStatement($assoc, $stmt, $coll) { $rsm = $this->currentPersisterContext->rsm; - $hints = array( + $hints = [ UnitOfWork::HINT_DEFEREAGERLOAD => true, 'collection' => $coll - ); + ]; if (isset($assoc['indexBy'])) { $rsm = clone ($this->currentPersisterContext->rsm); // this is necessary because the "default rsm" should be changed. @@ -975,8 +979,8 @@ private function getManyToManyStatement(array $assoc, $sourceEntity, $offset = n $sourceClass = $this->em->getClassMetadata($assoc['sourceEntity']); $class = $sourceClass; $association = $assoc; - $criteria = array(); - $parameters = array(); + $criteria = []; + $parameters = []; if ( ! $assoc['isOwningSide']) { $class = $this->em->getClassMetadata($assoc['targetEntity']); @@ -1018,11 +1022,11 @@ private function getManyToManyStatement(array $assoc, $sourceEntity, $offset = n } $criteria[$quotedJoinTable . '.' . $quotedKeyColumn] = $value; - $parameters[] = array( + $parameters[] = [ 'value' => $value, 'field' => $field, 'class' => $sourceClass, - ); + ]; } $sql = $this->getSelectSQL($criteria, $assoc, null, $limit, $offset); @@ -1060,11 +1064,11 @@ public function getSelectSQL($criteria, $assoc = null, $lockMode = null, $limit switch ($lockMode) { case LockMode::PESSIMISTIC_READ: - $lockSql = ' ' . $this->platform->getReadLockSql(); + $lockSql = ' ' . $this->platform->getReadLockSQL(); break; case LockMode::PESSIMISTIC_WRITE: - $lockSql = ' ' . $this->platform->getWriteLockSql(); + $lockSql = ' ' . $this->platform->getWriteLockSQL(); break; } @@ -1096,7 +1100,7 @@ public function getSelectSQL($criteria, $assoc = null, $lockMode = null, $limit /** * {@inheritDoc} */ - public function getCountSQL($criteria = array()) + public function getCountSQL($criteria = []) { $tableName = $this->quoteStrategy->getTableName($this->class, $this->platform); $tableAlias = $this->getSQLTableAlias($this->class->name); @@ -1132,7 +1136,7 @@ public function getCountSQL($criteria = array()) */ protected final function getOrderBySQL(array $orderBy, $baseTableAlias) { - $orderByList = array(); + $orderByList = []; foreach ($orderBy as $fieldName => $orientation) { @@ -1194,7 +1198,7 @@ protected function getSelectColumnsSQL() return $this->currentPersisterContext->selectColumnListSql; } - $columnList = array(); + $columnList = []; $this->currentPersisterContext->rsm->addEntityResult($this->class->name, 'r'); // r for root // Add regular columns to select list @@ -1247,7 +1251,7 @@ protected function getSelectColumnsSQL() } $association = $assoc; - $joinCondition = array(); + $joinCondition = []; if (isset($assoc['indexBy'])) { $this->currentPersisterContext->rsm->addIndexBy($assocAlias, $assoc['indexBy']); @@ -1315,7 +1319,7 @@ protected function getSelectColumnAssociationSQL($field, $assoc, ClassMetadata $ return ''; } - $columnList = array(); + $columnList = []; $targetClass = $this->em->getClassMetadata($assoc['targetEntity']); $isIdentifier = isset($assoc['id']) && $assoc['id'] === true; $sqlTableAlias = $this->getSQLTableAlias($class->name, ($alias == 'r' ? '' : $alias)); @@ -1325,7 +1329,7 @@ protected function getSelectColumnAssociationSQL($field, $assoc, ClassMetadata $ $resultColumnName = $this->getSQLColumnAlias($joinColumn['name']); $type = PersisterHelper::getTypeOfColumn($joinColumn['referencedColumnName'], $targetClass, $this->em); - $this->currentPersisterContext->rsm->addMetaResult($alias, $resultColumnName, $quotedColumn, $isIdentifier, $type); + $this->currentPersisterContext->rsm->addMetaResult($alias, $resultColumnName, $joinColumn['name'], $isIdentifier, $type); $columnList[] = sprintf('%s.%s AS %s', $sqlTableAlias, $quotedColumn, $resultColumnName); } @@ -1343,7 +1347,7 @@ protected function getSelectColumnAssociationSQL($field, $assoc, ClassMetadata $ */ protected function getSelectManyToManyJoinSQL(array $manyToMany) { - $conditions = array(); + $conditions = []; $association = $manyToMany; $sourceTableAlias = $this->getSQLTableAlias($this->class->name); @@ -1385,7 +1389,7 @@ public function getInsertSQL() return $this->insertSql; } - $values = array(); + $values = []; $columns = array_unique($columns); foreach ($columns as $column) { @@ -1419,7 +1423,7 @@ public function getInsertSQL() */ protected function getInsertColumnList() { - $columns = array(); + $columns = []; foreach ($this->class->reflFields as $name => $field) { if ($this->class->isVersioned && $this->class->versionField == $name) { @@ -1442,7 +1446,7 @@ protected function getInsertColumnList() continue; } - if ($this->class->generatorType != ClassMetadata::GENERATOR_TYPE_IDENTITY || $this->class->identifier[0] != $name) { + if (! $this->class->isIdGeneratorIdentity() || $this->class->identifier[0] != $name) { $columns[] = $this->quoteStrategy->getColumnName($name, $this->class, $this->platform); $this->columnTypes[$name] = $this->class->fieldMappings[$name]['type']; } @@ -1516,12 +1520,12 @@ public function lock(array $criteria, $lockMode) switch ($lockMode) { case LockMode::PESSIMISTIC_READ: - $lockSql = $this->platform->getReadLockSql(); + $lockSql = $this->platform->getReadLockSQL(); break; case LockMode::PESSIMISTIC_WRITE: - $lockSql = $this->platform->getWriteLockSql(); + $lockSql = $this->platform->getWriteLockSQL(); break; } @@ -1579,7 +1583,7 @@ protected function getSelectConditionCriteriaSQL(Criteria $criteria) */ public function getSelectConditionStatementSQL($field, $value, $assoc = null, $comparison = null) { - $selectedColumns = array(); + $selectedColumns = []; $columns = $this->getSelectConditionStatementColumnSQL($field, $assoc); if (count($columns) > 1 && $comparison === Comparison::IN) { @@ -1660,13 +1664,13 @@ private function getSelectConditionStatementColumnSQL($field, $assoc = null) ? $this->class->fieldMappings[$field]['inherited'] : $this->class->name; - return array($this->getSQLTableAlias($className) . '.' . $this->quoteStrategy->getColumnName($field, $this->class, $this->platform)); + return [$this->getSQLTableAlias($className) . '.' . $this->quoteStrategy->getColumnName($field, $this->class, $this->platform)]; } if (isset($this->class->associationMappings[$field])) { $association = $this->class->associationMappings[$field]; // Many-To-Many requires join table check for joinColumn - $columns = array(); + $columns = []; $class = $this->class; if ($association['type'] === ClassMetadata::MANY_TO_MANY) { @@ -1705,7 +1709,7 @@ private function getSelectConditionStatementColumnSQL($field, $assoc = null) // therefore checking for spaces and function calls which are not allowed. // found a join column condition, not really a "field" - return array($field); + return [$field]; } throw ORMException::unrecognizedField($field); @@ -1725,7 +1729,7 @@ private function getSelectConditionStatementColumnSQL($field, $assoc = null) */ protected function getSelectConditionSQL(array $criteria, $assoc = null) { - $conditions = array(); + $conditions = []; foreach ($criteria as $field => $value) { $conditions[] = $this->getSelectConditionStatementSQL($field, $value, $assoc); @@ -1770,11 +1774,11 @@ private function getOneToManyStatement(array $assoc, $sourceEntity, $offset = nu { $this->switchPersisterContext($offset, $limit); - $criteria = array(); - $parameters = array(); + $criteria = []; + $parameters = []; $owningAssoc = $this->class->associationMappings[$assoc['mappedBy']]; $sourceClass = $this->em->getClassMetadata($assoc['sourceEntity']); - $tableAlias = $this->getSQLTableAlias(isset($owningAssoc['inherited']) ? $owningAssoc['inherited'] : $this->class->name); + $tableAlias = $this->getSQLTableAlias($owningAssoc['inherited'] ?? $this->class->name); foreach ($owningAssoc['targetToSourceKeyColumns'] as $sourceKeyColumn => $targetKeyColumn) { if ($sourceClass->containsForeignIdentifier) { @@ -1787,11 +1791,11 @@ private function getOneToManyStatement(array $assoc, $sourceEntity, $offset = nu } $criteria[$tableAlias . "." . $targetKeyColumn] = $value; - $parameters[] = array( + $parameters[] = [ 'value' => $value, 'field' => $field, 'class' => $sourceClass, - ); + ]; continue; } @@ -1800,11 +1804,11 @@ private function getOneToManyStatement(array $assoc, $sourceEntity, $offset = nu $value = $sourceClass->reflFields[$field]->getValue($sourceEntity); $criteria[$tableAlias . "." . $targetKeyColumn] = $value; - $parameters[] = array( + $parameters[] = [ 'value' => $value, 'field' => $field, 'class' => $sourceClass, - ); + ]; } @@ -1819,8 +1823,8 @@ private function getOneToManyStatement(array $assoc, $sourceEntity, $offset = nu */ public function expandParameters($criteria) { - $params = array(); - $types = array(); + $params = []; + $types = []; foreach ($criteria as $field => $value) { if ($value === null) { @@ -1831,7 +1835,7 @@ public function expandParameters($criteria) $params = array_merge($params, $this->getValues($value)); } - return array($params, $types); + return [$params, $types]; } /** @@ -1848,8 +1852,8 @@ public function expandParameters($criteria) */ private function expandToManyParameters($criteria) { - $params = array(); - $types = array(); + $params = []; + $types = []; foreach ($criteria as $criterion) { if ($criterion['value'] === null) { @@ -1860,14 +1864,15 @@ private function expandToManyParameters($criteria) $params = array_merge($params, $this->getValues($criterion['value'])); } - return array($params, $types); + return [$params, $types]; } /** * Infers field types to be used by parameter type casting. * - * @param string $field - * @param mixed $value + * @param string $field + * @param mixed $value + * @param ClassMetadata $class * * @return array * @@ -1875,11 +1880,11 @@ private function expandToManyParameters($criteria) */ private function getTypes($field, $value, ClassMetadata $class) { - $types = array(); + $types = []; switch (true) { case (isset($class->fieldMappings[$field])): - $types = array_merge($types, array($class->fieldMappings[$field]['type'])); + $types = array_merge($types, [$class->fieldMappings[$field]['type']]); break; case (isset($class->associationMappings[$field])): @@ -1926,19 +1931,19 @@ private function getTypes($field, $value, ClassMetadata $class) private function getValues($value) { if (is_array($value)) { - $newValue = array(); + $newValue = []; foreach ($value as $itemValue) { $newValue = array_merge($newValue, $this->getValues($itemValue)); } - return array($newValue); + return [$newValue]; } if (is_object($value) && $this->em->getMetadataFactory()->hasMetadataFor(ClassUtils::getClass($value))) { $class = $this->em->getClassMetadata(get_class($value)); if ($class->isIdentifierComposite) { - $newValue = array(); + $newValue = []; foreach ($class->getIdentifierValues($value) as $innerValue) { $newValue = array_merge($newValue, $this->getValues($innerValue)); @@ -1948,7 +1953,7 @@ private function getValues($value) } } - return array($this->getIndividualValue($value)); + return [$this->getIndividualValue($value)]; } /** @@ -2038,7 +2043,7 @@ public function getSQLColumnAlias($columnName) */ protected function generateFilterConditionSQL(ClassMetadata $targetEntity, $targetTableAlias) { - $filterClauses = array(); + $filterClauses = []; foreach ($this->em->getFilters()->getEnabledFilters() as $filter) { if ('' !== $filterExpr = $filter->addFilterConstraint($targetEntity, $targetTableAlias)) { @@ -2069,4 +2074,22 @@ protected function switchPersisterContext($offset, $limit) $this->currentPersisterContext = $this->limitsHandlingContext; } + + /** + * @return string[] + */ + protected function getClassIdentifiersTypes(ClassMetadata $class) : array + { + $entityManager = $this->em; + + return array_map( + static function ($fieldName) use ($class, $entityManager) : string { + $types = PersisterHelper::getTypeOfField($fieldName, $class, $entityManager); + assert(isset($types[0])); + + return $types[0]; + }, + $class->identifier + ); + } } diff --git a/lib/Doctrine/ORM/Persisters/Entity/CachedPersisterContext.php b/lib/Doctrine/ORM/Persisters/Entity/CachedPersisterContext.php index 81fde938b3e..132dac7e4de 100644 --- a/lib/Doctrine/ORM/Persisters/Entity/CachedPersisterContext.php +++ b/lib/Doctrine/ORM/Persisters/Entity/CachedPersisterContext.php @@ -76,7 +76,7 @@ class CachedPersisterContext * * @var array */ - public $sqlTableAliases = array(); + public $sqlTableAliases = []; /** * Whether this persistent context is considering limit operations applied to the selection queries diff --git a/lib/Doctrine/ORM/Persisters/Entity/EntityPersister.php b/lib/Doctrine/ORM/Persisters/Entity/EntityPersister.php index ff018a05007..9ac63166832 100644 --- a/lib/Doctrine/ORM/Persisters/Entity/EntityPersister.php +++ b/lib/Doctrine/ORM/Persisters/Entity/EntityPersister.php @@ -81,7 +81,7 @@ public function getSelectSQL($criteria, $assoc = null, $lockMode = null, $limit * * @return string */ - public function getCountSQL($criteria = array()); + public function getCountSQL($criteria = []); /** * Expands the parameters from the given criteria and use the correct binding types if found. @@ -165,7 +165,7 @@ public function delete($entity); * * @return int */ - public function count($criteria = array()); + public function count($criteria = []); /** * Gets the name of the table that owns the column the given field is mapped to. @@ -197,7 +197,7 @@ public function getOwningTable($fieldName); * * @todo Check identity map? loadById method? Try to guess whether $criteria is the id? */ - public function load(array $criteria, $entity = null, $assoc = null, array $hints = array(), $lockMode = null, $limit = null, array $orderBy = null); + public function load(array $criteria, $entity = null, $assoc = null, array $hints = [], $lockMode = null, $limit = null, array $orderBy = null); /** * Loads an entity by identifier. @@ -225,7 +225,7 @@ public function loadById(array $identifier, $entity = null); * * @throws \Doctrine\ORM\Mapping\MappingException */ - public function loadOneToOneEntity(array $assoc, $sourceEntity, array $identifier = array()); + public function loadOneToOneEntity(array $assoc, $sourceEntity, array $identifier = []); /** * Refreshes a managed entity. @@ -260,7 +260,7 @@ public function loadCriteria(Criteria $criteria); * * @return array */ - public function loadAll(array $criteria = array(), array $orderBy = null, $limit = null, $offset = null); + public function loadAll(array $criteria = [], array $orderBy = null, $limit = null, $offset = null); /** * Gets (sliced or full) elements of the given collection. diff --git a/lib/Doctrine/ORM/Persisters/Entity/JoinedSubclassPersister.php b/lib/Doctrine/ORM/Persisters/Entity/JoinedSubclassPersister.php index 0975cf56ef1..1f6d40133c7 100644 --- a/lib/Doctrine/ORM/Persisters/Entity/JoinedSubclassPersister.php +++ b/lib/Doctrine/ORM/Persisters/Entity/JoinedSubclassPersister.php @@ -45,14 +45,14 @@ class JoinedSubclassPersister extends AbstractEntityInheritancePersister * * @var array */ - private $owningTableMap = array(); + private $owningTableMap = []; /** * Map of table to quoted table names. * * @var array */ - private $quotedTableMap = array(); + private $quotedTableMap = []; /** * {@inheritdoc} @@ -127,10 +127,10 @@ public function getOwningTable($fieldName) public function executeInserts() { if ( ! $this->queuedInserts) { - return array(); + return []; } - $postInsertIds = array(); + $postInsertIds = []; $idGenerator = $this->class->idGenerator; $isPostInsertId = $idGenerator->isPostInsertGenerator(); $rootClass = ($this->class->name !== $this->class->rootEntityName) @@ -143,7 +143,7 @@ public function executeInserts() $rootTableStmt = $this->conn->prepare($rootPersister->getInsertSQL()); // Prepare statements for sub tables. - $subTableStmts = array(); + $subTableStmts = []; if ($rootClass !== $this->class) { $subTableStmts[$this->class->getTableName()] = $this->conn->prepare($this->getInsertSQL()); @@ -176,13 +176,13 @@ public function executeInserts() if ($isPostInsertId) { $generatedId = $idGenerator->generate($this->em, $entity); - $id = array( + $id = [ $this->class->identifier[0] => $generatedId - ); - $postInsertIds[] = array( + ]; + $postInsertIds[] = [ 'generatedId' => $generatedId, 'entity' => $entity, - ); + ]; } else { $id = $this->em->getUnitOfWork()->getEntityIdentifier($entity); } @@ -196,9 +196,7 @@ public function executeInserts() foreach ($subTableStmts as $tableName => $stmt) { /** @var \Doctrine\DBAL\Statement $stmt */ $paramIndex = 1; - $data = isset($insertData[$tableName]) - ? $insertData[$tableName] - : array(); + $data = $insertData[$tableName] ?? []; foreach ((array) $id as $idName => $idVal) { $type = isset($this->columnTypes[$idName]) ? $this->columnTypes[$idName] : Type::STRING; @@ -222,7 +220,7 @@ public function executeInserts() $stmt->closeCursor(); } - $this->queuedInserts = array(); + $this->queuedInserts = []; return $postInsertIds; } @@ -258,7 +256,7 @@ public function update($entity) if ( ! isset($updateData[$versionedTable])) { $tableName = $this->quoteStrategy->getTableName($versionedClass, $this->platform); - $this->updateTable($entity, $tableName, array(), true); + $this->updateTable($entity, $tableName, [], true); } $identifiers = $this->em->getUnitOfWork()->getEntityIdentifier($entity); @@ -280,22 +278,25 @@ public function delete($entity) // If the database platform supports FKs, just // delete the row from the root table. Cascades do the rest. if ($this->platform->supportsForeignKeyConstraints()) { - $rootClass = $this->em->getClassMetadata($this->class->rootEntityName); - $rootTable = $this->quoteStrategy->getTableName($rootClass, $this->platform); + $rootClass = $this->em->getClassMetadata($this->class->rootEntityName); + $rootTable = $this->quoteStrategy->getTableName($rootClass, $this->platform); + $rootTypes = $this->getClassIdentifiersTypes($rootClass); - return (bool) $this->conn->delete($rootTable, $id); + return (bool) $this->conn->delete($rootTable, $id, $rootTypes); } // Delete from all tables individually, starting from this class' table up to the root table. $rootTable = $this->quoteStrategy->getTableName($this->class, $this->platform); + $rootTypes = $this->getClassIdentifiersTypes($this->class); - $affectedRows = $this->conn->delete($rootTable, $id); + $affectedRows = $this->conn->delete($rootTable, $id, $rootTypes); foreach ($this->class->parentClasses as $parentClass) { $parentMetadata = $this->em->getClassMetadata($parentClass); $parentTable = $this->quoteStrategy->getTableName($parentMetadata, $this->platform); + $parentTypes = $this->getClassIdentifiersTypes($parentMetadata); - $this->conn->delete($parentTable, $id); + $this->conn->delete($parentTable, $id, $parentTypes); } return (bool) $affectedRows; @@ -341,13 +342,13 @@ public function getSelectSQL($criteria, $assoc = null, $lockMode = null, $limit switch ($lockMode) { case LockMode::PESSIMISTIC_READ: - $lockSql = ' ' . $this->platform->getReadLockSql(); + $lockSql = ' ' . $this->platform->getReadLockSQL(); break; case LockMode::PESSIMISTIC_WRITE: - $lockSql = ' ' . $this->platform->getWriteLockSql(); + $lockSql = ' ' . $this->platform->getWriteLockSQL(); break; } @@ -369,7 +370,7 @@ public function getSelectSQL($criteria, $assoc = null, $lockMode = null, $limit /** * {@inheritDoc} */ - public function getCountSQL($criteria = array()) + public function getCountSQL($criteria = []) { $tableName = $this->quoteStrategy->getTableName($this->class, $this->platform); $baseTableAlias = $this->getSQLTableAlias($this->class->name); @@ -406,7 +407,7 @@ protected function getLockTablesSql($lockMode) // INNER JOIN parent tables foreach ($this->class->parentClasses as $parentClassName) { - $conditions = array(); + $conditions = []; $tableAlias = $this->getSQLTableAlias($parentClassName); $parentClass = $this->em->getClassMetadata($parentClassName); $joinSql .= ' INNER JOIN ' . $this->quoteStrategy->getTableName($parentClass, $this->platform) . ' ' . $tableAlias . ' ON '; @@ -433,7 +434,7 @@ protected function getSelectColumnsSQL() return $this->currentPersisterContext->selectColumnListSql; } - $columnList = array(); + $columnList = []; $discrColumn = $this->class->discriminatorColumn['name']; $discrColumnType = $this->class->discriminatorColumn['type']; $baseTableAlias = $this->getSQLTableAlias($this->class->name); @@ -462,22 +463,14 @@ protected function getSelectColumnsSQL() ? $this->getSQLTableAlias($mapping['inherited']) : $baseTableAlias; - foreach ($mapping['targetToSourceKeyColumns'] as $srcColumn) { - $className = isset($mapping['inherited']) - ? $mapping['inherited'] - : $this->class->name; - - $targetClass = $this->em->getClassMetadata($mapping['targetEntity']); + $targetClass = $this->em->getClassMetadata($mapping['targetEntity']); + foreach ($mapping['joinColumns'] as $joinColumn) { $columnList[] = $this->getSelectJoinColumnSQL( $tableAlias, - $srcColumn, - $className, - PersisterHelper::getTypeOfColumn( - $mapping['sourceToTargetKeyColumns'][$srcColumn], - $targetClass, - $this->em - ) + $joinColumn['name'], + $this->quoteStrategy->getJoinColumnName($joinColumn, $this->class, $this->platform), + PersisterHelper::getTypeOfColumn($joinColumn['referencedColumnName'], $targetClass, $this->em) ); } } @@ -511,22 +504,14 @@ protected function getSelectColumnsSQL() continue; } - foreach ($mapping['targetToSourceKeyColumns'] as $srcColumn) { - $className = isset($mapping['inherited']) - ? $mapping['inherited'] - : $subClass->name; - - $targetClass = $this->em->getClassMetadata($mapping['targetEntity']); + $targetClass = $this->em->getClassMetadata($mapping['targetEntity']); + foreach ($mapping['joinColumns'] as $joinColumn) { $columnList[] = $this->getSelectJoinColumnSQL( $tableAlias, - $srcColumn, - $className, - PersisterHelper::getTypeOfColumn( - $mapping['sourceToTargetKeyColumns'][$srcColumn], - $targetClass, - $this->em - ) + $joinColumn['name'], + $this->quoteStrategy->getJoinColumnName($joinColumn, $subClass, $this->platform), + PersisterHelper::getTypeOfColumn($joinColumn['referencedColumnName'], $targetClass, $this->em) ); } } @@ -545,7 +530,7 @@ protected function getInsertColumnList() // Identifier columns must always come first in the column list of subclasses. $columns = $this->class->parentClasses ? $this->class->getIdentifierColumnNames() - : array(); + : []; foreach ($this->class->reflFields as $name => $field) { if (isset($this->class->fieldMappings[$name]['inherited']) @@ -599,7 +584,7 @@ private function getJoinSql($baseTableAlias) // INNER JOIN parent tables foreach ($this->class->parentClasses as $parentClassName) { - $conditions = array(); + $conditions = []; $parentClass = $this->em->getClassMetadata($parentClassName); $tableAlias = $this->getSQLTableAlias($parentClassName); $joinSql .= ' INNER JOIN ' . $this->quoteStrategy->getTableName($parentClass, $this->platform) . ' ' . $tableAlias . ' ON '; @@ -614,7 +599,7 @@ private function getJoinSql($baseTableAlias) // OUTER JOIN sub tables foreach ($this->class->subClasses as $subClassName) { - $conditions = array(); + $conditions = []; $subClass = $this->em->getClassMetadata($subClassName); $tableAlias = $this->getSQLTableAlias($subClassName); $joinSql .= ' LEFT JOIN ' . $this->quoteStrategy->getTableName($subClass, $this->platform) . ' ' . $tableAlias . ' ON '; diff --git a/lib/Doctrine/ORM/Persisters/Entity/SingleTablePersister.php b/lib/Doctrine/ORM/Persisters/Entity/SingleTablePersister.php index 8dc71bb1d8c..4b8352b350c 100644 --- a/lib/Doctrine/ORM/Persisters/Entity/SingleTablePersister.php +++ b/lib/Doctrine/ORM/Persisters/Entity/SingleTablePersister.php @@ -87,19 +87,14 @@ protected function getSelectColumnsSQL() continue; } - $className = isset($assoc['inherited']) ? $assoc['inherited'] : $this->class->name; $targetClass = $this->em->getClassMetadata($assoc['targetEntity']); - foreach ($assoc['targetToSourceKeyColumns'] as $srcColumn) { + foreach ($assoc['joinColumns'] as $joinColumn) { $columnList[] = $this->getSelectJoinColumnSQL( $tableAlias, - $srcColumn, - $className, - PersisterHelper::getTypeOfColumn( - $assoc['sourceToTargetKeyColumns'][$srcColumn], - $targetClass, - $this->em - ) + $joinColumn['name'], + $this->quoteStrategy->getJoinColumnName($joinColumn, $subClass, $this->platform), + PersisterHelper::getTypeOfColumn($joinColumn['referencedColumnName'], $targetClass, $this->em) ); } } @@ -164,7 +159,7 @@ protected function getSelectConditionCriteriaSQL(Criteria $criteria) */ protected function getSelectConditionDiscriminatorValueSQL() { - $values = array(); + $values = []; if ($this->class->discriminatorValue !== null) { // discriminators can be 0 $values[] = $this->conn->quote($this->class->discriminatorValue); diff --git a/lib/Doctrine/ORM/Persisters/PersisterException.php b/lib/Doctrine/ORM/Persisters/PersisterException.php index 71fd0d179bc..09f73b21b5d 100644 --- a/lib/Doctrine/ORM/Persisters/PersisterException.php +++ b/lib/Doctrine/ORM/Persisters/PersisterException.php @@ -24,6 +24,9 @@ class PersisterException extends ORMException { /** + * @param string $class + * @param string $associationName + * * @return PersisterException */ static public function matchingAssocationFieldRequiresObject($class, $associationName) diff --git a/lib/Doctrine/ORM/Persisters/SqlExpressionVisitor.php b/lib/Doctrine/ORM/Persisters/SqlExpressionVisitor.php index f23bfa3da9a..476ecaba81e 100644 --- a/lib/Doctrine/ORM/Persisters/SqlExpressionVisitor.php +++ b/lib/Doctrine/ORM/Persisters/SqlExpressionVisitor.php @@ -70,7 +70,7 @@ public function walkComparison(Comparison $comparison) if (isset($this->classMetadata->associationMappings[$field]) && $value !== null && ! is_object($value) && - ! in_array($comparison->getOperator(), array(Comparison::IN, Comparison::NIN))) { + ! in_array($comparison->getOperator(), [Comparison::IN, Comparison::NIN])) { throw PersisterException::matchingAssocationFieldRequiresObject($this->classMetadata->name, $field); } @@ -89,7 +89,7 @@ public function walkComparison(Comparison $comparison) */ public function walkCompositeExpression(CompositeExpression $expr) { - $expressionList = array(); + $expressionList = []; foreach ($expr->getExpressionList() as $child) { $expressionList[] = $this->dispatch($child); diff --git a/lib/Doctrine/ORM/Persisters/SqlValueVisitor.php b/lib/Doctrine/ORM/Persisters/SqlValueVisitor.php index 0e680ad078d..a5df126c4d9 100644 --- a/lib/Doctrine/ORM/Persisters/SqlValueVisitor.php +++ b/lib/Doctrine/ORM/Persisters/SqlValueVisitor.php @@ -34,25 +34,25 @@ class SqlValueVisitor extends ExpressionVisitor /** * @var array */ - private $values = array(); + private $values = []; /** * @var array */ - private $types = array(); + private $types = []; /** * Converts a comparison expression into the target query language output. * * @param \Doctrine\Common\Collections\Expr\Comparison $comparison * - * @return mixed + * @return void */ public function walkComparison(Comparison $comparison) { - $value = $this->getValueFromComparison($comparison); - $field = $comparison->getField(); - $operator = $comparison->getOperator(); + $value = $this->getValueFromComparison($comparison); + $field = $comparison->getField(); + $operator = $comparison->getOperator(); if (($operator === Comparison::EQ || $operator === Comparison::IS) && $value === null) { return; @@ -61,7 +61,7 @@ public function walkComparison(Comparison $comparison) } $this->values[] = $value; - $this->types[] = array($field, $value); + $this->types[] = [$field, $value, $operator]; } /** @@ -69,7 +69,7 @@ public function walkComparison(Comparison $comparison) * * @param \Doctrine\Common\Collections\Expr\CompositeExpression $expr * - * @return mixed + * @return void */ public function walkCompositeExpression(CompositeExpression $expr) { @@ -97,7 +97,7 @@ public function walkValue(Value $value) */ public function getParamsAndTypes() { - return array($this->values, $this->types); + return [$this->values, $this->types]; } /** @@ -111,8 +111,18 @@ protected function getValueFromComparison(Comparison $comparison) { $value = $comparison->getValue()->getValue(); - return $comparison->getOperator() == Comparison::CONTAINS - ? "%{$value}%" - : $value; + switch ($comparison->getOperator()) { + case Comparison::CONTAINS: + return "%{$value}%"; + + case Comparison::STARTS_WITH: + return "{$value}%"; + + case Comparison::ENDS_WITH: + return "%{$value}"; + + default: + return $value; + } } } diff --git a/lib/Doctrine/ORM/Proxy/Proxy.php b/lib/Doctrine/ORM/Proxy/Proxy.php index f478d4905c0..75a61a75604 100644 --- a/lib/Doctrine/ORM/Proxy/Proxy.php +++ b/lib/Doctrine/ORM/Proxy/Proxy.php @@ -26,6 +26,8 @@ * * @author Roman Borschel * @since 2.0 + * + * @deprecated 2.7 This interface is being removed from the ORM and won't have any replacement, proxies will no longer implement it. */ interface Proxy extends BaseProxy { diff --git a/lib/Doctrine/ORM/Proxy/ProxyFactory.php b/lib/Doctrine/ORM/Proxy/ProxyFactory.php index 72f161eabf4..31fac18a208 100644 --- a/lib/Doctrine/ORM/Proxy/ProxyFactory.php +++ b/lib/Doctrine/ORM/Proxy/ProxyFactory.php @@ -37,6 +37,8 @@ * @author Giorgio Sironi * @author Marco Pivetta * @since 2.0 + * + * @deprecated 2.7 This class is being removed from the ORM and won't have any replacement */ class ProxyFactory extends AbstractProxyFactory { @@ -76,7 +78,7 @@ public function __construct(EntityManagerInterface $em, $proxyDir, $proxyNs, $au { $proxyGenerator = new ProxyGenerator($proxyDir, $proxyNs); - $proxyGenerator->setPlaceholder('baseProxyInterface', 'Doctrine\ORM\Proxy\Proxy'); + $proxyGenerator->setPlaceholder('baseProxyInterface', Proxy::class); parent::__construct($proxyGenerator, $em->getMetadataFactory(), $autoGenerate); $this->em = $em; @@ -91,7 +93,9 @@ public function __construct(EntityManagerInterface $em, $proxyDir, $proxyNs, $au protected function skipClass(ClassMetadata $metadata) { /* @var $metadata \Doctrine\ORM\Mapping\ClassMetadataInfo */ - return $metadata->isMappedSuperclass || $metadata->getReflectionClass()->isAbstract(); + return $metadata->isMappedSuperclass + || $metadata->isEmbeddedClass + || $metadata->getReflectionClass()->isAbstract(); } /** @@ -196,7 +200,7 @@ private function createCloner(ClassMetadata $classMetadata, EntityPersister $ent ); } - foreach ($class->getReflectionClass()->getProperties() as $property) { + foreach ($class->getReflectionProperties() as $property) { if ( ! $class->hasField($property->name) && ! $class->hasAssociation($property->name)) { continue; } diff --git a/lib/Doctrine/ORM/Query.php b/lib/Doctrine/ORM/Query.php index a7c6f852de7..c9d8fb673e0 100644 --- a/lib/Doctrine/ORM/Query.php +++ b/lib/Doctrine/ORM/Query.php @@ -19,13 +19,18 @@ namespace Doctrine\ORM; +use Doctrine\Common\Collections\ArrayCollection; use Doctrine\DBAL\LockMode; +use Doctrine\ORM\Mapping\ClassMetadata; +use Doctrine\ORM\Query\Exec\AbstractSqlExecutor; +use Doctrine\ORM\Query\Parameter; +use Doctrine\ORM\Query\ParameterTypeInferer; use Doctrine\ORM\Query\Parser; use Doctrine\ORM\Query\ParserResult; use Doctrine\ORM\Query\QueryException; -use Doctrine\ORM\Mapping\ClassMetadata; -use Doctrine\ORM\Query\ParameterTypeInferer; -use Doctrine\Common\Collections\ArrayCollection; +use Doctrine\ORM\Utility\HierarchyDiscriminatorResolver; +use function array_keys; +use function assert; /** * A Query object represents a DQL query. @@ -135,12 +140,12 @@ final class Query extends AbstractQuery * * @var array */ - private $_parsedTypes = array(); + private $_parsedTypes = []; /** * Cached DQL query. * - * @var string + * @var string|null */ private $_dql = null; @@ -154,14 +159,14 @@ final class Query extends AbstractQuery /** * The first result to return (the "offset"). * - * @var integer + * @var int|null */ private $_firstResult = null; /** * The maximum number of results to return (the "limit"). * - * @var integer + * @var integer|null */ private $_maxResults = null; @@ -202,7 +207,7 @@ final class Query extends AbstractQuery */ public function getSQL() { - return $this->_parse()->getSQLExecutor()->getSQLStatements(); + return $this->_parse()->getSqlExecutor()->getSqlStatements(); } /** @@ -241,7 +246,7 @@ protected function getResultSetMapping() */ private function _parse() { - $types = array(); + $types = []; foreach ($this->parameters as $parameter) { /** @var Query\Parameter $parameter */ @@ -309,7 +314,9 @@ protected function _doExecute() if ($paramCount > $mappingCount) { throw QueryException::tooManyParameters($mappingCount, $paramCount); - } elseif ($paramCount < $mappingCount) { + } + + if ($paramCount < $mappingCount) { throw QueryException::tooFewParameters($mappingCount, $paramCount); } @@ -320,9 +327,36 @@ protected function _doExecute() list($sqlParams, $types) = $this->processParameterMappings($paramMappings); + $this->evictResultSetCache( + $executor, + $sqlParams, + $types, + $this->_em->getConnection()->getParams() + ); + return $executor->execute($this->_em->getConnection(), $sqlParams, $types); } + private function evictResultSetCache( + AbstractSqlExecutor $executor, + array $sqlParams, + array $types, + array $connectionParams + ) { + if (null === $this->_queryCacheProfile || ! $this->getExpireResultCache()) { + return; + } + + $cacheDriver = $this->_queryCacheProfile->getResultCacheDriver(); + $statements = (array) $executor->getSqlStatements(); // Type casted since it can either be a string or an array + + foreach ($statements as $statement) { + $cacheKeys = $this->_queryCacheProfile->generateCacheKeys($statement, $sqlParams, $types, $connectionParams); + + $cacheDriver->delete(reset($cacheKeys)); + } + } + /** * Evict entity cache region */ @@ -352,26 +386,17 @@ private function evictEntityCacheRegion() */ private function processParameterMappings($paramMappings) { - $sqlParams = array(); - $types = array(); + $sqlParams = []; + $types = []; foreach ($this->parameters as $parameter) { - $key = $parameter->getName(); - $value = $parameter->getValue(); - $rsm = $this->getResultSetMapping(); + $key = $parameter->getName(); if ( ! isset($paramMappings[$key])) { throw QueryException::unknownParameter($key); } - if (isset($rsm->metadataParameterMapping[$key]) && $value instanceof ClassMetadata) { - $value = $value->getMetadataValue($rsm->metadataParameterMapping[$key]); - } - - $value = $this->processParameterValue($value); - $type = ($parameter->getValue() === $value) - ? $parameter->getType() - : ParameterTypeInferer::inferType($value); + [$value, $type] = $this->resolveParameterValue($parameter); foreach ($paramMappings[$key] as $position) { $types[$position] = $type; @@ -381,7 +406,7 @@ private function processParameterMappings($paramMappings) // optimized multi value sql positions away for now, // they are not allowed in DQL anyways. - $value = array($value); + $value = [$value]; $countValue = count($value); for ($i = 0, $l = count($sqlPositions); $i < $l; $i++) { @@ -401,7 +426,39 @@ private function processParameterMappings($paramMappings) $types = array_values($types); } - return array($sqlParams, $types); + return [$sqlParams, $types]; + } + + /** @return mixed[] tuple of (value, type) */ + private function resolveParameterValue(Parameter $parameter) : array + { + if ($parameter->typeWasSpecified()) { + return [$parameter->getValue(), $parameter->getType()]; + } + + $key = $parameter->getName(); + $originalValue = $parameter->getValue(); + $value = $originalValue; + $rsm = $this->getResultSetMapping(); + + assert($rsm !== null); + + if ($value instanceof ClassMetadata && isset($rsm->metadataParameterMapping[$key])) { + $value = $value->getMetadataValue($rsm->metadataParameterMapping[$key]); + } + + if ($value instanceof ClassMetadata && isset($rsm->discriminatorParameters[$key])) { + $value = array_keys(HierarchyDiscriminatorResolver::resolveDiscriminatorsForClass($value, $this->_em)); + } + + $processedValue = $this->processParameterValue($value); + + return [ + $processedValue, + $originalValue === $processedValue + ? $parameter->getType() + : ParameterTypeInferer::inferType($processedValue), + ]; } /** @@ -530,7 +587,7 @@ public function setDQL($dqlQuery) /** * Returns the DQL query that is represented by this query object. * - * @return string DQL query. + * @return string|null */ public function getDQL() { @@ -561,7 +618,7 @@ public function getState() */ public function contains($dql) { - return stripos($this->getDQL(), $dql) === false ? false : true; + return stripos($this->getDQL(), $dql) !== false; } /** @@ -583,7 +640,7 @@ public function setFirstResult($firstResult) * Gets the position of the first result the query object was set to retrieve (the "offset"). * Returns NULL if {@link setFirstResult} was not applied to this query. * - * @return integer The position of the first result. + * @return int|null The position of the first result. */ public function getFirstResult() { @@ -593,7 +650,7 @@ public function getFirstResult() /** * Sets the maximum number of results to retrieve (the "limit"). * - * @param integer $maxResults + * @param integer|null $maxResults * * @return Query This query object. */ @@ -609,7 +666,7 @@ public function setMaxResults($maxResults) * Gets the maximum number of results the query object was set to retrieve (the "limit"). * Returns NULL if {@link setMaxResults} was not applied to this query. * - * @return integer Maximum number of results. + * @return integer|null Maximum number of results. */ public function getMaxResults() { @@ -621,7 +678,7 @@ public function getMaxResults() * iterated over the result. * * @param ArrayCollection|array|null $parameters The query parameters. - * @param integer $hydrationMode The hydration mode to use. + * @param string|int $hydrationMode The hydration mode to use. * * @return \Doctrine\ORM\Internal\Hydration\IterableResult */ @@ -665,7 +722,7 @@ public function setHydrationMode($hydrationMode) */ public function setLockMode($lockMode) { - if (in_array($lockMode, array(LockMode::NONE, LockMode::PESSIMISTIC_READ, LockMode::PESSIMISTIC_WRITE), true)) { + if (in_array($lockMode, [LockMode::NONE, LockMode::PESSIMISTIC_READ, LockMode::PESSIMISTIC_WRITE], true)) { if ( ! $this->_em->getConnection()->isTransactionActive()) { throw TransactionRequiredException::transactionRequired(); } @@ -707,7 +764,7 @@ protected function _getQueryCacheId() ->getName(); return md5( - $this->getDql() . serialize($this->_hints) . + $this->getDQL() . serialize($this->_hints) . '&platform=' . $platform . ($this->_em->hasFilters() ? $this->_em->getFilters()->getHash() : '') . '&firstResult=' . $this->_firstResult . '&maxResult=' . $this->_maxResults . diff --git a/lib/Doctrine/ORM/Query/AST/CoalesceExpression.php b/lib/Doctrine/ORM/Query/AST/CoalesceExpression.php index 194f9ace55f..9e3b4c526fb 100644 --- a/lib/Doctrine/ORM/Query/AST/CoalesceExpression.php +++ b/lib/Doctrine/ORM/Query/AST/CoalesceExpression.php @@ -23,7 +23,7 @@ * CoalesceExpression ::= "COALESCE" "(" ScalarExpression {"," ScalarExpression}* ")" * * @since 2.1 - * + * * @link www.doctrine-project.org * @author Benjamin Eberlei * @author Guilherme Blanco @@ -35,7 +35,7 @@ class CoalesceExpression extends Node /** * @var array */ - public $scalarExpressions = array(); + public $scalarExpressions = []; /** * @param array $scalarExpressions diff --git a/lib/Doctrine/ORM/Query/AST/ConditionalExpression.php b/lib/Doctrine/ORM/Query/AST/ConditionalExpression.php index 62c7b2bca26..bf823629b69 100644 --- a/lib/Doctrine/ORM/Query/AST/ConditionalExpression.php +++ b/lib/Doctrine/ORM/Query/AST/ConditionalExpression.php @@ -33,7 +33,7 @@ class ConditionalExpression extends Node /** * @var array */ - public $conditionalTerms = array(); + public $conditionalTerms = []; /** * @param array $conditionalTerms diff --git a/lib/Doctrine/ORM/Query/AST/ConditionalTerm.php b/lib/Doctrine/ORM/Query/AST/ConditionalTerm.php index bb92db119bf..7122c9c6822 100644 --- a/lib/Doctrine/ORM/Query/AST/ConditionalTerm.php +++ b/lib/Doctrine/ORM/Query/AST/ConditionalTerm.php @@ -32,7 +32,7 @@ class ConditionalTerm extends Node /** * @var array */ - public $conditionalFactors = array(); + public $conditionalFactors = []; /** * @param array $conditionalFactors diff --git a/lib/Doctrine/ORM/Query/AST/FromClause.php b/lib/Doctrine/ORM/Query/AST/FromClause.php index b1d8dfe6b8f..fdb61ca373a 100644 --- a/lib/Doctrine/ORM/Query/AST/FromClause.php +++ b/lib/Doctrine/ORM/Query/AST/FromClause.php @@ -22,7 +22,7 @@ /** * FromClause ::= "FROM" IdentificationVariableDeclaration {"," IdentificationVariableDeclaration} * - * + * * @link www.doctrine-project.org * @since 2.0 * @author Guilherme Blanco @@ -34,7 +34,7 @@ class FromClause extends Node /** * @var array */ - public $identificationVariableDeclarations = array(); + public $identificationVariableDeclarations = []; /** * @param array $identificationVariableDeclarations diff --git a/lib/Doctrine/ORM/Query/AST/Functions/AbsFunction.php b/lib/Doctrine/ORM/Query/AST/Functions/AbsFunction.php index 8fade4c7a89..4c614355844 100644 --- a/lib/Doctrine/ORM/Query/AST/Functions/AbsFunction.php +++ b/lib/Doctrine/ORM/Query/AST/Functions/AbsFunction.php @@ -41,6 +41,7 @@ class AbsFunction extends FunctionNode /** * @override + * @inheritdoc */ public function getSql(\Doctrine\ORM\Query\SqlWalker $sqlWalker) { @@ -51,6 +52,7 @@ public function getSql(\Doctrine\ORM\Query\SqlWalker $sqlWalker) /** * @override + * @inheritdoc */ public function parse(\Doctrine\ORM\Query\Parser $parser) { diff --git a/lib/Doctrine/ORM/Query/AST/Functions/AvgFunction.php b/lib/Doctrine/ORM/Query/AST/Functions/AvgFunction.php new file mode 100644 index 00000000000..6cb8d92b6b2 --- /dev/null +++ b/lib/Doctrine/ORM/Query/AST/Functions/AvgFunction.php @@ -0,0 +1,54 @@ +. + */ + +namespace Doctrine\ORM\Query\AST\Functions; + +use Doctrine\ORM\Query\Parser; +use Doctrine\ORM\Query\SqlWalker; +use Doctrine\ORM\Query\AST\AggregateExpression; + +/** + * "AVG" "(" ["DISTINCT"] StringPrimary ")" + * + * @since 2.6 + * @author Mathew Davies + */ +final class AvgFunction extends FunctionNode +{ + /** + * @var AggregateExpression + */ + private $aggregateExpression; + + /** + * @inheritDoc + */ + public function getSql(SqlWalker $sqlWalker): string + { + return $this->aggregateExpression->dispatch($sqlWalker); + } + + /** + * @inheritDoc + */ + public function parse(Parser $parser): void + { + $this->aggregateExpression = $parser->AggregateExpression(); + } +} diff --git a/lib/Doctrine/ORM/Query/AST/Functions/BitAndFunction.php b/lib/Doctrine/ORM/Query/AST/Functions/BitAndFunction.php index 3ea69c0c115..469a4b0a24e 100644 --- a/lib/Doctrine/ORM/Query/AST/Functions/BitAndFunction.php +++ b/lib/Doctrine/ORM/Query/AST/Functions/BitAndFunction.php @@ -36,6 +36,7 @@ class BitAndFunction extends FunctionNode /** * @override + * @inheritdoc */ public function getSql(\Doctrine\ORM\Query\SqlWalker $sqlWalker) { @@ -49,6 +50,7 @@ public function getSql(\Doctrine\ORM\Query\SqlWalker $sqlWalker) /** * @override + * @inheritdoc */ public function parse(\Doctrine\ORM\Query\Parser $parser) { diff --git a/lib/Doctrine/ORM/Query/AST/Functions/BitOrFunction.php b/lib/Doctrine/ORM/Query/AST/Functions/BitOrFunction.php index 6b0d1eb4c32..d3a3efc8324 100644 --- a/lib/Doctrine/ORM/Query/AST/Functions/BitOrFunction.php +++ b/lib/Doctrine/ORM/Query/AST/Functions/BitOrFunction.php @@ -36,6 +36,7 @@ class BitOrFunction extends FunctionNode /** * @override + * @inheritdoc */ public function getSql(\Doctrine\ORM\Query\SqlWalker $sqlWalker) { @@ -49,6 +50,7 @@ public function getSql(\Doctrine\ORM\Query\SqlWalker $sqlWalker) /** * @override + * @inheritdoc */ public function parse(\Doctrine\ORM\Query\Parser $parser) { diff --git a/lib/Doctrine/ORM/Query/AST/Functions/ConcatFunction.php b/lib/Doctrine/ORM/Query/AST/Functions/ConcatFunction.php index 1c58f6cbdd6..b7c5ae13f82 100644 --- a/lib/Doctrine/ORM/Query/AST/Functions/ConcatFunction.php +++ b/lib/Doctrine/ORM/Query/AST/Functions/ConcatFunction.php @@ -38,26 +38,28 @@ class ConcatFunction extends FunctionNode public $secondStringPrimary; - public $concatExpressions = array(); + public $concatExpressions = []; /** * @override + * @inheritdoc */ public function getSql(\Doctrine\ORM\Query\SqlWalker $sqlWalker) { $platform = $sqlWalker->getConnection()->getDatabasePlatform(); - $args = array(); + $args = []; foreach ($this->concatExpressions as $expression) { $args[] = $sqlWalker->walkStringPrimary($expression); } - return call_user_func_array(array($platform,'getConcatExpression'), $args); + return call_user_func_array([$platform,'getConcatExpression'], $args); } /** * @override + * @inheritdoc */ public function parse(\Doctrine\ORM\Query\Parser $parser) { diff --git a/lib/Doctrine/ORM/Query/AST/Functions/CountFunction.php b/lib/Doctrine/ORM/Query/AST/Functions/CountFunction.php new file mode 100644 index 00000000000..f232cf43f65 --- /dev/null +++ b/lib/Doctrine/ORM/Query/AST/Functions/CountFunction.php @@ -0,0 +1,54 @@ +. + */ + +namespace Doctrine\ORM\Query\AST\Functions; + +use Doctrine\ORM\Query\Parser; +use Doctrine\ORM\Query\SqlWalker; +use Doctrine\ORM\Query\AST\AggregateExpression; + +/** + * "COUNT" "(" ["DISTINCT"] StringPrimary ")" + * + * @since 2.6 + * @author Mathew Davies + */ +final class CountFunction extends FunctionNode +{ + /** + * @var AggregateExpression + */ + private $aggregateExpression; + + /** + * @inheritDoc + */ + public function getSql(SqlWalker $sqlWalker): string + { + return $this->aggregateExpression->dispatch($sqlWalker); + } + + /** + * @inheritDoc + */ + public function parse(Parser $parser): void + { + $this->aggregateExpression = $parser->AggregateExpression(); + } +} diff --git a/lib/Doctrine/ORM/Query/AST/Functions/CurrentDateFunction.php b/lib/Doctrine/ORM/Query/AST/Functions/CurrentDateFunction.php index 8e8ce1c77b0..565b87581b3 100644 --- a/lib/Doctrine/ORM/Query/AST/Functions/CurrentDateFunction.php +++ b/lib/Doctrine/ORM/Query/AST/Functions/CurrentDateFunction.php @@ -36,6 +36,7 @@ class CurrentDateFunction extends FunctionNode { /** * @override + * @inheritdoc */ public function getSql(\Doctrine\ORM\Query\SqlWalker $sqlWalker) { @@ -44,6 +45,7 @@ public function getSql(\Doctrine\ORM\Query\SqlWalker $sqlWalker) /** * @override + * @inheritdoc */ public function parse(\Doctrine\ORM\Query\Parser $parser) { diff --git a/lib/Doctrine/ORM/Query/AST/Functions/CurrentTimeFunction.php b/lib/Doctrine/ORM/Query/AST/Functions/CurrentTimeFunction.php index 4bab247c0ff..ec9ceb757f5 100644 --- a/lib/Doctrine/ORM/Query/AST/Functions/CurrentTimeFunction.php +++ b/lib/Doctrine/ORM/Query/AST/Functions/CurrentTimeFunction.php @@ -36,6 +36,7 @@ class CurrentTimeFunction extends FunctionNode { /** * @override + * @inheritdoc */ public function getSql(\Doctrine\ORM\Query\SqlWalker $sqlWalker) { @@ -44,6 +45,7 @@ public function getSql(\Doctrine\ORM\Query\SqlWalker $sqlWalker) /** * @override + * @inheritdoc */ public function parse(\Doctrine\ORM\Query\Parser $parser) { diff --git a/lib/Doctrine/ORM/Query/AST/Functions/CurrentTimestampFunction.php b/lib/Doctrine/ORM/Query/AST/Functions/CurrentTimestampFunction.php index 8a9b4185fb2..4203072128d 100644 --- a/lib/Doctrine/ORM/Query/AST/Functions/CurrentTimestampFunction.php +++ b/lib/Doctrine/ORM/Query/AST/Functions/CurrentTimestampFunction.php @@ -36,6 +36,7 @@ class CurrentTimestampFunction extends FunctionNode { /** * @override + * @inheritdoc */ public function getSql(\Doctrine\ORM\Query\SqlWalker $sqlWalker) { @@ -44,6 +45,7 @@ public function getSql(\Doctrine\ORM\Query\SqlWalker $sqlWalker) /** * @override + * @inheritdoc */ public function parse(\Doctrine\ORM\Query\Parser $parser) { diff --git a/lib/Doctrine/ORM/Query/AST/Functions/DateAddFunction.php b/lib/Doctrine/ORM/Query/AST/Functions/DateAddFunction.php index 2a9aead98a4..edec7f9874a 100644 --- a/lib/Doctrine/ORM/Query/AST/Functions/DateAddFunction.php +++ b/lib/Doctrine/ORM/Query/AST/Functions/DateAddFunction.php @@ -41,6 +41,7 @@ class DateAddFunction extends FunctionNode /** * @override + * @inheritdoc */ public function getSql(SqlWalker $sqlWalker) { @@ -50,7 +51,11 @@ public function getSql(SqlWalker $sqlWalker) $this->firstDateExpression->dispatch($sqlWalker), $this->intervalExpression->dispatch($sqlWalker) ); - + case 'minute': + return $sqlWalker->getConnection()->getDatabasePlatform()->getDateAddMinutesExpression( + $this->firstDateExpression->dispatch($sqlWalker), + $this->intervalExpression->dispatch($sqlWalker) + ); case 'hour': return $sqlWalker->getConnection()->getDatabasePlatform()->getDateAddHourExpression( $this->firstDateExpression->dispatch($sqlWalker), @@ -61,22 +66,32 @@ public function getSql(SqlWalker $sqlWalker) $this->firstDateExpression->dispatch($sqlWalker), $this->intervalExpression->dispatch($sqlWalker) ); - + case 'week': + return $sqlWalker->getConnection()->getDatabasePlatform()->getDateAddWeeksExpression( + $this->firstDateExpression->dispatch($sqlWalker), + $this->intervalExpression->dispatch($sqlWalker) + ); case 'month': return $sqlWalker->getConnection()->getDatabasePlatform()->getDateAddMonthExpression( $this->firstDateExpression->dispatch($sqlWalker), $this->intervalExpression->dispatch($sqlWalker) ); + case 'year': + return $sqlWalker->getConnection()->getDatabasePlatform()->getDateAddYearsExpression( + $this->firstDateExpression->dispatch($sqlWalker), + $this->intervalExpression->dispatch($sqlWalker) + ); default: throw QueryException::semanticalError( - 'DATE_ADD() only supports units of type second, hour, day and month.' + 'DATE_ADD() only supports units of type second, minute, hour, day, week, month and year.' ); } } /** * @override + * @inheritdoc */ public function parse(Parser $parser) { diff --git a/lib/Doctrine/ORM/Query/AST/Functions/DateDiffFunction.php b/lib/Doctrine/ORM/Query/AST/Functions/DateDiffFunction.php index a33c2d06f33..53724825f4e 100644 --- a/lib/Doctrine/ORM/Query/AST/Functions/DateDiffFunction.php +++ b/lib/Doctrine/ORM/Query/AST/Functions/DateDiffFunction.php @@ -38,6 +38,7 @@ class DateDiffFunction extends FunctionNode /** * @override + * @inheritdoc */ public function getSql(SqlWalker $sqlWalker) { @@ -49,6 +50,7 @@ public function getSql(SqlWalker $sqlWalker) /** * @override + * @inheritdoc */ public function parse(Parser $parser) { diff --git a/lib/Doctrine/ORM/Query/AST/Functions/DateSubFunction.php b/lib/Doctrine/ORM/Query/AST/Functions/DateSubFunction.php index d0e890fa793..8dcc1353719 100644 --- a/lib/Doctrine/ORM/Query/AST/Functions/DateSubFunction.php +++ b/lib/Doctrine/ORM/Query/AST/Functions/DateSubFunction.php @@ -35,10 +35,21 @@ class DateSubFunction extends DateAddFunction { /** * @override + * @inheritdoc */ public function getSql(SqlWalker $sqlWalker) { switch (strtolower($this->unit->value)) { + case 'second': + return $sqlWalker->getConnection()->getDatabasePlatform()->getDateSubSecondsExpression( + $this->firstDateExpression->dispatch($sqlWalker), + $this->intervalExpression->dispatch($sqlWalker) + ); + case 'minute': + return $sqlWalker->getConnection()->getDatabasePlatform()->getDateSubMinutesExpression( + $this->firstDateExpression->dispatch($sqlWalker), + $this->intervalExpression->dispatch($sqlWalker) + ); case 'hour': return $sqlWalker->getConnection()->getDatabasePlatform()->getDateSubHourExpression( $this->firstDateExpression->dispatch($sqlWalker), @@ -49,16 +60,25 @@ public function getSql(SqlWalker $sqlWalker) $this->firstDateExpression->dispatch($sqlWalker), $this->intervalExpression->dispatch($sqlWalker) ); - + case 'week': + return $sqlWalker->getConnection()->getDatabasePlatform()->getDateSubWeeksExpression( + $this->firstDateExpression->dispatch($sqlWalker), + $this->intervalExpression->dispatch($sqlWalker) + ); case 'month': return $sqlWalker->getConnection()->getDatabasePlatform()->getDateSubMonthExpression( $this->firstDateExpression->dispatch($sqlWalker), $this->intervalExpression->dispatch($sqlWalker) ); + case 'year': + return $sqlWalker->getConnection()->getDatabasePlatform()->getDateSubYearsExpression( + $this->firstDateExpression->dispatch($sqlWalker), + $this->intervalExpression->dispatch($sqlWalker) + ); default: throw QueryException::semanticalError( - 'DATE_SUB() only supports units of type hour, day and month.' + 'DATE_SUB() only supports units of type second, minute, hour, day, week, month and year.' ); } } diff --git a/lib/Doctrine/ORM/Query/AST/Functions/LengthFunction.php b/lib/Doctrine/ORM/Query/AST/Functions/LengthFunction.php index e2729feebf7..3d2b1a6c92a 100644 --- a/lib/Doctrine/ORM/Query/AST/Functions/LengthFunction.php +++ b/lib/Doctrine/ORM/Query/AST/Functions/LengthFunction.php @@ -38,6 +38,7 @@ class LengthFunction extends FunctionNode /** * @override + * @inheritdoc */ public function getSql(\Doctrine\ORM\Query\SqlWalker $sqlWalker) { @@ -48,6 +49,7 @@ public function getSql(\Doctrine\ORM\Query\SqlWalker $sqlWalker) /** * @override + * @inheritdoc */ public function parse(\Doctrine\ORM\Query\Parser $parser) { diff --git a/lib/Doctrine/ORM/Query/AST/Functions/LocateFunction.php b/lib/Doctrine/ORM/Query/AST/Functions/LocateFunction.php index cba45bc1cb1..473aa34eec9 100644 --- a/lib/Doctrine/ORM/Query/AST/Functions/LocateFunction.php +++ b/lib/Doctrine/ORM/Query/AST/Functions/LocateFunction.php @@ -44,6 +44,7 @@ class LocateFunction extends FunctionNode /** * @override + * @inheritdoc */ public function getSql(\Doctrine\ORM\Query\SqlWalker $sqlWalker) { @@ -60,6 +61,7 @@ public function getSql(\Doctrine\ORM\Query\SqlWalker $sqlWalker) /** * @override + * @inheritdoc */ public function parse(\Doctrine\ORM\Query\Parser $parser) { diff --git a/lib/Doctrine/ORM/Query/AST/Functions/LowerFunction.php b/lib/Doctrine/ORM/Query/AST/Functions/LowerFunction.php index 5f0387e6f45..5f0fb950018 100644 --- a/lib/Doctrine/ORM/Query/AST/Functions/LowerFunction.php +++ b/lib/Doctrine/ORM/Query/AST/Functions/LowerFunction.php @@ -38,6 +38,7 @@ class LowerFunction extends FunctionNode /** * @override + * @inheritdoc */ public function getSql(\Doctrine\ORM\Query\SqlWalker $sqlWalker) { @@ -48,6 +49,7 @@ public function getSql(\Doctrine\ORM\Query\SqlWalker $sqlWalker) /** * @override + * @inheritdoc */ public function parse(\Doctrine\ORM\Query\Parser $parser) { diff --git a/lib/Doctrine/ORM/Query/AST/Functions/MaxFunction.php b/lib/Doctrine/ORM/Query/AST/Functions/MaxFunction.php new file mode 100644 index 00000000000..eba9b86393a --- /dev/null +++ b/lib/Doctrine/ORM/Query/AST/Functions/MaxFunction.php @@ -0,0 +1,54 @@ +. + */ + +namespace Doctrine\ORM\Query\AST\Functions; + +use Doctrine\ORM\Query\Parser; +use Doctrine\ORM\Query\SqlWalker; +use Doctrine\ORM\Query\AST\AggregateExpression; + +/** + * "MAX" "(" ["DISTINCT"] StringPrimary ")" + * + * @since 2.6 + * @author Mathew Davies + */ +final class MaxFunction extends FunctionNode +{ + /** + * @var AggregateExpression + */ + private $aggregateExpression; + + /** + * @inheritDoc + */ + public function getSql(SqlWalker $sqlWalker): string + { + return $this->aggregateExpression->dispatch($sqlWalker); + } + + /** + * @inheritDoc + */ + public function parse(Parser $parser): void + { + $this->aggregateExpression = $parser->AggregateExpression(); + } +} diff --git a/lib/Doctrine/ORM/Query/AST/Functions/MinFunction.php b/lib/Doctrine/ORM/Query/AST/Functions/MinFunction.php new file mode 100644 index 00000000000..e1c08691323 --- /dev/null +++ b/lib/Doctrine/ORM/Query/AST/Functions/MinFunction.php @@ -0,0 +1,54 @@ +. + */ + +namespace Doctrine\ORM\Query\AST\Functions; + +use Doctrine\ORM\Query\Parser; +use Doctrine\ORM\Query\SqlWalker; +use Doctrine\ORM\Query\AST\AggregateExpression; + +/** + * "MIN" "(" ["DISTINCT"] StringPrimary ")" + * + * @since 2.6 + * @author Mathew Davies + */ +final class MinFunction extends FunctionNode +{ + /** + * @var AggregateExpression + */ + private $aggregateExpression; + + /** + * @inheritDoc + */ + public function getSql(SqlWalker $sqlWalker): string + { + return $this->aggregateExpression->dispatch($sqlWalker); + } + + /** + * @inheritDoc + */ + public function parse(Parser $parser): void + { + $this->aggregateExpression = $parser->AggregateExpression(); + } +} diff --git a/lib/Doctrine/ORM/Query/AST/Functions/ModFunction.php b/lib/Doctrine/ORM/Query/AST/Functions/ModFunction.php index f00c6db7f93..61bc9a79ed9 100644 --- a/lib/Doctrine/ORM/Query/AST/Functions/ModFunction.php +++ b/lib/Doctrine/ORM/Query/AST/Functions/ModFunction.php @@ -46,6 +46,7 @@ class ModFunction extends FunctionNode /** * @override + * @inheritdoc */ public function getSql(\Doctrine\ORM\Query\SqlWalker $sqlWalker) { @@ -57,6 +58,7 @@ public function getSql(\Doctrine\ORM\Query\SqlWalker $sqlWalker) /** * @override + * @inheritdoc */ public function parse(\Doctrine\ORM\Query\Parser $parser) { diff --git a/lib/Doctrine/ORM/Query/AST/Functions/SizeFunction.php b/lib/Doctrine/ORM/Query/AST/Functions/SizeFunction.php index 7970508f17f..bf0f7a4ec04 100644 --- a/lib/Doctrine/ORM/Query/AST/Functions/SizeFunction.php +++ b/lib/Doctrine/ORM/Query/AST/Functions/SizeFunction.php @@ -41,6 +41,7 @@ class SizeFunction extends FunctionNode /** * @override + * @inheritdoc * @todo If the collection being counted is already joined, the SQL can be simpler (more efficient). */ public function getSql(\Doctrine\ORM\Query\SqlWalker $sqlWalker) @@ -110,6 +111,7 @@ public function getSql(\Doctrine\ORM\Query\SqlWalker $sqlWalker) /** * @override + * @inheritdoc */ public function parse(\Doctrine\ORM\Query\Parser $parser) { diff --git a/lib/Doctrine/ORM/Query/AST/Functions/SqrtFunction.php b/lib/Doctrine/ORM/Query/AST/Functions/SqrtFunction.php index c9f1038c494..08155d25b56 100644 --- a/lib/Doctrine/ORM/Query/AST/Functions/SqrtFunction.php +++ b/lib/Doctrine/ORM/Query/AST/Functions/SqrtFunction.php @@ -41,6 +41,7 @@ class SqrtFunction extends FunctionNode /** * @override + * @inheritdoc */ public function getSql(\Doctrine\ORM\Query\SqlWalker $sqlWalker) { @@ -51,6 +52,7 @@ public function getSql(\Doctrine\ORM\Query\SqlWalker $sqlWalker) /** * @override + * @inheritdoc */ public function parse(\Doctrine\ORM\Query\Parser $parser) { diff --git a/lib/Doctrine/ORM/Query/AST/Functions/SubstringFunction.php b/lib/Doctrine/ORM/Query/AST/Functions/SubstringFunction.php index ee80c06acfa..a6a80f8112b 100644 --- a/lib/Doctrine/ORM/Query/AST/Functions/SubstringFunction.php +++ b/lib/Doctrine/ORM/Query/AST/Functions/SubstringFunction.php @@ -48,6 +48,7 @@ class SubstringFunction extends FunctionNode /** * @override + * @inheritdoc */ public function getSql(\Doctrine\ORM\Query\SqlWalker $sqlWalker) { @@ -65,6 +66,7 @@ public function getSql(\Doctrine\ORM\Query\SqlWalker $sqlWalker) /** * @override + * @inheritdoc */ public function parse(\Doctrine\ORM\Query\Parser $parser) { diff --git a/lib/Doctrine/ORM/Query/AST/Functions/SumFunction.php b/lib/Doctrine/ORM/Query/AST/Functions/SumFunction.php new file mode 100644 index 00000000000..c9fcf7b04e7 --- /dev/null +++ b/lib/Doctrine/ORM/Query/AST/Functions/SumFunction.php @@ -0,0 +1,54 @@ +. + */ + +namespace Doctrine\ORM\Query\AST\Functions; + +use Doctrine\ORM\Query\Parser; +use Doctrine\ORM\Query\SqlWalker; +use Doctrine\ORM\Query\AST\AggregateExpression; + +/** + * "SUM" "(" ["DISTINCT"] StringPrimary ")" + * + * @since 2.6 + * @author Mathew Davies + */ +final class SumFunction extends FunctionNode +{ + /** + * @var AggregateExpression + */ + private $aggregateExpression; + + /** + * @inheritDoc + */ + public function getSql(SqlWalker $sqlWalker): string + { + return $this->aggregateExpression->dispatch($sqlWalker); + } + + /** + * @inheritDoc + */ + public function parse(Parser $parser): void + { + $this->aggregateExpression = $parser->AggregateExpression(); + } +} diff --git a/lib/Doctrine/ORM/Query/AST/Functions/UpperFunction.php b/lib/Doctrine/ORM/Query/AST/Functions/UpperFunction.php index 22592a174e4..28e0f162714 100644 --- a/lib/Doctrine/ORM/Query/AST/Functions/UpperFunction.php +++ b/lib/Doctrine/ORM/Query/AST/Functions/UpperFunction.php @@ -38,6 +38,7 @@ class UpperFunction extends FunctionNode /** * @override + * @inheritdoc */ public function getSql(\Doctrine\ORM\Query\SqlWalker $sqlWalker) { @@ -48,6 +49,7 @@ public function getSql(\Doctrine\ORM\Query\SqlWalker $sqlWalker) /** * @override + * @inheritdoc */ public function parse(\Doctrine\ORM\Query\Parser $parser) { diff --git a/lib/Doctrine/ORM/Query/AST/GeneralCaseExpression.php b/lib/Doctrine/ORM/Query/AST/GeneralCaseExpression.php index a74eed599dc..e7937d60d2e 100644 --- a/lib/Doctrine/ORM/Query/AST/GeneralCaseExpression.php +++ b/lib/Doctrine/ORM/Query/AST/GeneralCaseExpression.php @@ -23,7 +23,7 @@ * GeneralCaseExpression ::= "CASE" WhenClause {WhenClause}* "ELSE" ScalarExpression "END" * * @since 2.2 - * + * * @link www.doctrine-project.org * @author Benjamin Eberlei * @author Guilherme Blanco @@ -35,7 +35,7 @@ class GeneralCaseExpression extends Node /** * @var array */ - public $whenClauses = array(); + public $whenClauses = []; /** * @var mixed diff --git a/lib/Doctrine/ORM/Query/AST/GroupByClause.php b/lib/Doctrine/ORM/Query/AST/GroupByClause.php index c05fa5863d0..687512a4c73 100644 --- a/lib/Doctrine/ORM/Query/AST/GroupByClause.php +++ b/lib/Doctrine/ORM/Query/AST/GroupByClause.php @@ -33,7 +33,7 @@ class GroupByClause extends Node /** * @var array */ - public $groupByItems = array(); + public $groupByItems = []; /** * @param array $groupByItems diff --git a/lib/Doctrine/ORM/Query/AST/IdentificationVariableDeclaration.php b/lib/Doctrine/ORM/Query/AST/IdentificationVariableDeclaration.php index a8f7f6d350e..2e2032ca341 100644 --- a/lib/Doctrine/ORM/Query/AST/IdentificationVariableDeclaration.php +++ b/lib/Doctrine/ORM/Query/AST/IdentificationVariableDeclaration.php @@ -43,7 +43,7 @@ class IdentificationVariableDeclaration extends Node /** * @var array */ - public $joins = array(); + public $joins = []; /** * @param RangeVariableDeclaration|null $rangeVariableDecl diff --git a/lib/Doctrine/ORM/Query/AST/InExpression.php b/lib/Doctrine/ORM/Query/AST/InExpression.php index 9d0a8b54ee8..64ef1340573 100644 --- a/lib/Doctrine/ORM/Query/AST/InExpression.php +++ b/lib/Doctrine/ORM/Query/AST/InExpression.php @@ -42,7 +42,7 @@ class InExpression extends Node /** * @var array */ - public $literals = array(); + public $literals = []; /** * @var Subselect|null diff --git a/lib/Doctrine/ORM/Query/AST/InputParameter.php b/lib/Doctrine/ORM/Query/AST/InputParameter.php index cf50140be9b..4da550f9b4f 100644 --- a/lib/Doctrine/ORM/Query/AST/InputParameter.php +++ b/lib/Doctrine/ORM/Query/AST/InputParameter.php @@ -47,7 +47,7 @@ class InputParameter extends Node */ public function __construct($value) { - if (strlen($value) == 1) { + if (strlen($value) === 1) { throw \Doctrine\ORM\Query\QueryException::invalidParameterFormat($value); } diff --git a/lib/Doctrine/ORM/Query/AST/NewObjectExpression.php b/lib/Doctrine/ORM/Query/AST/NewObjectExpression.php index 65b94ac63cf..ec011ce29f0 100644 --- a/lib/Doctrine/ORM/Query/AST/NewObjectExpression.php +++ b/lib/Doctrine/ORM/Query/AST/NewObjectExpression.php @@ -13,7 +13,7 @@ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * This software consists of voluntary contributions made by many individuals - * and is licensed under the MIT. For more information, see + * and is licensed under the MIT license. For more information, see * . */ diff --git a/lib/Doctrine/ORM/Query/AST/OrderByClause.php b/lib/Doctrine/ORM/Query/AST/OrderByClause.php index 75d16c7319d..e0e30e9d997 100644 --- a/lib/Doctrine/ORM/Query/AST/OrderByClause.php +++ b/lib/Doctrine/ORM/Query/AST/OrderByClause.php @@ -33,7 +33,7 @@ class OrderByClause extends Node /** * @var array */ - public $orderByItems = array(); + public $orderByItems = []; /** * @param array $orderByItems diff --git a/lib/Doctrine/ORM/Query/AST/SelectClause.php b/lib/Doctrine/ORM/Query/AST/SelectClause.php index 1df143677be..f8e6f472a1e 100644 --- a/lib/Doctrine/ORM/Query/AST/SelectClause.php +++ b/lib/Doctrine/ORM/Query/AST/SelectClause.php @@ -38,7 +38,7 @@ class SelectClause extends Node /** * @var array */ - public $selectExpressions = array(); + public $selectExpressions = []; /** * @param array $selectExpressions diff --git a/lib/Doctrine/ORM/Query/AST/SimpleArithmeticExpression.php b/lib/Doctrine/ORM/Query/AST/SimpleArithmeticExpression.php index 9bd485045f3..80ecd15ce57 100644 --- a/lib/Doctrine/ORM/Query/AST/SimpleArithmeticExpression.php +++ b/lib/Doctrine/ORM/Query/AST/SimpleArithmeticExpression.php @@ -33,7 +33,7 @@ class SimpleArithmeticExpression extends Node /** * @var array */ - public $arithmeticTerms = array(); + public $arithmeticTerms = []; /** * @param array $arithmeticTerms diff --git a/lib/Doctrine/ORM/Query/AST/SimpleCaseExpression.php b/lib/Doctrine/ORM/Query/AST/SimpleCaseExpression.php index 5272f3962a8..67e354e5569 100644 --- a/lib/Doctrine/ORM/Query/AST/SimpleCaseExpression.php +++ b/lib/Doctrine/ORM/Query/AST/SimpleCaseExpression.php @@ -23,7 +23,7 @@ * SimpleCaseExpression ::= "CASE" CaseOperand SimpleWhenClause {SimpleWhenClause}* "ELSE" ScalarExpression "END" * * @since 2.2 - * + * * @link www.doctrine-project.org * @author Benjamin Eberlei * @author Guilherme Blanco @@ -40,7 +40,7 @@ class SimpleCaseExpression extends Node /** * @var array */ - public $simpleWhenClauses = array(); + public $simpleWhenClauses = []; /** * @var mixed diff --git a/lib/Doctrine/ORM/Query/AST/SubselectFromClause.php b/lib/Doctrine/ORM/Query/AST/SubselectFromClause.php index 8d009fcfdc1..9704061e8cd 100644 --- a/lib/Doctrine/ORM/Query/AST/SubselectFromClause.php +++ b/lib/Doctrine/ORM/Query/AST/SubselectFromClause.php @@ -33,7 +33,7 @@ class SubselectFromClause extends Node /** * @var array */ - public $identificationVariableDeclarations = array(); + public $identificationVariableDeclarations = []; /** * @param array $identificationVariableDeclarations diff --git a/lib/Doctrine/ORM/Query/AST/UpdateClause.php b/lib/Doctrine/ORM/Query/AST/UpdateClause.php index 430ed14eb93..23c722a62b2 100644 --- a/lib/Doctrine/ORM/Query/AST/UpdateClause.php +++ b/lib/Doctrine/ORM/Query/AST/UpdateClause.php @@ -43,7 +43,7 @@ class UpdateClause extends Node /** * @var array */ - public $updateItems = array(); + public $updateItems = []; /** * @param string $abstractSchemaName diff --git a/lib/Doctrine/ORM/Query/Exec/MultiTableDeleteExecutor.php b/lib/Doctrine/ORM/Query/Exec/MultiTableDeleteExecutor.php index b14ddb53422..2f3d5acf5d6 100644 --- a/lib/Doctrine/ORM/Query/Exec/MultiTableDeleteExecutor.php +++ b/lib/Doctrine/ORM/Query/Exec/MultiTableDeleteExecutor.php @@ -23,6 +23,7 @@ use Doctrine\DBAL\Types\Type; use Doctrine\ORM\Query\AST; use Doctrine\ORM\Utility\PersisterHelper; +use Throwable; /** * Executes the SQL statements for bulk DQL DELETE statements on classes in @@ -81,7 +82,7 @@ public function __construct(AST\Node $AST, $sqlWalker) . ' SELECT t0.' . implode(', t0.', $idColumnNames); $rangeDecl = new AST\RangeVariableDeclaration($primaryClass->name, $primaryDqlAlias); - $fromClause = new AST\FromClause(array(new AST\IdentificationVariableDeclaration($rangeDecl, null, array()))); + $fromClause = new AST\FromClause([new AST\IdentificationVariableDeclaration($rangeDecl, null, [])]); $this->_insertSql .= $sqlWalker->walkFromClause($fromClause); // Append WHERE clause, if there is one. @@ -93,7 +94,7 @@ public function __construct(AST\Node $AST, $sqlWalker) $idSubselect = 'SELECT ' . $idColumnList . ' FROM ' . $tempTable; // 3. Create and store DELETE statements - $classNames = array_merge($primaryClass->parentClasses, array($primaryClass->name), $primaryClass->subClasses); + $classNames = array_merge($primaryClass->parentClasses, [$primaryClass->name], $primaryClass->subClasses); foreach (array_reverse($classNames) as $className) { $tableName = $quoteStrategy->getTableName($em->getClassMetadata($className), $platform); $this->_sqlStatements[] = 'DELETE FROM ' . $tableName @@ -101,12 +102,12 @@ public function __construct(AST\Node $AST, $sqlWalker) } // 4. Store DDL for temporary identifier table. - $columnDefinitions = array(); + $columnDefinitions = []; foreach ($idColumnNames as $idColumnName) { - $columnDefinitions[$idColumnName] = array( + $columnDefinitions[$idColumnName] = [ 'notnull' => true, 'type' => Type::getType(PersisterHelper::getTypeOfColumn($idColumnName, $rootClass, $em)), - ); + ]; } $this->_createTempTableSql = $platform->getCreateTemporaryTableSnippetSQL() . ' ' . $tempTable . ' (' . $platform->getColumnDeclarationListSQL($columnDefinitions) . ')'; @@ -129,7 +130,7 @@ public function execute(Connection $conn, array $params, array $types) foreach ($this->_sqlStatements as $sql) { $conn->executeUpdate($sql); } - } catch (\Exception $exception) { + } catch (Throwable $exception) { // FAILURE! Drop temporary table to avoid possible collisions $conn->executeUpdate($this->_dropTempTableSql); diff --git a/lib/Doctrine/ORM/Query/Exec/MultiTableUpdateExecutor.php b/lib/Doctrine/ORM/Query/Exec/MultiTableUpdateExecutor.php index 995f9cad12c..47db0342103 100644 --- a/lib/Doctrine/ORM/Query/Exec/MultiTableUpdateExecutor.php +++ b/lib/Doctrine/ORM/Query/Exec/MultiTableUpdateExecutor.php @@ -24,6 +24,7 @@ use Doctrine\ORM\Query\ParameterTypeInferer; use Doctrine\ORM\Query\AST; use Doctrine\ORM\Utility\PersisterHelper; +use Throwable; /** * Executes the SQL statements for bulk DQL UPDATE statements on classes in @@ -52,7 +53,7 @@ class MultiTableUpdateExecutor extends AbstractSqlExecutor /** * @var array */ - private $_sqlParameters = array(); + private $_sqlParameters = []; /** * @var int @@ -92,7 +93,7 @@ public function __construct(AST\Node $AST, $sqlWalker) . ' SELECT t0.' . implode(', t0.', $idColumnNames); $rangeDecl = new AST\RangeVariableDeclaration($primaryClass->name, $updateClause->aliasIdentificationVariable); - $fromClause = new AST\FromClause(array(new AST\IdentificationVariableDeclaration($rangeDecl, null, array()))); + $fromClause = new AST\FromClause([new AST\IdentificationVariableDeclaration($rangeDecl, null, [])]); $this->_insertSql .= $sqlWalker->walkFromClause($fromClause); @@ -100,7 +101,7 @@ public function __construct(AST\Node $AST, $sqlWalker) $idSubselect = 'SELECT ' . $idColumnList . ' FROM ' . $tempTable; // 3. Create and store UPDATE statements - $classNames = array_merge($primaryClass->parentClasses, array($primaryClass->name), $primaryClass->subClasses); + $classNames = array_merge($primaryClass->parentClasses, [$primaryClass->name], $primaryClass->subClasses); $i = -1; foreach (array_reverse($classNames) as $className) { @@ -143,13 +144,13 @@ public function __construct(AST\Node $AST, $sqlWalker) } // 4. Store DDL for temporary identifier table. - $columnDefinitions = array(); + $columnDefinitions = []; foreach ($idColumnNames as $idColumnName) { - $columnDefinitions[$idColumnName] = array( + $columnDefinitions[$idColumnName] = [ 'notnull' => true, 'type' => Type::getType(PersisterHelper::getTypeOfColumn($idColumnName, $rootClass, $em)), - ); + ]; } $this->_createTempTableSql = $platform->getCreateTemporaryTableSnippetSQL() . ' ' . $tempTable . ' (' @@ -176,19 +177,19 @@ public function execute(Connection $conn, array $params, array $types) // Execute UPDATE statements foreach ($this->_sqlStatements as $key => $statement) { - $paramValues = array(); - $paramTypes = array(); + $paramValues = []; + $paramTypes = []; if (isset($this->_sqlParameters[$key])) { foreach ($this->_sqlParameters[$key] as $parameterKey => $parameterName) { $paramValues[] = $params[$parameterKey]; - $paramTypes[] = isset($types[$parameterKey]) ? $types[$parameterKey] : ParameterTypeInferer::inferType($params[$parameterKey]); + $paramTypes[] = $types[$parameterKey] ?? ParameterTypeInferer::inferType($params[$parameterKey]); } } $conn->executeUpdate($statement, $paramValues, $paramTypes); } - } catch (\Exception $exception) { + } catch (Throwable $exception) { // FAILURE! Drop temporary table to avoid possible collisions $conn->executeUpdate($this->_dropTempTableSql); diff --git a/lib/Doctrine/ORM/Query/Expr.php b/lib/Doctrine/ORM/Query/Expr.php index 70f9ac9e271..25231822d11 100644 --- a/lib/Doctrine/ORM/Query/Expr.php +++ b/lib/Doctrine/ORM/Query/Expr.php @@ -41,10 +41,8 @@ class Expr * // (u.type = ?1) AND (u.role = ?2) * $expr->andX($expr->eq('u.type', ':1'), $expr->eq('u.role', ':2')); * - * @param \Doctrine\ORM\Query\Expr\Comparison | - * \Doctrine\ORM\Query\Expr\Func | - * \Doctrine\ORM\Query\Expr\Orx - * $x Optional clause. Defaults to null, but requires at least one defined when converting to string. + * @param Expr\Comparison|Expr\Func|Expr\Orx|string $x Optional clause. Defaults to null, but requires at least one + * defined when converting to string. * * @return Expr\Andx */ @@ -220,7 +218,7 @@ public function gte($x, $y) */ public function avg($x) { - return new Expr\Func('AVG', array($x)); + return new Expr\Func('AVG', [$x]); } /** @@ -232,7 +230,7 @@ public function avg($x) */ public function max($x) { - return new Expr\Func('MAX', array($x)); + return new Expr\Func('MAX', [$x]); } /** @@ -244,7 +242,7 @@ public function max($x) */ public function min($x) { - return new Expr\Func('MIN', array($x)); + return new Expr\Func('MIN', [$x]); } /** @@ -256,7 +254,7 @@ public function min($x) */ public function count($x) { - return new Expr\Func('COUNT', array($x)); + return new Expr\Func('COUNT', [$x]); } /** @@ -280,7 +278,7 @@ public function countDistinct($x) */ public function exists($subquery) { - return new Expr\Func('EXISTS', array($subquery)); + return new Expr\Func('EXISTS', [$subquery]); } /** @@ -292,7 +290,7 @@ public function exists($subquery) */ public function all($subquery) { - return new Expr\Func('ALL', array($subquery)); + return new Expr\Func('ALL', [$subquery]); } /** @@ -304,7 +302,7 @@ public function all($subquery) */ public function some($subquery) { - return new Expr\Func('SOME', array($subquery)); + return new Expr\Func('SOME', [$subquery]); } /** @@ -316,7 +314,7 @@ public function some($subquery) */ public function any($subquery) { - return new Expr\Func('ANY', array($subquery)); + return new Expr\Func('ANY', [$subquery]); } /** @@ -328,7 +326,7 @@ public function any($subquery) */ public function not($restriction) { - return new Expr\Func('NOT', array($restriction)); + return new Expr\Func('NOT', [$restriction]); } /** @@ -340,7 +338,7 @@ public function not($restriction) */ public function abs($x) { - return new Expr\Func('ABS', array($x)); + return new Expr\Func('ABS', [$x]); } /** @@ -429,7 +427,7 @@ public function quot($x, $y) */ public function sqrt($x) { - return new Expr\Func('SQRT', array($x)); + return new Expr\Func('SQRT', [$x]); } /** @@ -548,7 +546,7 @@ public function concat($x, $y) */ public function substring($x, $from, $len = null) { - $args = array($x, $from); + $args = [$x, $from]; if (null !== $len) { $args[] = $len; } @@ -565,7 +563,7 @@ public function substring($x, $from, $len = null) */ public function lower($x) { - return new Expr\Func('LOWER', array($x)); + return new Expr\Func('LOWER', [$x]); } /** @@ -577,7 +575,7 @@ public function lower($x) */ public function upper($x) { - return new Expr\Func('UPPER', array($x)); + return new Expr\Func('UPPER', [$x]); } /** @@ -589,7 +587,7 @@ public function upper($x) */ public function length($x) { - return new Expr\Func('LENGTH', array($x)); + return new Expr\Func('LENGTH', [$x]); } /** @@ -617,17 +615,17 @@ private function _quoteLiteral($literal) return (string) $literal; } else if (is_bool($literal)) { return $literal ? "true" : "false"; - } else { - return "'" . str_replace("'", "''", $literal) . "'"; } + + return "'" . str_replace("'", "''", $literal) . "'"; } /** * Creates an instance of BETWEEN() function, with the given argument. * - * @param mixed $val Valued to be inspected by range values. - * @param integer $x Starting range value to be used in BETWEEN() function. - * @param integer $y End point value to be used in BETWEEN() function. + * @param mixed $val Valued to be inspected by range values. + * @param integer|string $x Starting range value to be used in BETWEEN() function. + * @param integer|string $y End point value to be used in BETWEEN() function. * * @return Expr\Func A BETWEEN expression. */ diff --git a/lib/Doctrine/ORM/Query/Expr/Andx.php b/lib/Doctrine/ORM/Query/Expr/Andx.php index 432f714f6d9..dd91916a671 100644 --- a/lib/Doctrine/ORM/Query/Expr/Andx.php +++ b/lib/Doctrine/ORM/Query/Expr/Andx.php @@ -38,12 +38,12 @@ class Andx extends Composite /** * @var array */ - protected $allowedClasses = array( - 'Doctrine\ORM\Query\Expr\Comparison', - 'Doctrine\ORM\Query\Expr\Func', - 'Doctrine\ORM\Query\Expr\Orx', - 'Doctrine\ORM\Query\Expr\Andx', - ); + protected $allowedClasses = [ + Comparison::class, + Func::class, + Orx::class, + Andx::class, + ]; /** * @return array diff --git a/lib/Doctrine/ORM/Query/Expr/Base.php b/lib/Doctrine/ORM/Query/Expr/Base.php index 6eac70a27c6..d4b8d3871f1 100644 --- a/lib/Doctrine/ORM/Query/Expr/Base.php +++ b/lib/Doctrine/ORM/Query/Expr/Base.php @@ -48,17 +48,17 @@ abstract class Base /** * @var array */ - protected $allowedClasses = array(); + protected $allowedClasses = []; /** * @var array */ - protected $parts = array(); + protected $parts = []; /** - * @param array $args + * @param mixed $args */ - public function __construct($args = array()) + public function __construct($args = []) { $this->addMultiple($args); } @@ -68,7 +68,7 @@ public function __construct($args = array()) * * @return Base */ - public function addMultiple($args = array()) + public function addMultiple($args = []) { foreach ((array) $args as $arg) { $this->add($arg); diff --git a/lib/Doctrine/ORM/Query/Expr/Composite.php b/lib/Doctrine/ORM/Query/Expr/Composite.php index 4d9a251986c..6b8a04fa5cf 100644 --- a/lib/Doctrine/ORM/Query/Expr/Composite.php +++ b/lib/Doctrine/ORM/Query/Expr/Composite.php @@ -39,7 +39,7 @@ public function __toString() return (string) $this->parts[0]; } - $components = array(); + $components = []; foreach ($this->parts as $part) { $components[] = $this->processQueryPart($part); diff --git a/lib/Doctrine/ORM/Query/Expr/OrderBy.php b/lib/Doctrine/ORM/Query/Expr/OrderBy.php index 932548bd603..a5f8ef95765 100644 --- a/lib/Doctrine/ORM/Query/Expr/OrderBy.php +++ b/lib/Doctrine/ORM/Query/Expr/OrderBy.php @@ -48,12 +48,12 @@ class OrderBy /** * @var array */ - protected $allowedClasses = array(); + protected $allowedClasses = []; /** * @var array */ - protected $parts = array(); + protected $parts = []; /** * @param string|null $sort @@ -97,7 +97,7 @@ public function getParts() /** * @return string */ - public function __tostring() + public function __toString() { return $this->preSeparator . implode($this->separator, $this->parts) . $this->postSeparator; } diff --git a/lib/Doctrine/ORM/Query/Expr/Orx.php b/lib/Doctrine/ORM/Query/Expr/Orx.php index c4ff7ae30d0..d36abfa922c 100644 --- a/lib/Doctrine/ORM/Query/Expr/Orx.php +++ b/lib/Doctrine/ORM/Query/Expr/Orx.php @@ -38,12 +38,12 @@ class Orx extends Composite /** * @var array */ - protected $allowedClasses = array( - 'Doctrine\ORM\Query\Expr\Comparison', - 'Doctrine\ORM\Query\Expr\Func', - 'Doctrine\ORM\Query\Expr\Andx', - 'Doctrine\ORM\Query\Expr\Orx', - ); + protected $allowedClasses = [ + Comparison::class, + Func::class, + Andx::class, + Orx::class, + ]; /** * @return array diff --git a/lib/Doctrine/ORM/Query/Expr/Select.php b/lib/Doctrine/ORM/Query/Expr/Select.php index 21df6c735d4..8ab5153f1f6 100644 --- a/lib/Doctrine/ORM/Query/Expr/Select.php +++ b/lib/Doctrine/ORM/Query/Expr/Select.php @@ -43,9 +43,7 @@ class Select extends Base /** * @var array */ - protected $allowedClasses = array( - 'Doctrine\ORM\Query\Expr\Func' - ); + protected $allowedClasses = [Func::class]; /** * @return array diff --git a/lib/Doctrine/ORM/Query/Filter/SQLFilter.php b/lib/Doctrine/ORM/Query/Filter/SQLFilter.php index b0248fbac15..c48edd43faf 100644 --- a/lib/Doctrine/ORM/Query/Filter/SQLFilter.php +++ b/lib/Doctrine/ORM/Query/Filter/SQLFilter.php @@ -75,7 +75,7 @@ final public function setParameter($name, $value, $type = null) $type = ParameterTypeInferer::inferType($value); } - $this->parameters[$name] = array('value' => $value, 'type' => $type); + $this->parameters[$name] = ['value' => $value, 'type' => $type]; // Keep the parameters sorted for the hash ksort($this->parameters); @@ -122,7 +122,7 @@ final public function hasParameter($name) return true; } - + /** * Returns as string representation of the SQLFilter parameters (the state). * diff --git a/lib/Doctrine/ORM/Query/FilterCollection.php b/lib/Doctrine/ORM/Query/FilterCollection.php index ffbaeaf1293..ca7f1ac3289 100644 --- a/lib/Doctrine/ORM/Query/FilterCollection.php +++ b/lib/Doctrine/ORM/Query/FilterCollection.php @@ -59,7 +59,7 @@ class FilterCollection * * @var \Doctrine\ORM\Query\Filter\SQLFilter[] */ - private $enabledFilters = array(); + private $enabledFilters = []; /** * @var string The filter hash from the last time the query was parsed. @@ -176,16 +176,16 @@ public function has($name) /** * Checks if a filter is enabled. - * + * * @param string $name Name of the filter. - * + * * @return boolean True if the filter is enabled, false otherwise. */ public function isEnabled($name) { return isset($this->enabledFilters[$name]); } - + /** * @return boolean True, if the filter collection is clean. */ diff --git a/lib/Doctrine/ORM/Query/Lexer.php b/lib/Doctrine/ORM/Query/Lexer.php index b31b93b8716..573e433deab 100644 --- a/lib/Doctrine/ORM/Query/Lexer.php +++ b/lib/Doctrine/ORM/Query/Lexer.php @@ -19,6 +19,8 @@ namespace Doctrine\ORM\Query; +use Doctrine\Common\Lexer\AbstractLexer; + /** * Scans a DQL query for tokens. * @@ -27,7 +29,7 @@ * @author Roman Borschel * @since 2.0 */ -class Lexer extends \Doctrine\Common\Lexer +class Lexer extends AbstractLexer { // All tokens that are not valid identifiers must be < 100 const T_NONE = 1; @@ -129,13 +131,13 @@ public function __construct($input) */ protected function getCatchablePatterns() { - return array( + return [ '[a-z_][a-z0-9_]*\:[a-z_][a-z0-9_]*(?:\\\[a-z_][a-z0-9_]*)*', // aliased name '[a-z_\\\][a-z0-9_]*(?:\\\[a-z_][a-z0-9_]*)*', // identifier or qualified name '(?:[0-9]+(?:[\.][0-9]+)*)(?:e[+-]?[0-9]+)?', // numbers "'(?:[^']|'')*'", // quoted strings '\?[0-9]*|:[a-z_][a-z0-9_]*' // parameters - ); + ]; } /** @@ -143,7 +145,7 @@ protected function getCatchablePatterns() */ protected function getNonCatchablePatterns() { - return array('\s+', '(.)'); + return ['\s+', '(.)']; } /** diff --git a/lib/Doctrine/ORM/Query/Parameter.php b/lib/Doctrine/ORM/Query/Parameter.php index 39e2a7a4f21..6e968a1a9a7 100644 --- a/lib/Doctrine/ORM/Query/Parameter.php +++ b/lib/Doctrine/ORM/Query/Parameter.php @@ -19,6 +19,8 @@ namespace Doctrine\ORM\Query; +use function trim; + /** * Defines a Query Parameter. * @@ -49,6 +51,13 @@ class Parameter */ private $type; + /** + * Whether the parameter type was explicitly specified or not + * + * @var bool + */ + private $typeSpecified; + /** * Constructor. * @@ -58,7 +67,8 @@ class Parameter */ public function __construct($name, $value, $type = null) { - $this->name = trim($name, ':'); + $this->name = trim($name, ':'); + $this->typeSpecified = $type !== null; $this->setValue($value, $type); } @@ -104,4 +114,9 @@ public function setValue($value, $type = null) $this->value = $value; $this->type = $type ?: ParameterTypeInferer::inferType($value); } + + public function typeWasSpecified() : bool + { + return $this->typeSpecified; + } } diff --git a/lib/Doctrine/ORM/Query/ParameterTypeInferer.php b/lib/Doctrine/ORM/Query/ParameterTypeInferer.php index a12a559a730..07b78f008bd 100644 --- a/lib/Doctrine/ORM/Query/ParameterTypeInferer.php +++ b/lib/Doctrine/ORM/Query/ParameterTypeInferer.php @@ -45,7 +45,7 @@ class ParameterTypeInferer */ public static function inferType($value) { - if (is_integer($value)) { + if (is_int($value)) { return Type::INTEGER; } @@ -57,8 +57,12 @@ public static function inferType($value) return Type::DATETIME; } + if ($value instanceof \DateInterval) { + return Type::DATEINTERVAL; + } + if (is_array($value)) { - return is_integer(current($value)) + return is_int(current($value)) ? Connection::PARAM_INT_ARRAY : Connection::PARAM_STR_ARRAY; } diff --git a/lib/Doctrine/ORM/Query/Parser.php b/lib/Doctrine/ORM/Query/Parser.php index 6f8eda51469..7b3e8ff491a 100644 --- a/lib/Doctrine/ORM/Query/Parser.php +++ b/lib/Doctrine/ORM/Query/Parser.php @@ -19,8 +19,11 @@ namespace Doctrine\ORM\Query; -use Doctrine\ORM\Query; use Doctrine\ORM\Mapping\ClassMetadata; +use Doctrine\ORM\Query; +use Doctrine\ORM\Query\AST\Functions; +use function in_array; +use function strpos; /** * An LL(*) recursive-descent parser for the context-free grammar of the Doctrine Query Language. @@ -40,44 +43,51 @@ class Parser * * @var array */ - private static $_STRING_FUNCTIONS = array( - 'concat' => 'Doctrine\ORM\Query\AST\Functions\ConcatFunction', - 'substring' => 'Doctrine\ORM\Query\AST\Functions\SubstringFunction', - 'trim' => 'Doctrine\ORM\Query\AST\Functions\TrimFunction', - 'lower' => 'Doctrine\ORM\Query\AST\Functions\LowerFunction', - 'upper' => 'Doctrine\ORM\Query\AST\Functions\UpperFunction', - 'identity' => 'Doctrine\ORM\Query\AST\Functions\IdentityFunction', - ); + private static $_STRING_FUNCTIONS = [ + 'concat' => Functions\ConcatFunction::class, + 'substring' => Functions\SubstringFunction::class, + 'trim' => Functions\TrimFunction::class, + 'lower' => Functions\LowerFunction::class, + 'upper' => Functions\UpperFunction::class, + 'identity' => Functions\IdentityFunction::class, + ]; /** * READ-ONLY: Maps BUILT-IN numeric function names to AST class names. * * @var array */ - private static $_NUMERIC_FUNCTIONS = array( - 'length' => 'Doctrine\ORM\Query\AST\Functions\LengthFunction', - 'locate' => 'Doctrine\ORM\Query\AST\Functions\LocateFunction', - 'abs' => 'Doctrine\ORM\Query\AST\Functions\AbsFunction', - 'sqrt' => 'Doctrine\ORM\Query\AST\Functions\SqrtFunction', - 'mod' => 'Doctrine\ORM\Query\AST\Functions\ModFunction', - 'size' => 'Doctrine\ORM\Query\AST\Functions\SizeFunction', - 'date_diff' => 'Doctrine\ORM\Query\AST\Functions\DateDiffFunction', - 'bit_and' => 'Doctrine\ORM\Query\AST\Functions\BitAndFunction', - 'bit_or' => 'Doctrine\ORM\Query\AST\Functions\BitOrFunction', - ); + private static $_NUMERIC_FUNCTIONS = [ + 'length' => Functions\LengthFunction::class, + 'locate' => Functions\LocateFunction::class, + 'abs' => Functions\AbsFunction::class, + 'sqrt' => Functions\SqrtFunction::class, + 'mod' => Functions\ModFunction::class, + 'size' => Functions\SizeFunction::class, + 'date_diff' => Functions\DateDiffFunction::class, + 'bit_and' => Functions\BitAndFunction::class, + 'bit_or' => Functions\BitOrFunction::class, + + // Aggregate functions + 'min' => Functions\MinFunction::class, + 'max' => Functions\MaxFunction::class, + 'avg' => Functions\AvgFunction::class, + 'sum' => Functions\SumFunction::class, + 'count' => Functions\CountFunction::class, + ]; /** * READ-ONLY: Maps BUILT-IN datetime function names to AST class names. * * @var array */ - private static $_DATETIME_FUNCTIONS = array( - 'current_date' => 'Doctrine\ORM\Query\AST\Functions\CurrentDateFunction', - 'current_time' => 'Doctrine\ORM\Query\AST\Functions\CurrentTimeFunction', - 'current_timestamp' => 'Doctrine\ORM\Query\AST\Functions\CurrentTimestampFunction', - 'date_add' => 'Doctrine\ORM\Query\AST\Functions\DateAddFunction', - 'date_sub' => 'Doctrine\ORM\Query\AST\Functions\DateSubFunction', - ); + private static $_DATETIME_FUNCTIONS = [ + 'current_date' => Functions\CurrentDateFunction::class, + 'current_time' => Functions\CurrentTimeFunction::class, + 'current_timestamp' => Functions\CurrentTimestampFunction::class, + 'date_add' => Functions\DateAddFunction::class, + 'date_sub' => Functions\DateSubFunction::class, + ]; /* * Expressions that were encountered during parsing of identifiers and expressions @@ -87,27 +97,27 @@ class Parser /** * @var array */ - private $deferredIdentificationVariables = array(); + private $deferredIdentificationVariables = []; /** * @var array */ - private $deferredPartialObjectExpressions = array(); + private $deferredPartialObjectExpressions = []; /** * @var array */ - private $deferredPathExpressions = array(); + private $deferredPathExpressions = []; /** * @var array */ - private $deferredResultVariables = array(); + private $deferredResultVariables = []; /** * @var array */ - private $deferredNewObjectExpressions = array(); + private $deferredNewObjectExpressions = []; /** * The lexer. @@ -142,7 +152,7 @@ class Parser * * @var array */ - private $queryComponents = array(); + private $queryComponents = []; /** * Keeps the nesting level of defined ResultVariables. @@ -156,7 +166,7 @@ class Parser * * @var array */ - private $customTreeWalkers = array(); + private $customTreeWalkers = []; /** * The custom last tree walker, if any, that is responsible for producing the output. @@ -168,24 +178,7 @@ class Parser /** * @var array */ - private $identVariableExpressions = array(); - - /** - * Checks if a function is internally defined. Used to prevent overwriting - * of built-in functions through user-defined functions. - * - * @param string $functionName - * - * @return bool - */ - static public function isInternalFunction($functionName) - { - $functionName = strtolower($functionName); - - return isset(self::$_STRING_FUNCTIONS[$functionName]) - || isset(self::$_DATETIME_FUNCTIONS[$functionName]) - || isset(self::$_NUMERIC_FUNCTIONS[$functionName]); - } + private $identVariableExpressions = []; /** * Creates a new query parser object. @@ -196,7 +189,7 @@ public function __construct(Query $query) { $this->query = $query; $this->em = $query->getEntityManager(); - $this->lexer = new Lexer($query->getDql()); + $this->lexer = new Lexer($query->getDQL()); $this->parserResult = new ParserResult(); } @@ -276,7 +269,7 @@ public function getAST() } if ($this->deferredPathExpressions) { - $this->processDeferredPathExpressions($AST); + $this->processDeferredPathExpressions(); } if ($this->deferredResultVariables) { @@ -312,21 +305,24 @@ public function match($token) $lookaheadType = $this->lexer->lookahead['type']; // Short-circuit on first condition, usually types match - if ($lookaheadType !== $token) { - // If parameter is not identifier (1-99) must be exact match - if ($token < Lexer::T_IDENTIFIER) { - $this->syntaxError($this->lexer->getLiteral($token)); - } + if ($lookaheadType === $token) { + $this->lexer->moveNext(); + return; + } - // If parameter is keyword (200+) must be exact match - if ($token > Lexer::T_IDENTIFIER) { - $this->syntaxError($this->lexer->getLiteral($token)); - } + // If parameter is not identifier (1-99) must be exact match + if ($token < Lexer::T_IDENTIFIER) { + $this->syntaxError($this->lexer->getLiteral($token)); + } - // If parameter is T_IDENTIFIER, then matches T_IDENTIFIER (100) and keywords (200+) - if ($token === Lexer::T_IDENTIFIER && $lookaheadType < Lexer::T_IDENTIFIER) { - $this->syntaxError($this->lexer->getLiteral($token)); - } + // If parameter is keyword (200+) must be exact match + if ($token > Lexer::T_IDENTIFIER) { + $this->syntaxError($this->lexer->getLiteral($token)); + } + + // If parameter is T_IDENTIFIER, then matches T_IDENTIFIER (100) and keywords (200+) + if ($token === Lexer::T_IDENTIFIER && $lookaheadType < Lexer::T_IDENTIFIER) { + $this->syntaxError($this->lexer->getLiteral($token)); } $this->lexer->moveNext(); @@ -396,7 +392,7 @@ public function parse() $this->queryComponents = $treeWalkerChain->getQueryComponents(); } - $outputWalkerClass = $this->customOutputWalker ?: __NAMESPACE__ . '\SqlWalker'; + $outputWalkerClass = $this->customOutputWalker ?: SqlWalker::class; $outputWalker = new $outputWalkerClass($this->query, $this->parserResult, $this->queryComponents); // Assign an SQL executor to the parser result @@ -474,14 +470,14 @@ public function syntaxError($expected = '', $token = null) public function semanticalError($message = '', $token = null) { if ($token === null) { - $token = $this->lexer->lookahead; + $token = $this->lexer->lookahead ?? ['position' => null]; } // Minimum exposed chars ahead of token $distance = 12; // Find a position of a final word to display in error string - $dql = $this->query->getDql(); + $dql = $this->query->getDQL(); $length = strlen($dql); $pos = $token['position'] + $distance; $pos = strpos($dql, ' ', ($length > $pos) ? $pos : $length); @@ -541,7 +537,7 @@ private function peekBeyondClosingParenthesis($resetPeek = true) */ private function isMathOperator($token) { - return in_array($token['type'], array(Lexer::T_PLUS, Lexer::T_MINUS, Lexer::T_DIVIDE, Lexer::T_MULTIPLY)); + return $token !== null && in_array($token['type'], [Lexer::T_PLUS, Lexer::T_MINUS, Lexer::T_DIVIDE, Lexer::T_MULTIPLY]); } /** @@ -556,7 +552,7 @@ private function isFunction() $this->lexer->resetPeek(); - return ($lookaheadType >= Lexer::T_IDENTIFIER && $peek['type'] === Lexer::T_OPEN_PARENTHESIS); + return $lookaheadType >= Lexer::T_IDENTIFIER && $peek !== null && $peek['type'] === Lexer::T_OPEN_PARENTHESIS; } /** @@ -568,7 +564,7 @@ private function isFunction() */ private function isAggregateFunction($tokenType) { - return in_array($tokenType, array(Lexer::T_AVG, Lexer::T_MIN, Lexer::T_MAX, Lexer::T_SUM, Lexer::T_COUNT)); + return in_array($tokenType, [Lexer::T_AVG, Lexer::T_MIN, Lexer::T_MAX, Lexer::T_SUM, Lexer::T_COUNT]); } /** @@ -578,7 +574,7 @@ private function isAggregateFunction($tokenType) */ private function isNextAllAnySome() { - return in_array($this->lexer->lookahead['type'], array(Lexer::T_ALL, Lexer::T_ANY, Lexer::T_SOME)); + return in_array($this->lexer->lookahead['type'], [Lexer::T_ALL, Lexer::T_ANY, Lexer::T_SOME]); } /** @@ -748,11 +744,9 @@ private function processDeferredResultVariables() * SingleValuedAssociationPathExpression ::= IdentificationVariable "." SingleValuedAssociationField * CollectionValuedPathExpression ::= IdentificationVariable "." CollectionValuedAssociationField * - * @param mixed $AST - * * @return void */ - private function processDeferredPathExpressions($AST) + private function processDeferredPathExpressions() { foreach ($this->deferredPathExpressions as $deferredItem) { $pathExpression = $deferredItem['expression']; @@ -787,7 +781,7 @@ private function processDeferredPathExpressions($AST) if ( ! ($expectedType & $fieldType)) { // We need to recognize which was expected type(s) - $expectedStringTypes = array(); + $expectedStringTypes = []; // Validate state field type if ($expectedType & AST\PathExpression::TYPE_STATE_FIELD) { @@ -845,9 +839,11 @@ private function processRootEntityAliasSelected() */ public function QueryLanguage() { + $statement = null; + $this->lexer->moveNext(); - switch ($this->lexer->lookahead['type']) { + switch ($this->lexer->lookahead['type'] ?? null) { case Lexer::T_SELECT: $statement = $this->SelectStatement(); break; @@ -929,11 +925,11 @@ public function IdentificationVariable() $identVariable = $this->lexer->token['value']; - $this->deferredIdentificationVariables[] = array( + $this->deferredIdentificationVariables[] = [ 'expression' => $identVariable, 'nestingLevel' => $this->nestingLevel, 'token' => $this->lexer->token, - ); + ]; return $identVariable; } @@ -967,20 +963,20 @@ public function AbstractSchemaName() if ($this->lexer->isNextToken(Lexer::T_FULLY_QUALIFIED_NAME)) { $this->match(Lexer::T_FULLY_QUALIFIED_NAME); - $schemaName = $this->lexer->token['value']; - } else if ($this->lexer->isNextToken(Lexer::T_IDENTIFIER)) { + return $this->lexer->token['value']; + } + + if ($this->lexer->isNextToken(Lexer::T_IDENTIFIER)) { $this->match(Lexer::T_IDENTIFIER); - $schemaName = $this->lexer->token['value']; - } else { - $this->match(Lexer::T_ALIASED_NAME); + return $this->lexer->token['value']; + } - list($namespaceAlias, $simpleClassName) = explode(':', $this->lexer->token['value']); + $this->match(Lexer::T_ALIASED_NAME); - $schemaName = $this->em->getConfiguration()->getEntityNamespace($namespaceAlias) . '\\' . $simpleClassName; - } + [$namespaceAlias, $simpleClassName] = explode(':', $this->lexer->token['value']); - return $schemaName; + return $this->em->getConfiguration()->getEntityNamespace($namespaceAlias) . '\\' . $simpleClassName; } /** @@ -1028,11 +1024,11 @@ public function ResultVariable() $resultVariable = $this->lexer->token['value']; // Defer ResultVariable validation - $this->deferredResultVariables[] = array( + $this->deferredResultVariables[] = [ 'expression' => $resultVariable, 'nestingLevel' => $this->nestingLevel, 'token' => $this->lexer->token, - ); + ]; return $resultVariable; } @@ -1100,11 +1096,11 @@ public function PathExpression($expectedTypes) $pathExpr = new AST\PathExpression($expectedTypes, $identVariable, $field); // Defer PathExpression validation if requested to be deferred - $this->deferredPathExpressions[] = array( + $this->deferredPathExpressions[] = [ 'expression' => $pathExpr, 'nestingLevel' => $this->nestingLevel, 'token' => $this->lexer->token, - ); + ]; return $pathExpr; } @@ -1183,7 +1179,7 @@ public function SelectClause() } // Process SelectExpressions (1..N) - $selectExpressions = array(); + $selectExpressions = []; $selectExpressions[] = $this->SelectExpression(); while ($this->lexer->isNextToken(Lexer::T_COMMA)) { @@ -1237,20 +1233,20 @@ public function UpdateClause() $class = $this->em->getClassMetadata($abstractSchemaName); // Building queryComponent - $queryComponent = array( + $queryComponent = [ 'metadata' => $class, 'parent' => null, 'relation' => null, 'map' => null, 'nestingLevel' => $this->nestingLevel, 'token' => $token, - ); + ]; $this->queryComponents[$aliasIdentificationVariable] = $queryComponent; $this->match(Lexer::T_SET); - $updateItems = array(); + $updateItems = []; $updateItems[] = $this->UpdateItem(); while ($this->lexer->isNextToken(Lexer::T_COMMA)) { @@ -1289,20 +1285,22 @@ public function DeleteClause() $this->match(Lexer::T_AS); } - $aliasIdentificationVariable = $this->AliasIdentificationVariable(); + $aliasIdentificationVariable = $this->lexer->isNextToken(Lexer::T_IDENTIFIER) + ? $this->AliasIdentificationVariable() + : 'alias_should_have_been_set'; $deleteClause->aliasIdentificationVariable = $aliasIdentificationVariable; $class = $this->em->getClassMetadata($deleteClause->abstractSchemaName); // Building queryComponent - $queryComponent = array( + $queryComponent = [ 'metadata' => $class, 'parent' => null, 'relation' => null, 'map' => null, 'nestingLevel' => $this->nestingLevel, 'token' => $token, - ); + ]; $this->queryComponents[$aliasIdentificationVariable] = $queryComponent; @@ -1318,7 +1316,7 @@ public function FromClause() { $this->match(Lexer::T_FROM); - $identificationVariableDeclarations = array(); + $identificationVariableDeclarations = []; $identificationVariableDeclarations[] = $this->IdentificationVariableDeclaration(); while ($this->lexer->isNextToken(Lexer::T_COMMA)) { @@ -1339,7 +1337,7 @@ public function SubselectFromClause() { $this->match(Lexer::T_FROM); - $identificationVariables = array(); + $identificationVariables = []; $identificationVariables[] = $this->SubselectIdentificationVariableDeclaration(); while ($this->lexer->isNextToken(Lexer::T_COMMA)) { @@ -1385,7 +1383,7 @@ public function GroupByClause() $this->match(Lexer::T_GROUP); $this->match(Lexer::T_BY); - $groupByItems = array($this->GroupByItem()); + $groupByItems = [$this->GroupByItem()]; while ($this->lexer->isNextToken(Lexer::T_COMMA)) { $this->match(Lexer::T_COMMA); @@ -1406,7 +1404,7 @@ public function OrderByClause() $this->match(Lexer::T_ORDER); $this->match(Lexer::T_BY); - $orderByItems = array(); + $orderByItems = []; $orderByItems[] = $this->OrderByItem(); while ($this->lexer->isNextToken(Lexer::T_COMMA)) { @@ -1467,7 +1465,7 @@ public function GroupByItem() // We need to check if we are in a IdentificationVariable or SingleValuedPathExpression $glimpse = $this->lexer->glimpse(); - if ($glimpse['type'] === Lexer::T_DOT) { + if ($glimpse !== null && $glimpse['type'] === Lexer::T_DOT) { return $this->SingleValuedPathExpression(); } @@ -1503,7 +1501,7 @@ public function OrderByItem() $glimpse = $this->lexer->glimpse(); switch (true) { - case ($this->isFunction($peek)): + case ($this->isFunction()): $expr = $this->FunctionDeclaration(); break; @@ -1511,7 +1509,7 @@ public function OrderByItem() $expr = $this->SimpleArithmeticExpression(); break; - case ($glimpse['type'] === Lexer::T_DOT): + case $glimpse !== null && $glimpse['type'] === Lexer::T_DOT: $expr = $this->SingleValuedPathExpression(); break; @@ -1583,7 +1581,7 @@ public function NewValue() */ public function IdentificationVariableDeclaration() { - $joins = array(); + $joins = []; $rangeVariableDeclaration = $this->RangeVariableDeclaration(); $indexBy = $this->lexer->isNextToken(Lexer::T_INDEX) ? $this->IndexBy() @@ -1723,9 +1721,15 @@ public function Join() * RangeVariableDeclaration ::= AbstractSchemaName ["AS"] AliasIdentificationVariable * * @return \Doctrine\ORM\Query\AST\RangeVariableDeclaration + * + * @throws QueryException */ public function RangeVariableDeclaration() { + if ($this->lexer->isNextToken(Lexer::T_OPEN_PARENTHESIS) && $this->lexer->glimpse()['type'] === Lexer::T_SELECT) { + $this->semanticalError('Subquery is not supported here', $this->lexer->token); + } + $abstractSchemaName = $this->AbstractSchemaName(); $this->validateAbstractSchemaName($abstractSchemaName); @@ -1739,14 +1743,14 @@ public function RangeVariableDeclaration() $classMetadata = $this->em->getClassMetadata($abstractSchemaName); // Building queryComponent - $queryComponent = array( + $queryComponent = [ 'metadata' => $classMetadata, 'parent' => null, 'relation' => null, 'map' => null, 'nestingLevel' => $this->nestingLevel, 'token' => $token - ); + ]; $this->queryComponents[$aliasIdentificationVariable] = $queryComponent; @@ -1776,14 +1780,14 @@ public function JoinAssociationDeclaration() $targetClass = $this->em->getClassMetadata($class->associationMappings[$field]['targetEntity']); // Building queryComponent - $joinQueryComponent = array( + $joinQueryComponent = [ 'metadata' => $targetClass, 'parent' => $joinAssociationPathExpression->identificationVariable, 'relation' => $class->getAssociationMapping($field), 'map' => null, 'nestingLevel' => $this->nestingLevel, 'token' => $this->lexer->lookahead - ); + ]; $this->queryComponents[$aliasIdentificationVariable] = $joinQueryComponent; @@ -1794,13 +1798,13 @@ public function JoinAssociationDeclaration() * PartialObjectExpression ::= "PARTIAL" IdentificationVariable "." PartialFieldSet * PartialFieldSet ::= "{" SimpleStateField {"," SimpleStateField}* "}" * - * @return array + * @return \Doctrine\ORM\Query\AST\PartialObjectExpression */ public function PartialObjectExpression() { $this->match(Lexer::T_PARTIAL); - $partialFieldSet = array(); + $partialFieldSet = []; $identificationVariable = $this->IdentificationVariable(); @@ -1822,15 +1826,15 @@ public function PartialObjectExpression() while ($this->lexer->isNextToken(Lexer::T_COMMA)) { $this->match(Lexer::T_COMMA); $this->match(Lexer::T_IDENTIFIER); - + $field = $this->lexer->token['value']; - + while ($this->lexer->isNextToken(Lexer::T_DOT)) { $this->match(Lexer::T_DOT); $this->match(Lexer::T_IDENTIFIER); $field .= '.'.$this->lexer->token['value']; } - + $partialFieldSet[] = $field; } @@ -1839,11 +1843,11 @@ public function PartialObjectExpression() $partialObjectExpression = new AST\PartialObjectExpression($identificationVariable, $partialFieldSet); // Defer PartialObjectExpression validation - $this->deferredPartialObjectExpressions[] = array( + $this->deferredPartialObjectExpressions[] = [ 'expression' => $partialObjectExpression, 'nestingLevel' => $this->nestingLevel, 'token' => $this->lexer->token, - ); + ]; return $partialObjectExpression; } @@ -1875,11 +1879,11 @@ public function NewObjectExpression() $expression = new AST\NewObjectExpression($className, $args); // Defer NewObjectExpression validation - $this->deferredNewObjectExpressions[] = array( + $this->deferredNewObjectExpressions[] = [ 'token' => $token, 'expression' => $expression, 'nestingLevel' => $this->nestingLevel, - ); + ]; return $expression; } @@ -1979,9 +1983,6 @@ public function ScalarExpression() // SUM(u.id) + COUNT(u.id) return $this->SimpleArithmeticExpression(); - case ($this->isAggregateFunction($this->lexer->lookahead['type'])): - return $this->AggregateExpression(); - default: // IDENTITY(u) return $this->FunctionDeclaration(); @@ -2058,7 +2059,7 @@ public function CoalesceExpression() $this->match(Lexer::T_OPEN_PARENTHESIS); // Process ScalarExpressions (1..N) - $scalarExpressions = array(); + $scalarExpressions = []; $scalarExpressions[] = $this->ScalarExpression(); while ($this->lexer->isNextToken(Lexer::T_COMMA)) { @@ -2101,7 +2102,7 @@ public function GeneralCaseExpression() $this->match(Lexer::T_CASE); // Process WhenClause (1..N) - $whenClauses = array(); + $whenClauses = []; do { $whenClauses[] = $this->WhenClause(); @@ -2126,7 +2127,7 @@ public function SimpleCaseExpression() $caseOperand = $this->StateFieldPathExpression(); // Process SimpleWhenClause (1..N) - $simpleWhenClauses = array(); + $simpleWhenClauses = []; do { $simpleWhenClauses[] = $this->SimpleWhenClause(); @@ -2210,11 +2211,6 @@ public function SelectExpression() $expression = $this->ScalarExpression(); break; - case ($this->isAggregateFunction($lookaheadType)): - // COUNT(u.id) - $expression = $this->AggregateExpression(); - break; - default: // IDENTITY(u) $expression = $this->FunctionDeclaration(); @@ -2283,11 +2279,11 @@ public function SelectExpression() $aliasResultVariable = $this->AliasResultVariable(); // Include AliasResultVariable in query components. - $this->queryComponents[$aliasResultVariable] = array( + $this->queryComponents[$aliasResultVariable] = [ 'resultVariable' => $expression, 'nestingLevel' => $this->nestingLevel, 'token' => $token, - ); + ]; } // AST @@ -2377,11 +2373,11 @@ public function SimpleSelectExpression() $expr->fieldIdentificationVariable = $resultVariable; // Include AliasResultVariable in query components. - $this->queryComponents[$resultVariable] = array( + $this->queryComponents[$resultVariable] = [ 'resultvariable' => $expr, 'nestingLevel' => $this->nestingLevel, 'token' => $token, - ); + ]; } return $expr; @@ -2394,7 +2390,7 @@ public function SimpleSelectExpression() */ public function ConditionalExpression() { - $conditionalTerms = array(); + $conditionalTerms = []; $conditionalTerms[] = $this->ConditionalTerm(); while ($this->lexer->isNextToken(Lexer::T_OR)) { @@ -2419,7 +2415,7 @@ public function ConditionalExpression() */ public function ConditionalTerm() { - $conditionalFactors = array(); + $conditionalFactors = []; $conditionalFactors[] = $this->ConditionalFactor(); while ($this->lexer->isNextToken(Lexer::T_AND)) { @@ -2484,9 +2480,11 @@ public function ConditionalPrimary() // Peek beyond the matching closing parenthesis ')' $peek = $this->peekBeyondClosingParenthesis(); - if (in_array($peek['value'], array("=", "<", "<=", "<>", ">", ">=", "!=")) || - in_array($peek['type'], array(Lexer::T_NOT, Lexer::T_BETWEEN, Lexer::T_LIKE, Lexer::T_IN, Lexer::T_IS, Lexer::T_EXISTS)) || - $this->isMathOperator($peek)) { + if ($peek !== null && ( + in_array($peek['value'], ['=', '<', '<=', '<>', '>', '>=', '!=']) || + in_array($peek['type'], [Lexer::T_NOT, Lexer::T_BETWEEN, Lexer::T_LIKE, Lexer::T_IN, Lexer::T_IS, Lexer::T_EXISTS]) || + $this->isMathOperator($peek) + )) { $condPrimary->simpleConditionalExpression = $this->SimpleConditionalExpression(); return $condPrimary; @@ -2741,7 +2739,7 @@ public function ArithmeticExpression() */ public function SimpleArithmeticExpression() { - $terms = array(); + $terms = []; $terms[] = $this->ArithmeticTerm(); while (($isPlus = $this->lexer->isNextToken(Lexer::T_PLUS)) || $this->lexer->isNextToken(Lexer::T_MINUS)) { @@ -2767,7 +2765,7 @@ public function SimpleArithmeticExpression() */ public function ArithmeticTerm() { - $factors = array(); + $factors = []; $factors[] = $this->ArithmeticFactor(); while (($isMult = $this->lexer->isNextToken(Lexer::T_MULTIPLY)) || $this->lexer->isNextToken(Lexer::T_DIVIDE)) { @@ -2838,11 +2836,11 @@ public function ArithmeticPrimary() case Lexer::T_IDENTIFIER: $peek = $this->lexer->glimpse(); - if ($peek['value'] == '(') { + if ($peek !== null && $peek['value'] === '(') { return $this->FunctionDeclaration(); } - if ($peek['value'] == '.') { + if ($peek !== null && $peek['value'] === '.') { return $this->SingleValuedPathExpression(); } @@ -2858,11 +2856,7 @@ public function ArithmeticPrimary() default: $peek = $this->lexer->glimpse(); - if ($peek['value'] == '(') { - if ($this->isAggregateFunction($this->lexer->lookahead['type'])) { - return $this->AggregateExpression(); - } - + if ($peek !== null && $peek['value'] === '(') { return $this->FunctionDeclaration(); } @@ -2873,8 +2867,7 @@ public function ArithmeticPrimary() /** * StringExpression ::= StringPrimary | ResultVariable | "(" Subselect ")" * - * @return \Doctrine\ORM\Query\AST\StringPrimary | - * \Doctrine\ORM\Query\AST\Subselect | + * @return \Doctrine\ORM\Query\AST\Subselect | * string */ public function StringExpression() @@ -2934,7 +2927,6 @@ public function StringPrimary() case Lexer::T_COALESCE: case Lexer::T_NULLIF: return $this->CaseExpression(); - default: if ($this->isAggregateFunction($lookaheadType)) { return $this->AggregateExpression(); @@ -2988,7 +2980,7 @@ public function AggregateExpression() $lookaheadType = $this->lexer->lookahead['type']; $isDistinct = false; - if ( ! in_array($lookaheadType, array(Lexer::T_COUNT, Lexer::T_AVG, Lexer::T_MAX, Lexer::T_MIN, Lexer::T_SUM))) { + if ( ! in_array($lookaheadType, [Lexer::T_COUNT, Lexer::T_AVG, Lexer::T_MAX, Lexer::T_MIN, Lexer::T_SUM])) { $this->syntaxError('One of: MAX, MIN, AVG, SUM, COUNT'); } @@ -3018,7 +3010,7 @@ public function QuantifiedExpression() $lookaheadType = $this->lexer->lookahead['type']; $value = $this->lexer->lookahead['value']; - if ( ! in_array($lookaheadType, array(Lexer::T_ALL, Lexer::T_ANY, Lexer::T_SOME))) { + if ( ! in_array($lookaheadType, [Lexer::T_ALL, Lexer::T_ANY, Lexer::T_SOME])) { $this->syntaxError('ALL, ANY or SOME'); } @@ -3097,7 +3089,7 @@ public function InExpression() if ($this->lexer->isNextToken(Lexer::T_SELECT)) { $inExpression->subselect = $this->Subselect(); } else { - $literals = array(); + $literals = []; $literals[] = $this->InParameter(); while ($this->lexer->isNextToken(Lexer::T_COMMA)) { @@ -3130,7 +3122,7 @@ public function InstanceOfExpression() $this->match(Lexer::T_INSTANCE); $this->match(Lexer::T_OF); - $exprValues = array(); + $exprValues = []; if ($this->lexer->isNextToken(Lexer::T_OPEN_PARENTHESIS)) { $this->match(Lexer::T_OPEN_PARENTHESIS); @@ -3203,7 +3195,7 @@ public function LikeExpression() $escapeChar = null; - if ($this->lexer->lookahead['type'] === Lexer::T_ESCAPE) { + if ($this->lexer->lookahead !== null && $this->lexer->lookahead['type'] === Lexer::T_ESCAPE) { $this->match(Lexer::T_ESCAPE); $this->match(Lexer::T_STRING); @@ -3238,10 +3230,6 @@ public function NullComparisonExpression() $expr = $this->CoalesceExpression(); break; - case $this->isAggregateFunction($this->lexer->lookahead['type']): - $expr = $this->AggregateExpression(); - break; - case $this->isFunction(): $expr = $this->FunctionDeclaration(); break; @@ -3264,6 +3252,12 @@ public function NullComparisonExpression() $this->semanticalError('Cannot add having condition on undefined result variable.'); } + // Validate SingleValuedPathExpression (ie.: "product") + if (isset($this->queryComponents[$lookaheadValue]['metadata'])) { + $expr = $this->SingleValuedPathExpression(); + break; + } + // Validating ResultVariable if ( ! isset($this->queryComponents[$lookaheadValue]['resultVariable'])) { $this->semanticalError('Cannot add having condition on a non result variable.'); @@ -3372,8 +3366,13 @@ public function FunctionDeclaration() $token = $this->lexer->lookahead; $funcName = strtolower($token['value']); - // Check for built-in functions first! + $customFunctionDeclaration = $this->CustomFunctionDeclaration(); + + // Check for custom functions functions first! switch (true) { + case $customFunctionDeclaration !== null: + return $customFunctionDeclaration; + case (isset(self::$_STRING_FUNCTIONS[$funcName])): return $this->FunctionsReturningStrings(); @@ -3384,7 +3383,7 @@ public function FunctionDeclaration() return $this->FunctionsReturningDatetime(); default: - return $this->CustomFunctionDeclaration(); + $this->syntaxError('known function', $token); } } @@ -3412,7 +3411,7 @@ private function CustomFunctionDeclaration() return $this->CustomFunctionsReturningDatetime(); default: - $this->syntaxError('known function', $token); + return null; } } diff --git a/lib/Doctrine/ORM/Query/ParserResult.php b/lib/Doctrine/ORM/Query/ParserResult.php index dfc7361f8ba..84ad17822bc 100644 --- a/lib/Doctrine/ORM/Query/ParserResult.php +++ b/lib/Doctrine/ORM/Query/ParserResult.php @@ -51,7 +51,7 @@ class ParserResult * * @var array */ - private $_parameterMappings = array(); + private $_parameterMappings = []; /** * Initializes a new instance of the ParserResult class. diff --git a/lib/Doctrine/ORM/Query/QueryException.php b/lib/Doctrine/ORM/Query/QueryException.php index 8245722a91b..b78e27bcfee 100644 --- a/lib/Doctrine/ORM/Query/QueryException.php +++ b/lib/Doctrine/ORM/Query/QueryException.php @@ -19,6 +19,8 @@ namespace Doctrine\ORM\Query; +use Doctrine\ORM\Query\AST\PathExpression; + /** * Description of QueryException. * @@ -204,13 +206,15 @@ public static function overwritingJoinConditionsNotYetSupported($assoc) } /** + * @param PathExpression $pathExpr + * * @return QueryException */ - public static function associationPathInverseSideNotSupported() + public static function associationPathInverseSideNotSupported(PathExpression $pathExpr) { return new self( - "A single-valued association path expression to an inverse side is not supported". - " in DQL queries. Use an explicit join instead." + 'A single-valued association path expression to an inverse side is not supported in DQL queries. ' . + 'Instead of "' . $pathExpr->identificationVariable . '.' . $pathExpr->field . '" use an explicit join.' ); } diff --git a/lib/Doctrine/ORM/Query/QueryExpressionVisitor.php b/lib/Doctrine/ORM/Query/QueryExpressionVisitor.php index 73a1b4dd140..0381ac037d4 100644 --- a/lib/Doctrine/ORM/Query/QueryExpressionVisitor.php +++ b/lib/Doctrine/ORM/Query/QueryExpressionVisitor.php @@ -37,12 +37,12 @@ class QueryExpressionVisitor extends ExpressionVisitor /** * @var array */ - private static $operatorMap = array( + private static $operatorMap = [ Comparison::GT => Expr\Comparison::GT, Comparison::GTE => Expr\Comparison::GTE, Comparison::LT => Expr\Comparison::LT, Comparison::LTE => Expr\Comparison::LTE - ); + ]; /** * @var array @@ -57,7 +57,7 @@ class QueryExpressionVisitor extends ExpressionVisitor /** * @var array */ - private $parameters = array(); + private $parameters = []; /** * Constructor @@ -88,7 +88,7 @@ public function getParameters() */ public function clearParameters() { - $this->parameters = array(); + $this->parameters = []; } /** @@ -108,7 +108,7 @@ private static function convertComparisonOperator($criteriaOperator) */ public function walkCompositeExpression(CompositeExpression $expr) { - $expressionList = array(); + $expressionList = []; foreach ($expr->getExpressionList() as $child) { $expressionList[] = $this->dispatch($child); @@ -160,11 +160,11 @@ public function walkComparison(Comparison $comparison) switch ($comparison->getOperator()) { case Comparison::IN: $this->parameters[] = $parameter; - + return $this->expr->in($field, $placeholder); case Comparison::NIN: $this->parameters[] = $parameter; - + return $this->expr->notIn($field, $placeholder); case Comparison::EQ: case Comparison::IS: @@ -172,19 +172,31 @@ public function walkComparison(Comparison $comparison) return $this->expr->isNull($field); } $this->parameters[] = $parameter; - + return $this->expr->eq($field, $placeholder); case Comparison::NEQ: if ($this->walkValue($comparison->getValue()) === null) { return $this->expr->isNotNull($field); } $this->parameters[] = $parameter; - + return $this->expr->neq($field, $placeholder); case Comparison::CONTAINS: $parameter->setValue('%' . $parameter->getValue() . '%', $parameter->getType()); $this->parameters[] = $parameter; - + + return $this->expr->like($field, $placeholder); + case Comparison::MEMBER_OF: + return $this->expr->isMemberOf($comparison->getField(), $comparison->getValue()->getValue()); + case Comparison::STARTS_WITH: + $parameter->setValue($parameter->getValue() . '%', $parameter->getType()); + $this->parameters[] = $parameter; + + return $this->expr->like($field, $placeholder); + case Comparison::ENDS_WITH: + $parameter->setValue('%' . $parameter->getValue(), $parameter->getType()); + $this->parameters[] = $parameter; + return $this->expr->like($field, $placeholder); default: $operator = self::convertComparisonOperator($comparison->getOperator()); diff --git a/lib/Doctrine/ORM/Query/ResultSetMapping.php b/lib/Doctrine/ORM/Query/ResultSetMapping.php index b80acf0cc42..640b8e65caf 100644 --- a/lib/Doctrine/ORM/Query/ResultSetMapping.php +++ b/lib/Doctrine/ORM/Query/ResultSetMapping.php @@ -57,7 +57,7 @@ class ResultSetMapping * @ignore * @var array */ - public $aliasMap = array(); + public $aliasMap = []; /** * Maps alias names to related association field names. @@ -65,7 +65,7 @@ class ResultSetMapping * @ignore * @var array */ - public $relationMap = array(); + public $relationMap = []; /** * Maps alias names to parent alias names. @@ -73,7 +73,7 @@ class ResultSetMapping * @ignore * @var array */ - public $parentAliasMap = array(); + public $parentAliasMap = []; /** * Maps column names in the result set to field names for each class. @@ -81,7 +81,7 @@ class ResultSetMapping * @ignore * @var array */ - public $fieldMappings = array(); + public $fieldMappings = []; /** * Maps column names in the result set to the alias/field name to use in the mapped result. @@ -89,7 +89,7 @@ class ResultSetMapping * @ignore * @var array */ - public $scalarMappings = array(); + public $scalarMappings = []; /** * Maps column names in the result set to the alias/field type to use in the mapped result. @@ -97,7 +97,7 @@ class ResultSetMapping * @ignore * @var array */ - public $typeMappings = array(); + public $typeMappings = []; /** * Maps entities in the result set to the alias name to use in the mapped result. @@ -105,7 +105,7 @@ class ResultSetMapping * @ignore * @var array */ - public $entityMappings = array(); + public $entityMappings = []; /** * Maps column names of meta columns (foreign keys, discriminator columns, ...) to field names. @@ -113,7 +113,7 @@ class ResultSetMapping * @ignore * @var array */ - public $metaMappings = array(); + public $metaMappings = []; /** * Maps column names in the result set to the alias they belong to. @@ -121,7 +121,7 @@ class ResultSetMapping * @ignore * @var array */ - public $columnOwnerMap = array(); + public $columnOwnerMap = []; /** * List of columns in the result set that are used as discriminator columns. @@ -129,7 +129,7 @@ class ResultSetMapping * @ignore * @var array */ - public $discriminatorColumns = array(); + public $discriminatorColumns = []; /** * Maps alias names to field names that should be used for indexing. @@ -137,7 +137,7 @@ class ResultSetMapping * @ignore * @var array */ - public $indexByMap = array(); + public $indexByMap = []; /** * Map from column names to class names that declare the field the column is mapped to. @@ -145,28 +145,35 @@ class ResultSetMapping * @ignore * @var array */ - public $declaringClasses = array(); + public $declaringClasses = []; /** * This is necessary to hydrate derivate foreign keys correctly. * * @var array */ - public $isIdentifierColumn = array(); + public $isIdentifierColumn = []; /** * Maps column names in the result set to field names for each new object expression. * * @var array */ - public $newObjectMappings = array(); + public $newObjectMappings = []; /** * Maps metadata parameter names to the metadata attribute. * * @var array */ - public $metadataParameterMapping = array(); + public $metadataParameterMapping = []; + + /** + * Contains query parameter names to be resolved as discriminator values + * + * @var array + */ + public $discriminatorParameters = []; /** * Adds an entity result to this ResultSetMapping. @@ -451,7 +458,7 @@ public function getDeclaringClass($columnName) /** * @param string $alias * - * @return AssociationMapping + * @return string */ public function getRelation($alias) { @@ -577,4 +584,3 @@ public function addMetaResult($alias, $columnName, $fieldName, $isIdentifierColu return $this; } } - diff --git a/lib/Doctrine/ORM/Query/ResultSetMappingBuilder.php b/lib/Doctrine/ORM/Query/ResultSetMappingBuilder.php index 73eb5ae5aa6..0bf11814b97 100644 --- a/lib/Doctrine/ORM/Query/ResultSetMappingBuilder.php +++ b/lib/Doctrine/ORM/Query/ResultSetMappingBuilder.php @@ -97,7 +97,7 @@ public function __construct(EntityManagerInterface $em, $defaultRenameMode = sel * * @return void */ - public function addRootEntityFromClassMetadata($class, $alias, $renamedColumns = array(), $renameMode = null) + public function addRootEntityFromClassMetadata($class, $alias, $renamedColumns = [], $renameMode = null) { $renameMode = $renameMode ?: $this->defaultRenameMode; $columnAliasMap = $this->getColumnAliasMap($class, $renameMode, $renamedColumns); @@ -119,7 +119,7 @@ public function addRootEntityFromClassMetadata($class, $alias, $renamedColumns = * * @return void */ - public function addJoinedEntityFromClassMetadata($class, $alias, $parentAlias, $relation, $renamedColumns = array(), $renameMode = null) + public function addJoinedEntityFromClassMetadata($class, $alias, $parentAlias, $relation, $renamedColumns = [], $renameMode = null) { $renameMode = $renameMode ?: $this->defaultRenameMode; $columnAliasMap = $this->getColumnAliasMap($class, $renameMode, $renamedColumns); @@ -139,7 +139,7 @@ public function addJoinedEntityFromClassMetadata($class, $alias, $parentAlias, $ * * @throws \InvalidArgumentException */ - protected function addAllClassFields($class, $alias, $columnAliasMap = array()) + protected function addAllClassFields($class, $alias, $columnAliasMap = []) { $classMetadata = $this->em->getClassMetadata($class); $platform = $this->em->getConnection()->getDatabasePlatform(); @@ -206,8 +206,7 @@ private function getColumnAlias($columnName, $mode, array $customRenameColumns) return $columnName . $this->sqlCounter++; case self::COLUMN_RENAMING_CUSTOM: - return isset($customRenameColumns[$columnName]) - ? $customRenameColumns[$columnName] : $columnName; + return $customRenameColumns[$columnName] ?? $columnName; case self::COLUMN_RENAMING_NONE: return $columnName; @@ -232,7 +231,7 @@ private function getColumnAliasMap($className, $mode, array $customRenameColumns $mode = self::COLUMN_RENAMING_CUSTOM; } - $columnAlias = array(); + $columnAlias = []; $class = $this->em->getClassMetadata($className); foreach ($class->getColumnNames() as $columnName) { @@ -436,13 +435,12 @@ public function addNamedNativeQueryEntityResultMapping(ClassMetadataInfo $classM * * @return string */ - public function generateSelectClause($tableAliases = array()) + public function generateSelectClause($tableAliases = []) { $sql = ""; foreach ($this->columnOwnerMap as $columnName => $dqlAlias) { - $tableAlias = isset($tableAliases[$dqlAlias]) - ? $tableAliases[$dqlAlias] : $dqlAlias; + $tableAlias = $tableAliases[$dqlAlias] ?? $dqlAlias; if ($sql) { $sql .= ", "; @@ -470,6 +468,6 @@ public function generateSelectClause($tableAliases = array()) */ public function __toString() { - return $this->generateSelectClause(array()); + return $this->generateSelectClause([]); } } diff --git a/lib/Doctrine/ORM/Query/SqlWalker.php b/lib/Doctrine/ORM/Query/SqlWalker.php index 0fb389de046..d06d070610f 100644 --- a/lib/Doctrine/ORM/Query/SqlWalker.php +++ b/lib/Doctrine/ORM/Query/SqlWalker.php @@ -25,6 +25,7 @@ use Doctrine\ORM\Mapping\ClassMetadataInfo; use Doctrine\ORM\OptimisticLockException; use Doctrine\ORM\Query; +use Doctrine\ORM\Utility\HierarchyDiscriminatorResolver; use Doctrine\ORM\Utility\PersisterHelper; /** @@ -37,7 +38,6 @@ * @author Alexander * @author Fabio B. Silva * @since 2.0 - * @todo Rename: SQLWalker */ class SqlWalker implements TreeWalker { @@ -109,28 +109,28 @@ class SqlWalker implements TreeWalker /** * @var array */ - private $tableAliasMap = array(); + private $tableAliasMap = []; /** * Map from result variable names to their SQL column alias names. * * @var array */ - private $scalarResultAliasMap = array(); + private $scalarResultAliasMap = []; /** * Map from Table-Alias + Column-Name to OrderBy-Direction. * * @var array */ - private $orderedColumnsMap = array(); + private $orderedColumnsMap = []; /** * Map from DQL-Alias + Field-Name to SQL Column Alias. * * @var array */ - private $scalarFields = array(); + private $scalarFields = []; /** * Map of all components/classes that appear in the DQL query. @@ -144,14 +144,14 @@ class SqlWalker implements TreeWalker * * @var array */ - private $selectedClasses = array(); + private $selectedClasses = []; /** * The DQL alias of the root class of the currently traversed query. * * @var array */ - private $rootAliases = array(); + private $rootAliases = []; /** * Flag that indicates whether to generate SQL table aliases in the SQL. @@ -245,7 +245,7 @@ public function getQueryComponents() */ public function setQueryComponent($dqlAlias, array $queryComponent) { - $requiredKeys = array('metadata', 'parent', 'relation', 'map', 'nestingLevel', 'token'); + $requiredKeys = ['metadata', 'parent', 'relation', 'map', 'nestingLevel', 'token']; if (array_diff($requiredKeys, array_keys($queryComponent))) { throw QueryException::invalidQueryComponent($dqlAlias); @@ -354,7 +354,7 @@ private function _generateClassTableInheritanceJoins($class, $dqlAlias) $sql .= isset($this->queryComponents[$dqlAlias]['relation']) ? ' LEFT ' : ' INNER '; $sql .= 'JOIN ' . $this->quoteStrategy->getTableName($parentClass, $this->platform) . ' ' . $tableAlias . ' ON '; - $sqlParts = array(); + $sqlParts = []; foreach ($this->quoteStrategy->getIdentifierColumnNames($class, $this->platform) as $columnName) { $sqlParts[] = $baseTableAlias . '.' . $columnName . ' = ' . $tableAlias . '.' . $columnName; @@ -380,7 +380,7 @@ private function _generateClassTableInheritanceJoins($class, $dqlAlias) $sql .= ' LEFT JOIN ' . $this->quoteStrategy->getTableName($subClass, $this->platform) . ' ' . $tableAlias . ' ON '; - $sqlParts = array(); + $sqlParts = []; foreach ($this->quoteStrategy->getIdentifierColumnNames($subClass, $this->platform) as $columnName) { $sqlParts[] = $baseTableAlias . '.' . $columnName . ' = ' . $tableAlias . '.' . $columnName; @@ -397,7 +397,7 @@ private function _generateClassTableInheritanceJoins($class, $dqlAlias) */ private function _generateOrderedCollectionOrderByItems() { - $orderedColumns = array(); + $orderedColumns = []; foreach ($this->selectedClasses as $selectedClass) { $dqlAlias = $selectedClass['dqlAlias']; @@ -439,7 +439,7 @@ private function _generateOrderedCollectionOrderByItems() */ private function _generateDiscriminatorColumnConditionSQL(array $dqlAliases) { - $sqlParts = array(); + $sqlParts = []; foreach ($dqlAliases as $dqlAlias) { $class = $this->queryComponents[$dqlAlias]['metadata']; @@ -447,7 +447,7 @@ private function _generateDiscriminatorColumnConditionSQL(array $dqlAliases) if ( ! $class->isInheritanceTypeSingleTable()) continue; $conn = $this->em->getConnection(); - $values = array(); + $values = []; if ($class->discriminatorValue !== null) { // discriminators can be 0 $values[] = $conn->quote($class->discriminatorValue); @@ -501,10 +501,9 @@ private function generateFilterConditionSQL(ClassMetadata $targetEntity, $target default: //@todo: throw exception? return ''; - break; } - $filterClauses = array(); + $filterClauses = []; foreach ($this->em->getFilters()->getEnabledFilters() as $filter) { if ('' !== $filterExpr = $filter->addFilterConstraint($targetEntity, $targetTableAlias)) { $filterClauses[] = '(' . $filterExpr . ')'; @@ -607,7 +606,7 @@ public function walkEntityIdentificationVariable($identVariable) { $class = $this->queryComponents[$identVariable]['metadata']; $tableAlias = $this->getSQLTableAlias($class->getTableName(), $identVariable); - $sqlParts = array(); + $sqlParts = []; foreach ($this->quoteStrategy->getIdentifierColumnNames($class, $this->platform) as $columnName) { $sqlParts[] = $tableAlias . '.' . $columnName; @@ -645,6 +644,7 @@ public function walkPathExpression($pathExpr) { $sql = ''; + /* @var $pathExpr Query\AST\PathExpression */ switch ($pathExpr->type) { case AST\PathExpression::TYPE_STATE_FIELD: $fieldName = $pathExpr->field; @@ -672,7 +672,7 @@ public function walkPathExpression($pathExpr) $assoc = $class->associationMappings[$fieldName]; if ( ! $assoc['isOwningSide']) { - throw QueryException::associationPathInverseSideNotSupported(); + throw QueryException::associationPathInverseSideNotSupported($pathExpr); } // COMPOSITE KEYS NOT (YET?) SUPPORTED @@ -700,7 +700,7 @@ public function walkPathExpression($pathExpr) public function walkSelectClause($selectClause) { $sql = 'SELECT ' . (($selectClause->isDistinct) ? 'DISTINCT ' : ''); - $sqlSelectExpressions = array_filter(array_map(array($this, 'walkSelectExpression'), $selectClause->selectExpressions)); + $sqlSelectExpressions = array_filter(array_map([$this, 'walkSelectExpression'], $selectClause->selectExpressions)); if ($this->query->getHint(Query::HINT_INTERNAL_ITERATION) == true && $selectClause->isDistinct) { $this->query->setHint(self::HINT_DISTINCT, true); @@ -749,9 +749,8 @@ public function walkSelectClause($selectClause) // Add foreign key columns of class and also parent classes foreach ($class->associationMappings as $assoc) { - if ( ! ($assoc['isOwningSide'] && $assoc['type'] & ClassMetadata::TO_ONE)) { - continue; - } else if ( !$addMetaColumns && !isset($assoc['id'])) { + if ( ! ($assoc['isOwningSide'] && $assoc['type'] & ClassMetadata::TO_ONE) + || ( ! $addMetaColumns && !isset($assoc['id']))) { continue; } @@ -765,7 +764,8 @@ public function walkSelectClause($selectClause) $columnAlias = $this->getSQLColumnAlias($columnName); $columnType = PersisterHelper::getTypeOfColumn($joinColumn['referencedColumnName'], $targetClass, $this->em); - $sqlSelectExpressions[] = $sqlTableAlias . '.' . $columnName . ' AS ' . $columnAlias; + $quotedColumnName = $this->quoteStrategy->getJoinColumnName($joinColumn, $class, $this->platform); + $sqlSelectExpressions[] = $sqlTableAlias . '.' . $quotedColumnName . ' AS ' . $columnAlias; $this->rsm->addMetaResult($dqlAlias, $columnAlias, $columnName, $isIdentifier, $columnType); } @@ -793,7 +793,8 @@ public function walkSelectClause($selectClause) $columnAlias = $this->getSQLColumnAlias($columnName); $columnType = PersisterHelper::getTypeOfColumn($joinColumn['referencedColumnName'], $targetClass, $this->em); - $sqlSelectExpressions[] = $sqlTableAlias . '.' . $columnName . ' AS ' . $columnAlias; + $quotedColumnName = $this->quoteStrategy->getJoinColumnName($joinColumn, $subClass, $this->platform); + $sqlSelectExpressions[] = $sqlTableAlias . '.' . $quotedColumnName . ' AS ' . $columnAlias; $this->rsm->addMetaResult($dqlAlias, $columnAlias, $columnName, $subClass->isIdentifier($columnName), $columnType); } @@ -813,7 +814,7 @@ public function walkSelectClause($selectClause) public function walkFromClause($fromClause) { $identificationVarDecls = $fromClause->identificationVariableDeclarations; - $sqlParts = array(); + $sqlParts = []; foreach ($identificationVarDecls as $identificationVariableDecl) { $sqlParts[] = $this->walkIdentificationVariableDeclaration($identificationVariableDecl); @@ -874,6 +875,19 @@ public function walkIndexBy($indexBy) * @return string */ public function walkRangeVariableDeclaration($rangeVariableDeclaration) + { + return $this->generateRangeVariableDeclarationSQL($rangeVariableDeclaration, false); + } + + /** + * Generate appropriate SQL for RangeVariableDeclaration AST node + * + * @param AST\RangeVariableDeclaration $rangeVariableDeclaration + * @param bool $buildNestedJoins + * + * @return string + */ + private function generateRangeVariableDeclarationSQL($rangeVariableDeclaration, bool $buildNestedJoins) : string { $class = $this->em->getClassMetadata($rangeVariableDeclaration->abstractSchemaName); $dqlAlias = $rangeVariableDeclaration->aliasIdentificationVariable; @@ -888,11 +902,17 @@ public function walkRangeVariableDeclaration($rangeVariableDeclaration) $this->query->getHint(Query::HINT_LOCK_MODE) ); - if ($class->isInheritanceTypeJoined()) { - $sql .= $this->_generateClassTableInheritanceJoins($class, $dqlAlias); + if ( ! $class->isInheritanceTypeJoined()) { + return $sql; } - return $sql; + $classTableInheritanceJoins = $this->_generateClassTableInheritanceJoins($class, $dqlAlias); + + if ( ! $buildNestedJoins) { + return $sql . $classTableInheritanceJoins; + } + + return $classTableInheritanceJoins === '' ? $sql : '(' . $sql . $classTableInheritanceJoins . ')'; } /** @@ -938,7 +958,7 @@ public function walkJoinAssociationDeclaration($joinAssociationDeclaration, $joi // The owning side is necessary at this point because only it contains the JoinColumn information. switch (true) { case ($assoc['type'] & ClassMetadata::TO_ONE): - $conditions = array(); + $conditions = []; foreach ($assoc['joinColumns'] as $joinColumn) { $quotedSourceColumn = $this->quoteStrategy->getJoinColumnName($joinColumn, $targetClass, $this->platform); @@ -954,7 +974,7 @@ public function walkJoinAssociationDeclaration($joinAssociationDeclaration, $joi } // Apply remaining inheritance restrictions - $discrSql = $this->_generateDiscriminatorColumnConditionSQL(array($joinedDqlAlias)); + $discrSql = $this->_generateDiscriminatorColumnConditionSQL([$joinedDqlAlias]); if ($discrSql) { $conditions[] = $discrSql; @@ -967,10 +987,10 @@ public function walkJoinAssociationDeclaration($joinAssociationDeclaration, $joi $conditions[] = $filterExpr; } - $targetTableJoin = array( + $targetTableJoin = [ 'table' => $targetTableName . ' ' . $targetTableAlias, 'condition' => implode(' AND ', $conditions), - ); + ]; break; case ($assoc['type'] == ClassMetadata::MANY_TO_MANY): @@ -979,7 +999,7 @@ public function walkJoinAssociationDeclaration($joinAssociationDeclaration, $joi $joinTableAlias = $this->getSQLTableAlias($joinTable['name'], $joinedDqlAlias); $joinTableName = $this->quoteStrategy->getJoinTableName($assoc, $sourceClass, $this->platform); - $conditions = array(); + $conditions = []; $relationColumns = ($relation['isOwningSide']) ? $assoc['joinTable']['joinColumns'] : $assoc['joinTable']['inverseJoinColumns']; @@ -996,7 +1016,7 @@ public function walkJoinAssociationDeclaration($joinAssociationDeclaration, $joi // Join target table $sql .= ($joinType == AST\Join::JOIN_TYPE_LEFT || $joinType == AST\Join::JOIN_TYPE_LEFTOUTER) ? ' LEFT JOIN ' : ' INNER JOIN '; - $conditions = array(); + $conditions = []; $relationColumns = ($relation['isOwningSide']) ? $assoc['joinTable']['inverseJoinColumns'] : $assoc['joinTable']['joinColumns']; @@ -1009,7 +1029,7 @@ public function walkJoinAssociationDeclaration($joinAssociationDeclaration, $joi } // Apply remaining inheritance restrictions - $discrSql = $this->_generateDiscriminatorColumnConditionSQL(array($joinedDqlAlias)); + $discrSql = $this->_generateDiscriminatorColumnConditionSQL([$joinedDqlAlias]); if ($discrSql) { $conditions[] = $discrSql; @@ -1022,10 +1042,10 @@ public function walkJoinAssociationDeclaration($joinAssociationDeclaration, $joi $conditions[] = $filterExpr; } - $targetTableJoin = array( + $targetTableJoin = [ 'table' => $targetTableName . ' ' . $targetTableAlias, 'condition' => implode(' AND ', $conditions), - ); + ]; break; default: @@ -1075,7 +1095,7 @@ public function walkFunction($function) */ public function walkOrderByClause($orderByClause) { - $orderByItems = array_map(array($this, 'walkOrderByItem'), $orderByClause->orderByItems); + $orderByItems = array_map([$this, 'walkOrderByItem'], $orderByClause->orderByItems); if (($collectionOrderByItems = $this->_generateOrderedCollectionOrderByItems()) !== '') { $orderByItems = array_merge($orderByItems, (array) $collectionOrderByItems); @@ -1125,7 +1145,7 @@ public function walkJoin($join) : ' INNER JOIN '; switch (true) { - case ($joinDeclaration instanceof \Doctrine\ORM\Query\AST\RangeVariableDeclaration): + case ($joinDeclaration instanceof AST\RangeVariableDeclaration): $class = $this->em->getClassMetadata($joinDeclaration->abstractSchemaName); $dqlAlias = $joinDeclaration->aliasIdentificationVariable; $tableAlias = $this->getSQLTableAlias($class->table['name'], $dqlAlias); @@ -1135,14 +1155,15 @@ public function walkJoin($join) $conditions[] = '(' . $this->walkConditionalExpression($join->conditionalExpression) . ')'; } - $condExprConjunction = ($class->isInheritanceTypeJoined() && $joinType != AST\Join::JOIN_TYPE_LEFT && $joinType != AST\Join::JOIN_TYPE_LEFTOUTER) + $isUnconditionalJoin = empty($conditions); + $condExprConjunction = ($class->isInheritanceTypeJoined() && $joinType != AST\Join::JOIN_TYPE_LEFT && $joinType != AST\Join::JOIN_TYPE_LEFTOUTER && $isUnconditionalJoin) ? ' AND ' : ' ON '; - $sql .= $this->walkRangeVariableDeclaration($joinDeclaration); + $sql .= $this->generateRangeVariableDeclarationSQL($joinDeclaration, !$isUnconditionalJoin); // Apply remaining inheritance restrictions - $discrSql = $this->_generateDiscriminatorColumnConditionSQL(array($dqlAlias)); + $discrSql = $this->_generateDiscriminatorColumnConditionSQL([$dqlAlias]); if ($discrSql) { $conditions[] = $discrSql; @@ -1161,7 +1182,7 @@ public function walkJoin($join) break; - case ($joinDeclaration instanceof \Doctrine\ORM\Query\AST\JoinAssociationDeclaration): + case ($joinDeclaration instanceof AST\JoinAssociationDeclaration): $sql .= $this->walkJoinAssociationDeclaration($joinDeclaration, $joinType, $join->conditionalExpression); break; } @@ -1169,33 +1190,6 @@ public function walkJoin($join) return $sql; } - /** - * Walks down a CaseExpression AST node and generates the corresponding SQL. - * - * @param AST\CoalesceExpression|AST\NullIfExpression|AST\GeneralCaseExpression|AST\SimpleCaseExpression $expression - * - * @return string The SQL. - */ - public function walkCaseExpression($expression) - { - switch (true) { - case ($expression instanceof AST\CoalesceExpression): - return $this->walkCoalesceExpression($expression); - - case ($expression instanceof AST\NullIfExpression): - return $this->walkNullIfExpression($expression); - - case ($expression instanceof AST\GeneralCaseExpression): - return $this->walkGeneralCaseExpression($expression); - - case ($expression instanceof AST\SimpleCaseExpression): - return $this->walkSimpleCaseExpression($expression); - - default: - return ''; - } - } - /** * Walks down a CoalesceExpression AST node and generates the corresponding SQL. * @@ -1207,7 +1201,7 @@ public function walkCoalesceExpression($coalesceExpression) { $sql = 'COALESCE('; - $scalarExpressions = array(); + $scalarExpressions = []; foreach ($coalesceExpression->scalarExpressions as $scalarExpression) { $scalarExpressions[] = $this->walkSimpleArithmeticExpression($scalarExpression); @@ -1376,7 +1370,7 @@ public function walkSelectExpression($selectExpression) $partialFieldSet = $expr->partialFieldSet; } else { $dqlAlias = $expr; - $partialFieldSet = array(); + $partialFieldSet = []; } $queryComp = $this->queryComponents[$dqlAlias]; @@ -1384,14 +1378,14 @@ public function walkSelectExpression($selectExpression) $resultAlias = $selectExpression->fieldIdentificationVariable ?: null; if ( ! isset($this->selectedClasses[$dqlAlias])) { - $this->selectedClasses[$dqlAlias] = array( + $this->selectedClasses[$dqlAlias] = [ 'class' => $class, 'dqlAlias' => $dqlAlias, 'resultAlias' => $resultAlias - ); + ]; } - $sqlParts = array(); + $sqlParts = []; // Select all fields from the queried class foreach ($class->fieldMappings as $fieldName => $mapping) { @@ -1476,7 +1470,7 @@ public function walkSubselect($subselect) $useAliasesBefore = $this->useSqlTableAliases; $rootAliasesBefore = $this->rootAliases; - $this->rootAliases = array(); // reset the rootAliases for the subselect + $this->rootAliases = []; // reset the rootAliases for the subselect $this->useSqlTableAliases = true; $sql = $this->walkSimpleSelectClause($subselect->simpleSelectClause); @@ -1499,7 +1493,7 @@ public function walkSubselect($subselect) public function walkSubselectFromClause($subselectFromClause) { $identificationVarDecls = $subselectFromClause->identificationVariableDeclarations; - $sqlParts = array (); + $sqlParts = []; foreach ($identificationVarDecls as $subselectIdVarDecl) { $sqlParts[] = $this->walkIdentificationVariableDeclaration($subselectIdVarDecl); @@ -1528,13 +1522,13 @@ public function walkParenthesisExpression(AST\ParenthesisExpression $parenthesis } /** - * @param AST\NewObjectExpression $newObjectExpression - * + * @param AST\NewObjectExpression $newObjectExpression + * @param null|string $newObjectResultAlias * @return string The SQL. */ public function walkNewObject($newObjectExpression, $newObjectResultAlias=null) { - $sqlSelectExpressions = array(); + $sqlSelectExpressions = []; $objIndex = $newObjectResultAlias?:$this->newObjectCounter++; foreach ($newObjectExpression->args as $argIndex => $e) { @@ -1582,11 +1576,11 @@ public function walkNewObject($newObjectExpression, $newObjectResultAlias=null) $this->scalarResultAliasMap[$resultAlias] = $columnAlias; $this->rsm->addScalarResult($columnAlias, $resultAlias, $fieldType); - $this->rsm->newObjectMappings[$columnAlias] = array( + $this->rsm->newObjectMappings[$columnAlias] = [ 'className' => $newObjectExpression->className, 'objIndex' => $objIndex, 'argIndex' => $argIndex - ); + ]; } return implode(', ', $sqlSelectExpressions); @@ -1605,12 +1599,6 @@ public function walkSimpleSelectExpression($simpleSelectExpression) $sql .= $this->walkPathExpression($expr); break; - case ($expr instanceof AST\AggregateExpression): - $alias = $simpleSelectExpression->fieldIdentificationVariable ?: $this->scalarResultCounter++; - - $sql .= $this->walkAggregateExpression($expr) . ' AS dctrn__' . $alias; - break; - case ($expr instanceof AST\Subselect): $alias = $simpleSelectExpression->fieldIdentificationVariable ?: $this->scalarResultCounter++; @@ -1663,7 +1651,7 @@ public function walkAggregateExpression($aggExpression) */ public function walkGroupByClause($groupByClause) { - $sqlParts = array(); + $sqlParts = []; foreach ($groupByClause->groupByItems as $groupByItem) { $sqlParts[] = $this->walkGroupByItem($groupByItem); @@ -1698,7 +1686,7 @@ public function walkGroupByItem($groupByItem) } // IdentificationVariable - $sqlParts = array(); + $sqlParts = []; foreach ($this->queryComponents[$groupByItem]['metadata']->fieldNames as $field) { $item = new AST\PathExpression(AST\PathExpression::TYPE_STATE_FIELD, $groupByItem, $field); @@ -1746,7 +1734,7 @@ public function walkUpdateClause($updateClause) $this->setSQLTableAlias($tableName, $tableName, $updateClause->aliasIdentificationVariable); $this->rootAliases[] = $updateClause->aliasIdentificationVariable; - $sql .= ' SET ' . implode(', ', array_map(array($this, 'walkUpdateItem'), $updateClause->updateItems)); + $sql .= ' SET ' . implode(', ', array_map([$this, 'walkUpdateItem'], $updateClause->updateItems)); return $sql; } @@ -1787,10 +1775,10 @@ public function walkUpdateItem($updateItem) public function walkWhereClause($whereClause) { $condSql = null !== $whereClause ? $this->walkConditionalExpression($whereClause->conditionalExpression) : ''; - $discrSql = $this->_generateDiscriminatorColumnConditionSql($this->rootAliases); + $discrSql = $this->_generateDiscriminatorColumnConditionSQL($this->rootAliases); if ($this->em->hasFilters()) { - $filterClauses = array(); + $filterClauses = []; foreach ($this->rootAliases as $dqlAlias) { $class = $this->queryComponents[$dqlAlias]['metadata']; $tableAlias = $this->getSQLTableAlias($class->table['name'], $dqlAlias); @@ -1831,7 +1819,7 @@ public function walkConditionalExpression($condExpr) return $this->walkConditionalTerm($condExpr); } - return implode(' OR ', array_map(array($this, 'walkConditionalTerm'), $condExpr->conditionalTerms)); + return implode(' OR ', array_map([$this, 'walkConditionalTerm'], $condExpr->conditionalTerms)); } /** @@ -1845,7 +1833,7 @@ public function walkConditionalTerm($condTerm) return $this->walkConditionalFactor($condTerm); } - return implode(' AND ', array_map(array($this, 'walkConditionalFactor'), $condTerm->conditionalFactors)); + return implode(' AND ', array_map([$this, 'walkConditionalFactor'], $condTerm->conditionalFactors)); } /** @@ -1930,7 +1918,7 @@ public function walkCollectionMemberExpression($collMemberExpr) $sql .= $this->quoteStrategy->getTableName($targetClass, $this->platform) . ' ' . $targetTableAlias . ' WHERE '; $owningAssoc = $targetClass->associationMappings[$assoc['mappedBy']]; - $sqlParts = array(); + $sqlParts = []; foreach ($owningAssoc['targetToSourceKeyColumns'] as $targetColumn => $sourceColumn) { $targetColumn = $this->quoteStrategy->getColumnName($class->fieldNames[$targetColumn], $class, $this->platform); @@ -1964,7 +1952,7 @@ public function walkCollectionMemberExpression($collMemberExpr) // join conditions $joinColumns = $assoc['isOwningSide'] ? $joinTable['inverseJoinColumns'] : $joinTable['joinColumns']; - $joinSqlParts = array(); + $joinSqlParts = []; foreach ($joinColumns as $joinColumn) { $targetColumn = $this->quoteStrategy->getColumnName($targetClass->fieldNames[$joinColumn['referencedColumnName']], $targetClass, $this->platform); @@ -1976,7 +1964,7 @@ public function walkCollectionMemberExpression($collMemberExpr) $sql .= ' WHERE '; $joinColumns = $assoc['isOwningSide'] ? $joinTable['joinColumns'] : $joinTable['inverseJoinColumns']; - $sqlParts = array(); + $sqlParts = []; foreach ($joinColumns as $joinColumn) { $targetColumn = $this->quoteStrategy->getColumnName($class->fieldNames[$joinColumn['referencedColumnName']], $class, $this->platform); @@ -2039,7 +2027,7 @@ public function walkInExpression($inExpr) $sql .= ($inExpr->subselect) ? $this->walkSubselect($inExpr->subselect) - : implode(', ', array_map(array($this, 'walkInParameter'), $inExpr->literals)); + : implode(', ', array_map([$this, 'walkInParameter'], $inExpr->literals)); $sql .= ')'; @@ -2048,6 +2036,7 @@ public function walkInExpression($inExpr) /** * {@inheritdoc} + * @throws \Doctrine\ORM\Query\QueryException */ public function walkInstanceOfExpression($instanceOfExpr) { @@ -2065,36 +2054,7 @@ public function walkInstanceOfExpression($instanceOfExpr) } $sql .= $class->discriminatorColumn['name'] . ($instanceOfExpr->not ? ' NOT IN ' : ' IN '); - - $sqlParameterList = array(); - - foreach ($instanceOfExpr->value as $parameter) { - if ($parameter instanceof AST\InputParameter) { - $this->rsm->addMetadataParameterMapping($parameter->name, 'discriminatorValue'); - - $sqlParameterList[] = $this->walkInputParameter($parameter); - - continue; - } - - // Get name from ClassMetadata to resolve aliases. - $entityClassName = $this->em->getClassMetadata($parameter)->name; - $discriminatorValue = $class->discriminatorValue; - - if ($entityClassName !== $class->name) { - $discrMap = array_flip($class->discriminatorMap); - - if ( ! isset($discrMap[$entityClassName])) { - throw QueryException::instanceOfUnrelatedClass($entityClassName, $class->rootEntityName); - } - - $discriminatorValue = $discrMap[$entityClassName]; - } - - $sqlParameterList[] = $this->conn->quote($discriminatorValue); - } - - $sql .= '(' . implode(', ', $sqlParameterList) . ')'; + $sql .= $this->getChildDiscriminatorsFromClassMetadata($discrClass, $instanceOfExpr); return $sql; } @@ -2119,10 +2079,7 @@ public function walkLiteral($literal) return $this->conn->quote($literal->value); case AST\Literal::BOOLEAN: - $bool = strtolower($literal->value) == 'true' ? true : false; - $boolVal = $this->conn->getDatabasePlatform()->convertBooleans($bool); - - return $boolVal; + return $this->conn->getDatabasePlatform()->convertBooleans('true' === strtolower($literal->value)); case AST\Literal::NUMERIC: return $literal->value; @@ -2243,7 +2200,7 @@ public function walkSimpleArithmeticExpression($simpleArithmeticExpr) return $this->walkArithmeticTerm($simpleArithmeticExpr); } - return implode(' ', array_map(array($this, 'walkArithmeticTerm'), $simpleArithmeticExpr->arithmeticTerms)); + return implode(' ', array_map([$this, 'walkArithmeticTerm'], $simpleArithmeticExpr->arithmeticTerms)); } /** @@ -2263,7 +2220,7 @@ public function walkArithmeticTerm($term) return $this->walkArithmeticFactor($term); } - return implode(' ', array_map(array($this, 'walkArithmeticFactor'), $term->arithmeticFactors)); + return implode(' ', array_map([$this, 'walkArithmeticFactor'], $term->arithmeticFactors)); } /** @@ -2331,4 +2288,37 @@ public function walkResultVariable($resultVariable) return $resultAlias; } + + /** + * @param ClassMetadataInfo $rootClass + * @param AST\InstanceOfExpression $instanceOfExpr + * @return string The list in parentheses of valid child discriminators from the given class + * @throws QueryException + */ + private function getChildDiscriminatorsFromClassMetadata(ClassMetadataInfo $rootClass, AST\InstanceOfExpression $instanceOfExpr): string + { + $sqlParameterList = []; + $discriminators = []; + foreach ($instanceOfExpr->value as $parameter) { + if ($parameter instanceof AST\InputParameter) { + $this->rsm->discriminatorParameters[$parameter->name] = $parameter->name; + $sqlParameterList[] = $this->walkInParameter($parameter); + continue; + } + + $metadata = $this->em->getClassMetadata($parameter); + + if ($metadata->getName() !== $rootClass->name && ! $metadata->getReflectionClass()->isSubclassOf($rootClass->name)) { + throw QueryException::instanceOfUnrelatedClass($parameter, $rootClass->name); + } + + $discriminators += HierarchyDiscriminatorResolver::resolveDiscriminatorsForClass($metadata, $this->em); + } + + foreach (array_keys($discriminators) as $dis) { + $sqlParameterList[] = $this->conn->quote($dis); + } + + return '(' . implode(', ', $sqlParameterList) . ')'; + } } diff --git a/lib/Doctrine/ORM/Query/TreeWalkerAdapter.php b/lib/Doctrine/ORM/Query/TreeWalkerAdapter.php index 529d855aa02..deee03ab53d 100644 --- a/lib/Doctrine/ORM/Query/TreeWalkerAdapter.php +++ b/lib/Doctrine/ORM/Query/TreeWalkerAdapter.php @@ -72,7 +72,7 @@ public function getQueryComponents() */ public function setQueryComponent($dqlAlias, array $queryComponent) { - $requiredKeys = array('metadata', 'parent', 'relation', 'map', 'nestingLevel', 'token'); + $requiredKeys = ['metadata', 'parent', 'relation', 'map', 'nestingLevel', 'token']; if (array_diff($requiredKeys, array_keys($queryComponent))) { throw QueryException::invalidQueryComponent($dqlAlias); diff --git a/lib/Doctrine/ORM/Query/TreeWalkerChain.php b/lib/Doctrine/ORM/Query/TreeWalkerChain.php index 573ef88ffce..074aa938709 100644 --- a/lib/Doctrine/ORM/Query/TreeWalkerChain.php +++ b/lib/Doctrine/ORM/Query/TreeWalkerChain.php @@ -72,7 +72,7 @@ public function getQueryComponents() */ public function setQueryComponent($dqlAlias, array $queryComponent) { - $requiredKeys = array('metadata', 'parent', 'relation', 'map', 'nestingLevel', 'token'); + $requiredKeys = ['metadata', 'parent', 'relation', 'map', 'nestingLevel', 'token']; if (array_diff($requiredKeys, array_keys($queryComponent))) { throw QueryException::invalidQueryComponent($dqlAlias); diff --git a/lib/Doctrine/ORM/Query/TreeWalkerChainIterator.php b/lib/Doctrine/ORM/Query/TreeWalkerChainIterator.php index ee329604f8b..e72e1d4dc4a 100644 --- a/lib/Doctrine/ORM/Query/TreeWalkerChainIterator.php +++ b/lib/Doctrine/ORM/Query/TreeWalkerChainIterator.php @@ -27,7 +27,7 @@ class TreeWalkerChainIterator implements \Iterator, \ArrayAccess /** * @var TreeWalker[] */ - private $walkers = array(); + private $walkers = []; /** * @var TreeWalkerChain */ @@ -119,7 +119,7 @@ public function offsetGet($offset) */ public function offsetSet($offset, $value) { - if (is_null($offset)) { + if (null === $offset) { $this->walkers[] = $value; } else { $this->walkers[$offset] = $value; diff --git a/lib/Doctrine/ORM/QueryBuilder.php b/lib/Doctrine/ORM/QueryBuilder.php index ca754d66dd2..af4d8cd2be6 100644 --- a/lib/Doctrine/ORM/QueryBuilder.php +++ b/lib/Doctrine/ORM/QueryBuilder.php @@ -57,17 +57,17 @@ class QueryBuilder * * @var array */ - private $_dqlParts = array( + private $_dqlParts = [ 'distinct' => false, - 'select' => array(), - 'from' => array(), - 'join' => array(), - 'set' => array(), + 'select' => [], + 'from' => [], + 'join' => [], + 'set' => [], 'where' => null, - 'groupBy' => array(), + 'groupBy' => [], 'having' => null, - 'orderBy' => array() - ); + 'orderBy' => [] + ]; /** * The type of query this is. Can be select, update or delete. @@ -107,7 +107,7 @@ class QueryBuilder /** * The maximum number of results to retrieve. * - * @var integer + * @var integer|null */ private $_maxResults = null; @@ -116,7 +116,7 @@ class QueryBuilder * * @var array */ - private $joinRootAliases = array(); + private $joinRootAliases = []; /** * Whether to use second level cache, if available. @@ -444,7 +444,7 @@ public function getRootAlias() */ public function getRootAliases() { - $aliases = array(); + $aliases = []; foreach ($this->_dqlParts['from'] as &$fromClause) { if (is_string($fromClause)) { @@ -496,7 +496,7 @@ public function getAllAliases() */ public function getRootEntities() { - $entities = array(); + $entities = []; foreach ($this->_dqlParts['from'] as &$fromClause) { if (is_string($fromClause)) { @@ -526,32 +526,21 @@ public function getRootEntities() * * @param string|integer $key The parameter position or name. * @param mixed $value The parameter value. - * @param string|null $type PDO::PARAM_* or \Doctrine\DBAL\Types\Type::* constant + * @param string|integer|null $type PDO::PARAM_* or \Doctrine\DBAL\Types\Type::* constant * * @return self */ public function setParameter($key, $value, $type = null) { - $filteredParameters = $this->parameters->filter( - function ($parameter) use ($key) - { - /* @var Query\Parameter $parameter */ - // Must not be identical because of string to integer conversion - return ($key == $parameter->getName()); - } - ); + $existingParameter = $this->getParameter($key); - if (count($filteredParameters)) { - /* @var Query\Parameter $parameter */ - $parameter = $filteredParameters->first(); - $parameter->setValue($value, $type); + if ($existingParameter !== null) { + $existingParameter->setValue($value, $type); return $this; } - $parameter = new Query\Parameter($key, $value, $type); - - $this->parameters->add($parameter); + $this->parameters->add(new Query\Parameter($key, $value, $type)); return $this; } @@ -614,15 +603,14 @@ public function getParameters() public function getParameter($key) { $filteredParameters = $this->parameters->filter( - function ($parameter) use ($key) - { - /* @var Query\Parameter $parameter */ - // Must not be identical because of string to integer conversion - return ($key == $parameter->getName()); + function (Query\Parameter $parameter) use ($key) : bool { + $parameterName = $parameter->getName(); + + return $key === $parameterName || (string) $key === (string) $parameterName; } ); - return count($filteredParameters) ? $filteredParameters->first() : null; + return ! $filteredParameters->isEmpty() ? $filteredParameters->first() : null; } /** @@ -653,7 +641,7 @@ public function getFirstResult() /** * Sets the maximum number of results to retrieve (the "limit"). * - * @param integer $maxResults The maximum number of results to retrieve. + * @param integer|null $maxResults The maximum number of results to retrieve. * * @return self */ @@ -668,7 +656,7 @@ public function setMaxResults($maxResults) * Gets the maximum number of results the query object was set to retrieve (the "limit"). * Returns NULL if {@link setMaxResults} was not applied to this query builder. * - * @return integer Maximum number of results. + * @return integer|null Maximum number of results. */ public function getMaxResults() { @@ -707,7 +695,7 @@ public function add($dqlPartName, $dqlPart, $append = false) // This is introduced for backwards compatibility reasons. // TODO: Remove for 3.0 if ($dqlPartName == 'join') { - $newDqlPart = array(); + $newDqlPart = []; foreach ($dqlPart as $k => $v) { $k = is_numeric($k) ? $this->getRootAlias() : $k; @@ -727,7 +715,7 @@ public function add($dqlPartName, $dqlPart, $append = false) $this->_dqlParts[$dqlPartName][] = $dqlPart; } } else { - $this->_dqlParts[$dqlPartName] = ($isMultiple) ? array($dqlPart) : $dqlPart; + $this->_dqlParts[$dqlPartName] = ($isMultiple) ? [$dqlPart] : $dqlPart; } $this->_state = self::STATE_DIRTY; @@ -990,7 +978,7 @@ public function innerJoin($join, $alias, $conditionType = null, $condition = nul Expr\Join::INNER_JOIN, $join, $alias, $conditionType, $condition, $indexBy ); - return $this->add('join', array($rootAlias => $join), true); + return $this->add('join', [$rootAlias => $join], true); } /** @@ -1025,7 +1013,7 @@ public function leftJoin($join, $alias, $conditionType = null, $condition = null Expr\Join::LEFT_JOIN, $join, $alias, $conditionType, $condition, $indexBy ); - return $this->add('join', array($rootAlias => $join), true); + return $this->add('join', [$rootAlias => $join], true); } /** @@ -1039,7 +1027,7 @@ public function leftJoin($join, $alias, $conditionType = null, $condition = null * * * @param string $key The key/field to set. - * @param string $value The value, expression, placeholder, etc. + * @param mixed $value The value, expression, placeholder, etc. * * @return self */ @@ -1374,9 +1362,9 @@ public function getDQLParts() private function _getDQLForDelete() { return 'DELETE' - . $this->_getReducedDQLQueryPart('from', array('pre' => ' ', 'separator' => ', ')) - . $this->_getReducedDQLQueryPart('where', array('pre' => ' WHERE ')) - . $this->_getReducedDQLQueryPart('orderBy', array('pre' => ' ORDER BY ', 'separator' => ', ')); + . $this->_getReducedDQLQueryPart('from', ['pre' => ' ', 'separator' => ', ']) + . $this->_getReducedDQLQueryPart('where', ['pre' => ' WHERE ']) + . $this->_getReducedDQLQueryPart('orderBy', ['pre' => ' ORDER BY ', 'separator' => ', ']); } /** @@ -1385,10 +1373,10 @@ private function _getDQLForDelete() private function _getDQLForUpdate() { return 'UPDATE' - . $this->_getReducedDQLQueryPart('from', array('pre' => ' ', 'separator' => ', ')) - . $this->_getReducedDQLQueryPart('set', array('pre' => ' SET ', 'separator' => ', ')) - . $this->_getReducedDQLQueryPart('where', array('pre' => ' WHERE ')) - . $this->_getReducedDQLQueryPart('orderBy', array('pre' => ' ORDER BY ', 'separator' => ', ')); + . $this->_getReducedDQLQueryPart('from', ['pre' => ' ', 'separator' => ', ']) + . $this->_getReducedDQLQueryPart('set', ['pre' => ' SET ', 'separator' => ', ']) + . $this->_getReducedDQLQueryPart('where', ['pre' => ' WHERE ']) + . $this->_getReducedDQLQueryPart('orderBy', ['pre' => ' ORDER BY ', 'separator' => ', ']); } /** @@ -1398,11 +1386,11 @@ private function _getDQLForSelect() { $dql = 'SELECT' . ($this->_dqlParts['distinct']===true ? ' DISTINCT' : '') - . $this->_getReducedDQLQueryPart('select', array('pre' => ' ', 'separator' => ', ')); + . $this->_getReducedDQLQueryPart('select', ['pre' => ' ', 'separator' => ', ']); $fromParts = $this->getDQLPart('from'); $joinParts = $this->getDQLPart('join'); - $fromClauses = array(); + $fromClauses = []; // Loop through all FROM clauses if ( ! empty($fromParts)) { @@ -1422,10 +1410,10 @@ private function _getDQLForSelect() } $dql .= implode(', ', $fromClauses) - . $this->_getReducedDQLQueryPart('where', array('pre' => ' WHERE ')) - . $this->_getReducedDQLQueryPart('groupBy', array('pre' => ' GROUP BY ', 'separator' => ', ')) - . $this->_getReducedDQLQueryPart('having', array('pre' => ' HAVING ')) - . $this->_getReducedDQLQueryPart('orderBy', array('pre' => ' ORDER BY ', 'separator' => ', ')); + . $this->_getReducedDQLQueryPart('where', ['pre' => ' WHERE ']) + . $this->_getReducedDQLQueryPart('groupBy', ['pre' => ' GROUP BY ', 'separator' => ', ']) + . $this->_getReducedDQLQueryPart('having', ['pre' => ' HAVING ']) + . $this->_getReducedDQLQueryPart('orderBy', ['pre' => ' ORDER BY ', 'separator' => ', ']); return $dql; } @@ -1436,17 +1424,17 @@ private function _getDQLForSelect() * * @return string */ - private function _getReducedDQLQueryPart($queryPartName, $options = array()) + private function _getReducedDQLQueryPart($queryPartName, $options = []) { $queryPart = $this->getDQLPart($queryPartName); if (empty($queryPart)) { - return (isset($options['empty']) ? $options['empty'] : ''); + return ($options['empty'] ?? ''); } - return (isset($options['pre']) ? $options['pre'] : '') + return ($options['pre'] ?? '') . (is_array($queryPart) ? implode($options['separator'], $queryPart) : $queryPart) - . (isset($options['post']) ? $options['post'] : ''); + . ($options['post'] ?? ''); } /** @@ -1458,7 +1446,7 @@ private function _getReducedDQLQueryPart($queryPartName, $options = array()) */ public function resetDQLParts($parts = null) { - if (is_null($parts)) { + if (null === $parts) { $parts = array_keys($this->_dqlParts); } @@ -1478,7 +1466,7 @@ public function resetDQLParts($parts = null) */ public function resetDQLPart($part) { - $this->_dqlParts[$part] = is_array($this->_dqlParts[$part]) ? array() : null; + $this->_dqlParts[$part] = is_array($this->_dqlParts[$part]) ? [] : null; $this->_state = self::STATE_DIRTY; return $this; @@ -1514,7 +1502,7 @@ public function __clone() } } - $parameters = array(); + $parameters = []; foreach ($this->parameters as $parameter) { $parameters[] = clone $parameter; diff --git a/lib/Doctrine/ORM/Repository/DefaultRepositoryFactory.php b/lib/Doctrine/ORM/Repository/DefaultRepositoryFactory.php index 12163eff615..680962413fc 100644 --- a/lib/Doctrine/ORM/Repository/DefaultRepositoryFactory.php +++ b/lib/Doctrine/ORM/Repository/DefaultRepositoryFactory.php @@ -34,7 +34,7 @@ final class DefaultRepositoryFactory implements RepositoryFactory * * @var \Doctrine\Common\Persistence\ObjectRepository[] */ - private $repositoryList = array(); + private $repositoryList = []; /** * {@inheritdoc} diff --git a/lib/Doctrine/ORM/Tools/AttachEntityListenersListener.php b/lib/Doctrine/ORM/Tools/AttachEntityListenersListener.php index bb0ca81b226..cf7cc8b8b95 100644 --- a/lib/Doctrine/ORM/Tools/AttachEntityListenersListener.php +++ b/lib/Doctrine/ORM/Tools/AttachEntityListenersListener.php @@ -33,7 +33,7 @@ class AttachEntityListenersListener /** * @var array[] */ - private $entityListeners = array(); + private $entityListeners = []; /** * Adds a entity listener for a specific entity. @@ -47,11 +47,11 @@ class AttachEntityListenersListener */ public function addEntityListener($entityClass, $listenerClass, $eventName, $listenerCallback = null) { - $this->entityListeners[ltrim($entityClass, '\\')][] = array( + $this->entityListeners[ltrim($entityClass, '\\')][] = [ 'event' => $eventName, 'class' => $listenerClass, 'method' => $listenerCallback ?: $eventName - ); + ]; } /** diff --git a/lib/Doctrine/ORM/Tools/Console/Command/ClearCache/CollectionRegionCommand.php b/lib/Doctrine/ORM/Tools/Console/Command/ClearCache/CollectionRegionCommand.php index f12bfa5602d..1c75ccccacc 100644 --- a/lib/Doctrine/ORM/Tools/Console/Command/ClearCache/CollectionRegionCommand.php +++ b/lib/Doctrine/ORM/Tools/Console/Command/ClearCache/CollectionRegionCommand.php @@ -19,13 +19,14 @@ namespace Doctrine\ORM\Tools\Console\Command\ClearCache; +use Doctrine\ORM\Cache; +use Doctrine\ORM\Cache\Region\DefaultRegion; use Symfony\Component\Console\Command\Command; -use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; -use Doctrine\ORM\Cache\Region\DefaultRegion; -use Doctrine\ORM\Cache; +use Symfony\Component\Console\Style\SymfonyStyle; /** * Command to clear a collection cache region. @@ -40,17 +41,14 @@ class CollectionRegionCommand extends Command */ protected function configure() { - $this - ->setName('orm:clear-cache:region:collection') - ->setDescription('Clear a second-level cache collection region.') - ->addArgument('owner-class', InputArgument::OPTIONAL, 'The owner entity name.') - ->addArgument('association', InputArgument::OPTIONAL, 'The association collection name.') - ->addArgument('owner-id', InputArgument::OPTIONAL, 'The owner identifier.') - ->addOption('all', null, InputOption::VALUE_NONE, 'If defined, all entity regions will be deleted/invalidated.') - ->addOption('flush', null, InputOption::VALUE_NONE, 'If defined, all cache entries will be flushed.'); - - - $this->setHelp(<<setName('orm:clear-cache:region:collection') + ->setDescription('Clear a second-level cache collection region') + ->addArgument('owner-class', InputArgument::OPTIONAL, 'The owner entity name.') + ->addArgument('association', InputArgument::OPTIONAL, 'The association collection name.') + ->addArgument('owner-id', InputArgument::OPTIONAL, 'The owner identifier.') + ->addOption('all', null, InputOption::VALUE_NONE, 'If defined, all entity regions will be deleted/invalidated.') + ->addOption('flush', null, InputOption::VALUE_NONE, 'If defined, all cache entries will be flushed.') + ->setHelp(<<%command.name% command is meant to clear a second-level cache collection regions for an associated Entity Manager. It is possible to delete/invalidate all collection region, a specific collection region or flushes the cache provider. @@ -74,7 +72,7 @@ protected function configure() Finally, be aware that if --flush option is passed, not all cache providers are able to flush entries, because of a limitation of its execution nature. EOT - ); + ); } /** @@ -82,6 +80,8 @@ protected function configure() */ protected function execute(InputInterface $input, OutputInterface $output) { + $ui = new SymfonyStyle($input, $output); + $em = $this->getHelper('em')->getEntityManager(); $ownerClass = $input->getArgument('owner-class'); $assoc = $input->getArgument('association'); @@ -92,7 +92,7 @@ protected function execute(InputInterface $input, OutputInterface $output) throw new \InvalidArgumentException('No second-level cache is configured on the given EntityManager.'); } - if ( (! $ownerClass || ! $assoc) && ! $input->getOption('all')) { + if (( ! $ownerClass || ! $assoc) && ! $input->getOption('all')) { throw new \InvalidArgumentException('Missing arguments "--owner-class" "--association"'); } @@ -108,27 +108,42 @@ protected function execute(InputInterface $input, OutputInterface $output) $collectionRegion->getCache()->flushAll(); - $output->writeln(sprintf('Flushing cache provider configured for "%s#%s"', $ownerClass, $assoc)); + $ui->comment( + sprintf( + 'Flushing cache provider configured for "%s#%s"', + $ownerClass, + $assoc + ) + ); - return; + return 0; } if ($input->getOption('all')) { - $output->writeln('Clearing all second-level cache collection regions'); + $ui->comment('Clearing all second-level cache collection regions'); $cache->evictEntityRegions(); - return; + return 0; } if ($ownerId) { - $output->writeln(sprintf('Clearing second-level cache entry for collection "%s#%s" owner entity identified by "%s"', $ownerClass, $assoc, $ownerId)); + $ui->comment( + sprintf( + 'Clearing second-level cache entry for collection "%s#%s" owner entity identified by "%s"', + $ownerClass, + $assoc, + $ownerId + ) + ); $cache->evictCollection($ownerClass, $assoc, $ownerId); - return; + return 0; } - $output->writeln(sprintf('Clearing second-level cache for collection "%s#%s"', $ownerClass, $assoc)); + $ui->comment(sprintf('Clearing second-level cache for collection "%s#%s"', $ownerClass, $assoc)); $cache->evictCollectionRegion($ownerClass, $assoc); + + return 0; } } diff --git a/lib/Doctrine/ORM/Tools/Console/Command/ClearCache/EntityRegionCommand.php b/lib/Doctrine/ORM/Tools/Console/Command/ClearCache/EntityRegionCommand.php index 0258b7de223..c246910c145 100644 --- a/lib/Doctrine/ORM/Tools/Console/Command/ClearCache/EntityRegionCommand.php +++ b/lib/Doctrine/ORM/Tools/Console/Command/ClearCache/EntityRegionCommand.php @@ -19,13 +19,14 @@ namespace Doctrine\ORM\Tools\Console\Command\ClearCache; +use Doctrine\ORM\Cache; +use Doctrine\ORM\Cache\Region\DefaultRegion; use Symfony\Component\Console\Command\Command; -use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; -use Doctrine\ORM\Cache\Region\DefaultRegion; -use Doctrine\ORM\Cache; +use Symfony\Component\Console\Style\SymfonyStyle; /** * Command to clear a entity cache region. @@ -40,16 +41,13 @@ class EntityRegionCommand extends Command */ protected function configure() { - $this - ->setName('orm:clear-cache:region:entity') - ->setDescription('Clear a second-level cache entity region.') - ->addArgument('entity-class', InputArgument::OPTIONAL, 'The entity name.') - ->addArgument('entity-id', InputArgument::OPTIONAL, 'The entity identifier.') - ->addOption('all', null, InputOption::VALUE_NONE, 'If defined, all entity regions will be deleted/invalidated.') - ->addOption('flush', null, InputOption::VALUE_NONE, 'If defined, all cache entries will be flushed.'); - - - $this->setHelp(<<setName('orm:clear-cache:region:entity') + ->setDescription('Clear a second-level cache entity region') + ->addArgument('entity-class', InputArgument::OPTIONAL, 'The entity name.') + ->addArgument('entity-id', InputArgument::OPTIONAL, 'The entity identifier.') + ->addOption('all', null, InputOption::VALUE_NONE, 'If defined, all entity regions will be deleted/invalidated.') + ->addOption('flush', null, InputOption::VALUE_NONE, 'If defined, all cache entries will be flushed.') + ->setHelp(<<%command.name% command is meant to clear a second-level cache entity region for an associated Entity Manager. It is possible to delete/invalidate all entity region, a specific entity region or flushes the cache provider. @@ -73,7 +71,7 @@ protected function configure() Finally, be aware that if --flush option is passed, not all cache providers are able to flush entries, because of a limitation of its execution nature. EOT - ); + ); } /** @@ -81,6 +79,8 @@ protected function configure() */ protected function execute(InputInterface $input, OutputInterface $output) { + $ui = new SymfonyStyle($input, $output); + $em = $this->getHelper('em')->getEntityManager(); $entityClass = $input->getArgument('entity-class'); $entityId = $input->getArgument('entity-id'); @@ -106,27 +106,35 @@ protected function execute(InputInterface $input, OutputInterface $output) $entityRegion->getCache()->flushAll(); - $output->writeln(sprintf('Flushing cache provider configured for entity named "%s"', $entityClass)); + $ui->comment(sprintf('Flushing cache provider configured for entity named "%s"', $entityClass)); - return; + return 0; } if ($input->getOption('all')) { - $output->writeln('Clearing all second-level cache entity regions'); + $ui->comment('Clearing all second-level cache entity regions'); $cache->evictEntityRegions(); - return; + return 0; } if ($entityId) { - $output->writeln(sprintf('Clearing second-level cache entry for entity "%s" identified by "%s"', $entityClass, $entityId)); + $ui->comment( + sprintf( + 'Clearing second-level cache entry for entity "%s" identified by "%s"', + $entityClass, + $entityId + ) + ); $cache->evictEntity($entityClass, $entityId); - return; + return 0; } - $output->writeln(sprintf('Clearing second-level cache for entity "%s"', $entityClass)); + $ui->comment(sprintf('Clearing second-level cache for entity "%s"', $entityClass)); $cache->evictEntityRegion($entityClass); + + return 0; } } diff --git a/lib/Doctrine/ORM/Tools/Console/Command/ClearCache/MetadataCommand.php b/lib/Doctrine/ORM/Tools/Console/Command/ClearCache/MetadataCommand.php index e23d36b24c1..e6531f22212 100644 --- a/lib/Doctrine/ORM/Tools/Console/Command/ClearCache/MetadataCommand.php +++ b/lib/Doctrine/ORM/Tools/Console/Command/ClearCache/MetadataCommand.php @@ -19,12 +19,13 @@ namespace Doctrine\ORM\Tools\Console\Command\ClearCache; +use Doctrine\Common\Cache\ApcCache; +use Doctrine\Common\Cache\XcacheCache; use Symfony\Component\Console\Command\Command; -use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; -use Doctrine\Common\Cache\ApcCache; -use Doctrine\Common\Cache\XcacheCache; +use Symfony\Component\Console\Style\SymfonyStyle; /** * Command to clear the metadata cache of the various cache drivers. @@ -43,17 +44,10 @@ class MetadataCommand extends Command */ protected function configure() { - $this - ->setName('orm:clear-cache:metadata') - ->setDescription('Clear all metadata cache of the various cache drivers.') - ->setDefinition(array( - new InputOption( - 'flush', null, InputOption::VALUE_NONE, - 'If defined, cache entries will be flushed instead of deleted/invalidated.' - ) - )); - - $this->setHelp(<<setName('orm:clear-cache:metadata') + ->setDescription('Clear all metadata cache of the various cache drivers') + ->addOption('flush', null, InputOption::VALUE_NONE, 'If defined, cache entries will be flushed instead of deleted/invalidated.') + ->setHelp(<<%command.name% command is meant to clear the metadata cache of associated Entity Manager. It is possible to invalidate all cache entries at once - called delete -, or flushes the cache provider instance completely. @@ -70,7 +64,7 @@ protected function configure() Finally, be aware that if --flush option is passed, not all cache providers are able to flush entries, because of a limitation of its execution nature. EOT - ); + ); } /** @@ -78,6 +72,8 @@ protected function configure() */ protected function execute(InputInterface $input, OutputInterface $output) { + $ui = new SymfonyStyle($input, $output); + $em = $this->getHelper('em')->getEntityManager(); $cacheDriver = $em->getConfiguration()->getMetadataCacheImpl(); @@ -93,8 +89,7 @@ protected function execute(InputInterface $input, OutputInterface $output) throw new \LogicException("Cannot clear XCache Cache from Console, its shared in the Webserver memory and not accessible from the CLI."); } - - $output->writeln('Clearing ALL Metadata cache entries'); + $ui->comment('Clearing all Metadata cache entries'); $result = $cacheDriver->deleteAll(); $message = ($result) ? 'Successfully deleted cache entries.' : 'No cache entries were deleted.'; @@ -104,6 +99,14 @@ protected function execute(InputInterface $input, OutputInterface $output) $message = ($result) ? 'Successfully flushed cache entries.' : $message; } - $output->writeln($message); + if ( ! $result) { + $ui->error($message); + + return 1; + } + + $ui->success($message); + + return 0; } } diff --git a/lib/Doctrine/ORM/Tools/Console/Command/ClearCache/QueryCommand.php b/lib/Doctrine/ORM/Tools/Console/Command/ClearCache/QueryCommand.php index f1be98d30fa..95bec91de8d 100644 --- a/lib/Doctrine/ORM/Tools/Console/Command/ClearCache/QueryCommand.php +++ b/lib/Doctrine/ORM/Tools/Console/Command/ClearCache/QueryCommand.php @@ -19,12 +19,13 @@ namespace Doctrine\ORM\Tools\Console\Command\ClearCache; +use Doctrine\Common\Cache\ApcCache; +use Doctrine\Common\Cache\XcacheCache; use Symfony\Component\Console\Command\Command; -use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; -use Doctrine\Common\Cache\ApcCache; -use Doctrine\Common\Cache\XcacheCache; +use Symfony\Component\Console\Style\SymfonyStyle; /** * Command to clear the query cache of the various cache drivers. @@ -43,17 +44,10 @@ class QueryCommand extends Command */ protected function configure() { - $this - ->setName('orm:clear-cache:query') - ->setDescription('Clear all query cache of the various cache drivers.') - ->setDefinition(array( - new InputOption( - 'flush', null, InputOption::VALUE_NONE, - 'If defined, cache entries will be flushed instead of deleted/invalidated.' - ) - )); - - $this->setHelp(<<setName('orm:clear-cache:query') + ->setDescription('Clear all query cache of the various cache drivers') + ->addOption('flush', null, InputOption::VALUE_NONE, 'If defined, cache entries will be flushed instead of deleted/invalidated.') + ->setHelp(<<%command.name% command is meant to clear the query cache of associated Entity Manager. It is possible to invalidate all cache entries at once - called delete -, or flushes the cache provider instance completely. @@ -70,7 +64,7 @@ protected function configure() Finally, be aware that if --flush option is passed, not all cache providers are able to flush entries, because of a limitation of its execution nature. EOT - ); + ); } /** @@ -78,6 +72,8 @@ protected function configure() */ protected function execute(InputInterface $input, OutputInterface $output) { + $ui = new SymfonyStyle($input, $output); + $em = $this->getHelper('em')->getEntityManager(); $cacheDriver = $em->getConfiguration()->getQueryCacheImpl(); @@ -91,8 +87,8 @@ protected function execute(InputInterface $input, OutputInterface $output) if ($cacheDriver instanceof XcacheCache) { throw new \LogicException("Cannot clear XCache Cache from Console, its shared in the Webserver memory and not accessible from the CLI."); } - - $output->write('Clearing ALL Query cache entries' . PHP_EOL); + + $ui->comment('Clearing all Query cache entries'); $result = $cacheDriver->deleteAll(); $message = ($result) ? 'Successfully deleted cache entries.' : 'No cache entries were deleted.'; @@ -102,6 +98,14 @@ protected function execute(InputInterface $input, OutputInterface $output) $message = ($result) ? 'Successfully flushed cache entries.' : $message; } - $output->write($message . PHP_EOL); + if ( ! $result) { + $ui->error($message); + + return 1; + } + + $ui->success($message); + + return 0; } } diff --git a/lib/Doctrine/ORM/Tools/Console/Command/ClearCache/QueryRegionCommand.php b/lib/Doctrine/ORM/Tools/Console/Command/ClearCache/QueryRegionCommand.php index 0637c7a4a07..36ffa125038 100644 --- a/lib/Doctrine/ORM/Tools/Console/Command/ClearCache/QueryRegionCommand.php +++ b/lib/Doctrine/ORM/Tools/Console/Command/ClearCache/QueryRegionCommand.php @@ -19,13 +19,14 @@ namespace Doctrine\ORM\Tools\Console\Command\ClearCache; +use Doctrine\ORM\Cache; +use Doctrine\ORM\Cache\Region\DefaultRegion; use Symfony\Component\Console\Command\Command; -use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; -use Doctrine\ORM\Cache\Region\DefaultRegion; -use Doctrine\ORM\Cache; +use Symfony\Component\Console\Style\SymfonyStyle; /** * Command to clear a query cache region. @@ -40,15 +41,12 @@ class QueryRegionCommand extends Command */ protected function configure() { - $this - ->setName('orm:clear-cache:region:query') - ->setDescription('Clear a second-level cache query region.') - ->addArgument('region-name', InputArgument::OPTIONAL, 'The query region to clear.') - ->addOption('all', null, InputOption::VALUE_NONE, 'If defined, all query regions will be deleted/invalidated.') - ->addOption('flush', null, InputOption::VALUE_NONE, 'If defined, all cache entries will be flushed.'); - - - $this->setHelp(<<setName('orm:clear-cache:region:query') + ->setDescription('Clear a second-level cache query region') + ->addArgument('region-name', InputArgument::OPTIONAL, 'The query region to clear.') + ->addOption('all', null, InputOption::VALUE_NONE, 'If defined, all query regions will be deleted/invalidated.') + ->addOption('flush', null, InputOption::VALUE_NONE, 'If defined, all cache entries will be flushed.') + ->setHelp(<<%command.name% command is meant to clear a second-level cache query region for an associated Entity Manager. It is possible to delete/invalidate all query region, a specific query region or flushes the cache provider. @@ -72,7 +70,7 @@ protected function configure() Finally, be aware that if --flush option is passed, not all cache providers are able to flush entries, because of a limitation of its execution nature. EOT - ); + ); } /** @@ -80,6 +78,8 @@ protected function configure() */ protected function execute(InputInterface $input, OutputInterface $output) { + $ui = new SymfonyStyle($input, $output); + $em = $this->getHelper('em')->getEntityManager(); $name = $input->getArgument('region-name'); $cache = $em->getCache(); @@ -105,20 +105,27 @@ protected function execute(InputInterface $input, OutputInterface $output) $queryRegion->getCache()->flushAll(); - $output->writeln(sprintf('Flushing cache provider configured for second-level cache query region named "%s"', $name)); + $ui->comment( + sprintf( + 'Flushing cache provider configured for second-level cache query region named "%s"', + $name + ) + ); - return; + return 0; } if ($input->getOption('all')) { - $output->writeln('Clearing all second-level cache query regions'); + $ui->comment('Clearing all second-level cache query regions'); $cache->evictQueryRegions(); - return; + return 0; } - $output->writeln(sprintf('Clearing second-level cache query region named "%s"', $name)); + $ui->comment(sprintf('Clearing second-level cache query region named "%s"', $name)); $cache->evictQueryRegion($name); + + return 0; } } diff --git a/lib/Doctrine/ORM/Tools/Console/Command/ClearCache/ResultCommand.php b/lib/Doctrine/ORM/Tools/Console/Command/ClearCache/ResultCommand.php index c21f5545270..42ad79c502c 100644 --- a/lib/Doctrine/ORM/Tools/Console/Command/ClearCache/ResultCommand.php +++ b/lib/Doctrine/ORM/Tools/Console/Command/ClearCache/ResultCommand.php @@ -19,12 +19,13 @@ namespace Doctrine\ORM\Tools\Console\Command\ClearCache; +use Doctrine\Common\Cache\ApcCache; +use Doctrine\Common\Cache\XcacheCache; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; -use Doctrine\Common\Cache\ApcCache; -use Doctrine\Common\Cache\XcacheCache; +use Symfony\Component\Console\Style\SymfonyStyle; /** * Command to clear the result cache of the various cache drivers. @@ -43,17 +44,10 @@ class ResultCommand extends Command */ protected function configure() { - $this - ->setName('orm:clear-cache:result') - ->setDescription('Clear all result cache of the various cache drivers.') - ->setDefinition(array( - new InputOption( - 'flush', null, InputOption::VALUE_NONE, - 'If defined, cache entries will be flushed instead of deleted/invalidated.' - ) - )); - - $this->setHelp(<<setName('orm:clear-cache:result') + ->setDescription('Clear all result cache of the various cache drivers') + ->addOption('flush', null, InputOption::VALUE_NONE, 'If defined, cache entries will be flushed instead of deleted/invalidated.') + ->setHelp(<<%command.name% command is meant to clear the result cache of associated Entity Manager. It is possible to invalidate all cache entries at once - called delete -, or flushes the cache provider instance completely. @@ -70,7 +64,7 @@ protected function configure() Finally, be aware that if --flush option is passed, not all cache providers are able to flush entries, because of a limitation of its execution nature. EOT - ); + ); } /** @@ -78,6 +72,8 @@ protected function configure() */ protected function execute(InputInterface $input, OutputInterface $output) { + $ui = new SymfonyStyle($input, $output); + $em = $this->getHelper('em')->getEntityManager(); $cacheDriver = $em->getConfiguration()->getResultCacheImpl(); @@ -92,8 +88,8 @@ protected function execute(InputInterface $input, OutputInterface $output) if ($cacheDriver instanceof XcacheCache) { throw new \LogicException("Cannot clear XCache Cache from Console, its shared in the Webserver memory and not accessible from the CLI."); } - - $output->writeln('Clearing ALL Result cache entries'); + + $ui->comment('Clearing all Result cache entries'); $result = $cacheDriver->deleteAll(); $message = ($result) ? 'Successfully deleted cache entries.' : 'No cache entries were deleted.'; @@ -103,6 +99,14 @@ protected function execute(InputInterface $input, OutputInterface $output) $message = ($result) ? 'Successfully flushed cache entries.' : $message; } - $output->writeln($message); + if ( ! $result) { + $ui->error($message); + + return 1; + } + + $ui->success($message); + + return 0; } } diff --git a/lib/Doctrine/ORM/Tools/Console/Command/ConvertDoctrine1SchemaCommand.php b/lib/Doctrine/ORM/Tools/Console/Command/ConvertDoctrine1SchemaCommand.php index 71d72deb84d..90de7322ad4 100644 --- a/lib/Doctrine/ORM/Tools/Console/Command/ConvertDoctrine1SchemaCommand.php +++ b/lib/Doctrine/ORM/Tools/Console/Command/ConvertDoctrine1SchemaCommand.php @@ -19,15 +19,15 @@ namespace Doctrine\ORM\Tools\Console\Command; -use Symfony\Component\Console\Input\InputArgument; -use Symfony\Component\Console\Input\InputOption; -use Symfony\Component\Console; -use Doctrine\ORM\Tools\Export\ClassMetadataExporter; use Doctrine\ORM\Tools\ConvertDoctrine1Schema; use Doctrine\ORM\Tools\EntityGenerator; -use Symfony\Component\Console\Output\OutputInterface; -use Symfony\Component\Console\Input\InputInterface; +use Doctrine\ORM\Tools\Export\ClassMetadataExporter; use Symfony\Component\Console\Command\Command; +use Symfony\Component\Console\Input\InputArgument; +use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Input\InputOption; +use Symfony\Component\Console\Output\OutputInterface; +use Symfony\Component\Console\Style\SymfonyStyle; /** * Command to convert a Doctrine 1 schema to a Doctrine 2 mapping file. @@ -38,6 +38,8 @@ * @author Guilherme Blanco * @author Jonathan Wage * @author Roman Borschel + * + * @deprecated 2.7 This class is being removed from the ORM and won't have any replacement */ class ConvertDoctrine1SchemaCommand extends Command { @@ -100,39 +102,16 @@ public function setMetadataExporter(ClassMetadataExporter $metadataExporter) */ protected function configure() { - $this - ->setName('orm:convert-d1-schema') - ->setAliases(array('orm:convert:d1-schema')) - ->setDescription('Converts Doctrine 1.X schema into a Doctrine 2.X schema.') - ->setDefinition(array( - new InputArgument( - 'from-path', InputArgument::REQUIRED, 'The path of Doctrine 1.X schema information.' - ), - new InputArgument( - 'to-type', InputArgument::REQUIRED, 'The destination Doctrine 2.X mapping type.' - ), - new InputArgument( - 'dest-path', InputArgument::REQUIRED, - 'The path to generate your Doctrine 2.X mapping information.' - ), - new InputOption( - 'from', null, InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY, - 'Optional paths of Doctrine 1.X schema information.', - array() - ), - new InputOption( - 'extend', null, InputOption::VALUE_OPTIONAL, - 'Defines a base class to be extended by generated entity classes.' - ), - new InputOption( - 'num-spaces', null, InputOption::VALUE_OPTIONAL, - 'Defines the number of indentation spaces', 4 - ) - )) - ->setHelp(<<setName('orm:convert-d1-schema') + ->setAliases(['orm:convert:d1-schema']) + ->setDescription('Converts Doctrine 1.x schema into a Doctrine 2.x schema') + ->addArgument('from-path', InputArgument::REQUIRED, 'The path of Doctrine 1.X schema information.') + ->addArgument('to-type', InputArgument::REQUIRED, 'The destination Doctrine 2.X mapping type.') + ->addArgument('dest-path', InputArgument::REQUIRED, 'The path to generate your Doctrine 2.X mapping information.') + ->addOption('from', null, InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY, 'Optional paths of Doctrine 1.X schema information.', []) + ->addOption('extend', null, InputOption::VALUE_OPTIONAL, 'Defines a base class to be extended by generated entity classes.') + ->addOption('num-spaces', null, InputOption::VALUE_OPTIONAL, 'Defines the number of indentation spaces', 4) + ->setHelp('Converts Doctrine 1.x schema into a Doctrine 2.x schema.'); } /** @@ -140,8 +119,11 @@ protected function configure() */ protected function execute(InputInterface $input, OutputInterface $output) { + $ui = new SymfonyStyle($input, $output); + $ui->warning('Command ' . $this->getName() . ' is deprecated and will be removed in Doctrine ORM 3.0.'); + // Process source directories - $fromPaths = array_merge(array($input->getArgument('from-path')), $input->getOption('from')); + $fromPaths = array_merge([$input->getArgument('from-path')], $input->getOption('from')); // Process destination directory $destPath = realpath($input->getArgument('dest-path')); @@ -151,6 +133,8 @@ protected function execute(InputInterface $input, OutputInterface $output) $numSpaces = $input->getOption('num-spaces'); $this->convertDoctrine1Schema($fromPaths, $destPath, $toType, $numSpaces, $extend, $output); + + return 0; } /** diff --git a/lib/Doctrine/ORM/Tools/Console/Command/ConvertMappingCommand.php b/lib/Doctrine/ORM/Tools/Console/Command/ConvertMappingCommand.php index b229f4a6c08..8de2b84a9ec 100644 --- a/lib/Doctrine/ORM/Tools/Console/Command/ConvertMappingCommand.php +++ b/lib/Doctrine/ORM/Tools/Console/Command/ConvertMappingCommand.php @@ -19,16 +19,17 @@ namespace Doctrine\ORM\Tools\Console\Command; -use Symfony\Component\Console\Input\InputArgument; -use Symfony\Component\Console\Input\InputOption; +use Doctrine\ORM\Mapping\Driver\DatabaseDriver; use Doctrine\ORM\Tools\Console\MetadataFilter; -use Doctrine\ORM\Tools\Export\ClassMetadataExporter; -use Doctrine\ORM\Tools\EntityGenerator; use Doctrine\ORM\Tools\DisconnectedClassMetadataFactory; -use Doctrine\ORM\Mapping\Driver\DatabaseDriver; -use Symfony\Component\Console\Output\OutputInterface; -use Symfony\Component\Console\Input\InputInterface; +use Doctrine\ORM\Tools\EntityGenerator; +use Doctrine\ORM\Tools\Export\ClassMetadataExporter; use Symfony\Component\Console\Command\Command; +use Symfony\Component\Console\Input\InputArgument; +use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Input\InputOption; +use Symfony\Component\Console\Output\OutputInterface; +use Symfony\Component\Console\Style\SymfonyStyle; /** * Command to convert your mapping information between the various formats. @@ -47,43 +48,18 @@ class ConvertMappingCommand extends Command */ protected function configure() { - $this - ->setName('orm:convert-mapping') - ->setAliases(array('orm:convert:mapping')) - ->setDescription('Convert mapping information between supported formats.') - ->setDefinition(array( - new InputOption( - 'filter', null, InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY, - 'A string pattern used to match entities that should be processed.' - ), - new InputArgument( - 'to-type', InputArgument::REQUIRED, 'The mapping type to be converted.' - ), - new InputArgument( - 'dest-path', InputArgument::REQUIRED, - 'The path to generate your entities classes.' - ), - new InputOption( - 'force', 'f', InputOption::VALUE_NONE, - 'Force to overwrite existing mapping files.' - ), - new InputOption( - 'from-database', null, null, 'Whether or not to convert mapping information from existing database.' - ), - new InputOption( - 'extend', null, InputOption::VALUE_OPTIONAL, - 'Defines a base class to be extended by generated entity classes.' - ), - new InputOption( - 'num-spaces', null, InputOption::VALUE_OPTIONAL, - 'Defines the number of indentation spaces', 4 - ), - new InputOption( - 'namespace', null, InputOption::VALUE_OPTIONAL, - 'Defines a namespace for the generated entity classes, if converted from database.' - ), - )) - ->setHelp(<<setName('orm:convert-mapping') + ->setAliases(['orm:convert:mapping']) + ->setDescription('Convert mapping information between supported formats') + ->addArgument('to-type', InputArgument::REQUIRED, 'The mapping type to be converted.') + ->addArgument('dest-path', InputArgument::REQUIRED, 'The path to generate your entities classes.') + ->addOption('filter', null, InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY, 'A string pattern used to match entities that should be processed.') + ->addOption('force', 'f', InputOption::VALUE_NONE, 'Force to overwrite existing mapping files.') + ->addOption('from-database', null, null, 'Whether or not to convert mapping information from existing database.') + ->addOption('extend', null, InputOption::VALUE_OPTIONAL, 'Defines a base class to be extended by generated entity classes.') + ->addOption('num-spaces', null, InputOption::VALUE_OPTIONAL, 'Defines the number of indentation spaces', 4) + ->addOption('namespace', null, InputOption::VALUE_OPTIONAL, 'Defines a namespace for the generated entity classes, if converted from database.') + ->setHelp(<<one-time command. It should not be necessary for @@ -106,7 +82,7 @@ protected function configure() \$config->setFilterSchemaAssetsExpression(\$regexp); EOT - ); + ); } /** @@ -114,6 +90,8 @@ protected function configure() */ protected function execute(InputInterface $input, OutputInterface $output) { + $ui = new SymfonyStyle($input, $output); + $em = $this->getHelper('em')->getEntityManager(); if ($input->getOption('from-database') === true) { @@ -169,20 +147,28 @@ protected function execute(InputInterface $input, OutputInterface $output) } } - if (count($metadata)) { - foreach ($metadata as $class) { - $output->writeln(sprintf('Processing entity "%s"', $class->name)); - } - - $exporter->setMetadata($metadata); - $exporter->export(); + if (empty($metadata)) { + $ui->success('No Metadata Classes to process.'); + return; + } - $output->writeln(PHP_EOL . sprintf( - 'Exporting "%s" mapping information to "%s"', $toType, $destPath - )); - } else { - $output->writeln('No Metadata Classes to process.'); + foreach ($metadata as $class) { + $ui->text(sprintf('Processing entity "%s"', $class->name)); } + + $exporter->setMetadata($metadata); + $exporter->export(); + + $ui->newLine(); + $ui->text( + sprintf( + 'Exporting "%s" mapping information to "%s"', + $toType, + $destPath + ) + ); + + return 0; } /** diff --git a/lib/Doctrine/ORM/Tools/Console/Command/EnsureProductionSettingsCommand.php b/lib/Doctrine/ORM/Tools/Console/Command/EnsureProductionSettingsCommand.php index 3601570eb32..eb0ff17567d 100644 --- a/lib/Doctrine/ORM/Tools/Console/Command/EnsureProductionSettingsCommand.php +++ b/lib/Doctrine/ORM/Tools/Console/Command/EnsureProductionSettingsCommand.php @@ -20,9 +20,11 @@ namespace Doctrine\ORM\Tools\Console\Command; use Symfony\Component\Console\Command\Command; -use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; +use Symfony\Component\Console\Style\SymfonyStyle; +use Throwable; /** * Command to ensure that Doctrine is properly configured for a production environment. @@ -42,19 +44,10 @@ class EnsureProductionSettingsCommand extends Command */ protected function configure() { - $this - ->setName('orm:ensure-production-settings') - ->setDescription('Verify that Doctrine is properly configured for a production environment.') - ->setDefinition(array( - new InputOption( - 'complete', null, InputOption::VALUE_NONE, - 'Flag to also inspect database connection existence.' - ) - )) - ->setHelp(<<setName('orm:ensure-production-settings') + ->setDescription('Verify that Doctrine is properly configured for a production environment') + ->addOption('complete', null, InputOption::VALUE_NONE, 'Flag to also inspect database connection existence.') + ->setHelp('Verify that Doctrine is properly configured for a production environment.'); } /** @@ -62,6 +55,8 @@ protected function configure() */ protected function execute(InputInterface $input, OutputInterface $output) { + $ui = new SymfonyStyle($input, $output); + $em = $this->getHelper('em')->getEntityManager(); try { @@ -70,12 +65,14 @@ protected function execute(InputInterface $input, OutputInterface $output) if ($input->getOption('complete') !== null) { $em->getConnection()->connect(); } - } catch (\Exception $e) { - $output->writeln('' . $e->getMessage() . ''); + } catch (Throwable $e) { + $ui->error($e->getMessage()); return 1; } - $output->writeln('Environment is correctly configured for production.'); + $ui->success('Environment is correctly configured for production.'); + + return 0; } } diff --git a/lib/Doctrine/ORM/Tools/Console/Command/GenerateEntitiesCommand.php b/lib/Doctrine/ORM/Tools/Console/Command/GenerateEntitiesCommand.php index bca32b7ec93..f1bba22d2c9 100644 --- a/lib/Doctrine/ORM/Tools/Console/Command/GenerateEntitiesCommand.php +++ b/lib/Doctrine/ORM/Tools/Console/Command/GenerateEntitiesCommand.php @@ -19,14 +19,15 @@ namespace Doctrine\ORM\Tools\Console\Command; -use Symfony\Component\Console\Input\InputArgument; -use Symfony\Component\Console\Input\InputOption; use Doctrine\ORM\Tools\Console\MetadataFilter; -use Doctrine\ORM\Tools\EntityGenerator; use Doctrine\ORM\Tools\DisconnectedClassMetadataFactory; -use Symfony\Component\Console\Output\OutputInterface; -use Symfony\Component\Console\Input\InputInterface; +use Doctrine\ORM\Tools\EntityGenerator; use Symfony\Component\Console\Command\Command; +use Symfony\Component\Console\Input\InputArgument; +use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Input\InputOption; +use Symfony\Component\Console\Output\OutputInterface; +use Symfony\Component\Console\Style\SymfonyStyle; /** * Command to generate entity classes and method stubs from your mapping information. @@ -37,6 +38,8 @@ * @author Guilherme Blanco * @author Jonathan Wage * @author Roman Borschel + * + * @deprecated 2.7 This class is being removed from the ORM and won't have any replacement */ class GenerateEntitiesCommand extends Command { @@ -45,48 +48,19 @@ class GenerateEntitiesCommand extends Command */ protected function configure() { - $this - ->setName('orm:generate-entities') - ->setAliases(array('orm:generate:entities')) - ->setDescription('Generate entity classes and method stubs from your mapping information.') - ->setDefinition(array( - new InputOption( - 'filter', null, InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY, - 'A string pattern used to match entities that should be processed.' - ), - new InputArgument( - 'dest-path', InputArgument::REQUIRED, 'The path to generate your entity classes.' - ), - new InputOption( - 'generate-annotations', null, InputOption::VALUE_OPTIONAL, - 'Flag to define if generator should generate annotation metadata on entities.', false - ), - new InputOption( - 'generate-methods', null, InputOption::VALUE_OPTIONAL, - 'Flag to define if generator should generate stub methods on entities.', true - ), - new InputOption( - 'regenerate-entities', null, InputOption::VALUE_OPTIONAL, - 'Flag to define if generator should regenerate entity if it exists.', false - ), - new InputOption( - 'update-entities', null, InputOption::VALUE_OPTIONAL, - 'Flag to define if generator should only update entity if it exists.', true - ), - new InputOption( - 'extend', null, InputOption::VALUE_REQUIRED, - 'Defines a base class to be extended by generated entity classes.' - ), - new InputOption( - 'num-spaces', null, InputOption::VALUE_REQUIRED, - 'Defines the number of indentation spaces', 4 - ), - new InputOption( - 'no-backup', null, InputOption::VALUE_NONE, - 'Flag to define if generator should avoid backuping existing entity file if it exists.' - ) - )) - ->setHelp(<<setName('orm:generate-entities') + ->setAliases(['orm:generate:entities']) + ->setDescription('Generate entity classes and method stubs from your mapping information') + ->addArgument('dest-path', InputArgument::REQUIRED, 'The path to generate your entity classes.') + ->addOption('filter', null, InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY, 'A string pattern used to match entities that should be processed.') + ->addOption('generate-annotations', null, InputOption::VALUE_OPTIONAL, 'Flag to define if generator should generate annotation metadata on entities.', false) + ->addOption('generate-methods', null, InputOption::VALUE_OPTIONAL, 'Flag to define if generator should generate stub methods on entities.', true) + ->addOption('regenerate-entities', null, InputOption::VALUE_OPTIONAL, 'Flag to define if generator should regenerate entity if it exists.', false) + ->addOption('update-entities', null, InputOption::VALUE_OPTIONAL, 'Flag to define if generator should only update entity if it exists.', true) + ->addOption('extend', null, InputOption::VALUE_REQUIRED, 'Defines a base class to be extended by generated entity classes.') + ->addOption('num-spaces', null, InputOption::VALUE_REQUIRED, 'Defines the number of indentation spaces', 4) + ->addOption('no-backup', null, InputOption::VALUE_NONE, 'Flag to define if generator should avoid backuping existing entity file if it exists.') + ->setHelp(<<--update-entities or --regenerate-entities flags your existing @@ -106,7 +80,7 @@ protected function configure() class is supposed to extend which. You have to adjust the entity code manually for inheritance to work! EOT - ); + ); } /** @@ -114,6 +88,9 @@ class is supposed to extend which. You have to adjust the entity */ protected function execute(InputInterface $input, OutputInterface $output) { + $ui = new SymfonyStyle($input, $output); + $ui->warning('Command ' . $this->getName() . ' is deprecated and will be removed in Doctrine ORM 3.0.'); + $em = $this->getHelper('em')->getEntityManager(); $cmf = new DisconnectedClassMetadataFactory(); @@ -136,34 +113,35 @@ protected function execute(InputInterface $input, OutputInterface $output) ); } - if (count($metadatas)) { - // Create EntityGenerator - $entityGenerator = new EntityGenerator(); - - $entityGenerator->setGenerateAnnotations($input->getOption('generate-annotations')); - $entityGenerator->setGenerateStubMethods($input->getOption('generate-methods')); - $entityGenerator->setRegenerateEntityIfExists($input->getOption('regenerate-entities')); - $entityGenerator->setUpdateEntityIfExists($input->getOption('update-entities')); - $entityGenerator->setNumSpaces($input->getOption('num-spaces')); - $entityGenerator->setBackupExisting(!$input->getOption('no-backup')); - - if (($extend = $input->getOption('extend')) !== null) { - $entityGenerator->setClassToExtend($extend); - } - - foreach ($metadatas as $metadata) { - $output->writeln( - sprintf('Processing entity "%s"', $metadata->name) - ); - } - - // Generating Entities - $entityGenerator->generate($metadatas, $destPath); - - // Outputting information message - $output->writeln(PHP_EOL . sprintf('Entity classes generated to "%s"', $destPath)); - } else { - $output->writeln('No Metadata Classes to process.'); + if (empty($metadatas)) { + $ui->success('No Metadata Classes to process.'); + return 0; + } + + $entityGenerator = new EntityGenerator(); + + $entityGenerator->setGenerateAnnotations($input->getOption('generate-annotations')); + $entityGenerator->setGenerateStubMethods($input->getOption('generate-methods')); + $entityGenerator->setRegenerateEntityIfExists($input->getOption('regenerate-entities')); + $entityGenerator->setUpdateEntityIfExists($input->getOption('update-entities')); + $entityGenerator->setNumSpaces($input->getOption('num-spaces')); + $entityGenerator->setBackupExisting(!$input->getOption('no-backup')); + + if (($extend = $input->getOption('extend')) !== null) { + $entityGenerator->setClassToExtend($extend); + } + + foreach ($metadatas as $metadata) { + $ui->text(sprintf('Processing entity "%s"', $metadata->name)); } + + // Generating Entities + $entityGenerator->generate($metadatas, $destPath); + + // Outputting information message + $ui->newLine(); + $ui->success(sprintf('Entity classes generated to "%s"', $destPath)); + + return 0; } } diff --git a/lib/Doctrine/ORM/Tools/Console/Command/GenerateProxiesCommand.php b/lib/Doctrine/ORM/Tools/Console/Command/GenerateProxiesCommand.php index 21edb9dab83..2cace34345c 100644 --- a/lib/Doctrine/ORM/Tools/Console/Command/GenerateProxiesCommand.php +++ b/lib/Doctrine/ORM/Tools/Console/Command/GenerateProxiesCommand.php @@ -19,12 +19,14 @@ namespace Doctrine\ORM\Tools\Console\Command; +use Doctrine\ORM\EntityManagerInterface; +use Doctrine\ORM\Tools\Console\MetadataFilter; +use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputArgument; +use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; -use Doctrine\ORM\Tools\Console\MetadataFilter; use Symfony\Component\Console\Output\OutputInterface; -use Symfony\Component\Console\Input\InputInterface; -use Symfony\Component\Console\Command\Command; +use Symfony\Component\Console\Style\SymfonyStyle; /** * Command to (re)generate the proxy classes used by doctrine. @@ -43,24 +45,12 @@ class GenerateProxiesCommand extends Command */ protected function configure() { - $this - ->setName('orm:generate-proxies') - ->setAliases(array('orm:generate:proxies')) - ->setDescription('Generates proxy classes for entity classes.') - ->setDefinition(array( - new InputOption( - 'filter', null, InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY, - 'A string pattern used to match entities that should be processed.' - ), - new InputArgument( - 'dest-path', InputArgument::OPTIONAL, - 'The path to generate your proxy classes. If none is provided, it will attempt to grab from configuration.' - ), - )) - ->setHelp(<<setName('orm:generate-proxies') + ->setAliases(['orm:generate:proxies']) + ->setDescription('Generates proxy classes for entity classes') + ->addArgument('dest-path', InputArgument::OPTIONAL, 'The path to generate your proxy classes. If none is provided, it will attempt to grab from configuration.') + ->addOption('filter', null, InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY, 'A string pattern used to match entities that should be processed.') + ->setHelp('Generates proxy classes for entity classes.'); } /** @@ -68,6 +58,9 @@ protected function configure() */ protected function execute(InputInterface $input, OutputInterface $output) { + $ui = new SymfonyStyle($input, $output); + + /** @var EntityManagerInterface $em */ $em = $this->getHelper('em')->getEntityManager(); $metadatas = $em->getMetadataFactory()->getAllMetadata(); @@ -96,20 +89,22 @@ protected function execute(InputInterface $input, OutputInterface $output) ); } - if ( count($metadatas)) { - foreach ($metadatas as $metadata) { - $output->writeln( - sprintf('Processing entity "%s"', $metadata->name) - ); - } - - // Generating Proxies - $em->getProxyFactory()->generateProxyClasses($metadatas, $destPath); + if (empty($metadatas)) { + $ui->success('No Metadata Classes to process.'); + return 0; + } - // Outputting information message - $output->writeln(PHP_EOL . sprintf('Proxy classes generated to "%s"', $destPath)); - } else { - $output->writeln('No Metadata Classes to process.'); + foreach ($metadatas as $metadata) { + $ui->text(sprintf('Processing entity "%s"', $metadata->name)); } + + // Generating Proxies + $em->getProxyFactory()->generateProxyClasses($metadatas, $destPath); + + // Outputting information message + $ui->newLine(); + $ui->text(sprintf('Proxy classes generated to "%s"', $destPath)); + + return 0; } } diff --git a/lib/Doctrine/ORM/Tools/Console/Command/GenerateRepositoriesCommand.php b/lib/Doctrine/ORM/Tools/Console/Command/GenerateRepositoriesCommand.php index d0cb053e90d..379c93597f6 100644 --- a/lib/Doctrine/ORM/Tools/Console/Command/GenerateRepositoriesCommand.php +++ b/lib/Doctrine/ORM/Tools/Console/Command/GenerateRepositoriesCommand.php @@ -19,13 +19,14 @@ namespace Doctrine\ORM\Tools\Console\Command; -use Symfony\Component\Console\Input\InputArgument; -use Symfony\Component\Console\Input\InputOption; use Doctrine\ORM\Tools\Console\MetadataFilter; use Doctrine\ORM\Tools\EntityRepositoryGenerator; -use Symfony\Component\Console\Output\OutputInterface; -use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Command\Command; +use Symfony\Component\Console\Input\InputArgument; +use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Input\InputOption; +use Symfony\Component\Console\Output\OutputInterface; +use Symfony\Component\Console\Style\SymfonyStyle; /** * Command to generate repository classes for mapping information. @@ -36,6 +37,8 @@ * @author Guilherme Blanco * @author Jonathan Wage * @author Roman Borschel + * + * @deprecated 2.7 This class is being removed from the ORM and won't have any replacement */ class GenerateRepositoriesCommand extends Command { @@ -44,23 +47,12 @@ class GenerateRepositoriesCommand extends Command */ protected function configure() { - $this - ->setName('orm:generate-repositories') - ->setAliases(array('orm:generate:repositories')) - ->setDescription('Generate repository classes from your mapping information.') - ->setDefinition(array( - new InputOption( - 'filter', null, InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY, - 'A string pattern used to match entities that should be processed.' - ), - new InputArgument( - 'dest-path', InputArgument::REQUIRED, 'The path to generate your repository classes.' - ) - )) - ->setHelp(<<setName('orm:generate-repositories') + ->setAliases(['orm:generate:repositories']) + ->setDescription('Generate repository classes from your mapping information') + ->addArgument('dest-path', InputArgument::REQUIRED, 'The path to generate your repository classes.') + ->addOption('filter', null, InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY, 'A string pattern used to match entities that should be processed.') + ->setHelp('Generate repository classes from your mapping information.'); } /** @@ -68,6 +60,9 @@ protected function configure() */ protected function execute(InputInterface $input, OutputInterface $output) { + $ui = new SymfonyStyle($input, $output); + $ui->warning('Command ' . $this->getName() . ' is deprecated and will be removed in Doctrine ORM 3.0.'); + $em = $this->getHelper('em')->getEntityManager(); $metadatas = $em->getMetadataFactory()->getAllMetadata(); @@ -90,32 +85,35 @@ protected function execute(InputInterface $input, OutputInterface $output) ); } - if (count($metadatas)) { - $numRepositories = 0; - $generator = new EntityRepositoryGenerator(); + if (empty($metadatas)) { + $ui->success('No Metadata Classes to process.'); + return 0; + } - $generator->setDefaultRepositoryName($repositoryName); + $numRepositories = 0; + $generator = new EntityRepositoryGenerator(); - foreach ($metadatas as $metadata) { - if ($metadata->customRepositoryClassName) { - $output->writeln( - sprintf('Processing repository "%s"', $metadata->customRepositoryClassName) - ); + $generator->setDefaultRepositoryName($repositoryName); - $generator->writeEntityRepositoryClass($metadata->customRepositoryClassName, $destPath); + foreach ($metadatas as $metadata) { + if ($metadata->customRepositoryClassName) { + $ui->text(sprintf('Processing repository "%s"', $metadata->customRepositoryClassName)); - $numRepositories++; - } - } + $generator->writeEntityRepositoryClass($metadata->customRepositoryClassName, $destPath); - if ($numRepositories) { - // Outputting information message - $output->writeln(PHP_EOL . sprintf('Repository classes generated to "%s"', $destPath)); - } else { - $output->writeln('No Repository classes were found to be processed.'); + ++$numRepositories; } - } else { - $output->writeln('No Metadata Classes to process.'); } + + if ($numRepositories === 0) { + $ui->text('No Repository classes were found to be processed.'); + return 0; + } + + // Outputting information message + $ui->newLine(); + $ui->text(sprintf('Repository classes generated to "%s"', $destPath)); + + return 0; } } diff --git a/lib/Doctrine/ORM/Tools/Console/Command/InfoCommand.php b/lib/Doctrine/ORM/Tools/Console/Command/InfoCommand.php index 560d18718b5..89f6c318576 100644 --- a/lib/Doctrine/ORM/Tools/Console/Command/InfoCommand.php +++ b/lib/Doctrine/ORM/Tools/Console/Command/InfoCommand.php @@ -20,9 +20,10 @@ namespace Doctrine\ORM\Tools\Console\Command; use Doctrine\ORM\Mapping\MappingException; +use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; -use Symfony\Component\Console\Command\Command; +use Symfony\Component\Console\Style\SymfonyStyle; /** * Show information about mapped entities. @@ -38,15 +39,14 @@ class InfoCommand extends Command */ protected function configure() { - $this - ->setName('orm:info') - ->setDescription('Show basic information about all mapped entities') - ->setHelp(<<setName('orm:info') + ->setDescription('Show basic information about all mapped entities') + ->setHelp(<<%command.name% shows basic information about which entities exist and possibly if their mapping information contains errors or not. EOT - ); + ); } /** @@ -54,6 +54,8 @@ protected function configure() */ protected function execute(InputInterface $input, OutputInterface $output) { + $ui = new SymfonyStyle($input, $output); + /* @var $entityManager \Doctrine\ORM\EntityManager */ $entityManager = $this->getHelper('em')->getEntityManager(); @@ -61,25 +63,34 @@ protected function execute(InputInterface $input, OutputInterface $output) ->getMetadataDriverImpl() ->getAllClassNames(); - if (!$entityClassNames) { - throw new \Exception( - 'You do not have any mapped Doctrine ORM entities according to the current configuration. '. - 'If you have entities or mapping files you should check your mapping configuration for errors.' + if ( ! $entityClassNames) { + $ui->caution( + [ + 'You do not have any mapped Doctrine ORM entities according to the current configuration.', + 'If you have entities or mapping files you should check your mapping configuration for errors.' + ] ); + + return 1; } - $output->writeln(sprintf("Found %d mapped entities:", count($entityClassNames))); + $ui->text(sprintf("Found %d mapped entities:", count($entityClassNames))); + $ui->newLine(); $failure = false; foreach ($entityClassNames as $entityClassName) { try { $entityManager->getClassMetadata($entityClassName); - $output->writeln(sprintf("[OK] %s", $entityClassName)); + $ui->text(sprintf("[OK] %s", $entityClassName)); } catch (MappingException $e) { - $output->writeln("[FAIL] ".$entityClassName); - $output->writeln(sprintf("%s", $e->getMessage())); - $output->writeln(''); + $ui->text( + [ + sprintf("[FAIL] %s", $entityClassName), + sprintf("%s", $e->getMessage()), + '' + ] + ); $failure = true; } diff --git a/lib/Doctrine/ORM/Tools/Console/Command/MappingDescribeCommand.php b/lib/Doctrine/ORM/Tools/Console/Command/MappingDescribeCommand.php index d80ac94516a..0e1f505f034 100644 --- a/lib/Doctrine/ORM/Tools/Console/Command/MappingDescribeCommand.php +++ b/lib/Doctrine/ORM/Tools/Console/Command/MappingDescribeCommand.php @@ -22,10 +22,14 @@ use Doctrine\Common\Persistence\Mapping\MappingException; use Doctrine\ORM\EntityManagerInterface; use Symfony\Component\Console\Command\Command; -use Symfony\Component\Console\Helper\Table; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; +use Symfony\Component\Console\Style\SymfonyStyle; +use const JSON_PRETTY_PRINT; +use const JSON_UNESCAPED_SLASHES; +use const JSON_UNESCAPED_UNICODE; +use function json_encode; /** * Show information about mapped entities. @@ -41,11 +45,10 @@ final class MappingDescribeCommand extends Command */ protected function configure() { - $this - ->setName('orm:mapping:describe') - ->addArgument('entityName', InputArgument::REQUIRED, 'Full or partial name of entity') - ->setDescription('Display information about mapped objects') - ->setHelp(<<setName('orm:mapping:describe') + ->addArgument('entityName', InputArgument::REQUIRED, 'Full or partial name of entity') + ->setDescription('Display information about mapped objects') + ->setHelp(<<%command.full_name% My\Namespace\Entity\MyEntity @@ -54,7 +57,7 @@ protected function configure() %command.full_name% MyEntity EOT - ); + ); } /** @@ -62,10 +65,12 @@ protected function configure() */ protected function execute(InputInterface $input, OutputInterface $output) { + $ui = new SymfonyStyle($input, $output); + /* @var $entityManager \Doctrine\ORM\EntityManagerInterface */ $entityManager = $this->getHelper('em')->getEntityManager(); - $this->displayEntity($input->getArgument('entityName'), $entityManager, $output); + $this->displayEntity($input->getArgument('entityName'), $entityManager, $ui); return 0; } @@ -75,20 +80,16 @@ protected function execute(InputInterface $input, OutputInterface $output) * * @param string $entityName Full or partial entity class name * @param EntityManagerInterface $entityManager - * @param OutputInterface $output + * @param SymfonyStyle $ui */ - private function displayEntity($entityName, EntityManagerInterface $entityManager, OutputInterface $output) + private function displayEntity($entityName, EntityManagerInterface $entityManager, SymfonyStyle $ui) { - $table = new Table($output); - - $table->setHeaders(array('Field', 'Value')); - $metadata = $this->getClassMetadata($entityName, $entityManager); - array_map( - array($table, 'addRow'), + $ui->table( + ['Field', 'Value'], array_merge( - array( + [ $this->formatField('Name', $metadata->name), $this->formatField('Root entity name', $metadata->rootEntityName), $this->formatField('Custom generator definition', $metadata->customGeneratorDefinition), @@ -118,15 +119,13 @@ private function displayEntity($entityName, EntityManagerInterface $entityManage $this->formatField('Read only?', $metadata->isReadOnly), $this->formatEntityListeners($metadata->entityListeners), - ), - array($this->formatField('Association mappings:', '')), + ], + [$this->formatField('Association mappings:', '')], $this->formatMappings($metadata->associationMappings), - array($this->formatField('Field mappings:', '')), + [$this->formatField('Field mappings:', '')], $this->formatMappings($metadata->fieldMappings) ) ); - - $table->render(); } /** @@ -138,10 +137,9 @@ private function displayEntity($entityName, EntityManagerInterface $entityManage */ private function getMappedEntities(EntityManagerInterface $entityManager) { - $entityClassNames = $entityManager - ->getConfiguration() - ->getMetadataDriverImpl() - ->getAllClassNames(); + $entityClassNames = $entityManager->getConfiguration() + ->getMetadataDriverImpl() + ->getAllClassNames(); if ( ! $entityClassNames) { throw new \InvalidArgumentException( @@ -185,7 +183,7 @@ function ($mappedEntity) use ($entityName) { if (count($matches) > 1) { throw new \InvalidArgumentException(sprintf( - 'Entity name "%s" is ambigous, possible matches: "%s"', + 'Entity name "%s" is ambiguous, possible matches: "%s"', $entityName, implode(', ', $matches) )); } @@ -219,11 +217,7 @@ private function formatValue($value) } if (is_array($value)) { - if (defined('JSON_UNESCAPED_UNICODE') && defined('JSON_UNESCAPED_SLASHES')) { - return json_encode($value, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); - } - - return json_encode($value); + return json_encode($value, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT); } if (is_object($value)) { @@ -251,7 +245,7 @@ private function formatField($label, $value) $value = 'None'; } - return array(sprintf('%s', $label), $this->formatValue($value)); + return [sprintf('%s', $label), $this->formatValue($value)]; } /** @@ -263,7 +257,7 @@ private function formatField($label, $value) */ private function formatMappings(array $propertyMappings) { - $output = array(); + $output = []; foreach ($propertyMappings as $propertyName => $mapping) { $output[] = $this->formatField(sprintf(' %s', $propertyName), ''); @@ -285,14 +279,6 @@ private function formatMappings(array $propertyMappings) */ private function formatEntityListeners(array $entityListeners) { - return $this->formatField( - 'Entity listeners', - array_map( - function ($entityListener) { - return get_class($entityListener); - }, - $entityListeners - ) - ); + return $this->formatField('Entity listeners', array_map('get_class', $entityListeners)); } } diff --git a/lib/Doctrine/ORM/Tools/Console/Command/RunDqlCommand.php b/lib/Doctrine/ORM/Tools/Console/Command/RunDqlCommand.php index abd999aef09..7f4069202bf 100644 --- a/lib/Doctrine/ORM/Tools/Console/Command/RunDqlCommand.php +++ b/lib/Doctrine/ORM/Tools/Console/Command/RunDqlCommand.php @@ -19,12 +19,13 @@ namespace Doctrine\ORM\Tools\Console\Command; +use Doctrine\Common\Util\Debug; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputArgument; -use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; -use Doctrine\Common\Util\Debug; +use Symfony\Component\Console\Style\SymfonyStyle; /** * Command to execute DQL queries in a given EntityManager. @@ -43,37 +44,15 @@ class RunDqlCommand extends Command */ protected function configure() { - $this - ->setName('orm:run-dql') - ->setDescription('Executes arbitrary DQL directly from the command line.') - ->setDefinition(array( - new InputArgument('dql', InputArgument::REQUIRED, 'The DQL to execute.'), - new InputOption( - 'hydrate', null, InputOption::VALUE_REQUIRED, - 'Hydration mode of result set. Should be either: object, array, scalar or single-scalar.', - 'object' - ), - new InputOption( - 'first-result', null, InputOption::VALUE_REQUIRED, - 'The first result in the result set.' - ), - new InputOption( - 'max-result', null, InputOption::VALUE_REQUIRED, - 'The maximum number of results in the result set.' - ), - new InputOption( - 'depth', null, InputOption::VALUE_REQUIRED, - 'Dumping depth of Entity graph.', 7 - ), - new InputOption( - 'show-sql', null, InputOption::VALUE_NONE, - 'Dump generated SQL instead of executing query' - ) - )) - ->setHelp(<<setName('orm:run-dql') + ->setDescription('Executes arbitrary DQL directly from the command line') + ->addArgument('dql', InputArgument::REQUIRED, 'The DQL to execute.') + ->addOption('hydrate', null, InputOption::VALUE_REQUIRED, 'Hydration mode of result set. Should be either: object, array, scalar or single-scalar.', 'object') + ->addOption('first-result', null, InputOption::VALUE_REQUIRED, 'The first result in the result set.') + ->addOption('max-result', null, InputOption::VALUE_REQUIRED, 'The maximum number of results in the result set.') + ->addOption('depth', null, InputOption::VALUE_REQUIRED, 'Dumping depth of Entity graph.', 7) + ->addOption('show-sql', null, InputOption::VALUE_NONE, 'Dump generated SQL instead of executing query') + ->setHelp('Executes arbitrary DQL directly from the command line.'); } /** @@ -81,17 +60,19 @@ protected function configure() */ protected function execute(InputInterface $input, OutputInterface $output) { + $ui = new SymfonyStyle($input, $output); + /* @var $em \Doctrine\ORM\EntityManagerInterface */ $em = $this->getHelper('em')->getEntityManager(); if (($dql = $input->getArgument('dql')) === null) { - throw new \RuntimeException("Argument 'DQL' is required in order to execute this command correctly."); + throw new \RuntimeException("Argument 'dql' is required in order to execute this command correctly."); } $depth = $input->getOption('depth'); if ( ! is_numeric($depth)) { - throw new \LogicException("Option 'depth' must contains an integer value"); + throw new \LogicException("Option 'depth' must contain an integer value"); } $hydrationModeName = $input->getOption('hydrate'); @@ -107,7 +88,7 @@ protected function execute(InputInterface $input, OutputInterface $output) if (($firstResult = $input->getOption('first-result')) !== null) { if ( ! is_numeric($firstResult)) { - throw new \LogicException("Option 'first-result' must contains an integer value"); + throw new \LogicException("Option 'first-result' must contain an integer value"); } $query->setFirstResult((int) $firstResult); @@ -115,19 +96,21 @@ protected function execute(InputInterface $input, OutputInterface $output) if (($maxResult = $input->getOption('max-result')) !== null) { if ( ! is_numeric($maxResult)) { - throw new \LogicException("Option 'max-result' must contains an integer value"); + throw new \LogicException("Option 'max-result' must contain an integer value"); } $query->setMaxResults((int) $maxResult); } if ($input->getOption('show-sql')) { - $output->writeln(Debug::dump($query->getSQL(), 2, true, false)); - return; + $ui->text($query->getSQL()); + return 0; } - $resultSet = $query->execute(array(), constant($hydrationMode)); + $resultSet = $query->execute([], constant($hydrationMode)); + + $ui->text(Debug::dump($resultSet, $input->getOption('depth'), true, false)); - $output->writeln(Debug::dump($resultSet, $input->getOption('depth'), true, false)); + return 0; } } diff --git a/lib/Doctrine/ORM/Tools/Console/Command/SchemaTool/AbstractCommand.php b/lib/Doctrine/ORM/Tools/Console/Command/SchemaTool/AbstractCommand.php index dc7e7ec7e86..21907d094a1 100644 --- a/lib/Doctrine/ORM/Tools/Console/Command/SchemaTool/AbstractCommand.php +++ b/lib/Doctrine/ORM/Tools/Console/Command/SchemaTool/AbstractCommand.php @@ -19,10 +19,11 @@ namespace Doctrine\ORM\Tools\Console\Command\SchemaTool; +use Doctrine\ORM\Tools\SchemaTool; +use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; -use Symfony\Component\Console\Command\Command; -use Doctrine\ORM\Tools\SchemaTool; +use Symfony\Component\Console\Style\SymfonyStyle; /** * Base class for CreateCommand, DropCommand and UpdateCommand. @@ -44,13 +45,15 @@ abstract class AbstractCommand extends Command * * @return null|int Null or 0 if everything went fine, or an error code. */ - abstract protected function executeSchemaCommand(InputInterface $input, OutputInterface $output, SchemaTool $schemaTool, array $metadatas); + abstract protected function executeSchemaCommand(InputInterface $input, OutputInterface $output, SchemaTool $schemaTool, array $metadatas, SymfonyStyle $ui); /** * {@inheritdoc} */ protected function execute(InputInterface $input, OutputInterface $output) { + $ui = new SymfonyStyle($input, $output); + $emHelper = $this->getHelper('em'); /* @var $em \Doctrine\ORM\EntityManager */ @@ -58,15 +61,12 @@ protected function execute(InputInterface $input, OutputInterface $output) $metadatas = $em->getMetadataFactory()->getAllMetadata(); - if ( ! empty($metadatas)) { - // Create SchemaTool - $tool = new SchemaTool($em); - - return $this->executeSchemaCommand($input, $output, $tool, $metadatas); - } else { - $output->writeln('No Metadata Classes to process.'); + if (empty($metadatas)) { + $ui->success('No Metadata Classes to process.'); return 0; } + + return $this->executeSchemaCommand($input, $output, new SchemaTool($em), $metadatas, $ui); } } diff --git a/lib/Doctrine/ORM/Tools/Console/Command/SchemaTool/CreateCommand.php b/lib/Doctrine/ORM/Tools/Console/Command/SchemaTool/CreateCommand.php index b2af0ca2cfd..0c2137417b3 100644 --- a/lib/Doctrine/ORM/Tools/Console/Command/SchemaTool/CreateCommand.php +++ b/lib/Doctrine/ORM/Tools/Console/Command/SchemaTool/CreateCommand.php @@ -19,10 +19,11 @@ namespace Doctrine\ORM\Tools\Console\Command\SchemaTool; -use Symfony\Component\Console\Input\InputOption; +use Doctrine\ORM\Tools\SchemaTool; use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; -use Doctrine\ORM\Tools\SchemaTool; +use Symfony\Component\Console\Style\SymfonyStyle; /** * Command to create the database schema for a set of classes based on their mappings. @@ -41,18 +42,10 @@ class CreateCommand extends AbstractCommand */ protected function configure() { - $this - ->setName('orm:schema-tool:create') - ->setDescription( - 'Processes the schema and either create it directly on EntityManager Storage Connection or generate the SQL output.' - ) - ->setDefinition(array( - new InputOption( - 'dump-sql', null, InputOption::VALUE_NONE, - 'Instead of trying to apply generated SQLs into EntityManager Storage Connection, output them.' - ) - )) - ->setHelp(<<setName('orm:schema-tool:create') + ->setDescription('Processes the schema and either create it directly on EntityManager Storage Connection or generate the SQL output') + ->addOption('dump-sql', null, InputOption::VALUE_NONE, 'Instead of trying to apply generated SQLs into EntityManager Storage Connection, output them.') + ->setHelp(<<Hint: If you have a database with tables that should not be managed @@ -61,25 +54,37 @@ protected function configure() \$config->setFilterSchemaAssetsExpression(\$regexp); EOT - ); + ); } /** * {@inheritdoc} */ - protected function executeSchemaCommand(InputInterface $input, OutputInterface $output, SchemaTool $schemaTool, array $metadatas) + protected function executeSchemaCommand(InputInterface $input, OutputInterface $output, SchemaTool $schemaTool, array $metadatas, SymfonyStyle $ui) { - if ($input->getOption('dump-sql')) { + $dumpSql = true === $input->getOption('dump-sql'); + + if ($dumpSql) { $sqls = $schemaTool->getCreateSchemaSql($metadatas); - $output->writeln(implode(';' . PHP_EOL, $sqls) . ';'); - } else { - $output->writeln('ATTENTION: This operation should not be executed in a production environment.' . PHP_EOL); + $ui->text('The following SQL statements will be executed:'); + $ui->newLine(); - $output->writeln('Creating database schema...'); - $schemaTool->createSchema($metadatas); - $output->writeln('Database schema created successfully!'); + foreach ($sqls as $sql) { + $ui->text(sprintf(' %s;', $sql)); + } + + return 0; } + $ui->caution('This operation should not be executed in a production environment!'); + + $ui->text('Creating database schema...'); + $ui->newLine(); + + $schemaTool->createSchema($metadatas); + + $ui->success('Database schema created successfully!'); + return 0; } } diff --git a/lib/Doctrine/ORM/Tools/Console/Command/SchemaTool/DropCommand.php b/lib/Doctrine/ORM/Tools/Console/Command/SchemaTool/DropCommand.php index b22237831ee..3d77fc8fd84 100644 --- a/lib/Doctrine/ORM/Tools/Console/Command/SchemaTool/DropCommand.php +++ b/lib/Doctrine/ORM/Tools/Console/Command/SchemaTool/DropCommand.php @@ -19,10 +19,11 @@ namespace Doctrine\ORM\Tools\Console\Command\SchemaTool; -use Symfony\Component\Console\Input\InputOption; +use Doctrine\ORM\Tools\SchemaTool; use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; -use Doctrine\ORM\Tools\SchemaTool; +use Symfony\Component\Console\Style\SymfonyStyle; /** * Command to drop the database schema for a set of classes based on their mappings. @@ -41,26 +42,12 @@ class DropCommand extends AbstractCommand */ protected function configure() { - $this - ->setName('orm:schema-tool:drop') - ->setDescription( - 'Drop the complete database schema of EntityManager Storage Connection or generate the corresponding SQL output.' - ) - ->setDefinition(array( - new InputOption( - 'dump-sql', null, InputOption::VALUE_NONE, - 'Instead of trying to apply generated SQLs into EntityManager Storage Connection, output them.' - ), - new InputOption( - 'force', 'f', InputOption::VALUE_NONE, - "Don't ask for the deletion of the database, but force the operation to run." - ), - new InputOption( - 'full-database', null, InputOption::VALUE_NONE, - 'Instead of using the Class Metadata to detect the database table schema, drop ALL assets that the database contains.' - ), - )) - ->setHelp(<<setName('orm:schema-tool:drop') + ->setDescription('Drop the complete database schema of EntityManager Storage Connection or generate the corresponding SQL output') + ->addOption('dump-sql', null, InputOption::VALUE_NONE, 'Instead of trying to apply generated SQLs into EntityManager Storage Connection, output them.') + ->addOption('force', 'f', InputOption::VALUE_NONE, "Don't ask for the deletion of the database, but force the operation to run.") + ->addOption('full-database', null, InputOption::VALUE_NONE, 'Instead of using the Class Metadata to detect the database table schema, drop ALL assets that the database contains.') + ->setHelp(<<setFilterSchemaAssetsExpression(\$regexp); EOT - ); + ); } /** * {@inheritdoc} */ - protected function executeSchemaCommand(InputInterface $input, OutputInterface $output, SchemaTool $schemaTool, array $metadatas) + protected function executeSchemaCommand(InputInterface $input, OutputInterface $output, SchemaTool $schemaTool, array $metadatas, SymfonyStyle $ui) { $isFullDatabaseDrop = $input->getOption('full-database'); + $dumpSql = true === $input->getOption('dump-sql'); + $force = true === $input->getOption('force'); - if ($input->getOption('dump-sql')) { + if ($dumpSql) { if ($isFullDatabaseDrop) { $sqls = $schemaTool->getDropDatabaseSQL(); } else { $sqls = $schemaTool->getDropSchemaSQL($metadatas); } - $output->writeln(implode(';' . PHP_EOL, $sqls)); + $ui->text('The following SQL statements will be executed:'); + $ui->newLine(); + + foreach ($sqls as $sql) { + $ui->text(sprintf(' %s;', $sql)); + } return 0; } - if ($input->getOption('force')) { - $output->writeln('Dropping database schema...'); + if ($force) { + $ui->text('Dropping database schema...'); + $ui->newLine(); if ($isFullDatabaseDrop) { $schemaTool->dropDatabase(); @@ -100,12 +95,12 @@ protected function executeSchemaCommand(InputInterface $input, OutputInterface $ $schemaTool->dropSchema($metadatas); } - $output->writeln('Database schema dropped successfully!'); + $ui->success('Database schema dropped successfully!'); return 0; } - $output->writeln('ATTENTION: This operation should not be executed in a production environment.' . PHP_EOL); + $ui->caution('This operation should not be executed in a production environment!'); if ($isFullDatabaseDrop) { $sqls = $schemaTool->getDropDatabaseSQL(); @@ -113,18 +108,23 @@ protected function executeSchemaCommand(InputInterface $input, OutputInterface $ $sqls = $schemaTool->getDropSchemaSQL($metadatas); } - if (count($sqls)) { - $output->writeln(sprintf('The Schema-Tool would execute "%s" queries to update the database.', count($sqls))); - $output->writeln('Please run the operation by passing one - or both - of the following options:'); - - $output->writeln(sprintf(' %s --force to execute the command', $this->getName())); - $output->writeln(sprintf(' %s --dump-sql to dump the SQL statements to the screen', $this->getName())); + if (empty($sqls)) { + $ui->success('Nothing to drop. The database is empty!'); - return 1; + return 0; } - $output->writeln('Nothing to drop. The database is empty!'); + $ui->text( + [ + sprintf('The Schema-Tool would execute "%s" queries to update the database.', count($sqls)), + '', + 'Please run the operation by passing one - or both - of the following options:', + '', + sprintf(' %s --force to execute the command', $this->getName()), + sprintf(' %s --dump-sql to dump the SQL statements to the screen', $this->getName()), + ] + ); - return 0; + return 1; } } diff --git a/lib/Doctrine/ORM/Tools/Console/Command/SchemaTool/UpdateCommand.php b/lib/Doctrine/ORM/Tools/Console/Command/SchemaTool/UpdateCommand.php index d38684ca910..c9059775b1e 100644 --- a/lib/Doctrine/ORM/Tools/Console/Command/SchemaTool/UpdateCommand.php +++ b/lib/Doctrine/ORM/Tools/Console/Command/SchemaTool/UpdateCommand.php @@ -19,10 +19,11 @@ namespace Doctrine\ORM\Tools\Console\Command\SchemaTool; -use Symfony\Component\Console\Input\InputOption; +use Doctrine\ORM\Tools\SchemaTool; use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; -use Doctrine\ORM\Tools\SchemaTool; +use Symfony\Component\Console\Style\SymfonyStyle; /** * Command to generate the SQL needed to update the database schema to match @@ -48,28 +49,12 @@ class UpdateCommand extends AbstractCommand */ protected function configure() { - $this - ->setName($this->name) - ->setDescription( - 'Executes (or dumps) the SQL needed to update the database schema to match the current mapping metadata.' - ) - ->setDefinition(array( - new InputOption( - 'complete', null, InputOption::VALUE_NONE, - 'If defined, all assets of the database which are not relevant to the current metadata will be dropped.' - ), - - new InputOption( - 'dump-sql', null, InputOption::VALUE_NONE, - 'Dumps the generated SQL statements to the screen (does not execute them).' - ), - new InputOption( - 'force', 'f', InputOption::VALUE_NONE, - 'Causes the generated SQL statements to be physically executed against your database.' - ), - )); - - $this->setHelp(<<setName($this->name) + ->setDescription('Executes (or dumps) the SQL needed to update the database schema to match the current mapping metadata') + ->addOption('complete', null, InputOption::VALUE_NONE, 'If defined, all assets of the database which are not relevant to the current metadata will be dropped.') + ->addOption('dump-sql', null, InputOption::VALUE_NONE, 'Dumps the generated SQL statements to the screen (does not execute them).') + ->addOption('force', 'f', InputOption::VALUE_NONE, 'Causes the generated SQL statements to be physically executed against your database.') + ->setHelp(<<%command.name% command generates the SQL needed to synchronize the database schema with the current mapping metadata of the default entity manager. @@ -99,21 +84,21 @@ protected function configure() \$config->setFilterSchemaAssetsExpression(\$regexp); EOT - ); + ); } /** * {@inheritdoc} */ - protected function executeSchemaCommand(InputInterface $input, OutputInterface $output, SchemaTool $schemaTool, array $metadatas) + protected function executeSchemaCommand(InputInterface $input, OutputInterface $output, SchemaTool $schemaTool, array $metadatas, SymfonyStyle $ui) { // Defining if update is complete or not (--complete not defined means $saveMode = true) $saveMode = ! $input->getOption('complete'); $sqls = $schemaTool->getUpdateSchemaSql($metadatas, $saveMode); - if (0 === count($sqls)) { - $output->writeln('Nothing to update - your database is already in sync with the current entity metadata.'); + if (empty($sqls)) { + $ui->success('Nothing to update - your database is already in sync with the current entity metadata.'); return 0; } @@ -122,35 +107,52 @@ protected function executeSchemaCommand(InputInterface $input, OutputInterface $ $force = true === $input->getOption('force'); if ($dumpSql) { - $output->writeln(implode(';' . PHP_EOL, $sqls) . ';'); + $ui->text('The following SQL statements will be executed:'); + $ui->newLine(); + + foreach ($sqls as $sql) { + $ui->text(sprintf(' %s;', $sql)); + } } if ($force) { if ($dumpSql) { - $output->writeln(''); + $ui->newLine(); } - $output->writeln('Updating database schema...'); + $ui->text('Updating database schema...'); + $ui->newLine(); + $schemaTool->updateSchema($metadatas, $saveMode); $pluralization = (1 === count($sqls)) ? 'query was' : 'queries were'; - $output->writeln(sprintf('Database schema updated successfully! "%s" %s executed', count($sqls), $pluralization)); + $ui->text(sprintf(' %s %s executed', count($sqls), $pluralization)); + $ui->success('Database schema updated successfully!'); } if ($dumpSql || $force) { return 0; } - $output->writeln('ATTENTION: This operation should not be executed in a production environment.'); - $output->writeln(' Use the incremental update to detect changes during development and use'); - $output->writeln(' the SQL DDL provided to manually update your database in production.'); - $output->writeln(''); - - $output->writeln(sprintf('The Schema-Tool would execute "%s" queries to update the database.', count($sqls))); - $output->writeln('Please run the operation by passing one - or both - of the following options:'); + $ui->caution( + [ + 'This operation should not be executed in a production environment!', + '', + 'Use the incremental update to detect changes during development and use', + 'the SQL DDL provided to manually update your database in production.', + ] + ); - $output->writeln(sprintf(' %s --force to execute the command', $this->getName())); - $output->writeln(sprintf(' %s --dump-sql to dump the SQL statements to the screen', $this->getName())); + $ui->text( + [ + sprintf('The Schema-Tool would execute "%s" queries to update the database.', count($sqls)), + '', + 'Please run the operation by passing one - or both - of the following options:', + '', + sprintf(' %s --force to execute the command', $this->getName()), + sprintf(' %s --dump-sql to dump the SQL statements to the screen', $this->getName()), + ] + ); return 1; } diff --git a/lib/Doctrine/ORM/Tools/Console/Command/ValidateSchemaCommand.php b/lib/Doctrine/ORM/Tools/Console/Command/ValidateSchemaCommand.php index eb7697ccb73..343d3b53db9 100644 --- a/lib/Doctrine/ORM/Tools/Console/Command/ValidateSchemaCommand.php +++ b/lib/Doctrine/ORM/Tools/Console/Command/ValidateSchemaCommand.php @@ -19,11 +19,12 @@ namespace Doctrine\ORM\Tools\Console\Command; +use Doctrine\ORM\Tools\SchemaValidator; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; -use Doctrine\ORM\Tools\SchemaValidator; +use Symfony\Component\Console\Style\SymfonyStyle; /** * Command to validate that the current mapping is valid. @@ -43,26 +44,11 @@ class ValidateSchemaCommand extends Command */ protected function configure() { - $this - ->setName('orm:validate-schema') - ->setDescription('Validate the mapping files.') - ->addOption( - 'skip-mapping', - null, - InputOption::VALUE_NONE, - 'Skip the mapping validation check' - ) - ->addOption( - 'skip-sync', - null, - InputOption::VALUE_NONE, - 'Skip checking if the mapping is in sync with the database' - ) - ->setHelp( - <<setName('orm:validate-schema') + ->setDescription('Validate the mapping files') + ->addOption('skip-mapping', null, InputOption::VALUE_NONE, 'Skip the mapping validation check') + ->addOption('skip-sync', null, InputOption::VALUE_NONE, 'Skip checking if the mapping is in sync with the database') + ->setHelp('Validate that the mapping files are correct and in sync with the database.'); } /** @@ -70,35 +56,43 @@ protected function configure() */ protected function execute(InputInterface $input, OutputInterface $output) { + $ui = new SymfonyStyle($input, $output); + $em = $this->getHelper('em')->getEntityManager(); $validator = new SchemaValidator($em); $exit = 0; + $ui->section('Mapping'); + if ($input->getOption('skip-mapping')) { - $output->writeln('[Mapping] Skipped mapping check.'); + $ui->text('[SKIPPED] The mapping was not checked.'); } elseif ($errors = $validator->validateMapping()) { foreach ($errors as $className => $errorMessages) { - $output->writeln("[Mapping] FAIL - The entity-class '" . $className . "' mapping is invalid:"); - - foreach ($errorMessages as $errorMessage) { - $output->writeln('* ' . $errorMessage); - } + $ui->text( + sprintf( + '[FAIL] The entity-class %s mapping is invalid:', + $className + ) + ); - $output->writeln(''); + $ui->listing($errorMessages); + $ui->newLine(); } - $exit += 1; + ++$exit; } else { - $output->writeln('[Mapping] OK - The mapping files are correct.'); + $ui->success('The mapping files are correct.'); } + $ui->section('Database'); + if ($input->getOption('skip-sync')) { - $output->writeln('[Database] SKIPPED - The database was not checked for synchronicity.'); - } elseif (!$validator->schemaInSyncWithMetadata()) { - $output->writeln('[Database] FAIL - The database schema is not in sync with the current mapping file.'); + $ui->text('[SKIPPED] The database was not checked for synchronicity.'); + } elseif ( ! $validator->schemaInSyncWithMetadata()) { + $ui->error('The database schema is not in sync with the current mapping file.'); $exit += 2; } else { - $output->writeln('[Database] OK - The database schema is in sync with the mapping files.'); + $ui->success('The database schema is in sync with the mapping files.'); } return $exit; diff --git a/lib/Doctrine/ORM/Tools/Console/ConsoleRunner.php b/lib/Doctrine/ORM/Tools/Console/ConsoleRunner.php index 64f2abe693c..c6a265cc079 100644 --- a/lib/Doctrine/ORM/Tools/Console/ConsoleRunner.php +++ b/lib/Doctrine/ORM/Tools/Console/ConsoleRunner.php @@ -19,42 +19,44 @@ namespace Doctrine\ORM\Tools\Console; -use Symfony\Component\Console\Application; -use Symfony\Component\Console\Helper\HelperSet; -use Doctrine\ORM\Version; +use Doctrine\DBAL\Tools\Console as DBALConsole; use Doctrine\ORM\EntityManagerInterface; - -use Doctrine\DBAL\Tools\Console\Helper\ConnectionHelper; use Doctrine\ORM\Tools\Console\Helper\EntityManagerHelper; +use Doctrine\ORM\Version; +use Symfony\Component\Console\Application; +use Symfony\Component\Console\Helper\HelperSet; /** * Handles running the Console Tools inside Symfony Console context. */ -class ConsoleRunner +final class ConsoleRunner { /** * Create a Symfony Console HelperSet * * @param EntityManagerInterface $entityManager + * * @return HelperSet */ - public static function createHelperSet(EntityManagerInterface $entityManager) + public static function createHelperSet(EntityManagerInterface $entityManager) : HelperSet { - return new HelperSet(array( - 'db' => new ConnectionHelper($entityManager->getConnection()), - 'em' => new EntityManagerHelper($entityManager) - )); + return new HelperSet( + [ + 'db' => new DBALConsole\Helper\ConnectionHelper($entityManager->getConnection()), + 'em' => new EntityManagerHelper($entityManager), + ] + ); } /** - * Runs console with the given helperset. + * Runs console with the given helper set. * * @param \Symfony\Component\Console\Helper\HelperSet $helperSet * @param \Symfony\Component\Console\Command\Command[] $commands * * @return void */ - static public function run(HelperSet $helperSet, $commands = array()) + public static function run(HelperSet $helperSet, array $commands = []) : void { $cli = self::createApplication($helperSet, $commands); $cli->run(); @@ -69,7 +71,7 @@ static public function run(HelperSet $helperSet, $commands = array()) * * @return \Symfony\Component\Console\Application */ - static public function createApplication(HelperSet $helperSet, $commands = array()) + public static function createApplication(HelperSet $helperSet, array $commands = []) : Application { $cli = new Application('Doctrine Command Line Interface', Version::VERSION); $cli->setCatchExceptions(true); @@ -85,34 +87,40 @@ static public function createApplication(HelperSet $helperSet, $commands = array * * @return void */ - static public function addCommands(Application $cli) + public static function addCommands(Application $cli) : void { - $cli->addCommands(array( - // DBAL Commands - new \Doctrine\DBAL\Tools\Console\Command\RunSqlCommand(), - new \Doctrine\DBAL\Tools\Console\Command\ImportCommand(), - - // ORM Commands - new \Doctrine\ORM\Tools\Console\Command\ClearCache\MetadataCommand(), - new \Doctrine\ORM\Tools\Console\Command\ClearCache\ResultCommand(), - new \Doctrine\ORM\Tools\Console\Command\ClearCache\QueryCommand(), - new \Doctrine\ORM\Tools\Console\Command\SchemaTool\CreateCommand(), - new \Doctrine\ORM\Tools\Console\Command\SchemaTool\UpdateCommand(), - new \Doctrine\ORM\Tools\Console\Command\SchemaTool\DropCommand(), - new \Doctrine\ORM\Tools\Console\Command\EnsureProductionSettingsCommand(), - new \Doctrine\ORM\Tools\Console\Command\ConvertDoctrine1SchemaCommand(), - new \Doctrine\ORM\Tools\Console\Command\GenerateRepositoriesCommand(), - new \Doctrine\ORM\Tools\Console\Command\GenerateEntitiesCommand(), - new \Doctrine\ORM\Tools\Console\Command\GenerateProxiesCommand(), - new \Doctrine\ORM\Tools\Console\Command\ConvertMappingCommand(), - new \Doctrine\ORM\Tools\Console\Command\RunDqlCommand(), - new \Doctrine\ORM\Tools\Console\Command\ValidateSchemaCommand(), - new \Doctrine\ORM\Tools\Console\Command\InfoCommand(), - new \Doctrine\ORM\Tools\Console\Command\MappingDescribeCommand(), - )); + $cli->addCommands( + [ + // DBAL Commands + new DBALConsole\Command\ImportCommand(), + new DBALConsole\Command\ReservedWordsCommand(), + new DBALConsole\Command\RunSqlCommand(), + + // ORM Commands + new Command\ClearCache\CollectionRegionCommand(), + new Command\ClearCache\EntityRegionCommand(), + new Command\ClearCache\MetadataCommand(), + new Command\ClearCache\QueryCommand(), + new Command\ClearCache\QueryRegionCommand(), + new Command\ClearCache\ResultCommand(), + new Command\SchemaTool\CreateCommand(), + new Command\SchemaTool\UpdateCommand(), + new Command\SchemaTool\DropCommand(), + new Command\EnsureProductionSettingsCommand(), + new Command\ConvertDoctrine1SchemaCommand(), + new Command\GenerateRepositoriesCommand(), + new Command\GenerateEntitiesCommand(), + new Command\GenerateProxiesCommand(), + new Command\ConvertMappingCommand(), + new Command\RunDqlCommand(), + new Command\ValidateSchemaCommand(), + new Command\InfoCommand(), + new Command\MappingDescribeCommand(), + ] + ); } - static public function printCliConfigTemplate() + public static function printCliConfigTemplate() : void { echo <<<'HELP' You are missing a "cli-config.php" or "config/cli-config.php" file in your @@ -131,6 +139,5 @@ static public function printCliConfigTemplate() return ConsoleRunner::createHelperSet($entityManager); HELP; - } } diff --git a/lib/Doctrine/ORM/Tools/Console/MetadataFilter.php b/lib/Doctrine/ORM/Tools/Console/MetadataFilter.php index 5a72b7d6d00..88357e35c94 100644 --- a/lib/Doctrine/ORM/Tools/Console/MetadataFilter.php +++ b/lib/Doctrine/ORM/Tools/Console/MetadataFilter.php @@ -35,7 +35,7 @@ class MetadataFilter extends \FilterIterator implements \Countable /** * @var array */ - private $filter = array(); + private $filter = []; /** * Filter Metadatas by one or more filter options. @@ -84,10 +84,6 @@ public function accept() ); } - if ($pregResult === 0) { - return false; - } - if ($pregResult) { return true; } diff --git a/lib/Doctrine/ORM/Tools/ConvertDoctrine1Schema.php b/lib/Doctrine/ORM/Tools/ConvertDoctrine1Schema.php index 52f3c92b972..41a103df4e6 100644 --- a/lib/Doctrine/ORM/Tools/ConvertDoctrine1Schema.php +++ b/lib/Doctrine/ORM/Tools/ConvertDoctrine1Schema.php @@ -20,7 +20,7 @@ namespace Doctrine\ORM\Tools; use Doctrine\ORM\Mapping\ClassMetadataInfo; -use Doctrine\Common\Util\Inflector; +use Doctrine\Common\Inflector\Inflector; use Doctrine\DBAL\Types\Type; use Symfony\Component\Yaml\Yaml; @@ -44,12 +44,12 @@ class ConvertDoctrine1Schema /** * @var array */ - private $legacyTypeMap = array( + private $legacyTypeMap = [ // TODO: This list may need to be updated 'clob' => 'text', 'timestamp' => 'datetime', 'enum' => 'string' - ); + ]; /** * Constructor passes the directory or array of directories @@ -72,7 +72,7 @@ public function __construct($from) */ public function getMetadata() { - $schema = array(); + $schema = []; foreach ($this->from as $path) { if (is_dir($path)) { $files = glob($path . '/*.yml'); @@ -84,7 +84,7 @@ public function getMetadata() } } - $metadatas = array(); + $metadatas = []; foreach ($schema as $className => $mappingInformation) { $metadatas[] = $this->convertToClassMetadataInfo($className, $mappingInformation); } @@ -153,12 +153,12 @@ private function convertColumns($className, array $model, ClassMetadataInfo $met } if ( ! $id) { - $fieldMapping = array( + $fieldMapping = [ 'fieldName' => 'id', 'columnName' => 'id', 'type' => 'integer', 'id' => true - ); + ]; $metadata->mapField($fieldMapping); $metadata->setIdGeneratorType(ClassMetadataInfo::GENERATOR_TYPE_AUTO); } @@ -178,7 +178,7 @@ private function convertColumn($className, $name, $column, ClassMetadataInfo $me { if (is_string($column)) { $string = $column; - $column = array(); + $column = []; $column['type'] = $string; } @@ -208,13 +208,13 @@ private function convertColumn($className, $name, $column, ClassMetadataInfo $me throw ToolsException::couldNotMapDoctrine1Type($column['type']); } - $fieldMapping = array(); + $fieldMapping = []; if (isset($column['primary'])) { $fieldMapping['id'] = true; } - $fieldMapping['fieldName'] = isset($column['alias']) ? $column['alias'] : $name; + $fieldMapping['fieldName'] = $column['alias'] ?? $name; $fieldMapping['columnName'] = $column['name']; $fieldMapping['type'] = $column['type']; @@ -222,7 +222,7 @@ private function convertColumn($className, $name, $column, ClassMetadataInfo $me $fieldMapping['length'] = $column['length']; } - $allowed = array('precision', 'scale', 'unique', 'options', 'notnull', 'version'); + $allowed = ['precision', 'scale', 'unique', 'options', 'notnull', 'version']; foreach ($column as $key => $value) { if (in_array($key, $allowed)) { @@ -237,9 +237,9 @@ private function convertColumn($className, $name, $column, ClassMetadataInfo $me } elseif (isset($column['sequence'])) { $metadata->setIdGeneratorType(ClassMetadataInfo::GENERATOR_TYPE_SEQUENCE); - $definition = array( + $definition = [ 'sequenceName' => is_array($column['sequence']) ? $column['sequence']['name']:$column['sequence'] - ); + ]; if (isset($column['sequence']['size'])) { $definition['allocationSize'] = $column['sequence']['size']; @@ -272,9 +272,9 @@ private function convertIndexes($className, array $model, ClassMetadataInfo $met $type = (isset($index['type']) && $index['type'] == 'unique') ? 'uniqueConstraints' : 'indexes'; - $metadata->table[$type][$name] = array( + $metadata->table[$type][$name] = [ 'columns' => $index['fields'] - ); + ]; } } @@ -311,17 +311,17 @@ private function convertRelations($className, array $model, ClassMetadataInfo $m if (isset($relation['refClass'])) { $type = 'many'; $foreignType = 'many'; - $joinColumns = array(); + $joinColumns = []; } else { - $type = isset($relation['type']) ? $relation['type'] : 'one'; - $foreignType = isset($relation['foreignType']) ? $relation['foreignType'] : 'many'; - $joinColumns = array( - array( + $type = $relation['type'] ?? 'one'; + $foreignType = $relation['foreignType'] ?? 'many'; + $joinColumns = [ + [ 'name' => $relation['local'], 'referencedColumnName' => $relation['foreign'], - 'onDelete' => isset($relation['onDelete']) ? $relation['onDelete'] : null, - ) - ); + 'onDelete' => $relation['onDelete'] ?? null, + ] + ]; } if ($type == 'one' && $foreignType == 'one') { @@ -332,7 +332,7 @@ private function convertRelations($className, array $model, ClassMetadataInfo $m $method = 'mapOneToMany'; } - $associationMapping = array(); + $associationMapping = []; $associationMapping['fieldName'] = $relation['alias']; $associationMapping['targetEntity'] = $relation['class']; $associationMapping['mappedBy'] = $relation['foreignAlias']; diff --git a/lib/Doctrine/ORM/Tools/DebugUnitOfWorkListener.php b/lib/Doctrine/ORM/Tools/DebugUnitOfWorkListener.php index 8c9a24f3887..50113826183 100644 --- a/lib/Doctrine/ORM/Tools/DebugUnitOfWorkListener.php +++ b/lib/Doctrine/ORM/Tools/DebugUnitOfWorkListener.php @@ -78,7 +78,7 @@ public function dumpIdentityMap(EntityManagerInterface $em) $uow = $em->getUnitOfWork(); $identityMap = $uow->getIdentityMap(); - $fh = fopen($this->file, "x+"); + $fh = fopen($this->file, 'xb+'); if (count($identityMap) == 0) { fwrite($fh, "Flush Operation [".$this->context."] - Empty identity map.\n"); @@ -143,7 +143,7 @@ private function getType($var) if (is_object($var)) { $refl = new \ReflectionObject($var); - return $refl->getShortname(); + return $refl->getShortName(); } return gettype($var); @@ -176,7 +176,7 @@ private function getIdString($entity, UnitOfWork $uow) $idstring .= " [REMOVED]"; } elseif ($state == UnitOfWork::STATE_MANAGED) { $idstring .= " [MANAGED]"; - } elseif ($state == UnitOfwork::STATE_DETACHED) { + } elseif ($state == UnitOfWork::STATE_DETACHED) { $idstring .= " [DETACHED]"; } diff --git a/lib/Doctrine/ORM/Tools/EntityGenerator.php b/lib/Doctrine/ORM/Tools/EntityGenerator.php index 0fd7f3e8453..5c304dbcb14 100644 --- a/lib/Doctrine/ORM/Tools/EntityGenerator.php +++ b/lib/Doctrine/ORM/Tools/EntityGenerator.php @@ -19,9 +19,13 @@ namespace Doctrine\ORM\Tools; -use Doctrine\ORM\Mapping\ClassMetadataInfo; -use Doctrine\Common\Util\Inflector; +use Doctrine\Common\Collections\Collection; +use Doctrine\Common\Inflector\Inflector; use Doctrine\DBAL\Types\Type; +use Doctrine\ORM\Mapping\ClassMetadataInfo; +use const E_USER_DEPRECATED; +use function str_replace; +use function trigger_error; /** * Generic class used to generate PHP5 entity classes from ClassMetadataInfo instances. @@ -43,6 +47,8 @@ * @author Guilherme Blanco * @author Jonathan Wage * @author Roman Borschel + * + * @deprecated 2.7 This class is being removed from the ORM and won't have any replacement */ class EntityGenerator { @@ -78,7 +84,7 @@ class EntityGenerator /** * @var array */ - protected $staticReflection = array(); + protected $staticReflection = []; /** * Number of spaces to use for indention in generated code. @@ -151,7 +157,7 @@ class EntityGenerator * * @var array */ - protected $typeAlias = array( + protected $typeAlias = [ Type::DATETIMETZ => '\DateTime', Type::DATETIME => '\DateTime', Type::DATE => '\DateTime', @@ -163,17 +169,18 @@ class EntityGenerator Type::TEXT => 'string', Type::BLOB => 'string', Type::DECIMAL => 'string', + Type::GUID => 'string', Type::JSON_ARRAY => 'array', Type::SIMPLE_ARRAY => 'array', Type::BOOLEAN => 'bool', - ); + ]; /** * Hash-map to handle generator types string. * * @var array */ - protected static $generatorStrategyMap = array( + protected static $generatorStrategyMap = [ ClassMetadataInfo::GENERATOR_TYPE_AUTO => 'AUTO', ClassMetadataInfo::GENERATOR_TYPE_SEQUENCE => 'SEQUENCE', ClassMetadataInfo::GENERATOR_TYPE_TABLE => 'TABLE', @@ -181,30 +188,30 @@ class EntityGenerator ClassMetadataInfo::GENERATOR_TYPE_NONE => 'NONE', ClassMetadataInfo::GENERATOR_TYPE_UUID => 'UUID', ClassMetadataInfo::GENERATOR_TYPE_CUSTOM => 'CUSTOM' - ); + ]; /** * Hash-map to handle the change tracking policy string. * * @var array */ - protected static $changeTrackingPolicyMap = array( + protected static $changeTrackingPolicyMap = [ ClassMetadataInfo::CHANGETRACKING_DEFERRED_IMPLICIT => 'DEFERRED_IMPLICIT', ClassMetadataInfo::CHANGETRACKING_DEFERRED_EXPLICIT => 'DEFERRED_EXPLICIT', ClassMetadataInfo::CHANGETRACKING_NOTIFY => 'NOTIFY', - ); + ]; /** * Hash-map to handle the inheritance type string. * * @var array */ - protected static $inheritanceTypeMap = array( + protected static $inheritanceTypeMap = [ ClassMetadataInfo::INHERITANCE_TYPE_NONE => 'NONE', ClassMetadataInfo::INHERITANCE_TYPE_JOINED => 'JOINED', ClassMetadataInfo::INHERITANCE_TYPE_SINGLE_TABLE => 'SINGLE_TABLE', ClassMetadataInfo::INHERITANCE_TYPE_TABLE_PER_CLASS => 'TABLE_PER_CLASS', - ); + ]; /** * @var string @@ -332,6 +339,8 @@ public function __construct() */ public function __construct() { + @trigger_error(self::class . ' is deprecated and will be removed in Doctrine ORM 3.0', E_USER_DEPRECATED); + if (version_compare(\Doctrine\Common\Version::VERSION, '2.2.0-DEV', '>=')) { $this->annotationsPrefix = 'ORM\\'; } @@ -371,12 +380,12 @@ public function writeEntityClass(ClassMetadataInfo $metadata, $outputDirectory) mkdir($dir, 0775, true); } - $this->isNew = !file_exists($path) || (file_exists($path) && $this->regenerateEntityIfExists); + $this->isNew = ! file_exists($path) || $this->regenerateEntityIfExists; if ( ! $this->isNew) { $this->parseTokensInEntityFile(file_get_contents($path)); } else { - $this->staticReflection[$metadata->name] = array('properties' => array(), 'methods' => array()); + $this->staticReflection[$metadata->name] = ['properties' => [], 'methods' => []]; } if ($this->backupExisting && file_exists($path)) { @@ -390,7 +399,7 @@ public function writeEntityClass(ClassMetadataInfo $metadata, $outputDirectory) if ($this->isNew) { file_put_contents($path, $this->generateEntityClass($metadata)); // If entity exists and we're allowed to update the entity class - } elseif ( ! $this->isNew && $this->updateEntityIfExists) { + } elseif ($this->updateEntityIfExists) { file_put_contents($path, $this->generateUpdatedEntityClass($metadata, $path)); } chmod($path, 0664); @@ -405,23 +414,23 @@ public function writeEntityClass(ClassMetadataInfo $metadata, $outputDirectory) */ public function generateEntityClass(ClassMetadataInfo $metadata) { - $placeHolders = array( + $placeHolders = [ '', '', '', '', '' - ); + ]; - $replacements = array( + $replacements = [ $this->generateEntityNamespace($metadata), $this->generateEntityUse(), $this->generateEntityDocBlock($metadata), $this->generateEntityClassName($metadata), $this->generateEntityBody($metadata) - ); + ]; - $code = str_replace($placeHolders, $replacements, static::$classTemplate) . "\n"; + $code = str_replace($placeHolders, $replacements, static::$classTemplate); return str_replace('', $this->spaces, $code); } @@ -442,7 +451,7 @@ public function generateUpdatedEntityClass(ClassMetadataInfo $metadata, $path) $body = str_replace('', $this->spaces, $body); $last = strrpos($currentCode, '}'); - return substr($currentCode, 0, $last) . $body . (strlen($body) > 0 ? "\n" : '') . "}\n"; + return substr($currentCode, 0, $last) . $body . ($body ? "\n" : '') . "}\n"; } /** @@ -603,18 +612,23 @@ protected function getType($type) */ protected function generateEntityNamespace(ClassMetadataInfo $metadata) { - if ($this->hasNamespace($metadata)) { - return 'namespace ' . $this->getNamespace($metadata) .';'; + if (! $this->hasNamespace($metadata)) { + return ''; } + + return 'namespace ' . $this->getNamespace($metadata) .';'; } + /** + * @return string + */ protected function generateEntityUse() { - if ($this->generateAnnotations) { - return "\n".'use Doctrine\ORM\Mapping as ORM;'."\n"; - } else { - return ""; + if (! $this->generateAnnotations) { + return ''; } + + return "\n".'use Doctrine\ORM\Mapping as ORM;'."\n"; } /** @@ -641,7 +655,7 @@ protected function generateEntityBody(ClassMetadataInfo $metadata) $stubMethods = $this->generateEntityStubMethods ? $this->generateEntityStubMethods($metadata) : null; $lifecycleCallbackMethods = $this->generateEntityLifecycleCallbackMethods($metadata); - $code = array(); + $code = []; if ($fieldMappingProperties) { $code[] = $fieldMappingProperties; @@ -683,7 +697,7 @@ protected function generateEntityConstructor(ClassMetadataInfo $metadata) return $this->generateEmbeddableConstructor($metadata); } - $collections = array(); + $collections = []; foreach ($metadata->associationMappings as $mapping) { if ($mapping['type'] & ClassMetadataInfo::TO_MANY) { @@ -705,14 +719,14 @@ protected function generateEntityConstructor(ClassMetadataInfo $metadata) */ private function generateEmbeddableConstructor(ClassMetadataInfo $metadata) { - $paramTypes = array(); - $paramVariables = array(); - $params = array(); - $fields = array(); + $paramTypes = []; + $paramVariables = []; + $params = []; + $fields = []; // Resort fields to put optional fields at the end of the method signature. - $requiredFields = array(); - $optionalFields = array(); + $requiredFields = []; + $optionalFields = []; foreach ($metadata->fieldMappings as $fieldMapping) { if (empty($fieldMapping['nullable'])) { @@ -737,9 +751,7 @@ private function generateEmbeddableConstructor(ClassMetadataInfo $metadata) } foreach ($fieldMappings as $fieldMapping) { - if (isset($fieldMapping['declaredField']) && - isset($metadata->embeddedClasses[$fieldMapping['declaredField']]) - ) { + if (isset($fieldMapping['declaredField'], $metadata->embeddedClasses[$fieldMapping['declaredField']])) { continue; } @@ -777,11 +789,11 @@ function ($type, $variable) use ($maxParamTypeLength) { $params = implode(', ', $params); } - $replacements = array( + $replacements = [ '' => implode("\n * ", $paramTags), '' => $params, '' => implode("\n" . $this->spaces, $fields), - ); + ]; $constructor = str_replace( array_keys($replacements), @@ -802,22 +814,23 @@ function ($type, $variable) use ($maxParamTypeLength) { protected function parseTokensInEntityFile($src) { $tokens = token_get_all($src); - $lastSeenNamespace = ""; + $tokensCount = count($tokens); + $lastSeenNamespace = ''; $lastSeenClass = false; $inNamespace = false; $inClass = false; - for ($i = 0; $i < count($tokens); $i++) { + for ($i = 0; $i < $tokensCount; $i++) { $token = $tokens[$i]; - if (in_array($token[0], array(T_WHITESPACE, T_COMMENT, T_DOC_COMMENT))) { + if (in_array($token[0], [T_WHITESPACE, T_COMMENT, T_DOC_COMMENT], true)) { continue; } if ($inNamespace) { - if ($token[0] == T_NS_SEPARATOR || $token[0] == T_STRING) { + if (in_array($token[0], [T_NS_SEPARATOR, T_STRING], true)) { $lastSeenNamespace .= $token[1]; - } elseif (is_string($token) && in_array($token, array(';', '{'))) { + } elseif (is_string($token) && in_array($token, [';', '{'], true)) { $inNamespace = false; } } @@ -825,22 +838,22 @@ protected function parseTokensInEntityFile($src) if ($inClass) { $inClass = false; $lastSeenClass = $lastSeenNamespace . ($lastSeenNamespace ? '\\' : '') . $token[1]; - $this->staticReflection[$lastSeenClass]['properties'] = array(); - $this->staticReflection[$lastSeenClass]['methods'] = array(); + $this->staticReflection[$lastSeenClass]['properties'] = []; + $this->staticReflection[$lastSeenClass]['methods'] = []; } - if ($token[0] == T_NAMESPACE) { - $lastSeenNamespace = ""; + if (T_NAMESPACE === $token[0]) { + $lastSeenNamespace = ''; $inNamespace = true; - } elseif ($token[0] == T_CLASS && $tokens[$i-1][0] != T_DOUBLE_COLON) { + } elseif (T_CLASS === $token[0] && T_DOUBLE_COLON !== $tokens[$i-1][0]) { $inClass = true; - } elseif ($token[0] == T_FUNCTION) { - if ($tokens[$i+2][0] == T_STRING) { + } elseif (T_FUNCTION === $token[0]) { + if (T_STRING === $tokens[$i+2][0]) { $this->staticReflection[$lastSeenClass]['methods'][] = strtolower($tokens[$i+2][1]); - } elseif ($tokens[$i+2] == "&" && $tokens[$i+3][0] == T_STRING) { + } elseif ($tokens[$i+2] == '&' && T_STRING === $tokens[$i+3][0]) { $this->staticReflection[$lastSeenClass]['methods'][] = strtolower($tokens[$i+3][1]); } - } elseif (in_array($token[0], array(T_VAR, T_PUBLIC, T_PRIVATE, T_PROTECTED)) && $tokens[$i+2][0] != T_FUNCTION) { + } elseif (in_array($token[0], [T_VAR, T_PUBLIC, T_PRIVATE, T_PROTECTED], true) && T_FUNCTION !== $tokens[$i+2][0]) { $this->staticReflection[$lastSeenClass]['properties'][] = substr($tokens[$i+2][1], 1); } } @@ -871,7 +884,7 @@ protected function hasProperty($property, ClassMetadataInfo $metadata) return ( isset($this->staticReflection[$metadata->name]) && - in_array($property, $this->staticReflection[$metadata->name]['properties']) + in_array($property, $this->staticReflection[$metadata->name]['properties'], true) ); } @@ -901,7 +914,7 @@ protected function hasMethod($method, ClassMetadataInfo $metadata) return ( isset($this->staticReflection[$metadata->name]) && - in_array(strtolower($method), $this->staticReflection[$metadata->name]['methods']) + in_array(strtolower($method), $this->staticReflection[$metadata->name]['methods'], true) ); } @@ -909,6 +922,8 @@ protected function hasMethod($method, ClassMetadataInfo $metadata) * @param ClassMetadataInfo $metadata * * @return array + * + * @throws \ReflectionException */ protected function getTraits(ClassMetadataInfo $metadata) { @@ -916,11 +931,9 @@ protected function getTraits(ClassMetadataInfo $metadata) return []; } - $reflClass = $metadata->reflClass === null - ? new \ReflectionClass($metadata->name) - : $metadata->reflClass; + $reflClass = $metadata->reflClass ?? new \ReflectionClass($metadata->name); - $traits = array(); + $traits = []; while ($reflClass !== false) { $traits = array_merge($traits, $reflClass->getTraits()); @@ -938,7 +951,7 @@ protected function getTraits(ClassMetadataInfo $metadata) */ protected function hasNamespace(ClassMetadataInfo $metadata) { - return strpos($metadata->name, '\\') ? true : false; + return (bool) strpos($metadata->name, '\\'); } /** @@ -946,7 +959,7 @@ protected function hasNamespace(ClassMetadataInfo $metadata) */ protected function extendsClass() { - return $this->classToExtend ? true : false; + return (bool) $this->classToExtend; } /** @@ -995,20 +1008,21 @@ protected function getNamespace(ClassMetadataInfo $metadata) */ protected function generateEntityDocBlock(ClassMetadataInfo $metadata) { - $lines = array(); + $lines = []; $lines[] = '/**'; $lines[] = ' * ' . $this->getClassName($metadata); if ($this->generateAnnotations) { $lines[] = ' *'; - $methods = array( + $methods = [ 'generateTableAnnotation', 'generateInheritanceAnnotation', 'generateDiscriminatorColumnAnnotation', 'generateDiscriminatorMapAnnotation', 'generateEntityAnnotation', - ); + 'generateEntityListenerAnnotation', + ]; foreach ($methods as $method) { if ($code = $this->$method($metadata)) { @@ -1051,13 +1065,13 @@ protected function generateEntityAnnotation(ClassMetadataInfo $metadata) * * @return string */ - protected function generateTableAnnotation($metadata) + protected function generateTableAnnotation(ClassMetadataInfo $metadata) { if ($metadata->isEmbeddedClass) { return ''; } - $table = array(); + $table = []; if (isset($metadata->table['schema'])) { $table[] = 'schema="' . $metadata->table['schema'] . '"'; @@ -1090,11 +1104,11 @@ protected function generateTableAnnotation($metadata) * * @return string */ - protected function generateTableConstraints($constraintName, $constraints) + protected function generateTableConstraints($constraintName, array $constraints) { - $annotations = array(); + $annotations = []; foreach ($constraints as $name => $constraint) { - $columns = array(); + $columns = []; foreach ($constraint['columns'] as $column) { $columns[] = '"' . $column . '"'; } @@ -1109,11 +1123,13 @@ protected function generateTableConstraints($constraintName, $constraints) * * @return string */ - protected function generateInheritanceAnnotation($metadata) + protected function generateInheritanceAnnotation(ClassMetadataInfo $metadata) { - if ($metadata->inheritanceType != ClassMetadataInfo::INHERITANCE_TYPE_NONE) { - return '@' . $this->annotationsPrefix . 'InheritanceType("'.$this->getInheritanceTypeString($metadata->inheritanceType).'")'; + if ($metadata->inheritanceType === ClassMetadataInfo::INHERITANCE_TYPE_NONE) { + return ''; } + + return '@' . $this->annotationsPrefix . 'InheritanceType("'.$this->getInheritanceTypeString($metadata->inheritanceType).'")'; } /** @@ -1121,16 +1137,18 @@ protected function generateInheritanceAnnotation($metadata) * * @return string */ - protected function generateDiscriminatorColumnAnnotation($metadata) + protected function generateDiscriminatorColumnAnnotation(ClassMetadataInfo $metadata) { - if ($metadata->inheritanceType != ClassMetadataInfo::INHERITANCE_TYPE_NONE) { - $discrColumn = $metadata->discriminatorColumn; - $columnDefinition = 'name="' . $discrColumn['name'] - . '", type="' . $discrColumn['type'] - . '", length=' . $discrColumn['length']; - - return '@' . $this->annotationsPrefix . 'DiscriminatorColumn(' . $columnDefinition . ')'; + if ($metadata->inheritanceType === ClassMetadataInfo::INHERITANCE_TYPE_NONE) { + return ''; } + + $discrColumn = $metadata->discriminatorColumn; + $columnDefinition = 'name="' . $discrColumn['name'] + . '", type="' . $discrColumn['type'] + . '", length=' . $discrColumn['length']; + + return '@' . $this->annotationsPrefix . 'DiscriminatorColumn(' . $columnDefinition . ')'; } /** @@ -1138,17 +1156,19 @@ protected function generateDiscriminatorColumnAnnotation($metadata) * * @return string */ - protected function generateDiscriminatorMapAnnotation($metadata) + protected function generateDiscriminatorMapAnnotation(ClassMetadataInfo $metadata) { - if ($metadata->inheritanceType != ClassMetadataInfo::INHERITANCE_TYPE_NONE) { - $inheritanceClassMap = array(); + if ($metadata->inheritanceType === ClassMetadataInfo::INHERITANCE_TYPE_NONE) { + return null; + } - foreach ($metadata->discriminatorMap as $type => $class) { - $inheritanceClassMap[] .= '"' . $type . '" = "' . $class . '"'; - } + $inheritanceClassMap = []; - return '@' . $this->annotationsPrefix . 'DiscriminatorMap({' . implode(', ', $inheritanceClassMap) . '})'; + foreach ($metadata->discriminatorMap as $type => $class) { + $inheritanceClassMap[] .= '"' . $type . '" = "' . $class . '"'; } + + return '@' . $this->annotationsPrefix . 'DiscriminatorMap({' . implode(', ', $inheritanceClassMap) . '})'; } /** @@ -1158,26 +1178,23 @@ protected function generateDiscriminatorMapAnnotation($metadata) */ protected function generateEntityStubMethods(ClassMetadataInfo $metadata) { - $methods = array(); + $methods = []; foreach ($metadata->fieldMappings as $fieldMapping) { - if (isset($fieldMapping['declaredField']) && - isset($metadata->embeddedClasses[$fieldMapping['declaredField']]) - ) { + if (isset($fieldMapping['declaredField'], $metadata->embeddedClasses[$fieldMapping['declaredField']])) { continue; } - if (( ! isset($fieldMapping['id']) || - ! $fieldMapping['id'] || - $metadata->generatorType == ClassMetadataInfo::GENERATOR_TYPE_NONE - ) && (! $metadata->isEmbeddedClass || ! $this->embeddablesImmutable) + $nullableField = $this->nullableFieldExpression($fieldMapping); + + if ((!$metadata->isEmbeddedClass || !$this->embeddablesImmutable) + && (!isset($fieldMapping['id']) || ! $fieldMapping['id'] || $metadata->generatorType === ClassMetadataInfo::GENERATOR_TYPE_NONE) + && $code = $this->generateEntityStubMethod($metadata, 'set', $fieldMapping['fieldName'], $fieldMapping['type'], $nullableField) ) { - if ($code = $this->generateEntityStubMethod($metadata, 'set', $fieldMapping['fieldName'], $fieldMapping['type'])) { - $methods[] = $code; - } + $methods[] = $code; } - if ($code = $this->generateEntityStubMethod($metadata, 'get', $fieldMapping['fieldName'], $fieldMapping['type'])) { + if ($code = $this->generateEntityStubMethod($metadata, 'get', $fieldMapping['fieldName'], $fieldMapping['type'], $nullableField)) { $methods[] = $code; } } @@ -1204,7 +1221,7 @@ protected function generateEntityStubMethods(ClassMetadataInfo $metadata) if ($code = $this->generateEntityStubMethod($metadata, 'set', $associationMapping['fieldName'], $associationMapping['targetEntity'], $nullable)) { $methods[] = $code; } - if ($code = $this->generateEntityStubMethod($metadata, 'get', $associationMapping['fieldName'], $associationMapping['targetEntity'])) { + if ($code = $this->generateEntityStubMethod($metadata, 'get', $associationMapping['fieldName'], $associationMapping['targetEntity'], $nullable)) { $methods[] = $code; } } elseif ($associationMapping['type'] & ClassMetadataInfo::TO_MANY) { @@ -1214,7 +1231,7 @@ protected function generateEntityStubMethods(ClassMetadataInfo $metadata) if ($code = $this->generateEntityStubMethod($metadata, 'remove', $associationMapping['fieldName'], $associationMapping['targetEntity'])) { $methods[] = $code; } - if ($code = $this->generateEntityStubMethod($metadata, 'get', $associationMapping['fieldName'], 'Doctrine\Common\Collections\Collection')) { + if ($code = $this->generateEntityStubMethod($metadata, 'get', $associationMapping['fieldName'], Collection::class)) { $methods[] = $code; } } @@ -1228,7 +1245,7 @@ protected function generateEntityStubMethods(ClassMetadataInfo $metadata) * * @return bool */ - protected function isAssociationIsNullable($associationMapping) + protected function isAssociationIsNullable(array $associationMapping) { if (isset($associationMapping['id']) && $associationMapping['id']) { return false; @@ -1238,7 +1255,7 @@ protected function isAssociationIsNullable($associationMapping) $joinColumns = $associationMapping['joinColumns']; } else { //@todo there is no way to retrieve targetEntity metadata - $joinColumns = array(); + $joinColumns = []; } foreach ($joinColumns as $joinColumn) { @@ -1257,21 +1274,19 @@ protected function isAssociationIsNullable($associationMapping) */ protected function generateEntityLifecycleCallbackMethods(ClassMetadataInfo $metadata) { - if (isset($metadata->lifecycleCallbacks) && $metadata->lifecycleCallbacks) { - $methods = array(); + if (empty($metadata->lifecycleCallbacks)) { + return ''; + } - foreach ($metadata->lifecycleCallbacks as $name => $callbacks) { - foreach ($callbacks as $callback) { - if ($code = $this->generateLifecycleCallbackMethod($name, $callback, $metadata)) { - $methods[] = $code; - } - } - } + $methods = []; - return implode("\n\n", $methods); + foreach ($metadata->lifecycleCallbacks as $name => $callbacks) { + foreach ($callbacks as $callback) { + $methods[] = $this->generateLifecycleCallbackMethod($name, $callback, $metadata); + } } - return ""; + return implode("\n\n", array_filter($methods)); } /** @@ -1281,7 +1296,7 @@ protected function generateEntityLifecycleCallbackMethods(ClassMetadataInfo $met */ protected function generateEntityAssociationMappingProperties(ClassMetadataInfo $metadata) { - $lines = array(); + $lines = []; foreach ($metadata->associationMappings as $associationMapping) { if ($this->hasProperty($associationMapping['fieldName'], $metadata)) { @@ -1303,15 +1318,12 @@ protected function generateEntityAssociationMappingProperties(ClassMetadataInfo */ protected function generateEntityFieldMappingProperties(ClassMetadataInfo $metadata) { - $lines = array(); + $lines = []; foreach ($metadata->fieldMappings as $fieldMapping) { - if ($this->hasProperty($fieldMapping['fieldName'], $metadata) || - $metadata->isInheritedField($fieldMapping['fieldName']) || - ( - isset($fieldMapping['declaredField']) && - isset($metadata->embeddedClasses[$fieldMapping['declaredField']]) - ) + if (isset($fieldMapping['declaredField'], $metadata->embeddedClasses[$fieldMapping['declaredField']]) || + $this->hasProperty($fieldMapping['fieldName'], $metadata) || + $metadata->isInheritedField($fieldMapping['fieldName']) ) { continue; } @@ -1331,7 +1343,7 @@ protected function generateEntityFieldMappingProperties(ClassMetadataInfo $metad */ protected function generateEntityEmbeddedProperties(ClassMetadataInfo $metadata) { - $lines = array(); + $lines = []; foreach ($metadata->embeddedClasses as $fieldName => $embeddedClass) { if (isset($embeddedClass['declaredField']) || $this->hasProperty($fieldName, $metadata)) { @@ -1354,11 +1366,11 @@ protected function generateEntityEmbeddedProperties(ClassMetadataInfo $metadata) * * @return string */ - protected function generateEntityStubMethod(ClassMetadataInfo $metadata, $type, $fieldName, $typeHint = null, $defaultValue = null) + protected function generateEntityStubMethod(ClassMetadataInfo $metadata, $type, $fieldName, $typeHint = null, $defaultValue = null) { $methodName = $type . Inflector::classify($fieldName); $variableName = Inflector::camelize($fieldName); - if (in_array($type, array("add", "remove"))) { + if (in_array($type, ["add", "remove"])) { $methodName = Inflector::singularize($methodName); $variableName = Inflector::singularize($variableName); } @@ -1380,16 +1392,16 @@ protected function generateEntityStubMethod(ClassMetadataInfo $metadata, $type, $methodTypeHint = '\\' . $typeHint . ' '; } - $replacements = array( - '' => ucfirst($type) . ' ' . $variableName, + $replacements = [ + '' => ucfirst($type) . ' ' . $variableName . '.', '' => $methodTypeHint, - '' => $variableType, + '' => $variableType . (null !== $defaultValue ? ('|' . $defaultValue) : ''), '' => $variableName, '' => $methodName, '' => $fieldName, - '' => ($defaultValue !== null ) ? (' = '.$defaultValue) : '', + '' => ($defaultValue !== null ) ? (' = ' . $defaultValue) : '', '' => $this->getClassName($metadata) - ); + ]; $method = str_replace( array_keys($replacements), @@ -1407,17 +1419,18 @@ protected function generateEntityStubMethod(ClassMetadataInfo $metadata, $type, * * @return string */ - protected function generateLifecycleCallbackMethod($name, $methodName, $metadata) + protected function generateLifecycleCallbackMethod($name, $methodName, ClassMetadataInfo $metadata) { if ($this->hasMethod($methodName, $metadata)) { return ''; } + $this->staticReflection[$metadata->name]['methods'][] = $methodName; - $replacements = array( + $replacements = [ '' => $this->annotationsPrefix . ucfirst($name), '' => $methodName, - ); + ]; $method = str_replace( array_keys($replacements), @@ -1435,7 +1448,7 @@ protected function generateLifecycleCallbackMethod($name, $methodName, $metadata */ protected function generateJoinColumnAnnotation(array $joinColumn) { - $joinColumnAnnot = array(); + $joinColumnAnnot = []; if (isset($joinColumn['name'])) { $joinColumnAnnot[] = 'name="' . $joinColumn['name'] . '"'; @@ -1472,7 +1485,7 @@ protected function generateJoinColumnAnnotation(array $joinColumn) */ protected function generateAssociationMappingPropertyDocBlock(array $associationMapping, ClassMetadataInfo $metadata) { - $lines = array(); + $lines = []; $lines[] = $this->spaces . '/**'; if ($associationMapping['type'] & ClassMetadataInfo::TO_MANY) { @@ -1507,7 +1520,7 @@ protected function generateAssociationMappingPropertyDocBlock(array $association $type = 'ManyToMany'; break; } - $typeOptions = array(); + $typeOptions = []; if (isset($associationMapping['targetEntity'])) { $typeOptions[] = 'targetEntity="' . $associationMapping['targetEntity'] . '"'; @@ -1522,7 +1535,7 @@ protected function generateAssociationMappingPropertyDocBlock(array $association } if ($associationMapping['cascade']) { - $cascades = array(); + $cascades = []; if ($associationMapping['isCascadePersist']) $cascades[] = '"persist"'; if ($associationMapping['isCascadeRemove']) $cascades[] = '"remove"'; @@ -1531,7 +1544,7 @@ protected function generateAssociationMappingPropertyDocBlock(array $association if ($associationMapping['isCascadeRefresh']) $cascades[] = '"refresh"'; if (count($cascades) === 5) { - $cascades = array('"all"'); + $cascades = ['"all"']; } $typeOptions[] = 'cascade={' . implode(',', $cascades) . '}'; @@ -1542,10 +1555,10 @@ protected function generateAssociationMappingPropertyDocBlock(array $association } if (isset($associationMapping['fetch']) && $associationMapping['fetch'] !== ClassMetadataInfo::FETCH_LAZY) { - $fetchMap = array( + $fetchMap = [ ClassMetadataInfo::FETCH_EXTRA_LAZY => 'EXTRA_LAZY', ClassMetadataInfo::FETCH_EAGER => 'EAGER', - ); + ]; $typeOptions[] = 'fetch="' . $fetchMap[$associationMapping['fetch']] . '"'; } @@ -1555,7 +1568,7 @@ protected function generateAssociationMappingPropertyDocBlock(array $association if (isset($associationMapping['joinColumns']) && $associationMapping['joinColumns']) { $lines[] = $this->spaces . ' * @' . $this->annotationsPrefix . 'JoinColumns({'; - $joinColumnsLines = array(); + $joinColumnsLines = []; foreach ($associationMapping['joinColumns'] as $joinColumn) { if ($joinColumnAnnot = $this->generateJoinColumnAnnotation($joinColumn)) { @@ -1568,7 +1581,7 @@ protected function generateAssociationMappingPropertyDocBlock(array $association } if (isset($associationMapping['joinTable']) && $associationMapping['joinTable']) { - $joinTable = array(); + $joinTable = []; $joinTable[] = 'name="' . $associationMapping['joinTable']['name'] . '"'; if (isset($associationMapping['joinTable']['schema'])) { @@ -1578,7 +1591,7 @@ protected function generateAssociationMappingPropertyDocBlock(array $association $lines[] = $this->spaces . ' * @' . $this->annotationsPrefix . 'JoinTable(' . implode(', ', $joinTable) . ','; $lines[] = $this->spaces . ' * joinColumns={'; - $joinColumnsLines = array(); + $joinColumnsLines = []; foreach ($associationMapping['joinTable']['joinColumns'] as $joinColumn) { $joinColumnsLines[] = $this->spaces . ' * ' . $this->generateJoinColumnAnnotation($joinColumn); @@ -1588,7 +1601,7 @@ protected function generateAssociationMappingPropertyDocBlock(array $association $lines[] = $this->spaces . ' * },'; $lines[] = $this->spaces . ' * inverseJoinColumns={'; - $inverseJoinColumnsLines = array(); + $inverseJoinColumnsLines = []; foreach ($associationMapping['joinTable']['inverseJoinColumns'] as $joinColumn) { $inverseJoinColumnsLines[] = $this->spaces . ' * ' . $this->generateJoinColumnAnnotation($joinColumn); @@ -1624,14 +1637,16 @@ protected function generateAssociationMappingPropertyDocBlock(array $association */ protected function generateFieldMappingPropertyDocBlock(array $fieldMapping, ClassMetadataInfo $metadata) { - $lines = array(); + $lines = []; $lines[] = $this->spaces . '/**'; - $lines[] = $this->spaces . ' * @var ' . $this->getType($fieldMapping['type']); + $lines[] = $this->spaces . ' * @var ' + . $this->getType($fieldMapping['type']) + . ($this->nullableFieldExpression($fieldMapping) ? '|null' : ''); if ($this->generateAnnotations) { $lines[] = $this->spaces . ' *'; - $column = array(); + $column = []; if (isset($fieldMapping['columnName'])) { $column[] = 'name="' . $fieldMapping['columnName'] . '"'; } @@ -1658,10 +1673,30 @@ protected function generateFieldMappingPropertyDocBlock(array $fieldMapping, Cla $options = []; + if (isset($fieldMapping['options']['default']) && $fieldMapping['options']['default']) { + $options[] = '"default"="' . $fieldMapping['options']['default'] .'"'; + } + if (isset($fieldMapping['options']['unsigned']) && $fieldMapping['options']['unsigned']) { $options[] = '"unsigned"=true'; } + if (isset($fieldMapping['options']['fixed']) && $fieldMapping['options']['fixed']) { + $options[] = '"fixed"=true'; + } + + if (isset($fieldMapping['options']['comment']) && $fieldMapping['options']['comment']) { + $options[] = '"comment"="' . str_replace('"', '""', $fieldMapping['options']['comment']) . '"'; + } + + if (isset($fieldMapping['options']['collation']) && $fieldMapping['options']['collation']) { + $options[] = '"collation"="' . $fieldMapping['options']['collation'] .'"'; + } + + if (isset($fieldMapping['options']['check']) && $fieldMapping['options']['check']) { + $options[] = '"check"="' . $fieldMapping['options']['check'] .'"'; + } + if ($options) { $column[] = 'options={'.implode(',', $options).'}'; } @@ -1684,7 +1719,7 @@ protected function generateFieldMappingPropertyDocBlock(array $fieldMapping, Cla } if ($metadata->sequenceGeneratorDefinition) { - $sequenceGenerator = array(); + $sequenceGenerator = []; if (isset($metadata->sequenceGeneratorDefinition['sequenceName'])) { $sequenceGenerator[] = 'sequenceName="' . $metadata->sequenceGeneratorDefinition['sequenceName'] . '"'; @@ -1719,17 +1754,21 @@ protected function generateFieldMappingPropertyDocBlock(array $fieldMapping, Cla */ protected function generateEmbeddedPropertyDocBlock(array $embeddedClass) { - $lines = array(); + $lines = []; $lines[] = $this->spaces . '/**'; $lines[] = $this->spaces . ' * @var \\' . ltrim($embeddedClass['class'], '\\'); if ($this->generateAnnotations) { $lines[] = $this->spaces . ' *'; - $embedded = array('class="' . $embeddedClass['class'] . '"'); + $embedded = ['class="' . $embeddedClass['class'] . '"']; - if (isset($fieldMapping['columnPrefix'])) { - $embedded[] = 'columnPrefix=' . var_export($embeddedClass['columnPrefix'], true); + if (isset($embeddedClass['columnPrefix'])) { + if (is_string($embeddedClass['columnPrefix'])) { + $embedded[] = 'columnPrefix="' . $embeddedClass['columnPrefix'] . '"'; + } else { + $embedded[] = 'columnPrefix=' . var_export($embeddedClass['columnPrefix'], true); + } } $lines[] = $this->spaces . ' * @' . @@ -1741,6 +1780,27 @@ protected function generateEmbeddedPropertyDocBlock(array $embeddedClass) return implode("\n", $lines); } + private function generateEntityListenerAnnotation(ClassMetadataInfo $metadata): string + { + if (0 === \count($metadata->entityListeners)) { + return ''; + } + + $processedClasses = []; + foreach ($metadata->entityListeners as $event => $eventListeners) { + foreach ($eventListeners as $eventListener) { + $processedClasses[] = '"' . $eventListener['class'] . '"'; + } + } + + return \sprintf( + '%s%s({%s})', + '@' . $this->annotationsPrefix, + 'EntityListeners', + \implode(',', \array_unique($processedClasses)) + ); + } + /** * @param string $code * @param int $num @@ -1808,6 +1868,20 @@ protected function getIdGeneratorTypeString($type) return static::$generatorStrategyMap[$type]; } + /** + * @param array $fieldMapping + * + * @return string|null + */ + private function nullableFieldExpression(array $fieldMapping) + { + if (isset($fieldMapping['nullable']) && true === $fieldMapping['nullable']) { + return 'null'; + } + + return null; + } + /** * Exports (nested) option elements. * @@ -1817,7 +1891,7 @@ protected function getIdGeneratorTypeString($type) */ private function exportTableOptions(array $options) { - $optionsStr = array(); + $optionsStr = []; foreach ($options as $name => $option) { if (is_array($option)) { diff --git a/lib/Doctrine/ORM/Tools/EntityRepositoryGenerator.php b/lib/Doctrine/ORM/Tools/EntityRepositoryGenerator.php index f431588fb09..9b3b290ac7f 100644 --- a/lib/Doctrine/ORM/Tools/EntityRepositoryGenerator.php +++ b/lib/Doctrine/ORM/Tools/EntityRepositoryGenerator.php @@ -19,6 +19,10 @@ namespace Doctrine\ORM\Tools; +use Doctrine\ORM\EntityRepository; +use const E_USER_DEPRECATED; +use function trigger_error; + /** * Class to generate entity repository classes * @@ -29,6 +33,8 @@ * @author Guilherme Blanco * @author Jonathan Wage * @author Roman Borschel + * + * @deprecated 2.7 This class is being removed from the ORM and won't have any replacement */ class EntityRepositoryGenerator { @@ -50,6 +56,11 @@ class extends } '; + public function __construct() + { + @trigger_error(self::class . ' is deprecated and will be removed in Doctrine ORM 3.0', E_USER_DEPRECATED); + } + /** * @param string $fullClassName * @@ -57,11 +68,11 @@ class extends */ public function generateEntityRepositoryClass($fullClassName) { - $variables = array( + $variables = [ '' => $this->generateEntityRepositoryNamespace($fullClassName), '' => $this->generateEntityRepositoryName($fullClassName), '' => $this->generateClassName($fullClassName) - ); + ]; return str_replace(array_keys($variables), array_values($variables), self::$_template); } @@ -70,7 +81,7 @@ public function generateEntityRepositoryClass($fullClassName) * Generates the namespace, if class do not have namespace, return empty string instead. * * @param string $fullClassName - * + * * @return string $namespace */ private function getClassNamespace($fullClassName) @@ -82,9 +93,9 @@ private function getClassNamespace($fullClassName) /** * Generates the class name - * + * * @param string $fullClassName - * + * * @return string */ private function generateClassName($fullClassName) @@ -102,7 +113,7 @@ private function generateClassName($fullClassName) /** * Generates the namespace statement, if class do not have namespace, return empty string instead. - * + * * @param string $fullClassName The full repository class name. * * @return string $namespace @@ -116,14 +127,14 @@ private function generateEntityRepositoryNamespace($fullClassName) /** * @param string $fullClassName - * + * * @return string $repositoryName */ private function generateEntityRepositoryName($fullClassName) { $namespace = $this->getClassNamespace($fullClassName); - $repositoryName = $this->repositoryName ?: 'Doctrine\ORM\EntityRepository'; + $repositoryName = $this->repositoryName ?: EntityRepository::class; if ($namespace && $repositoryName[0] !== '\\') { $repositoryName = '\\' . $repositoryName; @@ -158,7 +169,7 @@ public function writeEntityRepositoryClass($fullClassName, $outputDirectory) /** * @param string $repositoryName - * + * * @return \Doctrine\ORM\Tools\EntityRepositoryGenerator */ public function setDefaultRepositoryName($repositoryName) diff --git a/lib/Doctrine/ORM/Tools/Export/ClassMetadataExporter.php b/lib/Doctrine/ORM/Tools/Export/ClassMetadataExporter.php index 1ea2a3735a9..15c03b5c5af 100644 --- a/lib/Doctrine/ORM/Tools/Export/ClassMetadataExporter.php +++ b/lib/Doctrine/ORM/Tools/Export/ClassMetadataExporter.php @@ -19,6 +19,9 @@ namespace Doctrine\ORM\Tools\Export; +use const E_USER_DEPRECATED; +use function trigger_error; + /** * Class used for converting your mapping information between the * supported formats: yaml, xml, and php/annotation. @@ -26,19 +29,26 @@ * @link www.doctrine-project.org * @since 2.0 * @author Jonathan Wage + * + * @deprecated 2.7 This class is being removed from the ORM and won't have any replacement */ class ClassMetadataExporter { /** * @var array */ - private static $_exporterDrivers = array( - 'xml' => 'Doctrine\ORM\Tools\Export\Driver\XmlExporter', - 'yaml' => 'Doctrine\ORM\Tools\Export\Driver\YamlExporter', - 'yml' => 'Doctrine\ORM\Tools\Export\Driver\YamlExporter', - 'php' => 'Doctrine\ORM\Tools\Export\Driver\PhpExporter', - 'annotation' => 'Doctrine\ORM\Tools\Export\Driver\AnnotationExporter' - ); + private static $_exporterDrivers = [ + 'xml' => Driver\XmlExporter::class, + 'yaml' => Driver\YamlExporter::class, + 'yml' => Driver\YamlExporter::class, + 'php' => Driver\PhpExporter::class, + 'annotation' => Driver\AnnotationExporter::class + ]; + + public function __construct() + { + @trigger_error(self::class . ' is deprecated and will be removed in Doctrine ORM 3.0', E_USER_DEPRECATED); + } /** * Registers a new exporter driver class under a specified name. diff --git a/lib/Doctrine/ORM/Tools/Export/Driver/AbstractExporter.php b/lib/Doctrine/ORM/Tools/Export/Driver/AbstractExporter.php index ae8650525e1..efe8e7bcdc9 100644 --- a/lib/Doctrine/ORM/Tools/Export/Driver/AbstractExporter.php +++ b/lib/Doctrine/ORM/Tools/Export/Driver/AbstractExporter.php @@ -21,6 +21,8 @@ use Doctrine\ORM\Mapping\ClassMetadataInfo; use Doctrine\ORM\Tools\Export\ExportException; +use const E_USER_DEPRECATED; +use function trigger_error; /** * Abstract base class which is to be used for the Exporter drivers @@ -29,13 +31,15 @@ * @link www.doctrine-project.org * @since 2.0 * @author Jonathan Wage + * + * @deprecated 2.7 This class is being removed from the ORM and won't have any replacement */ abstract class AbstractExporter { /** * @var array */ - protected $_metadata = array(); + protected $_metadata = []; /** * @var string|null @@ -57,6 +61,8 @@ abstract class AbstractExporter */ public function __construct($dir = null) { + @trigger_error(static::class . ' is deprecated and will be removed in Doctrine ORM 3.0', E_USER_DEPRECATED); + $this->_outputDir = $dir; } diff --git a/lib/Doctrine/ORM/Tools/Export/Driver/AnnotationExporter.php b/lib/Doctrine/ORM/Tools/Export/Driver/AnnotationExporter.php index 044a1da53a8..29cb8df3633 100644 --- a/lib/Doctrine/ORM/Tools/Export/Driver/AnnotationExporter.php +++ b/lib/Doctrine/ORM/Tools/Export/Driver/AnnotationExporter.php @@ -28,6 +28,8 @@ * @link www.doctrine-project.org * @since 2.0 * @author Jonathan Wage + * + * @deprecated 2.7 This class is being removed from the ORM and won't have any replacement */ class AnnotationExporter extends AbstractExporter { @@ -59,7 +61,7 @@ public function exportClassMetadata(ClassMetadataInfo $metadata) } /** - * @param \Doctrine\ORM\Mapping\ClassMetadataInfo $metadata + * @param ClassMetadataInfo $metadata * * @return string */ @@ -69,7 +71,7 @@ protected function _generateOutputPath(ClassMetadataInfo $metadata) } /** - * @param \Doctrine\ORM\Tools\EntityGenerator $entityGenerator + * @param EntityGenerator $entityGenerator * * @return void */ diff --git a/lib/Doctrine/ORM/Tools/Export/Driver/PhpExporter.php b/lib/Doctrine/ORM/Tools/Export/Driver/PhpExporter.php index 5d88901a56a..c0cd1767bca 100644 --- a/lib/Doctrine/ORM/Tools/Export/Driver/PhpExporter.php +++ b/lib/Doctrine/ORM/Tools/Export/Driver/PhpExporter.php @@ -27,6 +27,8 @@ * @link www.doctrine-project.org * @since 2.0 * @author Jonathan Wage + * + * @deprecated 2.7 This class is being removed from the ORM and won't have any replacement */ class PhpExporter extends AbstractExporter { @@ -40,7 +42,7 @@ class PhpExporter extends AbstractExporter */ public function exportClassMetadata(ClassMetadataInfo $metadata) { - $lines = array(); + $lines = []; $lines[] = 'processEntityListeners($metadata)); + foreach ($metadata->fieldMappings as $fieldMapping) { $lines[] = '$metadata->mapField(' . $this->_varExport($fieldMapping) . ');'; } @@ -91,7 +95,7 @@ public function exportClassMetadata(ClassMetadataInfo $metadata) } foreach ($metadata->associationMappings as $associationMapping) { - $cascade = array('remove', 'persist', 'refresh', 'merge', 'detach'); + $cascade = ['remove', 'persist', 'refresh', 'merge', 'detach']; foreach ($cascade as $key => $value) { if ( ! $associationMapping['isCascade'.ucfirst($value)]) { unset($cascade[$key]); @@ -99,14 +103,15 @@ public function exportClassMetadata(ClassMetadataInfo $metadata) } if (count($cascade) === 5) { - $cascade = array('all'); + $cascade = ['all']; } - $associationMappingArray = array( + $method = null; + $associationMappingArray = [ 'fieldName' => $associationMapping['fieldName'], 'targetEntity' => $associationMapping['targetEntity'], 'cascade' => $cascade, - ); + ]; if (isset($associationMapping['fetch'])) { $associationMappingArray['fetch'] = $associationMapping['fetch']; @@ -114,21 +119,22 @@ public function exportClassMetadata(ClassMetadataInfo $metadata) if ($associationMapping['type'] & ClassMetadataInfo::TO_ONE) { $method = 'mapOneToOne'; - $oneToOneMappingArray = array( + $oneToOneMappingArray = [ 'mappedBy' => $associationMapping['mappedBy'], 'inversedBy' => $associationMapping['inversedBy'], 'joinColumns' => $associationMapping['isOwningSide'] ? $associationMapping['joinColumns'] : [], 'orphanRemoval' => $associationMapping['orphanRemoval'], - ); + ]; $associationMappingArray = array_merge($associationMappingArray, $oneToOneMappingArray); } elseif ($associationMapping['type'] == ClassMetadataInfo::ONE_TO_MANY) { $method = 'mapOneToMany'; - $potentialAssociationMappingIndexes = array( + $potentialAssociationMappingIndexes = [ 'mappedBy', 'orphanRemoval', 'orderBy', - ); + ]; + $oneToManyMappingArray = []; foreach ($potentialAssociationMappingIndexes as $index) { if (isset($associationMapping[$index])) { $oneToManyMappingArray[$index] = $associationMapping[$index]; @@ -137,11 +143,12 @@ public function exportClassMetadata(ClassMetadataInfo $metadata) $associationMappingArray = array_merge($associationMappingArray, $oneToManyMappingArray); } elseif ($associationMapping['type'] == ClassMetadataInfo::MANY_TO_MANY) { $method = 'mapManyToMany'; - $potentialAssociationMappingIndexes = array( + $potentialAssociationMappingIndexes = [ 'mappedBy', 'joinTable', 'orderBy', - ); + ]; + $manyToManyMappingArray = []; foreach ($potentialAssociationMappingIndexes as $index) { if (isset($associationMapping[$index])) { $manyToManyMappingArray[$index] = $associationMapping[$index]; @@ -174,4 +181,22 @@ protected function _varExport($var) return $export; } + + private function processEntityListeners(ClassMetadataInfo $metadata) : array + { + $lines = []; + + foreach ($metadata->entityListeners as $event => $entityListenerConfig) { + foreach ($entityListenerConfig as $entityListener) { + $lines[] = \sprintf( + '$metadata->addEntityListener(%s, %s, %s);', + \var_export($event, true), + \var_export($entityListener['class'], true), + \var_export($entityListener['method'], true) + ); + } + } + + return $lines; + } } diff --git a/lib/Doctrine/ORM/Tools/Export/Driver/XmlExporter.php b/lib/Doctrine/ORM/Tools/Export/Driver/XmlExporter.php index ba41d99862f..65036493799 100644 --- a/lib/Doctrine/ORM/Tools/Export/Driver/XmlExporter.php +++ b/lib/Doctrine/ORM/Tools/Export/Driver/XmlExporter.php @@ -20,6 +20,7 @@ namespace Doctrine\ORM\Tools\Export\Driver; use Doctrine\ORM\Mapping\ClassMetadataInfo; +use SimpleXMLElement; /** * ClassMetadata exporter for Doctrine XML mapping files. @@ -27,6 +28,8 @@ * @link www.doctrine-project.org * @since 2.0 * @author Jonathan Wage + * + * @deprecated 2.7 This class is being removed from the ORM and won't have any replacement */ class XmlExporter extends AbstractExporter { @@ -40,10 +43,10 @@ class XmlExporter extends AbstractExporter */ public function exportClassMetadata(ClassMetadataInfo $metadata) { - $xml = new \SimpleXmlElement(""); + $xml = new SimpleXmlElement(''); if ($metadata->isMappedSuperclass) { $root = $xml->addChild('mapped-superclass'); @@ -126,7 +129,7 @@ public function exportClassMetadata(ClassMetadataInfo $metadata) $fields = $metadata->fieldMappings; - $id = array(); + $id = []; foreach ($fields as $name => $field) { if (isset($field['id']) && $field['id']) { $id[$name] = $field; @@ -136,10 +139,10 @@ public function exportClassMetadata(ClassMetadataInfo $metadata) foreach ($metadata->associationMappings as $name => $assoc) { if (isset($assoc['id']) && $assoc['id']) { - $id[$name] = array( + $id[$name] = [ 'fieldName' => $name, 'associationKey' => true - ); + ]; } } @@ -225,12 +228,12 @@ public function exportClassMetadata(ClassMetadataInfo $metadata) } } - $orderMap = array( + $orderMap = [ ClassMetadataInfo::ONE_TO_ONE, ClassMetadataInfo::ONE_TO_MANY, ClassMetadataInfo::MANY_TO_ONE, ClassMetadataInfo::MANY_TO_MANY, - ); + ]; uasort($metadata->associationMappings, function($m1, $m2) use (&$orderMap){ $a1 = array_search($m1['type'], $orderMap); @@ -240,6 +243,7 @@ public function exportClassMetadata(ClassMetadataInfo $metadata) }); foreach ($metadata->associationMappings as $associationMapping) { + $associationMappingXml = null; if ($associationMapping['type'] == ClassMetadataInfo::ONE_TO_ONE) { $associationMappingXml = $root->addChild('one-to-one'); } elseif ($associationMapping['type'] == ClassMetadataInfo::MANY_TO_ONE) { @@ -273,7 +277,7 @@ public function exportClassMetadata(ClassMetadataInfo $metadata) $associationMappingXml->addAttribute('fetch', $this->_getFetchModeString($associationMapping['fetch'])); } - $cascade = array(); + $cascade = []; if ($associationMapping['isCascadeRemove']) { $cascade[] = 'cascade-remove'; } @@ -295,7 +299,7 @@ public function exportClassMetadata(ClassMetadataInfo $metadata) } if (count($cascade) === 5) { - $cascade = array('cascade-all'); + $cascade = ['cascade-all']; } if ($cascade) { @@ -389,16 +393,18 @@ public function exportClassMetadata(ClassMetadataInfo $metadata) } } + $this->processEntityListeners($metadata, $root); + return $this->_asXml($xml); } /** * Exports (nested) option elements. * - * @param \SimpleXMLElement $parentXml - * @param array $options + * @param SimpleXMLElement $parentXml + * @param array $options */ - private function exportTableOptions(\SimpleXMLElement $parentXml, array $options) + private function exportTableOptions(SimpleXMLElement $parentXml, array $options) : void { foreach ($options as $name => $option) { $isArray = is_array($option); @@ -417,12 +423,12 @@ private function exportTableOptions(\SimpleXMLElement $parentXml, array $options /** * Export sequence information (if available/configured) into the current identifier XML node * - * @param \SimpleXMLElement $identifierXmlNode + * @param SimpleXMLElement $identifierXmlNode * @param ClassMetadataInfo $metadata * * @return void */ - private function exportSequenceInformation(\SimpleXMLElement $identifierXmlNode, ClassMetadataInfo $metadata) + private function exportSequenceInformation(SimpleXMLElement $identifierXmlNode, ClassMetadataInfo $metadata) : void { $sequenceDefinition = $metadata->sequenceGeneratorDefinition; @@ -437,12 +443,7 @@ private function exportSequenceInformation(\SimpleXMLElement $identifierXmlNode, $sequenceGeneratorXml->addAttribute('initial-value', $sequenceDefinition['initialValue']); } - /** - * @param \SimpleXMLElement $simpleXml - * - * @return string $xml - */ - private function _asXml($simpleXml) + private function _asXml(SimpleXMLElement $simpleXml) : string { $dom = new \DOMDocument('1.0', 'UTF-8'); $dom->loadXML($simpleXml->asXML()); @@ -450,4 +451,46 @@ private function _asXml($simpleXml) return $dom->saveXML(); } + + private function processEntityListeners(ClassMetadataInfo $metadata, SimpleXMLElement $root): void + { + if (0 === \count($metadata->entityListeners)) { + return; + } + + $entityListenersXml = $root->addChild('entity-listeners'); + $entityListenersXmlMap = []; + + $this->generateEntityListenerXml($metadata, $entityListenersXmlMap, $entityListenersXml); + } + + private function generateEntityListenerXml(ClassMetadataInfo $metadata, array $entityListenersXmlMap, SimpleXMLElement $entityListenersXml): void + { + foreach ($metadata->entityListeners as $event => $entityListenerConfig) { + foreach ($entityListenerConfig as $entityListener) { + $entityListenerXml = $this->addClassToMapIfExists( + $entityListenersXmlMap, + $entityListener, + $entityListenersXml + ); + + $entityListenerCallbackXml = $entityListenerXml->addChild('lifecycle-callback'); + $entityListenerCallbackXml->addAttribute('type', $event); + $entityListenerCallbackXml->addAttribute('method', $entityListener['method']); + } + } + } + + private function addClassToMapIfExists(array $entityListenersXmlMap, array $entityListener, SimpleXMLElement $entityListenersXml): SimpleXMLElement + { + if (isset($entityListenersXmlMap[$entityListener['class']])) { + return $entityListenersXmlMap[$entityListener['class']]; + } + + $entityListenerXml = $entityListenersXml->addChild('entity-listener'); + $entityListenerXml->addAttribute('class', $entityListener['class']); + $entityListenersXmlMap[$entityListener['class']] = $entityListenerXml; + + return $entityListenerXml; + } } diff --git a/lib/Doctrine/ORM/Tools/Export/Driver/YamlExporter.php b/lib/Doctrine/ORM/Tools/Export/Driver/YamlExporter.php index 7677ad9501e..1fb960b3333 100644 --- a/lib/Doctrine/ORM/Tools/Export/Driver/YamlExporter.php +++ b/lib/Doctrine/ORM/Tools/Export/Driver/YamlExporter.php @@ -28,6 +28,8 @@ * @link www.doctrine-project.org * @since 2.0 * @author Jonathan Wage + * + * @deprecated 2.7 This class is being removed from the ORM and won't have any replacement */ class YamlExporter extends AbstractExporter { @@ -41,18 +43,19 @@ class YamlExporter extends AbstractExporter */ public function exportClassMetadata(ClassMetadataInfo $metadata) { - $array = array(); + $array = []; if ($metadata->isMappedSuperclass) { $array['type'] = 'mappedSuperclass'; } else { $array['type'] = 'entity'; } + $metadataTable = $metadata->table ?? ['name' => null]; - $array['table'] = $metadata->table['name']; + $array['table'] = $metadataTable['name']; - if (isset($metadata->table['schema'])) { - $array['schema'] = $metadata->table['schema']; + if (isset($metadataTable['schema'])) { + $array['schema'] = $metadataTable['schema']; } $inheritanceType = $metadata->inheritanceType; @@ -73,25 +76,25 @@ public function exportClassMetadata(ClassMetadataInfo $metadata) $array['changeTrackingPolicy'] = $this->_getChangeTrackingPolicyString($metadata->changeTrackingPolicy); } - if (isset($metadata->table['indexes'])) { - $array['indexes'] = $metadata->table['indexes']; + if (isset($metadataTable['indexes'])) { + $array['indexes'] = $metadataTable['indexes']; } if ($metadata->customRepositoryClassName) { $array['repositoryClass'] = $metadata->customRepositoryClassName; } - if (isset($metadata->table['uniqueConstraints'])) { - $array['uniqueConstraints'] = $metadata->table['uniqueConstraints']; + if (isset($metadataTable['uniqueConstraints'])) { + $array['uniqueConstraints'] = $metadataTable['uniqueConstraints']; } - if (isset($metadata->table['options'])) { - $array['options'] = $metadata->table['options']; + if (isset($metadataTable['options'])) { + $array['options'] = $metadataTable['options']; } $fieldMappings = $metadata->fieldMappings; - $ids = array(); + $ids = []; foreach ($fieldMappings as $name => $fieldMapping) { $fieldMapping['column'] = $fieldMapping['columnName']; @@ -118,13 +121,13 @@ public function exportClassMetadata(ClassMetadataInfo $metadata) if ($fieldMappings) { if ( ! isset($array['fields'])) { - $array['fields'] = array(); + $array['fields'] = []; } $array['fields'] = array_merge($array['fields'], $fieldMappings); } foreach ($metadata->associationMappings as $name => $associationMapping) { - $cascade = array(); + $cascade = []; if ($associationMapping['isCascadeRemove']) { $cascade[] = 'remove'; @@ -146,25 +149,25 @@ public function exportClassMetadata(ClassMetadataInfo $metadata) $cascade[] = 'detach'; } if (count($cascade) === 5) { - $cascade = array('all'); + $cascade = ['all']; } - $associationMappingArray = array( + $associationMappingArray = [ 'targetEntity' => $associationMapping['targetEntity'], 'cascade' => $cascade, - ); + ]; if (isset($associationMapping['fetch'])) { $associationMappingArray['fetch'] = $this->_getFetchModeString($associationMapping['fetch']); } - if (isset($mapping['id']) && $mapping['id'] === true) { + if (isset($associationMapping['id']) && $associationMapping['id'] === true) { $array['id'][$name]['associationKey'] = true; } if ($associationMapping['type'] & ClassMetadataInfo::TO_ONE) { $joinColumns = $associationMapping['isOwningSide'] ? $associationMapping['joinColumns'] : []; - $newJoinColumns = array(); + $newJoinColumns = []; foreach ($joinColumns as $joinColumn) { $newJoinColumns[$joinColumn['name']]['referencedColumnName'] = $joinColumn['referencedColumnName']; @@ -174,12 +177,12 @@ public function exportClassMetadata(ClassMetadataInfo $metadata) } } - $oneToOneMappingArray = array( + $oneToOneMappingArray = [ 'mappedBy' => $associationMapping['mappedBy'], 'inversedBy' => $associationMapping['inversedBy'], 'joinColumns' => $newJoinColumns, 'orphanRemoval' => $associationMapping['orphanRemoval'], - ); + ]; $associationMappingArray = array_merge($associationMappingArray, $oneToOneMappingArray); @@ -189,22 +192,22 @@ public function exportClassMetadata(ClassMetadataInfo $metadata) $array['manyToOne'][$name] = $associationMappingArray; } } elseif ($associationMapping['type'] == ClassMetadataInfo::ONE_TO_MANY) { - $oneToManyMappingArray = array( + $oneToManyMappingArray = [ 'mappedBy' => $associationMapping['mappedBy'], 'inversedBy' => $associationMapping['inversedBy'], 'orphanRemoval' => $associationMapping['orphanRemoval'], - 'orderBy' => isset($associationMapping['orderBy']) ? $associationMapping['orderBy'] : null - ); + 'orderBy' => $associationMapping['orderBy'] ?? null + ]; $associationMappingArray = array_merge($associationMappingArray, $oneToManyMappingArray); $array['oneToMany'][$name] = $associationMappingArray; } elseif ($associationMapping['type'] == ClassMetadataInfo::MANY_TO_MANY) { - $manyToManyMappingArray = array( + $manyToManyMappingArray = [ 'mappedBy' => $associationMapping['mappedBy'], 'inversedBy' => $associationMapping['inversedBy'], - 'joinTable' => isset($associationMapping['joinTable']) ? $associationMapping['joinTable'] : null, - 'orderBy' => isset($associationMapping['orderBy']) ? $associationMapping['orderBy'] : null - ); + 'joinTable' => $associationMapping['joinTable'] ?? null, + 'orderBy' => $associationMapping['orderBy'] ?? null + ]; $associationMappingArray = array_merge($associationMappingArray, $manyToManyMappingArray); $array['manyToMany'][$name] = $associationMappingArray; @@ -214,7 +217,9 @@ public function exportClassMetadata(ClassMetadataInfo $metadata) $array['lifecycleCallbacks'] = $metadata->lifecycleCallbacks; } - return $this->yamlDump(array($metadata->name => $array), 10); + $array = $this->processEntityListeners($metadata, $array); + + return $this->yamlDump([$metadata->name => $array], 10); } /** @@ -232,4 +237,32 @@ protected function yamlDump($array, $inline = 2) { return Yaml::dump($array, $inline); } + + private function processEntityListeners(ClassMetadataInfo $metadata, array $array) : array + { + if (0 === \count($metadata->entityListeners)) { + return $array; + } + + $array['entityListeners'] = []; + + foreach ($metadata->entityListeners as $event => $entityListenerConfig) { + $array = $this->processEntityListenerConfig($array, $entityListenerConfig, $event); + } + + return $array; + } + + private function processEntityListenerConfig(array $array, array $entityListenerConfig, string $event) : array + { + foreach ($entityListenerConfig as $entityListener) { + if (! isset($array['entityListeners'][$entityListener['class']])) { + $array['entityListeners'][$entityListener['class']] = []; + } + + $array['entityListeners'][$entityListener['class']][$event] = [$entityListener['method']]; + } + + return $array; + } } diff --git a/lib/Doctrine/ORM/Tools/Export/ExportException.php b/lib/Doctrine/ORM/Tools/Export/ExportException.php index 89ddfe22eb0..725ea2137c8 100644 --- a/lib/Doctrine/ORM/Tools/Export/ExportException.php +++ b/lib/Doctrine/ORM/Tools/Export/ExportException.php @@ -1,9 +1,29 @@ . + */ namespace Doctrine\ORM\Tools\Export; use Doctrine\ORM\ORMException; +/** + * @deprecated 2.7 This class is being removed from the ORM and won't have any replacement + */ class ExportException extends ORMException { /** @@ -35,4 +55,4 @@ public static function attemptOverwriteExistingFile($file) { return new self("Attempting to overwrite an existing file '".$file."'."); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/ORM/Tools/Pagination/CountOutputWalker.php b/lib/Doctrine/ORM/Tools/Pagination/CountOutputWalker.php index e44be6c57c4..f3db053ca29 100644 --- a/lib/Doctrine/ORM/Tools/Pagination/CountOutputWalker.php +++ b/lib/Doctrine/ORM/Tools/Pagination/CountOutputWalker.php @@ -1,14 +1,20 @@ . */ namespace Doctrine\ORM\Tools\Pagination; @@ -85,6 +91,14 @@ public function walkSelectStatement(SelectStatement $AST) $sql = parent::walkSelectStatement($AST); + if ($AST->groupByClause) { + return sprintf( + 'SELECT %s AS dctrn_count FROM (%s) dctrn_table', + $this->platform->getCountExpression('*'), + $sql + ); + } + // Find out the SQL alias of the identifier column of the root entity // It may be possible to make this work with multiple root entities but that // would probably require issuing multiple queries or doing a UNION SELECT @@ -102,7 +116,7 @@ public function walkSelectStatement(SelectStatement $AST) $rootIdentifier = $rootClass->identifier; // For every identifier, find out the SQL alias by combing through the ResultSetMapping - $sqlIdentifier = array(); + $sqlIdentifier = []; foreach ($rootIdentifier as $property) { if (isset($rootClass->fieldMappings[$property])) { foreach (array_keys($this->rsm->fieldMappings, $property) as $alias) { diff --git a/lib/Doctrine/ORM/Tools/Pagination/CountWalker.php b/lib/Doctrine/ORM/Tools/Pagination/CountWalker.php index ff0c6b36331..a8f26001aba 100644 --- a/lib/Doctrine/ORM/Tools/Pagination/CountWalker.php +++ b/lib/Doctrine/ORM/Tools/Pagination/CountWalker.php @@ -1,14 +1,20 @@ . */ namespace Doctrine\ORM\Tools\Pagination; @@ -53,11 +59,11 @@ public function walkSelectStatement(SelectStatement $AST) $queryComponents = $this->_getQueryComponents(); // Get the root entity and alias from the AST fromClause $from = $AST->fromClause->identificationVariableDeclarations; - + if (count($from) > 1) { throw new \RuntimeException("Cannot count query which selects two FROM components, cannot make distinction"); } - + $fromRoot = reset($from); $rootAlias = $fromRoot->rangeVariableDeclaration->aliasIdentificationVariable; $rootClass = $queryComponents[$rootAlias]['metadata']; @@ -75,11 +81,11 @@ public function walkSelectStatement(SelectStatement $AST) $pathExpression->type = $pathType; $distinct = $this->_getQuery()->getHint(self::HINT_DISTINCT); - $AST->selectClause->selectExpressions = array( + $AST->selectClause->selectExpressions = [ new SelectExpression( new AggregateExpression('count', $pathExpression, $distinct), null ) - ); + ]; // ORDER BY is not needed, only increases query execution through unnecessary sorting. $AST->orderByClause = null; diff --git a/lib/Doctrine/ORM/Tools/Pagination/LimitSubqueryOutputWalker.php b/lib/Doctrine/ORM/Tools/Pagination/LimitSubqueryOutputWalker.php index 92386e46de2..034b33b2c16 100644 --- a/lib/Doctrine/ORM/Tools/Pagination/LimitSubqueryOutputWalker.php +++ b/lib/Doctrine/ORM/Tools/Pagination/LimitSubqueryOutputWalker.php @@ -1,14 +1,20 @@ . */ namespace Doctrine\ORM\Tools\Pagination; @@ -37,6 +43,8 @@ */ class LimitSubqueryOutputWalker extends SqlWalker { + private const ORDER_BY_PATH_EXPRESSION = '/(?rebuildOrderByClauseForOuterScope($orderByClause); - - // Build the select distinct statement - $sql = sprintf( - 'SELECT DISTINCT %s FROM (%s) dctrn_result ORDER BY %s', - implode(', ', $sqlIdentifier), - $innerSql, - implode(', ', $orderBy) + // now only select distinct identifier + return \sprintf( + 'SELECT DISTINCT %s FROM (%s) dctrn_result', + \implode(', ', $sqlIdentifier), + $this->recreateInnerSql($orderByClause, $sqlIdentifier, $innerSql) ); - - return $sql; } /** - * Generates a new order by clause that works in the scope of a select query wrapping the original + * Generates a new SQL statement for the inner query to keep the correct sorting * * @param OrderByClause $orderByClause - * @return array + * @param array $identifiers + * @param string $innerSql + * + * @return string + */ + private function recreateInnerSql( + OrderByClause $orderByClause, + array $identifiers, + string $innerSql + ) : string { + [$searchPatterns, $replacements] = $this->generateSqlAliasReplacements(); + + $orderByItems = []; + + foreach ($orderByClause->orderByItems as $orderByItem) { + // Walk order by item to get string representation of it and + // replace path expressions in the order by clause with their column alias + $orderByItemString = \preg_replace( + $searchPatterns, + $replacements, + $this->walkOrderByItem($orderByItem) + ); + + $orderByItems[] = $orderByItemString; + $identifier = \substr($orderByItemString, 0, \strrpos($orderByItemString, ' ')); + + if (! \in_array($identifier, $identifiers, true)) { + $identifiers[] = $identifier; + } + } + + return $sql = \sprintf( + 'SELECT DISTINCT %s FROM (%s) dctrn_result_inner ORDER BY %s', + \implode(', ', $identifiers), + $innerSql, + \implode(', ', $orderByItems) + ); + } + + /** + * @return string[][] */ - private function rebuildOrderByClauseForOuterScope(OrderByClause $orderByClause) + private function generateSqlAliasReplacements() : array { - $dqlAliasToSqlTableAliasMap - = $searchPatterns - = $replacements - = $dqlAliasToClassMap - = $selectListAdditions - = $orderByItems - = []; + $aliasMap = $searchPatterns = $replacements = $metadataList = []; // Generate DQL alias -> SQL table alias mapping - foreach(array_keys($this->rsm->aliasMap) as $dqlAlias) { - $dqlAliasToClassMap[$dqlAlias] = $class = $this->queryComponents[$dqlAlias]['metadata']; - $dqlAliasToSqlTableAliasMap[$dqlAlias] = $this->getSQLTableAlias($class->getTableName(), $dqlAlias); + foreach (\array_keys($this->rsm->aliasMap) as $dqlAlias) { + $metadataList[$dqlAlias] = $class = $this->queryComponents[$dqlAlias]['metadata']; + $aliasMap[$dqlAlias] = $this->getSQLTableAlias($class->getTableName(), $dqlAlias); } - // Pattern to find table path expressions in the order by clause - $fieldSearchPattern = '/(?rsm->fieldMappings as $fieldAlias => $fieldName) { + foreach ($this->rsm->fieldMappings as $fieldAlias => $fieldName) { $dqlAliasForFieldAlias = $this->rsm->columnOwnerMap[$fieldAlias]; - $class = $dqlAliasToClassMap[$dqlAliasForFieldAlias]; + $class = $metadataList[$dqlAliasForFieldAlias]; - // If the field is from a joined child table, we won't be ordering - // on it. - if (!isset($class->fieldMappings[$fieldName])) { + // If the field is from a joined child table, we won't be ordering on it. + if (! isset($class->fieldMappings[$fieldName])) { continue; } @@ -419,37 +453,29 @@ private function rebuildOrderByClauseForOuterScope(OrderByClause $orderByClause) // Get the proper column name as will appear in the select list $columnName = $this->quoteStrategy->getColumnName( $fieldName, - $dqlAliasToClassMap[$dqlAliasForFieldAlias], + $metadataList[$dqlAliasForFieldAlias], $this->em->getConnection()->getDatabasePlatform() ); // Get the SQL table alias for the entity and field - $sqlTableAliasForFieldAlias = $dqlAliasToSqlTableAliasMap[$dqlAliasForFieldAlias]; + $sqlTableAliasForFieldAlias = $aliasMap[$dqlAliasForFieldAlias]; + if (isset($fieldMapping['declared']) && $fieldMapping['declared'] !== $class->name) { // Field was declared in a parent class, so we need to get the proper SQL table alias // for the joined parent table. $otherClassMetadata = $this->em->getClassMetadata($fieldMapping['declared']); - if (!$otherClassMetadata->isMappedSuperclass) { + + if (! $otherClassMetadata->isMappedSuperclass) { $sqlTableAliasForFieldAlias = $this->getSQLTableAlias($otherClassMetadata->getTableName(), $dqlAliasForFieldAlias); } } - // Compose search/replace patterns - $searchPatterns[] = sprintf($fieldSearchPattern, $sqlTableAliasForFieldAlias, $columnName); - $replacements[] = $fieldAlias; - } - - foreach($orderByClause->orderByItems as $orderByItem) { - // Walk order by item to get string representation of it - $orderByItemString = $this->walkOrderByItem($orderByItem); - - // Replace path expressions in the order by clause with their column alias - $orderByItemString = preg_replace($searchPatterns, $replacements, $orderByItemString); - - $orderByItems[] = $orderByItemString; + // Compose search and replace patterns + $searchPatterns[] = \sprintf(self::ORDER_BY_PATH_EXPRESSION, $sqlTableAliasForFieldAlias, $columnName); + $replacements[] = $fieldAlias; } - return $orderByItems; + return [$searchPatterns, $replacements]; } /** diff --git a/lib/Doctrine/ORM/Tools/Pagination/LimitSubqueryWalker.php b/lib/Doctrine/ORM/Tools/Pagination/LimitSubqueryWalker.php index fd51fb46bd5..5614138a86c 100644 --- a/lib/Doctrine/ORM/Tools/Pagination/LimitSubqueryWalker.php +++ b/lib/Doctrine/ORM/Tools/Pagination/LimitSubqueryWalker.php @@ -1,19 +1,20 @@ - * @copyright Copyright (c) 2010 David Abdemoulaie (http://hobodave.com/) - * @license http://hobodave.com/license.txt New BSD License + * This software consists of voluntary contributions made by many individuals + * and is licensed under the MIT license. For more information, see + * . */ namespace Doctrine\ORM\Tools\Pagination; @@ -38,10 +39,9 @@ */ class LimitSubqueryWalker extends TreeWalkerAdapter { - /** - * ID type hint. - */ - const IDENTIFIER_TYPE = 'doctrine_paginator.id.type'; + public const IDENTIFIER_TYPE = 'doctrine_paginator.id.type'; + + public const FORCE_DBAL_TYPE_CONVERSION = 'doctrine_paginator.scalar_result.force_dbal_type_conversion'; /** * Counter for generating unique order column aliases. @@ -68,20 +68,10 @@ public function walkSelectStatement(SelectStatement $AST) $fromRoot = reset($from); $rootAlias = $fromRoot->rangeVariableDeclaration->aliasIdentificationVariable; $rootClass = $queryComponents[$rootAlias]['metadata']; - $selectExpressions = array(); $this->validate($AST); - - foreach ($queryComponents as $dqlAlias => $qComp) { - // Preserve mixed data in query for ordering. - if (isset($qComp['resultVariable'])) { - $selectExpressions[] = new SelectExpression($qComp['resultVariable'], $dqlAlias); - continue; - } - } - $identifier = $rootClass->getSingleIdentifierFieldName(); - + if (isset($rootClass->associationMappings[$identifier])) { throw new \RuntimeException("Paginating an entity with foreign key as identifier only works when using the Output Walkers. Call Paginator#setUseOutputWalkers(true) before iterating the paginator."); } @@ -91,6 +81,8 @@ public function walkSelectStatement(SelectStatement $AST) Type::getType($rootClass->fieldMappings[$identifier]['type']) ); + $this->_getQuery()->setHint(self::FORCE_DBAL_TYPE_CONVERSION, true); + $pathExpression = new PathExpression( PathExpression::TYPE_STATE_FIELD | PathExpression::TYPE_SINGLE_VALUED_ASSOCIATION, $rootAlias, @@ -99,24 +91,33 @@ public function walkSelectStatement(SelectStatement $AST) $pathExpression->type = PathExpression::TYPE_STATE_FIELD; - array_unshift($selectExpressions, new SelectExpression($pathExpression, '_dctrn_id')); + $AST->selectClause->selectExpressions = [new SelectExpression($pathExpression, '_dctrn_id')]; + $AST->selectClause->isDistinct = true; - $AST->selectClause->selectExpressions = $selectExpressions; + if ( ! isset($AST->orderByClause)) { + return; + } - if (isset($AST->orderByClause)) { - foreach ($AST->orderByClause->orderByItems as $item) { - if ( ! $item->expression instanceof PathExpression) { - continue; - } - + foreach ($AST->orderByClause->orderByItems as $item) { + if ($item->expression instanceof PathExpression) { $AST->selectClause->selectExpressions[] = new SelectExpression( - $this->createSelectExpressionItem($item->expression), - '_dctrn_ord' . $this->_aliasCounter++ + $this->createSelectExpressionItem($item->expression), '_dctrn_ord' . $this->_aliasCounter++ ); + + continue; } - } - $AST->selectClause->isDistinct = true; + if (is_string($item->expression) && isset($queryComponents[$item->expression])) { + $qComp = $queryComponents[$item->expression]; + + if (isset($qComp['resultVariable'])) { + $AST->selectClause->selectExpressions[] = new SelectExpression( + $qComp['resultVariable'], + $item->expression + ); + } + } + } } /** @@ -135,7 +136,7 @@ private function validate(SelectStatement $AST) $fromRoot = reset($from); if ($query instanceof Query - && $query->getMaxResults() + && null !== $query->getMaxResults() && $AST->orderByClause && count($fromRoot->joins)) { // Check each orderby item. @@ -153,24 +154,24 @@ private function validate(SelectStatement $AST) } } } - + /** * Retrieve either an IdentityFunction (IDENTITY(u.assoc)) or a state field (u.name). - * + * * @param \Doctrine\ORM\Query\AST\PathExpression $pathExpression - * + * * @return \Doctrine\ORM\Query\AST\Functions\IdentityFunction */ private function createSelectExpressionItem(PathExpression $pathExpression) { if ($pathExpression->type === PathExpression::TYPE_SINGLE_VALUED_ASSOCIATION) { $identity = new IdentityFunction('identity'); - + $identity->pathExpression = clone $pathExpression; - + return $identity; } - + return clone $pathExpression; } } diff --git a/lib/Doctrine/ORM/Tools/Pagination/Paginator.php b/lib/Doctrine/ORM/Tools/Pagination/Paginator.php index 449aae1cac6..64cd9e243fa 100644 --- a/lib/Doctrine/ORM/Tools/Pagination/Paginator.php +++ b/lib/Doctrine/ORM/Tools/Pagination/Paginator.php @@ -19,11 +19,12 @@ namespace Doctrine\ORM\Tools\Pagination; -use Doctrine\ORM\Query\Parser; -use Doctrine\ORM\QueryBuilder; +use Doctrine\ORM\NoResultException; use Doctrine\ORM\Query; +use Doctrine\ORM\Query\Parser; use Doctrine\ORM\Query\ResultSetMapping; -use Doctrine\ORM\NoResultException; +use Doctrine\ORM\QueryBuilder; +use function array_map; /** * The paginator can handle various complex scenarios with DQL. @@ -138,30 +139,34 @@ public function getIterator() $offset = $this->query->getFirstResult(); $length = $this->query->getMaxResults(); - if ($this->fetchJoinCollection) { + if ($this->fetchJoinCollection && $length !== null) { $subQuery = $this->cloneQuery($this->query); if ($this->useOutputWalker($subQuery)) { - $subQuery->setHint(Query::HINT_CUSTOM_OUTPUT_WALKER, 'Doctrine\ORM\Tools\Pagination\LimitSubqueryOutputWalker'); + $subQuery->setHint(Query::HINT_CUSTOM_OUTPUT_WALKER, LimitSubqueryOutputWalker::class); } else { - $this->appendTreeWalker($subQuery, 'Doctrine\ORM\Tools\Pagination\LimitSubqueryWalker'); + $this->appendTreeWalker($subQuery, LimitSubqueryWalker::class); + $this->unbindUnusedQueryParams($subQuery); } $subQuery->setFirstResult($offset)->setMaxResults($length); - $ids = array_map('current', $subQuery->getScalarResult()); + $foundIdRows = $subQuery->getScalarResult(); - $whereInQuery = $this->cloneQuery($this->query); // don't do this for an empty id array - if (count($ids) === 0) { - return new \ArrayIterator(array()); + if ($foundIdRows === []) { + return new \ArrayIterator([]); } - $this->appendTreeWalker($whereInQuery, 'Doctrine\ORM\Tools\Pagination\WhereInWalker'); + $whereInQuery = $this->cloneQuery($this->query); + $ids = array_map('current', $foundIdRows); + + $this->appendTreeWalker($whereInQuery, WhereInWalker::class); $whereInQuery->setHint(WhereInWalker::HINT_PAGINATOR_ID_COUNT, count($ids)); $whereInQuery->setFirstResult(null)->setMaxResults(null); $whereInQuery->setParameter(WhereInWalker::PAGINATOR_ID_ALIAS, $ids); $whereInQuery->setCacheable($this->query->isCacheable()); + $whereInQuery->expireQueryCache(); $result = $whereInQuery->getResult($this->query->getHydrationMode()); } else { @@ -225,7 +230,7 @@ private function appendTreeWalker(Query $query, $walkerClass) $hints = $query->getHint(Query::HINT_CUSTOM_TREE_WALKERS); if ($hints === false) { - $hints = array(); + $hints = []; } $hints[] = $walkerClass; @@ -252,18 +257,24 @@ private function getCountQuery() $rsm = new ResultSetMapping(); $rsm->addScalarResult($platform->getSQLResultCasing('dctrn_count'), 'count'); - $countQuery->setHint(Query::HINT_CUSTOM_OUTPUT_WALKER, 'Doctrine\ORM\Tools\Pagination\CountOutputWalker'); + $countQuery->setHint(Query::HINT_CUSTOM_OUTPUT_WALKER, CountOutputWalker::class); $countQuery->setResultSetMapping($rsm); } else { - $this->appendTreeWalker($countQuery, 'Doctrine\ORM\Tools\Pagination\CountWalker'); + $this->appendTreeWalker($countQuery, CountWalker::class); + $this->unbindUnusedQueryParams($countQuery); } $countQuery->setFirstResult(null)->setMaxResults(null); - $parser = new Parser($countQuery); + return $countQuery; + } + + private function unbindUnusedQueryParams(Query $query): void + { + $parser = new Parser($query); $parameterMappings = $parser->parse()->getParameterMappings(); /* @var $parameters \Doctrine\Common\Collections\Collection|\Doctrine\ORM\Query\Parameter[] */ - $parameters = $countQuery->getParameters(); + $parameters = $query->getParameters(); foreach ($parameters as $key => $parameter) { $parameterName = $parameter->getName(); @@ -273,8 +284,6 @@ private function getCountQuery() } } - $countQuery->setParameters($parameters); - - return $countQuery; + $query->setParameters($parameters); } } diff --git a/lib/Doctrine/ORM/Tools/Pagination/RowNumberOverFunction.php b/lib/Doctrine/ORM/Tools/Pagination/RowNumberOverFunction.php index 52511b4b10a..a9d3e5d686e 100644 --- a/lib/Doctrine/ORM/Tools/Pagination/RowNumberOverFunction.php +++ b/lib/Doctrine/ORM/Tools/Pagination/RowNumberOverFunction.php @@ -40,6 +40,7 @@ class RowNumberOverFunction extends FunctionNode /** * @override + * @inheritdoc */ public function getSql(\Doctrine\ORM\Query\SqlWalker $sqlWalker) { @@ -50,6 +51,7 @@ public function getSql(\Doctrine\ORM\Query\SqlWalker $sqlWalker) /** * @override + * @inheritdoc * * @throws ORMException */ diff --git a/lib/Doctrine/ORM/Tools/Pagination/WhereInWalker.php b/lib/Doctrine/ORM/Tools/Pagination/WhereInWalker.php index 9f42a1eea7a..de66f64d7ec 100644 --- a/lib/Doctrine/ORM/Tools/Pagination/WhereInWalker.php +++ b/lib/Doctrine/ORM/Tools/Pagination/WhereInWalker.php @@ -1,35 +1,42 @@ - * @copyright Copyright (c) 2010 David Abdemoulaie (http://hobodave.com/) - * @license http://hobodave.com/license.txt New BSD License + * This software consists of voluntary contributions made by many individuals + * and is licensed under the MIT license. For more information, see + * . */ namespace Doctrine\ORM\Tools\Pagination; +use Doctrine\ORM\Mapping\ClassMetadata; use Doctrine\ORM\Query\AST\ArithmeticExpression; -use Doctrine\ORM\Query\AST\SimpleArithmeticExpression; -use Doctrine\ORM\Query\TreeWalkerAdapter; -use Doctrine\ORM\Query\AST\SelectStatement; -use Doctrine\ORM\Query\AST\PathExpression; -use Doctrine\ORM\Query\AST\InExpression; -use Doctrine\ORM\Query\AST\NullComparisonExpression; -use Doctrine\ORM\Query\AST\InputParameter; -use Doctrine\ORM\Query\AST\ConditionalPrimary; -use Doctrine\ORM\Query\AST\ConditionalTerm; use Doctrine\ORM\Query\AST\ConditionalExpression; use Doctrine\ORM\Query\AST\ConditionalFactor; +use Doctrine\ORM\Query\AST\ConditionalPrimary; +use Doctrine\ORM\Query\AST\ConditionalTerm; +use Doctrine\ORM\Query\AST\InExpression; +use Doctrine\ORM\Query\AST\InputParameter; +use Doctrine\ORM\Query\AST\NullComparisonExpression; +use Doctrine\ORM\Query\AST\PathExpression; +use Doctrine\ORM\Query\AST\SelectStatement; +use Doctrine\ORM\Query\AST\SimpleArithmeticExpression; use Doctrine\ORM\Query\AST\WhereClause; +use Doctrine\ORM\Query\TreeWalkerAdapter; +use Doctrine\ORM\Utility\PersisterHelper; +use function array_map; +use function assert; +use function is_array; /** * Replaces the whereClause of the AST with a WHERE id IN (:foo_1, :foo_2) equivalent. @@ -74,13 +81,14 @@ public function walkSelectStatement(SelectStatement $AST) $queryComponents = $this->_getQueryComponents(); // Get the root entity and alias from the AST fromClause $from = $AST->fromClause->identificationVariableDeclarations; - + if (count($from) > 1) { throw new \RuntimeException("Cannot count query which selects two FROM components, cannot make distinction"); } - + $fromRoot = reset($from); $rootAlias = $fromRoot->rangeVariableDeclaration->aliasIdentificationVariable; + /** @var ClassMetadata $rootClass */ $rootClass = $queryComponents[$rootAlias]['metadata']; $identifierFieldName = $rootClass->getSingleIdentifierFieldName(); @@ -97,11 +105,19 @@ public function walkSelectStatement(SelectStatement $AST) if ($count > 0) { $arithmeticExpression = new ArithmeticExpression(); $arithmeticExpression->simpleArithmeticExpression = new SimpleArithmeticExpression( - array($pathExpression) + [$pathExpression] ); $expression = new InExpression($arithmeticExpression); $expression->literals[] = new InputParameter(":" . self::PAGINATOR_ID_ALIAS); + $this->convertWhereInIdentifiersToDatabaseValue( + PersisterHelper::getTypeOfField( + $identifierFieldName, + $rootClass, + $this->_getQuery() + ->getEntityManager() + )[0] + ); } else { $expression = new NullComparisonExpression($pathExpression); $expression->not = false; @@ -113,30 +129,56 @@ public function walkSelectStatement(SelectStatement $AST) if ($AST->whereClause->conditionalExpression instanceof ConditionalTerm) { $AST->whereClause->conditionalExpression->conditionalFactors[] = $conditionalPrimary; } elseif ($AST->whereClause->conditionalExpression instanceof ConditionalPrimary) { - $AST->whereClause->conditionalExpression = new ConditionalExpression(array( - new ConditionalTerm(array( - $AST->whereClause->conditionalExpression, - $conditionalPrimary - )) - )); + $AST->whereClause->conditionalExpression = new ConditionalExpression( + [ + new ConditionalTerm( + [ + $AST->whereClause->conditionalExpression, + $conditionalPrimary + ] + ) + ] + ); } elseif ($AST->whereClause->conditionalExpression instanceof ConditionalExpression || $AST->whereClause->conditionalExpression instanceof ConditionalFactor ) { $tmpPrimary = new ConditionalPrimary; $tmpPrimary->conditionalExpression = $AST->whereClause->conditionalExpression; - $AST->whereClause->conditionalExpression = new ConditionalTerm(array( - $tmpPrimary, - $conditionalPrimary - )); + $AST->whereClause->conditionalExpression = new ConditionalTerm( + [ + $tmpPrimary, + $conditionalPrimary + ] + ); } } else { $AST->whereClause = new WhereClause( - new ConditionalExpression(array( - new ConditionalTerm(array( - $conditionalPrimary - )) - )) + new ConditionalExpression( + [ + new ConditionalTerm([$conditionalPrimary]) + ] + ) ); } } + + private function convertWhereInIdentifiersToDatabaseValue(string $type) : void + { + $query = $this->_getQuery(); + $identifiersParameter = $query->getParameter(self::PAGINATOR_ID_ALIAS); + + assert($identifiersParameter !== null); + + $identifiers = $identifiersParameter->getValue(); + + assert(is_array($identifiers)); + + $connection = $this->_getQuery() + ->getEntityManager() + ->getConnection(); + + $query->setParameter(self::PAGINATOR_ID_ALIAS, array_map(static function ($id) use ($connection, $type) { + return $connection->convertToDatabaseValue($id, $type); + }, $identifiers)); + } } diff --git a/lib/Doctrine/ORM/Tools/ResolveTargetEntityListener.php b/lib/Doctrine/ORM/Tools/ResolveTargetEntityListener.php index 574c9c28e12..36f1f929bde 100644 --- a/lib/Doctrine/ORM/Tools/ResolveTargetEntityListener.php +++ b/lib/Doctrine/ORM/Tools/ResolveTargetEntityListener.php @@ -39,17 +39,17 @@ class ResolveTargetEntityListener implements EventSubscriber /** * @var array[] indexed by original entity name */ - private $resolveTargetEntities = array(); + private $resolveTargetEntities = []; /** * {@inheritDoc} */ public function getSubscribedEvents() { - return array( + return [ Events::loadClassMetadata, Events::onClassMetadataNotFound - ); + ]; } /** @@ -80,7 +80,7 @@ public function onClassMetadataNotFound(OnClassMetadataNotFoundEventArgs $args) $args->setFoundMetadata( $args ->getObjectManager() - ->getClassMetadata($this->resolveTargetEntities[$args->getClassname()]['targetEntity']) + ->getClassMetadata($this->resolveTargetEntities[$args->getClassName()]['targetEntity']) ); } } diff --git a/lib/Doctrine/ORM/Tools/SchemaTool.php b/lib/Doctrine/ORM/Tools/SchemaTool.php index 15dddf7e6c0..ba63e6964d5 100644 --- a/lib/Doctrine/ORM/Tools/SchemaTool.php +++ b/lib/Doctrine/ORM/Tools/SchemaTool.php @@ -45,6 +45,8 @@ */ class SchemaTool { + private const KNOWN_COLUMN_OPTIONS = ['comment', 'unsigned', 'fixed', 'default']; + /** * @var \Doctrine\ORM\EntityManagerInterface */ @@ -92,7 +94,7 @@ public function createSchema(array $classes) foreach ($createSchemaSql as $sql) { try { $conn->executeQuery($sql); - } catch (\Exception $e) { + } catch (\Throwable $e) { throw ToolsException::schemaToolFailure($sql, $e); } } @@ -143,16 +145,16 @@ private function processingNotRequired($class, array $processedClasses) public function getSchemaFromMetadata(array $classes) { // Reminder for processed classes, used for hierarchies - $processedClasses = array(); + $processedClasses = []; $eventManager = $this->em->getEventManager(); $schemaManager = $this->em->getConnection()->getSchemaManager(); $metadataSchemaConfig = $schemaManager->createSchemaConfig(); $metadataSchemaConfig->setExplicitForeignKeyIndexes(false); - $schema = new Schema(array(), array(), $metadataSchemaConfig); + $schema = new Schema([], [], $metadataSchemaConfig); - $addedFks = array(); - $blacklistedFks = array(); + $addedFks = []; + $blacklistedFks = []; foreach ($classes as $class) { /** @var \Doctrine\ORM\Mapping\ClassMetadata $class */ @@ -183,19 +185,9 @@ public function getSchemaFromMetadata(array $classes) } } elseif ($class->isInheritanceTypeJoined()) { // Add all non-inherited fields as columns - $pkColumns = array(); foreach ($class->fieldMappings as $fieldName => $mapping) { if ( ! isset($mapping['inherited'])) { - $columnName = $this->quoteStrategy->getColumnName( - $mapping['fieldName'], - $class, - $this->platform - ); $this->gatherColumn($class, $mapping, $table); - - if ($class->isIdentifier($fieldName)) { - $pkColumns[] = $columnName; - } } } @@ -206,10 +198,12 @@ public function getSchemaFromMetadata(array $classes) $this->addDiscriminatorColumnDefinition($class, $table); } else { // Add an ID FK column to child tables - $inheritedKeyColumns = array(); + $pkColumns = []; + $inheritedKeyColumns = []; + foreach ($class->identifier as $identifierField) { - $idMapping = $class->fieldMappings[$identifierField]; - if (isset($idMapping['inherited'])) { + if (isset($class->fieldMappings[$identifierField]['inherited'])) { + $idMapping = $class->fieldMappings[$identifierField]; $this->gatherColumn($class, $idMapping, $table); $columnName = $this->quoteStrategy->getColumnName( $identifierField, @@ -221,9 +215,38 @@ public function getSchemaFromMetadata(array $classes) $pkColumns[] = $columnName; $inheritedKeyColumns[] = $columnName; + + continue; + } + + if (isset($class->associationMappings[$identifierField]['inherited'])) { + $idMapping = $class->associationMappings[$identifierField]; + + $targetEntity = current( + array_filter( + $classes, + function (ClassMetadata $class) use ($idMapping) : bool { + return $class->name === $idMapping['targetEntity']; + } + ) + ); + + foreach ($idMapping['joinColumns'] as $joinColumn) { + if (isset($targetEntity->fieldMappings[$joinColumn['referencedColumnName']])) { + $columnName = $this->quoteStrategy->getJoinColumnName( + $joinColumn, + $class, + $this->platform + ); + + $pkColumns[] = $columnName; + $inheritedKeyColumns[] = $columnName; + } + } } } - if (!empty($inheritedKeyColumns)) { + + if ( ! empty($inheritedKeyColumns)) { // Add a FK constraint on the ID column $table->addForeignKeyConstraint( $this->quoteStrategy->getTableName( @@ -232,14 +255,14 @@ public function getSchemaFromMetadata(array $classes) ), $inheritedKeyColumns, $inheritedKeyColumns, - array('onDelete' => 'CASCADE') + ['onDelete' => 'CASCADE'] ); } + if ( ! empty($pkColumns)) { + $table->setPrimaryKey($pkColumns); + } } - - $table->setPrimaryKey($pkColumns); - } elseif ($class->isInheritanceTypeTablePerClass()) { throw ORMException::notSupported(); } else { @@ -247,7 +270,7 @@ public function getSchemaFromMetadata(array $classes) $this->gatherRelationsSql($class, $table, $schema, $addedFks, $blacklistedFks); } - $pkColumns = array(); + $pkColumns = []; foreach ($class->identifier as $identifierField) { if (isset($class->fieldMappings[$identifierField])) { @@ -280,16 +303,16 @@ public function getSchemaFromMetadata(array $classes) if (isset($class->table['indexes'])) { foreach ($class->table['indexes'] as $indexName => $indexData) { if ( ! isset($indexData['flags'])) { - $indexData['flags'] = array(); + $indexData['flags'] = []; } - $table->addIndex($indexData['columns'], is_numeric($indexName) ? null : $indexName, (array) $indexData['flags'], isset($indexData['options']) ? $indexData['options'] : array()); + $table->addIndex($indexData['columns'], is_numeric($indexName) ? null : $indexName, (array) $indexData['flags'], $indexData['options'] ?? []); } } if (isset($class->table['uniqueConstraints'])) { foreach ($class->table['uniqueConstraints'] as $indexName => $indexData) { - $uniqIndex = new Index($indexName, $indexData['columns'], true, false, [], isset($indexData['options']) ? $indexData['options'] : []); + $uniqIndex = new Index($indexName, $indexData['columns'], true, false, [], $indexData['options'] ?? []); foreach ($table->getIndexes() as $tableIndexName => $tableIndex) { if ($tableIndex->isFullfilledBy($uniqIndex)) { @@ -298,7 +321,7 @@ public function getSchemaFromMetadata(array $classes) } } - $table->addUniqueIndex($indexData['columns'], is_numeric($indexName) ? null : $indexName, isset($indexData['options']) ? $indexData['options'] : array()); + $table->addUniqueIndex($indexData['columns'], is_numeric($indexName) ? null : $indexName, $indexData['options'] ?? []); } } @@ -330,7 +353,7 @@ public function getSchemaFromMetadata(array $classes) } } - if ( ! $this->platform->supportsSchemas() && ! $this->platform->canEmulateSchemas() ) { + if ( ! $this->platform->supportsSchemas() && ! $this->platform->canEmulateSchemas()) { $schema->visit(new RemoveNamespacedAssets()); } @@ -351,24 +374,23 @@ public function getSchemaFromMetadata(array $classes) * @param ClassMetadata $class * @param Table $table * - * @return array The portable column definition of the discriminator column as required by - * the DBAL. + * @return void */ private function addDiscriminatorColumnDefinition($class, Table $table) { $discrColumn = $class->discriminatorColumn; if ( ! isset($discrColumn['type']) || - (strtolower($discrColumn['type']) == 'string' && $discrColumn['length'] === null) + (strtolower($discrColumn['type']) == 'string' && ! isset($discrColumn['length'])) ) { $discrColumn['type'] = 'string'; $discrColumn['length'] = 255; } - $options = array( - 'length' => isset($discrColumn['length']) ? $discrColumn['length'] : null, + $options = [ + 'length' => $discrColumn['length'] ?? null, 'notnull' => true - ); + ]; if (isset($discrColumn['columnDefinition'])) { $options['columnDefinition'] = $discrColumn['columnDefinition']; @@ -384,11 +406,11 @@ private function addDiscriminatorColumnDefinition($class, Table $table) * @param ClassMetadata $class * @param Table $table * - * @return array The list of portable column definitions as required by the DBAL. + * @return void */ private function gatherColumns($class, Table $table) { - $pkColumns = array(); + $pkColumns = []; foreach ($class->fieldMappings as $mapping) { if ($class->isInheritanceTypeSingleTable() && isset($mapping['inherited'])) { @@ -401,12 +423,6 @@ private function gatherColumns($class, Table $table) $pkColumns[] = $this->quoteStrategy->getColumnName($mapping['fieldName'], $class, $this->platform); } } - - // For now, this is a hack required for single table inheritence, since this method is called - // twice by single table inheritence relations - if (!$table->hasIndex('primary')) { - //$table->setPrimaryKey($pkColumns); - } } /** @@ -416,24 +432,24 @@ private function gatherColumns($class, Table $table) * @param array $mapping The field mapping. * @param Table $table * - * @return array The portable column definition as required by the DBAL. + * @return void */ private function gatherColumn($class, array $mapping, Table $table) { $columnName = $this->quoteStrategy->getColumnName($mapping['fieldName'], $class, $this->platform); $columnType = $mapping['type']; - $options = array(); - $options['length'] = isset($mapping['length']) ? $mapping['length'] : null; + $options = []; + $options['length'] = $mapping['length'] ?? null; $options['notnull'] = isset($mapping['nullable']) ? ! $mapping['nullable'] : true; - if ($class->isInheritanceTypeSingleTable() && count($class->parentClasses) > 0) { + if ($class->isInheritanceTypeSingleTable() && $class->parentClasses) { $options['notnull'] = false; } - $options['platformOptions'] = array(); - $options['platformOptions']['version'] = $class->isVersioned && $class->versionField == $mapping['fieldName'] ? true : false; + $options['platformOptions'] = []; + $options['platformOptions']['version'] = $class->isVersioned && $class->versionField === $mapping['fieldName']; - if (strtolower($columnType) == 'string' && $options['length'] === null) { + if (strtolower($columnType) === 'string' && null === $options['length']) { $options['length'] = 255; } @@ -453,24 +469,13 @@ private function gatherColumn($class, array $mapping, Table $table) $options['columnDefinition'] = $mapping['columnDefinition']; } - if (isset($mapping['options'])) { - $knownOptions = array('comment', 'unsigned', 'fixed', 'default'); - - foreach ($knownOptions as $knownOption) { - if (array_key_exists($knownOption, $mapping['options'])) { - $options[$knownOption] = $mapping['options'][$knownOption]; - - unset($mapping['options'][$knownOption]); - } - } + // the 'default' option can be overwritten here + $options = $this->gatherColumnOptions($mapping) + $options; - $options['customSchemaOptions'] = $mapping['options']; - } - - if ($class->isIdGeneratorIdentity() && $class->getIdentifierFieldNames() == array($mapping['fieldName'])) { + if ($class->isIdGeneratorIdentity() && $class->getIdentifierFieldNames() == [$mapping['fieldName']]) { $options['autoincrement'] = true; } - if ($class->isInheritanceTypeJoined() && $class->name != $class->rootEntityName) { + if ($class->isInheritanceTypeJoined() && $class->name !== $class->rootEntityName) { $options['autoincrement'] = false; } @@ -481,9 +486,9 @@ private function gatherColumn($class, array $mapping, Table $table) $table->addColumn($columnName, $columnType, $options); } - $isUnique = isset($mapping['unique']) ? $mapping['unique'] : false; + $isUnique = $mapping['unique'] ?? false; if ($isUnique) { - $table->addUniqueIndex(array($columnName)); + $table->addUniqueIndex([$columnName]); } } @@ -503,15 +508,15 @@ private function gatherColumn($class, array $mapping, Table $table) */ private function gatherRelationsSql($class, $table, $schema, &$addedFks, &$blacklistedFks) { - foreach ($class->associationMappings as $mapping) { - if (isset($mapping['inherited'])) { + foreach ($class->associationMappings as $id => $mapping) { + if (isset($mapping['inherited']) && ! \in_array($id, $class->identifier, true)) { continue; } $foreignClass = $this->em->getClassMetadata($mapping['targetEntity']); if ($mapping['type'] & ClassMetadata::TO_ONE && $mapping['isOwningSide']) { - $primaryKeyColumns = array(); // PK is unnecessary for this relation-type + $primaryKeyColumns = []; // PK is unnecessary for this relation-type $this->gatherRelationJoinColumns( $mapping['joinColumns'], @@ -533,7 +538,7 @@ private function gatherRelationsSql($class, $table, $schema, &$addedFks, &$black $this->quoteStrategy->getJoinTableName($mapping, $foreignClass, $this->platform) ); - $primaryKeyColumns = array(); + $primaryKeyColumns = []; // Build first FK constraint (relation table => source table) $this->gatherRelationJoinColumns( @@ -581,7 +586,7 @@ private function getDefiningClass($class, $referencedColumnName) $referencedFieldName = $class->getFieldName($referencedColumnName); if ($class->hasField($referencedFieldName)) { - return array($class, $referencedFieldName); + return [$class, $referencedFieldName]; } if (in_array($referencedColumnName, $class->getIdentifierColumnNames())) { @@ -625,11 +630,11 @@ private function gatherRelationJoinColumns( &$blacklistedFks ) { - $localColumns = array(); - $foreignColumns = array(); - $fkOptions = array(); + $localColumns = []; + $foreignColumns = []; + $fkOptions = []; $foreignTableName = $this->quoteStrategy->getTableName($class, $this->platform); - $uniqueConstraints = array(); + $uniqueConstraints = []; foreach ($joinColumns as $joinColumn) { @@ -640,21 +645,21 @@ private function gatherRelationJoinColumns( if ( ! $definingClass) { throw new \Doctrine\ORM\ORMException( - "Column name `".$joinColumn['referencedColumnName']."` referenced for relation from ". - $mapping['sourceEntity'] . " towards ". $mapping['targetEntity'] . " does not exist." + 'Column name `' . $joinColumn['referencedColumnName'] . '` referenced for relation from ' + . $mapping['sourceEntity'] . ' towards ' . $mapping['targetEntity'] . ' does not exist.' ); } - $quotedColumnName = $this->quoteStrategy->getJoinColumnName($joinColumn, $class, $this->platform); - $quotedRefColumnName = $this->quoteStrategy->getReferencedJoinColumnName( + $quotedColumnName = $this->quoteStrategy->getJoinColumnName($joinColumn, $class, $this->platform); + $quotedRefColumnName = $this->quoteStrategy->getReferencedJoinColumnName( $joinColumn, $class, $this->platform ); - $primaryKeyColumns[] = $quotedColumnName; - $localColumns[] = $quotedColumnName; - $foreignColumns[] = $quotedRefColumnName; + $primaryKeyColumns[] = $quotedColumnName; + $localColumns[] = $quotedColumnName; + $foreignColumns[] = $quotedRefColumnName; if ( ! $theJoinTable->hasColumn($quotedColumnName)) { // Only add the column to the table if it does not exist already. @@ -670,15 +675,13 @@ private function gatherRelationJoinColumns( $columnDef = $fieldMapping['columnDefinition']; } - $columnOptions = array('notnull' => false, 'columnDefinition' => $columnDef); + $columnOptions = ['notnull' => false, 'columnDefinition' => $columnDef]; if (isset($joinColumn['nullable'])) { - $columnOptions['notnull'] = !$joinColumn['nullable']; + $columnOptions['notnull'] = ! $joinColumn['nullable']; } - if (isset($fieldMapping['options'])) { - $columnOptions['options'] = $fieldMapping['options']; - } + $columnOptions = $columnOptions + $this->gatherColumnOptions($fieldMapping); if ($fieldMapping['type'] == "string" && isset($fieldMapping['length'])) { $columnOptions['length'] = $fieldMapping['length']; @@ -691,7 +694,7 @@ private function gatherRelationJoinColumns( } if (isset($joinColumn['unique']) && $joinColumn['unique'] == true) { - $uniqueConstraints[] = array('columns' => array($quotedColumnName)); + $uniqueConstraints[] = ['columns' => [$quotedColumnName]]; } if (isset($joinColumn['onDelete'])) { @@ -706,6 +709,11 @@ private function gatherRelationJoinColumns( } $compositeName = $theJoinTable->getName().'.'.implode('', $localColumns); + + if (! $this->platform->supportsForeignKeyConstraints()) { + return; + } + if (isset($addedFks[$compositeName]) && ($foreignTableName != $addedFks[$compositeName]['foreignTableName'] || 0 < count(array_diff($foreignColumns, $addedFks[$compositeName]['foreignColumns']))) @@ -720,8 +728,8 @@ private function gatherRelationJoinColumns( } } $blacklistedFks[$compositeName] = true; - } elseif (!isset($blacklistedFks[$compositeName])) { - $addedFks[$compositeName] = array('foreignTableName' => $foreignTableName, 'foreignColumns' => $foreignColumns); + } elseif ( ! isset($blacklistedFks[$compositeName])) { + $addedFks[$compositeName] = ['foreignTableName' => $foreignTableName, 'foreignColumns' => $foreignColumns]; $theJoinTable->addUnnamedForeignKeyConstraint( $foreignTableName, $localColumns, @@ -731,6 +739,23 @@ private function gatherRelationJoinColumns( } } + /** + * @param mixed[] $mapping + * + * @return mixed[] + */ + private function gatherColumnOptions(array $mapping) : array + { + if (! isset($mapping['options'])) { + return []; + } + + $options = array_intersect_key($mapping['options'], array_flip(self::KNOWN_COLUMN_OPTIONS)); + $options['customSchemaOptions'] = array_diff_key($mapping['options'], $options); + + return $options; + } + /** * Drops the database schema for the given classes. * @@ -749,8 +774,8 @@ public function dropSchema(array $classes) foreach ($dropSchemaSql as $sql) { try { $conn->executeQuery($sql); - } catch (\Exception $e) { - + } catch (\Throwable $e) { + // ignored } } } @@ -827,7 +852,7 @@ public function getDropSchemaSQL(array $classes) if ($table->hasPrimaryKey()) { $columns = $table->getPrimaryKey()->getColumns(); if (count($columns) == 1) { - $checkSequence = $table->getName() . "_" . $columns[0] . "_seq"; + $checkSequence = $table->getName() . '_' . $columns[0] . '_seq'; if ($fullSchema->hasSequence($checkSequence)) { $visitor->acceptSequence($fullSchema->getSequence($checkSequence)); } diff --git a/lib/Doctrine/ORM/Tools/SchemaValidator.php b/lib/Doctrine/ORM/Tools/SchemaValidator.php index 03222700c10..6446598b8df 100644 --- a/lib/Doctrine/ORM/Tools/SchemaValidator.php +++ b/lib/Doctrine/ORM/Tools/SchemaValidator.php @@ -15,7 +15,7 @@ * This software consists of voluntary contributions made by many individuals * and is licensed under the MIT license. For more information, see * . -*/ + */ namespace Doctrine\ORM\Tools; @@ -63,7 +63,7 @@ public function __construct(EntityManagerInterface $em) */ public function validateMapping() { - $errors = array(); + $errors = []; $cmf = $this->em->getMetadataFactory(); $classes = $cmf->getAllMetadata(); @@ -85,12 +85,12 @@ public function validateMapping() */ public function validateClass(ClassMetadataInfo $class) { - $ce = array(); + $ce = []; $cmf = $this->em->getMetadataFactory(); foreach ($class->fieldMappings as $fieldName => $mapping) { if (!Type::hasType($mapping['type'])) { - $ce[] = "The field '" . $class->name . "#" . $fieldName."' uses a non-existant type '" . $mapping['type'] . "'."; + $ce[] = "The field '" . $class->name . "#" . $fieldName."' uses a non-existent type '" . $mapping['type'] . "'."; } } @@ -181,9 +181,9 @@ public function validateClass(ClassMetadataInfo $class) $identifierColumns = $targetMetadata->getIdentifierColumnNames(); foreach ($assoc['joinTable']['inverseJoinColumns'] as $inverseJoinColumn) { - if (!in_array($inverseJoinColumn['referencedColumnName'], $identifierColumns)) { - $ce[] = "The referenced column name '" . $joinColumn['referencedColumnName'] . "' " . - "has to be a primary key column on the target entity class '".$targetMetadata->name."'."; + if (! in_array($inverseJoinColumn['referencedColumnName'], $identifierColumns)) { + $ce[] = "The referenced column name '" . $inverseJoinColumn['referencedColumnName'] . "' " . + "has to be a primary key column on the target entity class '" .$targetMetadata->name . "'."; break; } } @@ -212,7 +212,7 @@ public function validateClass(ClassMetadataInfo $class) } if (count($identifierColumns) != count($assoc['joinColumns'])) { - $ids = array(); + $ids = []; foreach ($assoc['joinColumns'] as $joinColumn) { $ids[] = $joinColumn['name']; diff --git a/lib/Doctrine/ORM/Tools/Setup.php b/lib/Doctrine/ORM/Tools/Setup.php index 79d4670ad0f..302db6797b3 100644 --- a/lib/Doctrine/ORM/Tools/Setup.php +++ b/lib/Doctrine/ORM/Tools/Setup.php @@ -15,7 +15,7 @@ * This software consists of voluntary contributions made by many individuals * and is licensed under the MIT license. For more information, see * . -*/ + */ namespace Doctrine\ORM\Tools; @@ -123,31 +123,7 @@ public static function createConfiguration($isDevMode = false, $proxyDir = null, { $proxyDir = $proxyDir ?: sys_get_temp_dir(); - if ($isDevMode === false && $cache === null) { - if (extension_loaded('apc')) { - $cache = new \Doctrine\Common\Cache\ApcCache(); - } elseif (extension_loaded('xcache')) { - $cache = new \Doctrine\Common\Cache\XcacheCache(); - } elseif (extension_loaded('memcache')) { - $memcache = new \Memcache(); - $memcache->connect('127.0.0.1'); - $cache = new \Doctrine\Common\Cache\MemcacheCache(); - $cache->setMemcache($memcache); - } elseif (extension_loaded('redis')) { - $redis = new \Redis(); - $redis->connect('127.0.0.1'); - $cache = new \Doctrine\Common\Cache\RedisCache(); - $cache->setRedis($redis); - } else { - $cache = new ArrayCache(); - } - } elseif ($cache === null) { - $cache = new ArrayCache(); - } - - if ($cache instanceof CacheProvider) { - $cache->setNamespace("dc2_" . md5($proxyDir) . "_"); // to avoid collisions - } + $cache = self::createCacheConfiguration($isDevMode, $proxyDir, $cache); $config = new Configuration(); $config->setMetadataCacheImpl($cache); @@ -159,4 +135,61 @@ public static function createConfiguration($isDevMode = false, $proxyDir = null, return $config; } + + private static function createCacheConfiguration(bool $isDevMode, string $proxyDir, ?Cache $cache) : Cache + { + $cache = self::createCacheInstance($isDevMode, $cache); + + if ( ! $cache instanceof CacheProvider) { + return $cache; + } + + $namespace = $cache->getNamespace(); + + if ($namespace !== '') { + $namespace .= ':'; + } + + $cache->setNamespace($namespace . 'dc2_' . md5($proxyDir) . '_'); // to avoid collisions + + return $cache; + } + + private static function createCacheInstance(bool $isDevMode, ?Cache $cache) : Cache + { + if ($cache !== null) { + return $cache; + } + + if ($isDevMode === true) { + return new ArrayCache(); + } + + if (extension_loaded('apcu')) { + return new \Doctrine\Common\Cache\ApcuCache(); + } + + + if (extension_loaded('memcached')) { + $memcached = new \Memcached(); + $memcached->addServer('127.0.0.1', 11211); + + $cache = new \Doctrine\Common\Cache\MemcachedCache(); + $cache->setMemcached($memcached); + + return $cache; + } + + if (extension_loaded('redis')) { + $redis = new \Redis(); + $redis->connect('127.0.0.1'); + + $cache = new \Doctrine\Common\Cache\RedisCache(); + $cache->setRedis($redis); + + return $cache; + } + + return new ArrayCache(); + } } diff --git a/lib/Doctrine/ORM/Tools/ToolsException.php b/lib/Doctrine/ORM/Tools/ToolsException.php index 0a461640491..95b3af0acbd 100644 --- a/lib/Doctrine/ORM/Tools/ToolsException.php +++ b/lib/Doctrine/ORM/Tools/ToolsException.php @@ -20,6 +20,7 @@ namespace Doctrine\ORM\Tools; use Doctrine\ORM\ORMException; +use Throwable; /** * Tools related Exceptions. @@ -28,13 +29,7 @@ */ class ToolsException extends ORMException { - /** - * @param string $sql - * @param \Exception $e - * - * @return ToolsException - */ - public static function schemaToolFailure($sql, \Exception $e) + public static function schemaToolFailure(string $sql, Throwable $e) : self { return new self("Schema-Tool failed with Error '" . $e->getMessage() . "' while executing DDL: " . $sql, "0", $e); } diff --git a/lib/Doctrine/ORM/UnitOfWork.php b/lib/Doctrine/ORM/UnitOfWork.php index c54d97a0b2d..f7b32b3809f 100644 --- a/lib/Doctrine/ORM/UnitOfWork.php +++ b/lib/Doctrine/ORM/UnitOfWork.php @@ -19,36 +19,34 @@ namespace Doctrine\ORM; -use Doctrine\Common\Persistence\Mapping\RuntimeReflectionService; -use Doctrine\DBAL\LockMode; -use Doctrine\ORM\Internal\HydrationCompleteHandler; -use Doctrine\ORM\Mapping\Reflection\ReflectionPropertiesGetter; -use Exception; -use InvalidArgumentException; -use UnexpectedValueException; - use Doctrine\Common\Collections\ArrayCollection; use Doctrine\Common\Collections\Collection; use Doctrine\Common\NotifyPropertyChanged; -use Doctrine\Common\PropertyChangedListener; +use Doctrine\Common\Persistence\Mapping\RuntimeReflectionService; use Doctrine\Common\Persistence\ObjectManagerAware; -use Doctrine\ORM\Mapping\ClassMetadata; -use Doctrine\ORM\Proxy\Proxy; - +use Doctrine\Common\PropertyChangedListener; +use Doctrine\DBAL\LockMode; +use Doctrine\ORM\Cache\Persister\CachedPersister; use Doctrine\ORM\Event\LifecycleEventArgs; -use Doctrine\ORM\Event\PreUpdateEventArgs; -use Doctrine\ORM\Event\PreFlushEventArgs; +use Doctrine\ORM\Event\ListenersInvoker; use Doctrine\ORM\Event\OnFlushEventArgs; use Doctrine\ORM\Event\PostFlushEventArgs; -use Doctrine\ORM\Event\ListenersInvoker; - -use Doctrine\ORM\Cache\Persister\CachedPersister; +use Doctrine\ORM\Event\PreFlushEventArgs; +use Doctrine\ORM\Event\PreUpdateEventArgs; +use Doctrine\ORM\Internal\HydrationCompleteHandler; +use Doctrine\ORM\Mapping\ClassMetadata; +use Doctrine\ORM\Mapping\Reflection\ReflectionPropertiesGetter; +use Doctrine\ORM\Persisters\Collection\ManyToManyPersister; +use Doctrine\ORM\Persisters\Collection\OneToManyPersister; use Doctrine\ORM\Persisters\Entity\BasicEntityPersister; -use Doctrine\ORM\Persisters\Entity\SingleTablePersister; use Doctrine\ORM\Persisters\Entity\JoinedSubclassPersister; -use Doctrine\ORM\Persisters\Collection\OneToManyPersister; -use Doctrine\ORM\Persisters\Collection\ManyToManyPersister; +use Doctrine\ORM\Persisters\Entity\SingleTablePersister; +use Doctrine\ORM\Proxy\Proxy; use Doctrine\ORM\Utility\IdentifierFlattener; +use InvalidArgumentException; +use Throwable; +use UnexpectedValueException; +use function get_class; /** * The UnitOfWork is responsible for tracking changes to objects during an @@ -93,7 +91,7 @@ class UnitOfWork implements PropertyChangedListener /** * Hint used to collect all primary keys of associated entities during hydration * and execute it in a dedicated query afterwards - * @see https://doctrine-orm.readthedocs.org/en/latest/reference/dql-doctrine-query-language.html?highlight=eager#temporarily-change-fetch-mode-in-dql + * @see https://www.doctrine-project.org/projects/doctrine-orm/en/latest/reference/dql-doctrine-query-language.html#temporarily-change-fetch-mode-in-dql */ const HINT_DEFEREAGERLOAD = 'deferEagerLoad'; @@ -105,7 +103,7 @@ class UnitOfWork implements PropertyChangedListener * * @var array */ - private $identityMap = array(); + private $identityMap = []; /** * Map of all identifiers of managed entities. @@ -113,7 +111,7 @@ class UnitOfWork implements PropertyChangedListener * * @var array */ - private $entityIdentifiers = array(); + private $entityIdentifiers = []; /** * Map of the original entity data of managed entities. @@ -126,7 +124,7 @@ class UnitOfWork implements PropertyChangedListener * * @var array */ - private $originalEntityData = array(); + private $originalEntityData = []; /** * Map of entity changes. Keys are object ids (spl_object_hash). @@ -134,7 +132,7 @@ class UnitOfWork implements PropertyChangedListener * * @var array */ - private $entityChangeSets = array(); + private $entityChangeSets = []; /** * The (cached) states of any known entities. @@ -142,7 +140,7 @@ class UnitOfWork implements PropertyChangedListener * * @var array */ - private $entityStates = array(); + private $entityStates = []; /** * Map of entities that are scheduled for dirty checking at commit time. @@ -151,49 +149,62 @@ class UnitOfWork implements PropertyChangedListener * * @var array */ - private $scheduledForSynchronization = array(); + private $scheduledForSynchronization = []; /** * A list of all pending entity insertions. * * @var array */ - private $entityInsertions = array(); + private $entityInsertions = []; /** * A list of all pending entity updates. * * @var array */ - private $entityUpdates = array(); + private $entityUpdates = []; /** * Any pending extra updates that have been scheduled by persisters. * * @var array */ - private $extraUpdates = array(); + private $extraUpdates = []; /** * A list of all pending entity deletions. * * @var array */ - private $entityDeletions = array(); + private $entityDeletions = []; + + /** + * New entities that were discovered through relationships that were not + * marked as cascade-persist. During flush, this array is populated and + * then pruned of any entities that were discovered through a valid + * cascade-persist path. (Leftovers cause an error.) + * + * Keys are OIDs, payload is a two-item array describing the association + * and the entity. + * + * @var object[][]|array[][] indexed by respective object spl_object_hash() + */ + private $nonCascadedNewDetectedEntities = []; /** * All pending collection deletions. * * @var array */ - private $collectionDeletions = array(); + private $collectionDeletions = []; /** * All pending collection updates. * * @var array */ - private $collectionUpdates = array(); + private $collectionUpdates = []; /** * List of collections visited during changeset calculation on a commit-phase of a UnitOfWork. @@ -202,7 +213,7 @@ class UnitOfWork implements PropertyChangedListener * * @var array */ - private $visitedCollections = array(); + private $visitedCollections = []; /** * The EntityManager that "owns" this UnitOfWork instance. @@ -216,14 +227,14 @@ class UnitOfWork implements PropertyChangedListener * * @var array */ - private $persisters = array(); + private $persisters = []; /** * The collection persister instances used to persist collections. * * @var array */ - private $collectionPersisters = array(); + private $collectionPersisters = []; /** * The EventManager used for dispatching events. @@ -251,21 +262,21 @@ class UnitOfWork implements PropertyChangedListener * * @var array */ - private $orphanRemovals = array(); + private $orphanRemovals = []; /** * Read-Only objects are never evaluated * * @var array */ - private $readOnlyObjects = array(); + private $readOnlyObjects = []; /** * Map of Entity Class-Names and corresponding IDs that should eager loaded when requested. * * @var array */ - private $eagerLoadingEntities = array(); + private $eagerLoadingEntities = []; /** * @var boolean @@ -327,7 +338,7 @@ public function commit($entity = null) } // Compute changes done since last commit. - if ($entity === null) { + if (null === $entity) { $this->computeChangeSets(); } elseif (is_object($entity)) { $this->computeSingleEntityChangeSet($entity); @@ -346,9 +357,13 @@ public function commit($entity = null) $this->dispatchOnFlushEvent(); $this->dispatchPostFlushEvent(); + $this->postCommitCleanup($entity); + return; // Nothing to do. } + $this->assertThatThereAreNoUnintentionallyNonPersistedAssociations(); + if ($this->orphanRemovals) { foreach ($this->orphanRemovals as $orphan) { $this->remove($orphan); @@ -366,7 +381,18 @@ public function commit($entity = null) try { // Collection deletions (deletions of complete collections) foreach ($this->collectionDeletions as $collectionToDelete) { - $this->getCollectionPersister($collectionToDelete->getMapping())->delete($collectionToDelete); + if (! $collectionToDelete instanceof PersistentCollection) { + $this->getCollectionPersister($collectionToDelete->getMapping())->delete($collectionToDelete); + + continue; + } + + // Deferred explicit tracked collections can be removed only when owning relation was persisted + $owner = $collectionToDelete->getOwner(); + + if ($this->em->getClassMetadata(get_class($owner))->isChangeTrackingDeferredImplicit() || $this->isScheduledForDirtyCheck($owner)) { + $this->getCollectionPersister($collectionToDelete->getMapping())->delete($collectionToDelete); + } } if ($this->entityInsertions) { @@ -399,7 +425,7 @@ public function commit($entity = null) } $conn->commit(); - } catch (Exception $e) { + } catch (Throwable $e) { $this->em->close(); $conn->rollBack(); @@ -417,17 +443,41 @@ public function commit($entity = null) $this->dispatchPostFlushEvent(); - // Clear up + $this->postCommitCleanup($entity); + } + + /** + * @param null|object|object[] $entity + */ + private function postCommitCleanup($entity) : void + { $this->entityInsertions = $this->entityUpdates = $this->entityDeletions = $this->extraUpdates = - $this->entityChangeSets = $this->collectionUpdates = + $this->nonCascadedNewDetectedEntities = $this->collectionDeletions = $this->visitedCollections = - $this->scheduledForSynchronization = - $this->orphanRemovals = array(); + $this->orphanRemovals = []; + + if (null === $entity) { + $this->entityChangeSets = $this->scheduledForSynchronization = []; + + return; + } + + $entities = \is_object($entity) + ? [$entity] + : $entity; + + foreach ($entities as $object) { + $oid = \spl_object_hash($object); + + $this->clearEntityChangeSet($oid); + + unset($this->scheduledForSynchronization[$this->em->getClassMetadata(\get_class($object))->rootEntityName][$oid]); + } } /** @@ -504,7 +554,7 @@ private function executeExtraUpdates() $this->getEntityPersister(get_class($entity))->update($entity); } - $this->extraUpdates = array(); + $this->extraUpdates = []; } /** @@ -517,7 +567,7 @@ private function executeExtraUpdates() public function & getEntityChangeSet($entity) { $oid = spl_object_hash($entity); - $data = array(); + $data = []; if (!isset($this->entityChangeSets[$oid])) { return $data; @@ -578,7 +628,7 @@ public function computeChangeSet(ClassMetadata $class, $entity) $this->listenersInvoker->invoke($class, Events::preFlush, $entity, new PreFlushEventArgs($this->em), $invoke); } - $actualData = array(); + $actualData = []; foreach ($class->reflFields as $name => $refProp) { $value = $refProp->getValue($entity); @@ -622,11 +672,11 @@ public function computeChangeSet(ClassMetadata $class, $entity) // Entity is either NEW or MANAGED but not yet fully persisted (only has an id). // These result in an INSERT. $this->originalEntityData[$oid] = $actualData; - $changeSet = array(); + $changeSet = []; foreach ($actualData as $propName => $actualValue) { if ( ! isset($class->associationMappings[$propName])) { - $changeSet[$propName] = array(null, $actualValue); + $changeSet[$propName] = [null, $actualValue]; continue; } @@ -634,7 +684,7 @@ public function computeChangeSet(ClassMetadata $class, $entity) $assoc = $class->associationMappings[$propName]; if ($assoc['isOwningSide'] && $assoc['type'] & ClassMetadata::TO_ONE) { - $changeSet[$propName] = array(null, $actualValue); + $changeSet[$propName] = [null, $actualValue]; } } @@ -646,7 +696,7 @@ public function computeChangeSet(ClassMetadata $class, $entity) $isChangeTrackingNotify = $class->isChangeTrackingNotify(); $changeSet = ($isChangeTrackingNotify && isset($this->entityChangeSets[$oid])) ? $this->entityChangeSets[$oid] - : array(); + : []; foreach ($actualData as $propName => $actualValue) { // skip field, its a partially omitted one! @@ -667,7 +717,7 @@ public function computeChangeSet(ClassMetadata $class, $entity) continue; } - $changeSet[$propName] = array($orgValue, $actualValue); + $changeSet[$propName] = [$orgValue, $actualValue]; continue; } @@ -707,7 +757,7 @@ public function computeChangeSet(ClassMetadata $class, $entity) if ($assoc['type'] & ClassMetadata::TO_ONE) { if ($assoc['isOwningSide']) { - $changeSet[$propName] = array($orgValue, $actualValue); + $changeSet[$propName] = [$orgValue, $actualValue]; } if ($orgValue !== null && $assoc['orphanRemoval']) { @@ -737,7 +787,7 @@ public function computeChangeSet(ClassMetadata $class, $entity) $val instanceof PersistentCollection && $val->isDirty()) { - $this->entityChangeSets[$oid] = array(); + $this->entityChangeSets[$oid] = []; $this->originalEntityData[$oid] = $actualData; $this->entityUpdates[$oid] = $entity; } @@ -777,7 +827,7 @@ public function computeChangeSets() break; default: - $entitiesToProcess = array(); + $entitiesToProcess = []; } @@ -824,7 +874,7 @@ private function computeAssociationChanges($assoc, $value) // Look through the entities, and in any of their associations, // for transient (new) entities, recursively. ("Persistence by reachability") // Unwrap. Uninitialized collections will simply be empty. - $unwrappedValue = ($assoc['type'] & ClassMetadata::TO_ONE) ? array($value) : $value->unwrap(); + $unwrappedValue = ($assoc['type'] & ClassMetadata::TO_ONE) ? [$value] : $value->unwrap(); $targetClass = $this->em->getClassMetadata($assoc['targetEntity']); foreach ($unwrappedValue as $key => $entry) { @@ -841,11 +891,20 @@ private function computeAssociationChanges($assoc, $value) switch ($state) { case self::STATE_NEW: if ( ! $assoc['isCascadePersist']) { - throw ORMInvalidArgumentException::newEntityFoundThroughRelationship($assoc, $entry); + /* + * For now just record the details, because this may + * not be an issue if we later discover another pathway + * through the object-graph where cascade-persistence + * is enabled for this object. + */ + $this->nonCascadedNewDetectedEntities[\spl_object_hash($entry)] = [$assoc, $entry]; + + break; } $this->persistNew($targetClass, $entry); $this->computeChangeSet($targetClass, $entry); + break; case self::STATE_REMOVED: @@ -890,12 +949,16 @@ private function persistNew($class, $entity) $idValue = $idGen->generate($this->em, $entity); if ( ! $idGen instanceof \Doctrine\ORM\Id\AssignedGenerator) { - $idValue = array($class->identifier[0] => $idValue); + $idValue = [$class->getSingleIdentifierFieldName() => $this->convertSingleFieldIdentifierToPHPValue($class, $idValue)]; $class->setIdentifierValues($entity, $idValue); } - $this->entityIdentifiers[$oid] = $idValue; + // Some identifiers may be foreign keys to new entities. + // In this case, we don't have the value yet and should treat it as if we have a post-insert generator + if (! $this->hasMissingIdsWhichAreForeignKeys($class, $idValue)) { + $this->entityIdentifiers[$oid] = $idValue; + } } $this->entityStates[$oid] = self::STATE_MANAGED; @@ -903,6 +966,20 @@ private function persistNew($class, $entity) $this->scheduleForInsert($entity); } + /** + * @param mixed[] $idValue + */ + private function hasMissingIdsWhichAreForeignKeys(ClassMetadata $class, array $idValue) : bool + { + foreach ($idValue as $idField => $idFieldValue) { + if ($idFieldValue === null && isset($class->associationMappings[$idField])) { + return true; + } + } + + return false; + } + /** * INTERNAL: * Computes the changeset of an individual entity, independently of the @@ -938,7 +1015,7 @@ public function recomputeSingleEntityChangeSet(ClassMetadata $class, $entity) $class = $this->em->getClassMetadata(get_class($entity)); } - $actualData = array(); + $actualData = []; foreach ($class->reflFields as $name => $refProp) { if (( ! $class->isIdentifier($name) || ! $class->isIdGeneratorIdentity()) @@ -953,13 +1030,13 @@ public function recomputeSingleEntityChangeSet(ClassMetadata $class, $entity) } $originalData = $this->originalEntityData[$oid]; - $changeSet = array(); + $changeSet = []; foreach ($actualData as $propName => $actualValue) { - $orgValue = isset($originalData[$propName]) ? $originalData[$propName] : null; + $orgValue = $originalData[$propName] ?? null; if ($orgValue !== $actualValue) { - $changeSet[$propName] = array($orgValue, $actualValue); + $changeSet[$propName] = [$orgValue, $actualValue]; } } @@ -983,17 +1060,21 @@ public function recomputeSingleEntityChangeSet(ClassMetadata $class, $entity) */ private function executeInserts($class) { - $entities = array(); + $entities = []; $className = $class->name; $persister = $this->getEntityPersister($className); $invoke = $this->listenersInvoker->getSubscribedSystems($class, Events::postPersist); + $insertionsForClass = []; + foreach ($this->entityInsertions as $oid => $entity) { if ($this->em->getClassMetadata(get_class($entity))->name !== $className) { continue; } + $insertionsForClass[$oid] = $entity; + $persister->addInsert($entity); unset($this->entityInsertions[$oid]); @@ -1008,19 +1089,28 @@ private function executeInserts($class) if ($postInsertIds) { // Persister returned post-insert IDs foreach ($postInsertIds as $postInsertId) { - $id = $postInsertId['generatedId']; + $idField = $class->getSingleIdentifierFieldName(); + $idValue = $this->convertSingleFieldIdentifierToPHPValue($class, $postInsertId['generatedId']); + $entity = $postInsertId['entity']; $oid = spl_object_hash($entity); - $idField = $class->identifier[0]; - $class->reflFields[$idField]->setValue($entity, $id); + $class->reflFields[$idField]->setValue($entity, $idValue); - $this->entityIdentifiers[$oid] = array($idField => $id); + $this->entityIdentifiers[$oid] = [$idField => $idValue]; $this->entityStates[$oid] = self::STATE_MANAGED; - $this->originalEntityData[$oid][$idField] = $id; + $this->originalEntityData[$oid][$idField] = $idValue; $this->addToIdentityMap($entity); } + } else { + foreach ($insertionsForClass as $oid => $entity) { + if (! isset($this->entityIdentifiers[$oid])) { + //entity was not added to identity map because some identifiers are foreign keys to new entities. + //add it now + $this->addToEntityIdentifiersAndEntityMap($class, $oid, $entity); + } + } } foreach ($entities as $entity) { @@ -1028,6 +1118,30 @@ private function executeInserts($class) } } + /** + * @param object $entity + */ + private function addToEntityIdentifiersAndEntityMap(ClassMetadata $class, string $oid, $entity): void + { + $identifier = []; + + foreach ($class->getIdentifierFieldNames() as $idField) { + $value = $class->getFieldValue($entity, $idField); + + if (isset($class->associationMappings[$idField])) { + // NOTE: Single Columns as associated identifiers only allowed - this constraint it is enforced. + $value = $this->getSingleIdentifierValue($value); + } + + $identifier[$idField] = $this->originalEntityData[$oid][$idField] = $value; + } + + $this->entityStates[$oid] = self::STATE_MANAGED; + $this->entityIdentifiers[$oid] = $identifier; + + $this->addToIdentityMap($entity); + } + /** * Executes all entity updates for entities of the specified type. * @@ -1125,7 +1239,7 @@ private function getCommitOrder(array $entityChangeSet = null) // We have to inspect changeSet to be able to correctly build dependencies. // It is not possible to use IdentityMap here because post inserted ids // are not yet available. - $newNodes = array(); + $newNodes = []; foreach ($entityChangeSet as $entity) { $class = $this->em->getClassMetadata(get_class($entity)); @@ -1276,12 +1390,12 @@ public function scheduleForUpdate($entity) public function scheduleExtraUpdate($entity, array $changeset) { $oid = spl_object_hash($entity); - $extraUpdate = array($entity, $changeset); + $extraUpdate = [$entity, $changeset]; if (isset($this->extraUpdates[$oid])) { list(, $changeset2) = $this->extraUpdates[$oid]; - $extraUpdate = array($entity, $changeset + $changeset2); + $extraUpdate = [$entity, $changeset + $changeset2]; } $this->extraUpdates[$oid] = $extraUpdate; @@ -1398,12 +1512,13 @@ public function isEntityScheduled($entity) public function addToIdentityMap($entity) { $classMetadata = $this->em->getClassMetadata(get_class($entity)); - $idHash = implode(' ', $this->entityIdentifiers[spl_object_hash($entity)]); + $identifier = $this->entityIdentifiers[spl_object_hash($entity)]; - if ($idHash === '') { + if (empty($identifier) || in_array(null, $identifier, true)) { throw ORMInvalidArgumentException::entityWithoutIdentity($classMetadata->name, $entity); } + $idHash = implode(' ', $identifier); $className = $classMetadata->rootEntityName; if (isset($this->identityMap[$className][$idHash])) { @@ -1581,17 +1696,13 @@ public function isInIdentityMap($entity) { $oid = spl_object_hash($entity); - if ( ! isset($this->entityIdentifiers[$oid])) { + if (empty($this->entityIdentifiers[$oid])) { return false; } $classMetadata = $this->em->getClassMetadata(get_class($entity)); $idHash = implode(' ', $this->entityIdentifiers[$oid]); - if ($idHash === '') { - return false; - } - return isset($this->identityMap[$classMetadata->rootEntityName][$idHash]); } @@ -1620,7 +1731,7 @@ public function containsIdHash($idHash, $rootClassName) */ public function persist($entity) { - $visited = array(); + $visited = []; $this->doPersist($entity, $visited); } @@ -1697,7 +1808,7 @@ private function doPersist($entity, array &$visited) */ public function remove($entity) { - $visited = array(); + $visited = []; $this->doRemove($entity, $visited); } @@ -1767,11 +1878,11 @@ private function doRemove($entity, array &$visited) * @throws OptimisticLockException If the entity uses optimistic locking through a version * attribute and the version check against the managed copy fails. * - * @todo Require active transaction!? OptimisticLockException may result in undefined state!? + * @deprecated 2.7 This method is being removed from the ORM and won't have any replacement */ public function merge($entity) { - $visited = array(); + $visited = []; return $this->doMerge($entity, $visited); } @@ -1789,7 +1900,7 @@ public function merge($entity) * @throws OptimisticLockException If the entity uses optimistic locking through a version * attribute and the version check against the managed copy fails. * @throws ORMInvalidArgumentException If the entity instance is NEW. - * @throws EntityNotFoundException + * @throws EntityNotFoundException if an assigned identifier is used in the entity, but none is provided */ private function doMerge($entity, array &$visited, $prevManagedCopy = null, array $assoc = []) { @@ -1821,6 +1932,7 @@ private function doMerge($entity, array &$visited, $prevManagedCopy = null, arra if ( ! $id) { $managedCopy = $this->newInstance($class); + $this->mergeEntityStateIntoManagedCopy($entity, $managedCopy); $this->persistNew($class, $managedCopy); } else { $flatId = ($class->containsForeignIdentifier) @@ -1852,31 +1964,16 @@ private function doMerge($entity, array &$visited, $prevManagedCopy = null, arra $managedCopy = $this->newInstance($class); $class->setIdentifierValues($managedCopy, $id); + $this->mergeEntityStateIntoManagedCopy($entity, $managedCopy); $this->persistNew($class, $managedCopy); - } - } - - if ($class->isVersioned && $this->isLoaded($managedCopy) && $this->isLoaded($entity)) { - $reflField = $class->reflFields[$class->versionField]; - $managedCopyVersion = $reflField->getValue($managedCopy); - $entityVersion = $reflField->getValue($entity); - - // Throw exception if versions don't match. - if ($managedCopyVersion != $entityVersion) { - throw OptimisticLockException::lockFailedVersionMismatch($entity, $entityVersion, $managedCopyVersion); + } else { + $this->ensureVersionMatch($class, $entity, $managedCopy); + $this->mergeEntityStateIntoManagedCopy($entity, $managedCopy); } } $visited[$oid] = $managedCopy; // mark visited - if ($this->isLoaded($entity)) { - if ($managedCopy instanceof Proxy && ! $managedCopy->__isInitialized()) { - $managedCopy->__load(); - } - - $this->mergeEntityStateIntoManagedCopy($entity, $managedCopy); - } - if ($class->isChangeTrackingDeferredExplicit()) { $this->scheduleForDirtyCheck($entity); } @@ -1894,6 +1991,33 @@ private function doMerge($entity, array &$visited, $prevManagedCopy = null, arra return $managedCopy; } + /** + * @param ClassMetadata $class + * @param object $entity + * @param object $managedCopy + * + * @return void + * + * @throws OptimisticLockException + */ + private function ensureVersionMatch(ClassMetadata $class, $entity, $managedCopy) + { + if (! ($class->isVersioned && $this->isLoaded($managedCopy) && $this->isLoaded($entity))) { + return; + } + + $reflField = $class->reflFields[$class->versionField]; + $managedCopyVersion = $reflField->getValue($managedCopy); + $entityVersion = $reflField->getValue($entity); + + // Throw exception if versions don't match. + if ($managedCopyVersion == $entityVersion) { + return; + } + + throw OptimisticLockException::lockFailedVersionMismatch($entity, $entityVersion, $managedCopyVersion); + } + /** * Tests if an entity is loaded - must either be a loaded proxy or not a proxy * @@ -1944,10 +2068,12 @@ private function updateAssociationWithMergedEntity($entity, array $association, * @param object $entity The entity to detach. * * @return void + * + * @deprecated 2.7 This method is being removed from the ORM and won't have any replacement */ public function detach($entity) { - $visited = array(); + $visited = []; $this->doDetach($entity, $visited); } @@ -2008,7 +2134,7 @@ private function doDetach($entity, array &$visited, $noCascade = false) */ public function refresh($entity) { - $visited = array(); + $visited = []; $this->doRefresh($entity, $visited); } @@ -2250,7 +2376,7 @@ private function cascadeRemove($entity, array &$visited) function ($assoc) { return $assoc['isCascadeRemove']; } ); - $entitiesToCascade = array(); + $entitiesToCascade = []; foreach ($associationMappings as $assoc) { if ($entity instanceof Proxy && !$entity->__isInitialized__) { @@ -2365,25 +2491,29 @@ public function getCommitOrderCalculator() * @param string|null $entityName if given, only entities of this type will get detached. * * @return void + * + * @throws ORMInvalidArgumentException if an invalid entity name is given */ public function clear($entityName = null) { if ($entityName === null) { - $this->identityMap = - $this->entityIdentifiers = - $this->originalEntityData = - $this->entityChangeSets = - $this->entityStates = - $this->scheduledForSynchronization = - $this->entityInsertions = - $this->entityUpdates = - $this->entityDeletions = - $this->collectionDeletions = - $this->collectionUpdates = - $this->extraUpdates = - $this->readOnlyObjects = - $this->visitedCollections = - $this->orphanRemovals = array(); + $this->identityMap = + $this->entityIdentifiers = + $this->originalEntityData = + $this->entityChangeSets = + $this->entityStates = + $this->scheduledForSynchronization = + $this->entityInsertions = + $this->entityUpdates = + $this->entityDeletions = + $this->nonCascadedNewDetectedEntities = + $this->collectionDeletions = + $this->collectionUpdates = + $this->extraUpdates = + $this->readOnlyObjects = + $this->visitedCollections = + $this->eagerLoadingEntities = + $this->orphanRemovals = []; } else { $this->clearIdentityMapForEntityName($entityName); $this->clearEntityInsertionsForEntityName($entityName); @@ -2487,10 +2617,9 @@ private function newInstance($class) * * @todo Rename: getOrCreateEntity */ - public function createEntity($className, array $data, &$hints = array()) + public function createEntity($className, array $data, &$hints = []) { $class = $this->em->getClassMetadata($className); - //$isReadOnly = isset($hints[Query::HINT_READ_ONLY]); $id = $this->identifierFlattener->flattenIdentifier($class, $data); $idHash = implode(' ', $id); @@ -2520,28 +2649,22 @@ public function createEntity($className, array $data, &$hints = array()) if ($entity instanceof Proxy && ! $entity->__isInitialized()) { $entity->__setInitialized(true); - $overrideLocalValues = true; - if ($entity instanceof NotifyPropertyChanged) { $entity->addPropertyChangedListener($this); } } else { - $overrideLocalValues = isset($hints[Query::HINT_REFRESH]); - - // If only a specific entity is set to refresh, check that it's the one - if (isset($hints[Query::HINT_REFRESH_ENTITY])) { - $overrideLocalValues = $hints[Query::HINT_REFRESH_ENTITY] === $entity; + if ( ! isset($hints[Query::HINT_REFRESH]) + || (isset($hints[Query::HINT_REFRESH_ENTITY]) && $hints[Query::HINT_REFRESH_ENTITY] !== $entity)) { + return $entity; } } - if ($overrideLocalValues) { - // inject ObjectManager upon refresh. - if ($entity instanceof ObjectManagerAware) { - $entity->injectObjectManager($this->em, $class); - } - - $this->originalEntityData[$oid] = $data; + // inject ObjectManager upon refresh. + if ($entity instanceof ObjectManagerAware) { + $entity->injectObjectManager($this->em, $class); } + + $this->originalEntityData[$oid] = $data; } else { $entity = $this->newInstance($class); $oid = spl_object_hash($entity); @@ -2555,12 +2678,6 @@ public function createEntity($className, array $data, &$hints = array()) if ($entity instanceof NotifyPropertyChanged) { $entity->addPropertyChangedListener($this); } - - $overrideLocalValues = true; - } - - if ( ! $overrideLocalValues) { - return $entity; } foreach ($data as $field => $value) { @@ -2615,14 +2732,14 @@ public function createEntity($className, array $data, &$hints = array()) $class->reflFields[$field]->setValue($entity, $data[$field]); $this->originalEntityData[$oid][$field] = $data[$field]; - continue; + break; } - $associatedId = array(); + $associatedId = []; // TODO: Is this even computed right in all cases of composite keys? foreach ($assoc['targetToSourceKeyColumns'] as $targetColumn => $srcColumn) { - $joinColumnValue = isset($data[$srcColumn]) ? $data[$srcColumn] : null; + $joinColumnValue = $data[$srcColumn] ?? null; if ($joinColumnValue !== null) { if ($targetClass->containsForeignIdentifier) { @@ -2634,7 +2751,7 @@ public function createEntity($className, array $data, &$hints = array()) && in_array($targetClass->getFieldForColumn($targetColumn), $targetClass->identifier, true) ) { // the missing key is part of target's entity primary key - $associatedId = array(); + $associatedId = []; break; } } @@ -2644,7 +2761,7 @@ public function createEntity($className, array $data, &$hints = array()) $class->reflFields[$field]->setValue($entity, null); $this->originalEntityData[$oid][$field] = null; - continue; + break; } if ( ! isset($hints['fetchMode'][$class->name][$field])) { @@ -2764,10 +2881,8 @@ public function createEntity($className, array $data, &$hints = array()) } } - if ($overrideLocalValues) { - // defer invoking of postLoad event to hydration complete step - $this->hydrationCompleteHandler->deferPostLoadInvoking($class, $entity); - } + // defer invoking of postLoad event to hydration complete step + $this->hydrationCompleteHandler->deferPostLoadInvoking($class, $entity); return $entity; } @@ -2783,7 +2898,7 @@ public function triggerEagerLoads() // avoid infinite recursion $eagerLoadingEntities = $this->eagerLoadingEntities; - $this->eagerLoadingEntities = array(); + $this->eagerLoadingEntities = []; foreach ($eagerLoadingEntities as $entityName => $ids) { if ( ! $ids) { @@ -2793,7 +2908,7 @@ public function triggerEagerLoads() $class = $this->em->getClassMetadata($entityName); $this->getEntityPersister($entityName)->loadAll( - array_combine($class->identifier, array(array_values($ids))) + array_combine($class->identifier, [array_values($ids)]) ); } } @@ -3091,7 +3206,7 @@ public function registerManaged($entity, array $id, array $data) */ public function clearEntityChangeSet($oid) { - $this->entityChangeSets[$oid] = array(); + unset($this->entityChangeSets[$oid]); } /* PropertyChangedListener implementation */ @@ -3118,7 +3233,7 @@ public function propertyChanged($entity, $propertyName, $oldValue, $newValue) } // Update changeset and mark entity for synchronization - $this->entityChangeSets[$oid][$propertyName] = array($oldValue, $newValue); + $this->entityChangeSets[$oid][$propertyName] = [$oldValue, $newValue]; if ( ! isset($this->scheduledForSynchronization[$class->rootEntityName][$oid])) { $this->scheduleForDirtyCheck($entity); @@ -3331,6 +3446,22 @@ private function isIdentifierEquals($entity1, $entity2) return $id1 === $id2 || implode(' ', $id1) === implode(' ', $id2); } + /** + * @throws ORMInvalidArgumentException + */ + private function assertThatThereAreNoUnintentionallyNonPersistedAssociations() : void + { + $entitiesNeedingCascadePersist = \array_diff_key($this->nonCascadedNewDetectedEntities, $this->entityInsertions); + + $this->nonCascadedNewDetectedEntities = []; + + if ($entitiesNeedingCascadePersist) { + throw ORMInvalidArgumentException::newEntitiesFoundThroughRelationships( + \array_values($entitiesNeedingCascadePersist) + ); + } + } + /** * @param object $entity * @param object $managedCopy @@ -3341,6 +3472,14 @@ private function isIdentifierEquals($entity1, $entity2) */ private function mergeEntityStateIntoManagedCopy($entity, $managedCopy) { + if (! $this->isLoaded($entity)) { + return; + } + + if (! $this->isLoaded($managedCopy)) { + $managedCopy->__load(); + } + $class = $this->em->getClassMetadata(get_class($entity)); foreach ($this->reflectionPropertiesGetter->getProperties($class->name) as $prop) { @@ -3377,7 +3516,7 @@ private function mergeEntityStateIntoManagedCopy($entity, $managedCopy) $assoc2['targetEntity'], $relatedId ); - $this->registerManaged($other, $relatedId, array()); + $this->registerManaged($other, $relatedId, []); } } @@ -3403,8 +3542,6 @@ private function mergeEntityStateIntoManagedCopy($entity, $managedCopy) ); $managedCol->setOwner($managedCopy, $assoc2); $prop->setValue($managedCopy, $managedCol); - - $this->originalEntityData[spl_object_hash($entity)][$name] = $managedCol; } if ($assoc2['isCascadeMerge']) { @@ -3472,4 +3609,20 @@ private function clearEntityInsertionsForEntityName($entityName) } } } + + /** + * @param ClassMetadata $class + * @param mixed $identifierValue + * + * @return mixed the identifier after type conversion + * + * @throws \Doctrine\ORM\Mapping\MappingException if the entity has more than a single identifier + */ + private function convertSingleFieldIdentifierToPHPValue(ClassMetadata $class, $identifierValue) + { + return $this->em->getConnection()->convertToPHPValue( + $identifierValue, + $class->getTypeOfField($class->getSingleIdentifierFieldName()) + ); + } } diff --git a/lib/Doctrine/ORM/Utility/HierarchyDiscriminatorResolver.php b/lib/Doctrine/ORM/Utility/HierarchyDiscriminatorResolver.php new file mode 100644 index 00000000000..9b08b7f17d1 --- /dev/null +++ b/lib/Doctrine/ORM/Utility/HierarchyDiscriminatorResolver.php @@ -0,0 +1,41 @@ +subClasses; + $hierarchyClasses[] = $rootClassMetadata->name; + + $discriminators = []; + + foreach ($hierarchyClasses as $class) { + $currentMetadata = $entityManager->getClassMetadata($class); + $currentDiscriminator = $currentMetadata->discriminatorValue; + + if (null !== $currentDiscriminator) { + $discriminators[$currentDiscriminator] = null; + } + } + + return $discriminators; + } +} diff --git a/lib/Doctrine/ORM/Utility/IdentifierFlattener.php b/lib/Doctrine/ORM/Utility/IdentifierFlattener.php index 4a60385bd61..a283a683492 100644 --- a/lib/Doctrine/ORM/Utility/IdentifierFlattener.php +++ b/lib/Doctrine/ORM/Utility/IdentifierFlattener.php @@ -68,7 +68,7 @@ public function __construct(UnitOfWork $unitOfWork, ClassMetadataFactory $metada */ public function flattenIdentifier(ClassMetadata $class, array $id) { - $flatId = array(); + $flatId = []; foreach ($class->identifier as $field) { if (isset($class->associationMappings[$field]) && isset($id[$field]) && is_object($id[$field])) { @@ -85,7 +85,7 @@ public function flattenIdentifier(ClassMetadata $class, array $id) $flatId[$field] = implode(' ', $associatedId); } elseif (isset($class->associationMappings[$field])) { - $associatedId = array(); + $associatedId = []; foreach ($class->associationMappings[$field]['joinColumns'] as $joinColumn) { $associatedId[] = $id[$joinColumn['name']]; diff --git a/lib/Doctrine/ORM/Utility/PersisterHelper.php b/lib/Doctrine/ORM/Utility/PersisterHelper.php index ad99a7ea83d..fc6e492556f 100644 --- a/lib/Doctrine/ORM/Utility/PersisterHelper.php +++ b/lib/Doctrine/ORM/Utility/PersisterHelper.php @@ -39,18 +39,18 @@ class PersisterHelper * @param ClassMetadata $class * @param EntityManagerInterface $em * - * @return array + * @return array * * @throws QueryException */ public static function getTypeOfField($fieldName, ClassMetadata $class, EntityManagerInterface $em) { if (isset($class->fieldMappings[$fieldName])) { - return array($class->fieldMappings[$fieldName]['type']); + return [$class->fieldMappings[$fieldName]['type']]; } if ( ! isset($class->associationMappings[$fieldName])) { - return array(); + return []; } $assoc = $class->associationMappings[$fieldName]; @@ -65,7 +65,7 @@ public static function getTypeOfField($fieldName, ClassMetadata $class, EntityMa $joinData = $assoc; } - $types = array(); + $types = []; $targetClass = $em->getClassMetadata($assoc['targetEntity']); foreach ($joinData['joinColumns'] as $joinColumn) { diff --git a/lib/Doctrine/ORM/Version.php b/lib/Doctrine/ORM/Version.php index fee5b82c0a1..1af55173c73 100644 --- a/lib/Doctrine/ORM/Version.php +++ b/lib/Doctrine/ORM/Version.php @@ -22,7 +22,6 @@ /** * Class to store and retrieve the version of Doctrine * - * * @link www.doctrine-project.org * @since 2.0 * @version $Revision$ @@ -30,13 +29,15 @@ * @author Guilherme Blanco * @author Jonathan Wage * @author Roman Borschel + * + * @deprecated 2.7 This class is being removed from the ORM and won't have any replacement */ class Version { /** * Current Doctrine Version */ - const VERSION = '2.6.0-DEV'; + const VERSION = '2.7.0'; /** * Compares a Doctrine version with the current one. diff --git a/phpbench.json b/phpbench.json new file mode 100644 index 00000000000..74fdef412a7 --- /dev/null +++ b/phpbench.json @@ -0,0 +1,15 @@ +{ + "bootstrap": "vendor/autoload.php", + "path": "tests/Doctrine/Performance", + + "extensions": [ + "PhpBench\\Extensions\\Dbal\\DbalExtension", + "PhpBench\\Extensions\\XDebug\\XDebugExtension" + ], + + "storage": "dbal", + "storage.dbal.connection": { + "driver": "pdo_sqlite", + "path": "tests/Doctrine/Performance/history.db" + } +} diff --git a/phpcs.xml.dist b/phpcs.xml.dist new file mode 100644 index 00000000000..5aced8ad828 --- /dev/null +++ b/phpcs.xml.dist @@ -0,0 +1,158 @@ + + + + + + + + + + + + lib + tests + tools + + */tests/Doctrine/Tests/Proxies/__CG__/* + + + + + + + + + + + + */tests/* + + + + */tests/* + + + + lib/Doctrine/ORM/Events.php + lib/Doctrine/ORM/Tools/ToolEvents.php + + + + lib/Doctrine/ORM/Annotation/* + + + + lib/Doctrine/ORM/Internal/Hydration/AbstractHydrator.php + + + + lib/Doctrine/ORM/Query/Parser.php + + + + lib/Doctrine/ORM/Mapping/AssociationOverride.php + lib/Doctrine/ORM/Mapping/AssociationOverrides.php + lib/Doctrine/ORM/Mapping/AttributeOverride.php + lib/Doctrine/ORM/Mapping/AttributeOverrides.php + lib/Doctrine/ORM/Mapping/Cache.php + lib/Doctrine/ORM/Mapping/ChangeTrackingPolicy.php + lib/Doctrine/ORM/Mapping/Column.php + lib/Doctrine/ORM/Mapping/ColumnResult.php + lib/Doctrine/ORM/Mapping/CustomIdGenerator.php + lib/Doctrine/ORM/Mapping/DiscriminatorColumn.php + lib/Doctrine/ORM/Mapping/DiscriminatorMap.php + lib/Doctrine/ORM/Mapping/Embeddable.php + lib/Doctrine/ORM/Mapping/Embedded.php + lib/Doctrine/ORM/Mapping/Entity.php + lib/Doctrine/ORM/Mapping/EntityListeners.php + lib/Doctrine/ORM/Mapping/EntityResult.php + lib/Doctrine/ORM/Mapping/FieldResult.php + lib/Doctrine/ORM/Mapping/GeneratedValue.php + lib/Doctrine/ORM/Mapping/HasLifecycleCallbacks.php + lib/Doctrine/ORM/Mapping/Id.php + lib/Doctrine/ORM/Mapping/Index.php + lib/Doctrine/ORM/Mapping/InheritanceType.php + lib/Doctrine/ORM/Mapping/JoinColumn.php + lib/Doctrine/ORM/Mapping/JoinColumns.php + lib/Doctrine/ORM/Mapping/JoinTable.php + lib/Doctrine/ORM/Mapping/ManyToMany.php + lib/Doctrine/ORM/Mapping/ManyToOne.php + lib/Doctrine/ORM/Mapping/MappedSuperclass.php + lib/Doctrine/ORM/Mapping/NamedNativeQueries.php + lib/Doctrine/ORM/Mapping/NamedNativeQuery.php + lib/Doctrine/ORM/Mapping/NamedQueries.php + lib/Doctrine/ORM/Mapping/NamedQuery.php + lib/Doctrine/ORM/Mapping/OneToMany.php + lib/Doctrine/ORM/Mapping/OneToOne.php + lib/Doctrine/ORM/Mapping/OrderBy.php + lib/Doctrine/ORM/Mapping/PostLoad.php + lib/Doctrine/ORM/Mapping/PostPersist.php + lib/Doctrine/ORM/Mapping/PostRemove.php + lib/Doctrine/ORM/Mapping/PostUpdate.php + lib/Doctrine/ORM/Mapping/PreFlush.php + lib/Doctrine/ORM/Mapping/PrePersist.php + lib/Doctrine/ORM/Mapping/PreRemove.php + lib/Doctrine/ORM/Mapping/PreUpdate.php + lib/Doctrine/ORM/Mapping/SequenceGenerator.php + lib/Doctrine/ORM/Mapping/SqlResultSetMapping.php + lib/Doctrine/ORM/Mapping/SqlResultSetMappings.php + lib/Doctrine/ORM/Mapping/Table.php + lib/Doctrine/ORM/Mapping/UniqueConstraint.php + lib/Doctrine/ORM/Mapping/Version.php + + + + lib/Doctrine/ORM/Cache/DefaultQueryCache.php + + + + lib/Doctrine/ORM/EntityManagerInterface.php + + + + */tests/* + + + + */tests/* + + + + */tests/* + + + + */tests/* + + + + */tests/* + + + + */tests/* + + + + + tests/Doctrine/Tests/Models/Global/GlobalNamespaceModel.php + tests/Doctrine/Tests/Models/DDC3231/DDC3231User1NoNamespace.php + tests/Doctrine/Tests/Models/DDC3231/DDC3231User2NoNamespace.php + + + + + tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2084Test.php + + + + + tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2084Test.php + + + + + tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1301Test.php + tests/Doctrine/Tests/ORM/Functional/ExtraLazyCollectionTest.php + + diff --git a/phpstan.neon b/phpstan.neon new file mode 100644 index 00000000000..4046aa1655c --- /dev/null +++ b/phpstan.neon @@ -0,0 +1,4 @@ +parameters: + earlyTerminatingMethodCalls: + Doctrine\ORM\Query\Parser: + - syntaxError diff --git a/phpunit.xml.dist b/phpunit.xml.dist index e6fc543159c..ea31c212afd 100644 --- a/phpunit.xml.dist +++ b/phpunit.xml.dist @@ -11,18 +11,13 @@ tests/ folder: phpunit -c ... Example: phpunit -c mysqlconf.xml AllTests --> - - ./tests/Doctrine/Tests/ORM @@ -46,7 +41,7 @@ --> - + @@ -54,6 +49,8 @@ + + - \ No newline at end of file + diff --git a/tests/Doctrine/Performance/ChangeSet/UnitOfWorkComputeChangesBench.php b/tests/Doctrine/Performance/ChangeSet/UnitOfWorkComputeChangesBench.php new file mode 100644 index 00000000000..25cc2fffdbb --- /dev/null +++ b/tests/Doctrine/Performance/ChangeSet/UnitOfWorkComputeChangesBench.php @@ -0,0 +1,73 @@ +unitOfWork = EntityManagerFactory::getEntityManager([])->getUnitOfWork(); + + for ($i = 1; $i <= 100; ++$i) { + $user = new CmsUser; + $user->id = $i; + $user->status = 'user'; + $user->username = 'user' . $i; + $user->name = 'Mr.Smith-' . $i; + $this->users[] = $user; + + $this->unitOfWork->registerManaged( + $user, + [ + 'id' => $i, + ], + [ + 'id' => $user->id, + 'status' => $user->status, + 'username' => $user->username, + 'name' => $user->name, + 'address' => $user->address, + 'email' => $user->email, + ] + ); + } + + $this->unitOfWork->computeChangeSets(); + + if ($this->unitOfWork->getScheduledEntityUpdates()) { + throw new \LogicException('Unit of work should be clean at this stage'); + } + + foreach ($this->users AS $user) { + $user->status = 'other'; + $user->username .= '++'; + $user->name = str_replace('Mr.', 'Mrs.', $user->name); + } + } + + public function benchChangeSetComputation() + { + $this->unitOfWork->computeChangeSets(); + } +} + diff --git a/tests/Doctrine/Performance/EntityManagerFactory.php b/tests/Doctrine/Performance/EntityManagerFactory.php new file mode 100644 index 00000000000..0e891875db8 --- /dev/null +++ b/tests/Doctrine/Performance/EntityManagerFactory.php @@ -0,0 +1,73 @@ +setProxyDir(__DIR__ . '/../Tests/Proxies'); + $config->setProxyNamespace('Doctrine\Tests\Proxies'); + $config->setAutoGenerateProxyClasses(ProxyFactory::AUTOGENERATE_EVAL); + $config->setMetadataDriverImpl($config->newDefaultAnnotationDriver([ + realpath(__DIR__ . '/Models/Cache'), + realpath(__DIR__ . '/Models/GeoNames'), + ], true)); + + $entityManager = EntityManager::create( + [ + 'driverClass' => Driver::class, + 'memory' => true, + ], + $config + ); + + (new SchemaTool($entityManager)) + ->createSchema(array_map([$entityManager, 'getClassMetadata'], $schemaClassNames)); + + return $entityManager; + } + + public static function makeEntityManagerWithNoResultsConnection() : EntityManagerInterface + { + $config = new Configuration(); + + $config->setProxyDir(__DIR__ . '/../Tests/Proxies'); + $config->setProxyNamespace('Doctrine\Tests\Proxies'); + $config->setAutoGenerateProxyClasses(ProxyFactory::AUTOGENERATE_EVAL); + $config->setMetadataDriverImpl($config->newDefaultAnnotationDriver([ + realpath(__DIR__ . '/Models/Cache'), + realpath(__DIR__ . '/Models/Generic'), + realpath(__DIR__ . '/Models/GeoNames'), + ], true)); + + // A connection that doesn't really do anything + $connection = new class ([], new Driver(), null, new EventManager()) extends Connection + { + /** {@inheritdoc} */ + public function executeQuery($query, array $params = [], $types = [], ?QueryCacheProfile $qcp = null) + { + return new ArrayStatement([]); + } + }; + + return EntityManager::create($connection, $config); + } +} diff --git a/tests/Doctrine/Performance/Hydration/MixedQueryFetchJoinArrayHydrationPerformanceBench.php b/tests/Doctrine/Performance/Hydration/MixedQueryFetchJoinArrayHydrationPerformanceBench.php new file mode 100644 index 00000000000..bbda1f23dd8 --- /dev/null +++ b/tests/Doctrine/Performance/Hydration/MixedQueryFetchJoinArrayHydrationPerformanceBench.php @@ -0,0 +1,92 @@ + '1', + 'u__status' => 'developer', + 'u__username' => 'romanb', + 'u__name' => 'Roman', + 'sclr0' => 'ROMANB', + 'p__phonenumber' => '42', + ], + [ + 'u__id' => '1', + 'u__status' => 'developer', + 'u__username' => 'romanb', + 'u__name' => 'Roman', + 'sclr0' => 'ROMANB', + 'p__phonenumber' => '43', + ], + [ + 'u__id' => '2', + 'u__status' => 'developer', + 'u__username' => 'romanb', + 'u__name' => 'Roman', + 'sclr0' => 'JWAGE', + 'p__phonenumber' => '91' + ] + ]; + + for ($i = 4; $i < 10000; ++$i) { + $resultSet[] = [ + 'u__id' => $i, + 'u__status' => 'developer', + 'u__username' => 'jwage', + 'u__name' => 'Jonathan', + 'sclr0' => 'JWAGE' . $i, + 'p__phonenumber' => '91' + ]; + } + + $this->stmt = new HydratorMockStatement($resultSet); + $this->hydrator = new ArrayHydrator(EntityManagerFactory::getEntityManager([])); + $this->rsm = new ResultSetMapping; + + $this->rsm->addEntityResult(CmsUser::class, 'u'); + $this->rsm->addJoinedEntityResult(CmsPhonenumber::class, 'p', 'u', 'phonenumbers'); + $this->rsm->addFieldResult('u', 'u__id', 'id'); + $this->rsm->addFieldResult('u', 'u__status', 'status'); + $this->rsm->addFieldResult('u', 'u__username', 'username'); + $this->rsm->addFieldResult('u', 'u__name', 'name'); + $this->rsm->addScalarResult('sclr0', 'nameUpper'); + $this->rsm->addFieldResult('p', 'p__phonenumber', 'phonenumber'); + } + + public function benchHydration() + { + $this->hydrator->hydrateAll($this->stmt, $this->rsm); + } +} + diff --git a/tests/Doctrine/Performance/Hydration/MixedQueryFetchJoinFullObjectHydrationPerformanceBench.php b/tests/Doctrine/Performance/Hydration/MixedQueryFetchJoinFullObjectHydrationPerformanceBench.php new file mode 100644 index 00000000000..c70ca77cb10 --- /dev/null +++ b/tests/Doctrine/Performance/Hydration/MixedQueryFetchJoinFullObjectHydrationPerformanceBench.php @@ -0,0 +1,81 @@ + '1', + 'u__status' => 'developer', + 'u__username' => 'romanb', + 'u__name' => 'Roman', + 'sclr0' => 'ROMANB', + 'p__phonenumber' => '42', + 'a__id' => '1' + ] + ]; + + for ($i = 2; $i < 2000; ++$i) { + $resultSet[] = [ + 'u__id' => $i, + 'u__status' => 'developer', + 'u__username' => 'jwage', + 'u__name' => 'Jonathan', + 'sclr0' => 'JWAGE' . $i, + 'p__phonenumber' => '91', + 'a__id' => $i + ]; + } + + $this->stmt = new HydratorMockStatement($resultSet); + $this->hydrator = new ObjectHydrator(EntityManagerFactory::getEntityManager([])); + $this->rsm = new ResultSetMapping; + + $this->rsm->addEntityResult(CmsUser::class, 'u'); + $this->rsm->addJoinedEntityResult(CmsPhonenumber::class, 'p', 'u', 'phonenumbers'); + $this->rsm->addFieldResult('u', 'u__id', 'id'); + $this->rsm->addFieldResult('u', 'u__status', 'status'); + $this->rsm->addFieldResult('u', 'u__username', 'username'); + $this->rsm->addFieldResult('u', 'u__name', 'name'); + $this->rsm->addScalarResult('sclr0', 'nameUpper'); + $this->rsm->addFieldResult('p', 'p__phonenumber', 'phonenumber'); + $this->rsm->addJoinedEntityResult(CmsAddress::class, 'a', 'u', 'address'); + $this->rsm->addFieldResult('a', 'a__id', 'id'); + } + + public function benchHydration() + { + $this->hydrator->hydrateAll($this->stmt, $this->rsm); + } +} + diff --git a/tests/Doctrine/Performance/Hydration/MixedQueryFetchJoinPartialObjectHydrationPerformanceBench.php b/tests/Doctrine/Performance/Hydration/MixedQueryFetchJoinPartialObjectHydrationPerformanceBench.php new file mode 100644 index 00000000000..f2e33f76dbd --- /dev/null +++ b/tests/Doctrine/Performance/Hydration/MixedQueryFetchJoinPartialObjectHydrationPerformanceBench.php @@ -0,0 +1,93 @@ + '1', + 'u__status' => 'developer', + 'u__username' => 'romanb', + 'u__name' => 'Roman', + 'sclr0' => 'ROMANB', + 'p__phonenumber' => '42', + ], + [ + 'u__id' => '1', + 'u__status' => 'developer', + 'u__username' => 'romanb', + 'u__name' => 'Roman', + 'sclr0' => 'ROMANB', + 'p__phonenumber' => '43', + ], + [ + 'u__id' => '2', + 'u__status' => 'developer', + 'u__username' => 'romanb', + 'u__name' => 'Roman', + 'sclr0' => 'JWAGE', + 'p__phonenumber' => '91' + ] + ]; + + for ($i = 4; $i < 2000; ++$i) { + $resultSet[] = [ + 'u__id' => $i, + 'u__status' => 'developer', + 'u__username' => 'jwage', + 'u__name' => 'Jonathan', + 'sclr0' => 'JWAGE' . $i, + 'p__phonenumber' => '91' + ]; + } + + $this->stmt = new HydratorMockStatement($resultSet); + $this->hydrator = new ObjectHydrator(EntityManagerFactory::getEntityManager([])); + $this->rsm = new ResultSetMapping; + + $this->rsm->addEntityResult(CmsUser::class, 'u'); + $this->rsm->addJoinedEntityResult(CmsPhonenumber::class, 'p', 'u', 'phonenumbers'); + $this->rsm->addFieldResult('u', 'u__id', 'id'); + $this->rsm->addFieldResult('u', 'u__status', 'status'); + $this->rsm->addFieldResult('u', 'u__username', 'username'); + $this->rsm->addFieldResult('u', 'u__name', 'name'); + $this->rsm->addScalarResult('sclr0', 'nameUpper'); + $this->rsm->addFieldResult('p', 'p__phonenumber', 'phonenumber'); + } + + public function benchHydration() + { + $this->hydrator->hydrateAll($this->stmt, $this->rsm, [Query::HINT_FORCE_PARTIAL_LOAD => true]); + } +} + diff --git a/tests/Doctrine/Performance/Hydration/SimpleHydrationBench.php b/tests/Doctrine/Performance/Hydration/SimpleHydrationBench.php new file mode 100644 index 00000000000..a3fd637d67e --- /dev/null +++ b/tests/Doctrine/Performance/Hydration/SimpleHydrationBench.php @@ -0,0 +1,58 @@ +entityManager = EntityManagerFactory::getEntityManager([ + CMS\CmsUser::class, + CMS\CmsPhonenumber::class, + CMS\CmsAddress::class, + CMS\CmsEmail::class, + CMS\CmsGroup::class, + CMS\CmsTag::class, + CMS\CmsArticle::class, + CMS\CmsComment::class, + ]); + + for ($i = 2; $i < 10000; ++$i) { + $user = new CMS\CmsUser(); + + $user->status = 'developer'; + $user->username = 'jwage' . $i; + $user->name = 'Jonathan'; + + $this->entityManager->persist($user); + } + + $this->entityManager->flush(); + $this->entityManager->clear(); + + $this->repository = $this->entityManager->getRepository(CMS\CmsUser::class); + } + + public function benchHydration() + { + $this->repository->findAll(); + } +} diff --git a/tests/Doctrine/Performance/Hydration/SimpleInsertPerformanceBench.php b/tests/Doctrine/Performance/Hydration/SimpleInsertPerformanceBench.php new file mode 100644 index 00000000000..5806b6b9da4 --- /dev/null +++ b/tests/Doctrine/Performance/Hydration/SimpleInsertPerformanceBench.php @@ -0,0 +1,71 @@ +entityManager = EntityManagerFactory::getEntityManager([ + CMS\CmsUser::class, + CMS\CmsPhonenumber::class, + CMS\CmsAddress::class, + CMS\CmsEmail::class, + CMS\CmsGroup::class, + CMS\CmsTag::class, + CMS\CmsArticle::class, + CMS\CmsComment::class, + ]); + + for ($i = 1; $i <= 10000; ++$i) { + $user = new CMS\CmsUser; + $user->status = 'user'; + $user->username = 'user' . $i; + $user->name = 'Mr.Smith-' . $i; + + $this->users[$i] = $user; + } + + $this->tableName = $this->entityManager->getClassMetadata(CMS\CmsUser::class)->getTableName(); + } + + public function benchHydration() + { + // Yes, this is a lot of overhead, but I have no better solution other than + // completely mocking out the DB, which would be silly (query impact is + // necessarily part of our benchmarks) + $this->entityManager->getConnection()->executeQuery('DELETE FROM ' . $this->tableName)->execute(); + + foreach ($this->users as $key => $user) { + $this->entityManager->persist($user); + + if (! ($key % 20)) { + $this->entityManager->flush(); + $this->entityManager->clear(); + } + } + } +} diff --git a/tests/Doctrine/Performance/Hydration/SimpleQueryArrayHydrationPerformanceBench.php b/tests/Doctrine/Performance/Hydration/SimpleQueryArrayHydrationPerformanceBench.php new file mode 100644 index 00000000000..aa404554dc8 --- /dev/null +++ b/tests/Doctrine/Performance/Hydration/SimpleQueryArrayHydrationPerformanceBench.php @@ -0,0 +1,81 @@ + '1', + 'u__status' => 'developer', + 'u__username' => 'romanb', + 'u__name' => 'Roman', + ], + [ + 'u__id' => '1', + 'u__status' => 'developer', + 'u__username' => 'romanb', + 'u__name' => 'Roman', + ], + [ + 'u__id' => '2', + 'u__status' => 'developer', + 'u__username' => 'romanb', + 'u__name' => 'Roman', + ] + ]; + + for ($i = 4; $i < 10000; ++$i) { + $resultSet[] = [ + 'u__id' => $i, + 'u__status' => 'developer', + 'u__username' => 'jwage', + 'u__name' => 'Jonathan', + ]; + } + + $this->stmt = new HydratorMockStatement($resultSet); + $this->hydrator = new ArrayHydrator(EntityManagerFactory::getEntityManager([])); + $this->rsm = new ResultSetMapping; + + $this->rsm->addEntityResult(CmsUser::class, 'u'); + $this->rsm->addFieldResult('u', 'u__id', 'id'); + $this->rsm->addFieldResult('u', 'u__status', 'status'); + $this->rsm->addFieldResult('u', 'u__username', 'username'); + $this->rsm->addFieldResult('u', 'u__name', 'name'); + } + + public function benchHydration() + { + $this->hydrator->hydrateAll($this->stmt, $this->rsm); + } +} + diff --git a/tests/Doctrine/Performance/Hydration/SimpleQueryFullObjectHydrationPerformanceBench.php b/tests/Doctrine/Performance/Hydration/SimpleQueryFullObjectHydrationPerformanceBench.php new file mode 100644 index 00000000000..173001ff80c --- /dev/null +++ b/tests/Doctrine/Performance/Hydration/SimpleQueryFullObjectHydrationPerformanceBench.php @@ -0,0 +1,74 @@ + '1', + 'u__status' => 'developer', + 'u__username' => 'romanb', + 'u__name' => 'Roman', + 'a__id' => '1' + ] + ]; + + for ($i = 2; $i < 10000; ++$i) { + $resultSet[] = [ + 'u__id' => $i, + 'u__status' => 'developer', + 'u__username' => 'jwage', + 'u__name' => 'Jonathan', + 'a__id' => $i + ]; + } + + $this->stmt = new HydratorMockStatement($resultSet); + $this->hydrator = new ObjectHydrator(EntityManagerFactory::getEntityManager([])); + $this->rsm = new ResultSetMapping; + + $this->rsm->addEntityResult(CmsUser::class, 'u'); + $this->rsm->addFieldResult('u', 'u__id', 'id'); + $this->rsm->addFieldResult('u', 'u__status', 'status'); + $this->rsm->addFieldResult('u', 'u__username', 'username'); + $this->rsm->addFieldResult('u', 'u__name', 'name'); + $this->rsm->addJoinedEntityResult(CmsAddress::class, 'a', 'u', 'address'); + $this->rsm->addFieldResult('a', 'a__id', 'id'); + } + + public function benchHydration() + { + $this->hydrator->hydrateAll($this->stmt, $this->rsm); + } +} + diff --git a/tests/Doctrine/Performance/Hydration/SimpleQueryPartialObjectHydrationPerformanceBench.php b/tests/Doctrine/Performance/Hydration/SimpleQueryPartialObjectHydrationPerformanceBench.php new file mode 100644 index 00000000000..55d78973fe2 --- /dev/null +++ b/tests/Doctrine/Performance/Hydration/SimpleQueryPartialObjectHydrationPerformanceBench.php @@ -0,0 +1,81 @@ + '1', + 'u__status' => 'developer', + 'u__username' => 'romanb', + 'u__name' => 'Roman', + ], + [ + 'u__id' => '1', + 'u__status' => 'developer', + 'u__username' => 'romanb', + 'u__name' => 'Roman', + ], + [ + 'u__id' => '2', + 'u__status' => 'developer', + 'u__username' => 'romanb', + 'u__name' => 'Roman', + ] + ]; + + for ($i = 4; $i < 10000; ++$i) { + $resultSet[] = [ + 'u__id' => $i, + 'u__status' => 'developer', + 'u__username' => 'jwage', + 'u__name' => 'Jonathan', + ]; + } + + $this->stmt = new HydratorMockStatement($resultSet); + $this->hydrator = new ObjectHydrator(EntityManagerFactory::getEntityManager([])); + $this->rsm = new ResultSetMapping; + + $this->rsm->addEntityResult(CmsUser::class, 'u'); + $this->rsm->addFieldResult('u', 'u__id', 'id'); + $this->rsm->addFieldResult('u', 'u__status', 'status'); + $this->rsm->addFieldResult('u', 'u__username', 'username'); + $this->rsm->addFieldResult('u', 'u__name', 'name'); + } + + public function benchHydration() + { + $this->hydrator->hydrateAll($this->stmt, $this->rsm, [Query::HINT_FORCE_PARTIAL_LOAD => true]); + } +} + diff --git a/tests/Doctrine/Performance/Hydration/SimpleQueryScalarHydrationPerformanceBench.php b/tests/Doctrine/Performance/Hydration/SimpleQueryScalarHydrationPerformanceBench.php new file mode 100644 index 00000000000..4af2c0791bf --- /dev/null +++ b/tests/Doctrine/Performance/Hydration/SimpleQueryScalarHydrationPerformanceBench.php @@ -0,0 +1,81 @@ + '1', + 'u__status' => 'developer', + 'u__username' => 'romanb', + 'u__name' => 'Roman', + ], + [ + 'u__id' => '1', + 'u__status' => 'developer', + 'u__username' => 'romanb', + 'u__name' => 'Roman', + ], + [ + 'u__id' => '2', + 'u__status' => 'developer', + 'u__username' => 'romanb', + 'u__name' => 'Roman', + ] + ]; + + for ($i = 4; $i < 10000; ++$i) { + $resultSet[] = [ + 'u__id' => $i, + 'u__status' => 'developer', + 'u__username' => 'jwage', + 'u__name' => 'Jonathan', + ]; + } + + $this->stmt = new HydratorMockStatement($resultSet); + $this->hydrator = new ScalarHydrator(EntityManagerFactory::getEntityManager([])); + $this->rsm = new ResultSetMapping; + + $this->rsm->addEntityResult(CmsUser::class, 'u'); + $this->rsm->addFieldResult('u', 'u__id', 'id'); + $this->rsm->addFieldResult('u', 'u__status', 'status'); + $this->rsm->addFieldResult('u', 'u__username', 'username'); + $this->rsm->addFieldResult('u', 'u__name', 'name'); + } + + public function benchHydration() + { + $this->hydrator->hydrateAll($this->stmt, $this->rsm); + } +} + diff --git a/tests/Doctrine/Performance/Hydration/SingleTableInheritanceHydrationPerformanceBench.php b/tests/Doctrine/Performance/Hydration/SingleTableInheritanceHydrationPerformanceBench.php new file mode 100644 index 00000000000..ec6c17c3eef --- /dev/null +++ b/tests/Doctrine/Performance/Hydration/SingleTableInheritanceHydrationPerformanceBench.php @@ -0,0 +1,107 @@ +contractsRepository = $entityManager->getRepository(Company\CompanyContract::class); + $this->fixContractsRepository = $entityManager->getRepository(Company\CompanyFixContract::class); + $this->flexContractRepository = $entityManager->getRepository(Company\CompanyFlexContract::class); + $this->ultraContractRepository = $entityManager->getRepository(Company\CompanyFlexUltraContract::class); + + $person = new Company\CompanyEmployee(); + $person->setName('Poor Sales Guy'); + $person->setDepartment('Sales'); + $person->setSalary(100); + $entityManager->persist($person); + + for ($i = 0; $i < 33; $i++) { + $fixContract = new Company\CompanyFixContract(); + $flexContract = new Company\CompanyFlexContract(); + $ultraContract = new Company\CompanyFlexUltraContract(); + + $fixContract->setFixPrice(1000); + $fixContract->setSalesPerson($person); + $fixContract->markCompleted(); + + $flexContract->setSalesPerson($person); + $flexContract->setHoursWorked(100); + $flexContract->setPricePerHour(100); + $flexContract->markCompleted(); + + $ultraContract->setSalesPerson($person); + $ultraContract->setHoursWorked(150); + $ultraContract->setPricePerHour(150); + $ultraContract->setMaxPrice(7000); + + $entityManager->persist($fixContract); + $entityManager->persist($flexContract); + $entityManager->persist($ultraContract); + } + + $entityManager->flush(); + $entityManager->clear(); + } + + public function benchHydrateFixContracts() + { + $this->fixContractsRepository->findAll(); + } + + public function benchHydrateFlexContracts() + { + $this->flexContractRepository->findAll(); + } + + public function benchHydrateUltraContracts() + { + $this->ultraContractRepository->findAll(); + } + + public function benchHydrateAllContracts() + { + $this->contractsRepository->findAll(); + } +} diff --git a/tests/Doctrine/Performance/Hydration/SingleTableInheritanceInsertPerformanceBench.php b/tests/Doctrine/Performance/Hydration/SingleTableInheritanceInsertPerformanceBench.php new file mode 100644 index 00000000000..8014b0ed1f3 --- /dev/null +++ b/tests/Doctrine/Performance/Hydration/SingleTableInheritanceInsertPerformanceBench.php @@ -0,0 +1,100 @@ +entityManager = EntityManagerFactory::getEntityManager([ + Company\CompanyPerson::class, + Company\CompanyEmployee::class, + Company\CompanyManager::class, + Company\CompanyOrganization::class, + Company\CompanyEvent::class, + Company\CompanyAuction::class, + Company\CompanyRaffle::class, + Company\CompanyCar::class, + Company\CompanyContract::class, + ]); + + $person = new Company\CompanyEmployee(); + $person->setName('Poor Sales Guy'); + $person->setDepartment('Sales'); + $person->setSalary(100); + $this->entityManager->persist($person); + + for ($i = 0; $i < 33; $i++) { + $this->fixContracts[$i] = new Company\CompanyFixContract(); + $this->fixContracts[$i]->setFixPrice(1000); + $this->fixContracts[$i]->setSalesPerson($person); + $this->fixContracts[$i]->markCompleted(); + + $this->flexContracts[$i] = new Company\CompanyFlexContract(); + $this->flexContracts[$i]->setSalesPerson($person); + $this->flexContracts[$i]->setHoursWorked(100); + $this->flexContracts[$i]->setPricePerHour(100); + $this->flexContracts[$i]->markCompleted(); + + $this->ultraContracts[$i] = new Company\CompanyFlexUltraContract(); + $this->ultraContracts[$i]->setSalesPerson($person); + $this->ultraContracts[$i]->setHoursWorked(150); + $this->ultraContracts[$i]->setPricePerHour(150); + $this->ultraContracts[$i]->setMaxPrice(7000); + } + } + + public function benchInsertFixContracts() + { + array_map([$this->entityManager, 'persist'], $this->fixContracts); + $this->entityManager->flush(); + } + + public function benchInsertFlexContracts() + { + array_map([$this->entityManager, 'persist'], $this->flexContracts); + $this->entityManager->flush(); + } + + public function benchInsertUltraContracts() + { + array_map([$this->entityManager, 'persist'], $this->ultraContracts); + $this->entityManager->flush(); + } + + public function benchInsertAllContracts() + { + array_map([$this->entityManager, 'persist'], $this->fixContracts); + array_map([$this->entityManager, 'persist'], $this->flexContracts); + array_map([$this->entityManager, 'persist'], $this->ultraContracts); + $this->entityManager->flush(); + } +} diff --git a/tests/Doctrine/Performance/LazyLoading/ProxyInitializationTimeBench.php b/tests/Doctrine/Performance/LazyLoading/ProxyInitializationTimeBench.php new file mode 100644 index 00000000000..aeb5a1d2dee --- /dev/null +++ b/tests/Doctrine/Performance/LazyLoading/ProxyInitializationTimeBench.php @@ -0,0 +1,81 @@ +getProxyFactory(); + + for ($i = 0; $i < 10000; ++$i) { + $this->cmsUsers[$i] = $proxyFactory->getProxy(CmsUser::class, ['id' => $i]); + $this->cmsEmployees[$i] = $proxyFactory->getProxy(CmsEmployee::class, ['id' => $i]); + $this->initializedUsers[$i] = $proxyFactory->getProxy(CmsUser::class, ['id' => $i]); + $this->initializedEmployees[$i] = $proxyFactory->getProxy(CmsEmployee::class, ['id' => $i]); + + $this->initializedUsers[$i]->__load(); + $this->initializedEmployees[$i]->__load(); + } + } + + public function benchCmsUserInitialization() + { + foreach ($this->cmsUsers as $proxy) { + $proxy->__load(); + } + } + + public function benchCmsEmployeeInitialization() + { + foreach ($this->cmsEmployees as $proxy) { + $proxy->__load(); + } + } + + public function benchInitializationOfAlreadyInitializedCmsUsers() + { + foreach ($this->initializedUsers as $proxy) { + $proxy->__load(); + } + } + + public function benchInitializationOfAlreadyInitializedCmsEmployees() + { + foreach ($this->initializedEmployees as $proxy) { + $proxy->__load(); + } + } +} + diff --git a/tests/Doctrine/Performance/LazyLoading/ProxyInstantiationTimeBench.php b/tests/Doctrine/Performance/LazyLoading/ProxyInstantiationTimeBench.php new file mode 100644 index 00000000000..da5a2c94ff9 --- /dev/null +++ b/tests/Doctrine/Performance/LazyLoading/ProxyInstantiationTimeBench.php @@ -0,0 +1,40 @@ +proxyFactory = EntityManagerFactory::getEntityManager([])->getProxyFactory(); + } + + public function benchCmsUserInstantiation() + { + for ($i = 0; $i < 100000; ++$i) { + $this->proxyFactory->getProxy(CmsUser::class, ['id' => $i]); + } + } + + public function benchCmsEmployeeInstantiation() + { + for ($i = 0; $i < 100000; ++$i) { + $this->proxyFactory->getProxy(CmsEmployee::class, ['id' => $i]); + } + } +} + diff --git a/tests/Doctrine/Performance/Mock/NonLoadingPersister.php b/tests/Doctrine/Performance/Mock/NonLoadingPersister.php new file mode 100644 index 00000000000..35881c5a94b --- /dev/null +++ b/tests/Doctrine/Performance/Mock/NonLoadingPersister.php @@ -0,0 +1,31 @@ +realEntityManager = $realEntityManager; + } + + /** + * {@inheritDoc} + */ + public function getProxyFactory() + { + $config = $this->realEntityManager->getConfiguration(); + + return new ProxyFactory( + $this, + $config->getProxyDir(), + $config->getProxyNamespace(), + $config->getAutoGenerateProxyClasses() + ); + } + + /** + * {@inheritDoc} + */ + public function getMetadataFactory() + { + return $this->realEntityManager->getMetadataFactory(); + } + + /** + * {@inheritDoc} + */ + public function getClassMetadata($className) + { + return $this->realEntityManager->getClassMetadata($className); + } + + /** + * {@inheritDoc} + */ + public function getUnitOfWork() + { + return new NonProxyLoadingUnitOfWork(); + } + + /** + * {@inheritDoc} + */ + public function getCache() + { + return $this->realEntityManager->getCache(); + } + + /** + * {@inheritDoc} + */ + public function getConnection() + { + return $this->realEntityManager->getConnection(); + } + + /** + * {@inheritDoc} + */ + public function getExpressionBuilder() + { + return $this->realEntityManager->getExpressionBuilder(); + } + + /** + * {@inheritDoc} + */ + public function beginTransaction() + { + $this->realEntityManager->beginTransaction(); + } + + /** + * {@inheritDoc} + */ + public function transactional($func) + { + return $this->realEntityManager->transactional($func); + } + + /** + * {@inheritDoc} + */ + public function commit() + { + $this->realEntityManager->commit(); + } + + /** + * {@inheritDoc} + */ + public function rollback() + { + $this->realEntityManager->rollback(); + } + + /** + * {@inheritDoc} + */ + public function createQuery($dql = '') + { + return $this->realEntityManager->createQuery($dql); + } + + /** + * {@inheritDoc} + */ + public function createNamedQuery($name) + { + return $this->realEntityManager->createNamedQuery($name); + } + + /** + * {@inheritDoc} + */ + public function createNativeQuery($sql, ResultSetMapping $rsm) + { + return $this->realEntityManager->createNativeQuery($sql, $rsm); + } + + /** + * {@inheritDoc} + */ + public function createNamedNativeQuery($name) + { + return $this->realEntityManager->createNamedNativeQuery($name); + } + + /** + * {@inheritDoc} + */ + public function createQueryBuilder() + { + return $this->realEntityManager->createQueryBuilder(); + } + + /** + * {@inheritDoc} + */ + public function getReference($entityName, $id) + { + return $this->realEntityManager->getReference($entityName, $id); + } + + /** + * {@inheritDoc} + */ + public function getPartialReference($entityName, $identifier) + { + return $this->realEntityManager->getPartialReference($entityName, $identifier); + } + + /** + * {@inheritDoc} + */ + public function close() + { + $this->realEntityManager->close(); + } + + /** + * {@inheritDoc} + */ + public function copy($entity, $deep = false) + { + return $this->realEntityManager->copy($entity, $deep); + } + + /** + * {@inheritDoc} + */ + public function lock($entity, $lockMode, $lockVersion = null) + { + $this->realEntityManager->lock($entity, $lockMode, $lockVersion); + } + + /** + * {@inheritDoc} + */ + public function getEventManager() + { + return $this->realEntityManager->getEventManager(); + } + + /** + * {@inheritDoc} + */ + public function getConfiguration() + { + return $this->realEntityManager->getConfiguration(); + } + + /** + * {@inheritDoc} + */ + public function isOpen() + { + return $this->realEntityManager->isOpen(); + } + + /** + * {@inheritDoc} + */ + public function getHydrator($hydrationMode) + { + return $this->realEntityManager->getHydrator($hydrationMode); + } + + /** + * {@inheritDoc} + */ + public function newHydrator($hydrationMode) + { + return $this->realEntityManager->newHydrator($hydrationMode); + } + + /** + * {@inheritDoc} + */ + public function getFilters() + { + return $this->realEntityManager->getFilters(); + } + + /** + * {@inheritDoc} + */ + public function isFiltersStateClean() + { + return $this->realEntityManager->isFiltersStateClean(); + } + + /** + * {@inheritDoc} + */ + public function hasFilters() + { + return $this->realEntityManager->hasFilters(); + } + + /** + * {@inheritDoc} + */ + public function find($className, $id) + { + return $this->realEntityManager->find($className, $id); + } + + /** + * {@inheritDoc} + */ + public function persist($object) + { + $this->realEntityManager->persist($object); + } + + /** + * {@inheritDoc} + */ + public function remove($object) + { + $this->realEntityManager->remove($object); + } + + /** + * {@inheritDoc} + */ + public function merge($object) + { + return $this->realEntityManager->merge($object); + } + + /** + * {@inheritDoc} + */ + public function clear($objectName = null) + { + $this->realEntityManager->clear($objectName); + } + + /** + * {@inheritDoc} + */ + public function detach($object) + { + $this->realEntityManager->detach($object); + } + + /** + * {@inheritDoc} + */ + public function refresh($object) + { + $this->realEntityManager->refresh($object); + } + + /** + * {@inheritDoc} + */ + public function flush() + { + $this->realEntityManager->flush(); + } + + /** + * {@inheritDoc} + */ + public function getRepository($className) + { + return $this->realEntityManager->getRepository($className); + } + + /** + * {@inheritDoc} + */ + public function initializeObject($obj) + { + $this->realEntityManager->initializeObject($obj); + } + + /** + * {@inheritDoc} + */ + public function contains($object) + { + return $this->realEntityManager->contains($object); + } +} \ No newline at end of file diff --git a/tests/Doctrine/Performance/Mock/NonProxyLoadingUnitOfWork.php b/tests/Doctrine/Performance/Mock/NonProxyLoadingUnitOfWork.php new file mode 100644 index 00000000000..dd9139ae778 --- /dev/null +++ b/tests/Doctrine/Performance/Mock/NonProxyLoadingUnitOfWork.php @@ -0,0 +1,31 @@ +entityPersister = new NonLoadingPersister(); + } + + /** + * {@inheritDoc} + */ + public function getEntityPersister($entityName) + { + return $this->entityPersister; + } +} diff --git a/tests/Doctrine/Performance/Query/QueryBoundParameterProcessingBench.php b/tests/Doctrine/Performance/Query/QueryBoundParameterProcessingBench.php new file mode 100644 index 00000000000..9195804706b --- /dev/null +++ b/tests/Doctrine/Performance/Query/QueryBoundParameterProcessingBench.php @@ -0,0 +1,78 @@ +parsedQueryWithInferredParameterType = $entityManager->createQuery($dql); + $this->parsedQueryWithDeclaredParameterType = $entityManager->createQuery($dql); + + foreach (range(1, 10) as $index) { + $this->parsedQueryWithInferredParameterType->setParameter('parameter' . $index, new DateTime()); + $this->parsedQueryWithDeclaredParameterType->setParameter('parameter' . $index, new DateTime(), DateTimeType::DATETIME); + } + + // Force parsing upfront - we don't benchmark that bit in this scenario + $this->parsedQueryWithInferredParameterType->getSQL(); + $this->parsedQueryWithDeclaredParameterType->getSQL(); + } + + public function benchExecuteParsedQueryWithInferredParameterType() : void + { + $this->parsedQueryWithInferredParameterType->execute(); + } + + public function benchExecuteParsedQueryWithDeclaredParameterType() : void + { + $this->parsedQueryWithDeclaredParameterType->execute(); + } +} diff --git a/tests/Doctrine/Tests/DbalTypes/CustomIdObject.php b/tests/Doctrine/Tests/DbalTypes/CustomIdObject.php index df34ebccb5b..d777d2dc4bb 100644 --- a/tests/Doctrine/Tests/DbalTypes/CustomIdObject.php +++ b/tests/Doctrine/Tests/DbalTypes/CustomIdObject.php @@ -1,21 +1,4 @@ . - */ namespace Doctrine\Tests\DbalTypes; diff --git a/tests/Doctrine/Tests/DbalTypes/CustomIdObjectType.php b/tests/Doctrine/Tests/DbalTypes/CustomIdObjectType.php index 3d5aa0c19ac..0ebae5dff0e 100644 --- a/tests/Doctrine/Tests/DbalTypes/CustomIdObjectType.php +++ b/tests/Doctrine/Tests/DbalTypes/CustomIdObjectType.php @@ -1,21 +1,4 @@ . - */ namespace Doctrine\Tests\DbalTypes; @@ -25,7 +8,6 @@ class CustomIdObjectType extends Type { const NAME = 'CustomIdObject'; - const CLASSNAME = __CLASS__; /** * {@inheritdoc} diff --git a/tests/Doctrine/Tests/DbalTypes/NegativeToPositiveType.php b/tests/Doctrine/Tests/DbalTypes/NegativeToPositiveType.php index 8395b6acdd8..f5e50fa07ce 100644 --- a/tests/Doctrine/Tests/DbalTypes/NegativeToPositiveType.php +++ b/tests/Doctrine/Tests/DbalTypes/NegativeToPositiveType.php @@ -7,12 +7,14 @@ class NegativeToPositiveType extends Type { + const NAME = 'negative_to_positive'; + /** * {@inheritdoc} */ public function getName() { - return 'negative_to_positive'; + return self::NAME; } /** diff --git a/tests/Doctrine/Tests/DbalTypes/UpperCaseStringType.php b/tests/Doctrine/Tests/DbalTypes/UpperCaseStringType.php index 3811aa00d56..866a62475bf 100644 --- a/tests/Doctrine/Tests/DbalTypes/UpperCaseStringType.php +++ b/tests/Doctrine/Tests/DbalTypes/UpperCaseStringType.php @@ -7,12 +7,14 @@ class UpperCaseStringType extends StringType { + const NAME = 'upper_case_string'; + /** * {@inheritdoc} */ public function getName() { - return 'upper_case_string'; + return self::NAME; } /** diff --git a/tests/Doctrine/Tests/DoctrineTestCase.php b/tests/Doctrine/Tests/DoctrineTestCase.php index e5ce27af91d..457f52f366c 100644 --- a/tests/Doctrine/Tests/DoctrineTestCase.php +++ b/tests/Doctrine/Tests/DoctrineTestCase.php @@ -2,9 +2,11 @@ namespace Doctrine\Tests; +use PHPUnit\Framework\TestCase; + /** * Base testcase class for all Doctrine testcases. */ -abstract class DoctrineTestCase extends \PHPUnit_Framework_TestCase +abstract class DoctrineTestCase extends TestCase { } diff --git a/tests/Doctrine/Tests/EventListener/CacheMetadataListener.php b/tests/Doctrine/Tests/EventListener/CacheMetadataListener.php index f27e38c4779..e8cc6b23ae3 100644 --- a/tests/Doctrine/Tests/EventListener/CacheMetadataListener.php +++ b/tests/Doctrine/Tests/EventListener/CacheMetadataListener.php @@ -17,7 +17,7 @@ class CacheMetadataListener * * @var array */ - protected $enabledItems = array(); + protected $enabledItems = []; /** * @param \Doctrine\Common\Persistence\Event\LoadClassMetadataEventArgs $event @@ -63,9 +63,9 @@ protected function enableCaching(ClassMetadata $metadata, EntityManager $em) return; // Already handled in the past } - $cache = array( + $cache = [ 'usage' => ClassMetadata::CACHE_USAGE_NONSTRICT_READ_WRITE - ); + ]; if ($metadata->isVersioned) { return; diff --git a/tests/Doctrine/Tests/Mapping/UnderscoreNamingStrategyTest.php b/tests/Doctrine/Tests/Mapping/UnderscoreNamingStrategyTest.php new file mode 100644 index 00000000000..589dc7fd7e0 --- /dev/null +++ b/tests/Doctrine/Tests/Mapping/UnderscoreNamingStrategyTest.php @@ -0,0 +1,22 @@ +expectDeprecationMessage('Creating Doctrine\ORM\Mapping\UnderscoreNamingStrategy without making it number aware is deprecated and will be removed in Doctrine ORM 3.0.'); + new UnderscoreNamingStrategy(CASE_LOWER, false); + } +} diff --git a/tests/Doctrine/Tests/Mocks/CacheRegionMock.php b/tests/Doctrine/Tests/Mocks/CacheRegionMock.php index 519e724941c..c99303907ac 100644 --- a/tests/Doctrine/Tests/Mocks/CacheRegionMock.php +++ b/tests/Doctrine/Tests/Mocks/CacheRegionMock.php @@ -13,8 +13,8 @@ */ class CacheRegionMock implements Region { - public $calls = array(); - public $returns = array(); + public $calls = []; + public $returns = []; public $name; /** @@ -50,7 +50,7 @@ private function getReturn($method, $default) */ public function getName() { - $this->calls[__FUNCTION__][] = array(); + $this->calls[__FUNCTION__][] = []; return $this->name; } @@ -60,7 +60,7 @@ public function getName() */ public function contains(CacheKey $key) { - $this->calls[__FUNCTION__][] = array('key' => $key); + $this->calls[__FUNCTION__][] = ['key' => $key]; return $this->getReturn(__FUNCTION__, false); } @@ -70,7 +70,7 @@ public function contains(CacheKey $key) */ public function evict(CacheKey $key) { - $this->calls[__FUNCTION__][] = array('key' => $key); + $this->calls[__FUNCTION__][] = ['key' => $key]; return $this->getReturn(__FUNCTION__, true); } @@ -80,7 +80,7 @@ public function evict(CacheKey $key) */ public function evictAll() { - $this->calls[__FUNCTION__][] = array(); + $this->calls[__FUNCTION__][] = []; return $this->getReturn(__FUNCTION__, true); } @@ -90,7 +90,7 @@ public function evictAll() */ public function get(CacheKey $key) { - $this->calls[__FUNCTION__][] = array('key' => $key); + $this->calls[__FUNCTION__][] = ['key' => $key]; return $this->getReturn(__FUNCTION__, null); } @@ -100,7 +100,7 @@ public function get(CacheKey $key) */ public function getMultiple(CollectionCacheEntry $collection) { - $this->calls[__FUNCTION__][] = array('collection' => $collection); + $this->calls[__FUNCTION__][] = ['collection' => $collection]; return $this->getReturn(__FUNCTION__, null); } @@ -110,7 +110,7 @@ public function getMultiple(CollectionCacheEntry $collection) */ public function put(CacheKey $key, CacheEntry $entry, Lock $lock = null) { - $this->calls[__FUNCTION__][] = array('key' => $key, 'entry' => $entry); + $this->calls[__FUNCTION__][] = ['key' => $key, 'entry' => $entry]; return $this->getReturn(__FUNCTION__, true); } @@ -120,7 +120,7 @@ public function put(CacheKey $key, CacheEntry $entry, Lock $lock = null) */ public function clear() { - $this->calls = array(); - $this->returns = array(); + $this->calls = []; + $this->returns = []; } } diff --git a/tests/Doctrine/Tests/Mocks/ConcurrentRegionMock.php b/tests/Doctrine/Tests/Mocks/ConcurrentRegionMock.php index 49ed3298530..0f939999d70 100644 --- a/tests/Doctrine/Tests/Mocks/ConcurrentRegionMock.php +++ b/tests/Doctrine/Tests/Mocks/ConcurrentRegionMock.php @@ -17,12 +17,12 @@ */ class ConcurrentRegionMock implements ConcurrentRegion { - public $calls = array(); - public $exceptions = array(); - public $locks = array(); + public $calls = []; + public $exceptions = []; + public $locks = []; /** - * @var \Doctrine\ORM\Cache\Region + * @var \Doctrine\ORM\Cache\Region */ private $region; @@ -80,7 +80,7 @@ public function setLock(CacheKey $key, Lock $lock) */ public function contains(CacheKey $key) { - $this->calls[__FUNCTION__][] = array('key' => $key); + $this->calls[__FUNCTION__][] = ['key' => $key]; if (isset($this->locks[$key->hash])) { return false; @@ -96,7 +96,7 @@ public function contains(CacheKey $key) */ public function evict(CacheKey $key) { - $this->calls[__FUNCTION__][] = array('key' => $key); + $this->calls[__FUNCTION__][] = ['key' => $key]; $this->throwException(__FUNCTION__); @@ -108,7 +108,7 @@ public function evict(CacheKey $key) */ public function evictAll() { - $this->calls[__FUNCTION__][] = array(); + $this->calls[__FUNCTION__][] = []; $this->throwException(__FUNCTION__); @@ -120,7 +120,7 @@ public function evictAll() */ public function get(CacheKey $key) { - $this->calls[__FUNCTION__][] = array('key' => $key); + $this->calls[__FUNCTION__][] = ['key' => $key]; $this->throwException(__FUNCTION__); @@ -136,7 +136,7 @@ public function get(CacheKey $key) */ public function getMultiple(CollectionCacheEntry $collection) { - $this->calls[__FUNCTION__][] = array('collection' => $collection); + $this->calls[__FUNCTION__][] = ['collection' => $collection]; $this->throwException(__FUNCTION__); @@ -148,7 +148,7 @@ public function getMultiple(CollectionCacheEntry $collection) */ public function getName() { - $this->calls[__FUNCTION__][] = array(); + $this->calls[__FUNCTION__][] = []; $this->throwException(__FUNCTION__); @@ -160,7 +160,7 @@ public function getName() */ public function put(CacheKey $key, CacheEntry $entry, Lock $lock = null) { - $this->calls[__FUNCTION__][] = array('key' => $key, 'entry' => $entry); + $this->calls[__FUNCTION__][] = ['key' => $key, 'entry' => $entry]; $this->throwException(__FUNCTION__); @@ -181,7 +181,7 @@ public function put(CacheKey $key, CacheEntry $entry, Lock $lock = null) */ public function lock(CacheKey $key) { - $this->calls[__FUNCTION__][] = array('key' => $key); + $this->calls[__FUNCTION__][] = ['key' => $key]; $this->throwException(__FUNCTION__); @@ -197,7 +197,7 @@ public function lock(CacheKey $key) */ public function unlock(CacheKey $key, Lock $lock) { - $this->calls[__FUNCTION__][] = array('key' => $key, 'lock' => $lock); + $this->calls[__FUNCTION__][] = ['key' => $key, 'lock' => $lock]; $this->throwException(__FUNCTION__); diff --git a/tests/Doctrine/Tests/Mocks/ConnectionMock.php b/tests/Doctrine/Tests/Mocks/ConnectionMock.php index 49ca3e4ea5a..af8fc252e99 100644 --- a/tests/Doctrine/Tests/Mocks/ConnectionMock.php +++ b/tests/Doctrine/Tests/Mocks/ConnectionMock.php @@ -1,7 +1,9 @@ _inserts[$tableName][] = $data; } @@ -68,9 +80,9 @@ public function insert($tableName, array $data, array $types = array()) /** * {@inheritdoc} */ - public function executeUpdate($query, array $params = array(), array $types = array()) + public function executeUpdate($query, array $params = [], array $types = []) { - $this->_executeUpdates[] = array('query' => $query, 'params' => $params, 'types' => $types); + $this->_executeUpdates[] = ['query' => $query, 'params' => $params, 'types' => $types]; } /** @@ -84,11 +96,23 @@ public function lastInsertId($seqName = null) /** * {@inheritdoc} */ - public function fetchColumn($statement, array $params = array(), $colnum = 0, array $types = array()) + public function fetchColumn($statement, array $params = [], $colnum = 0, array $types = []) { + if (null !== $this->_fetchOneException) { + throw $this->_fetchOneException; + } + return $this->_fetchOneResult; } + /** + * {@inheritdoc} + */ + public function query() : Statement + { + return $this->_queryResult; + } + /** * {@inheritdoc} */ @@ -112,6 +136,16 @@ public function setFetchOneResult($fetchOneResult) $this->_fetchOneResult = $fetchOneResult; } + /** + * @param \Exception|null $exception + * + * @return void + */ + public function setFetchOneException(\Exception $exception = null) + { + $this->_fetchOneException = $exception; + } + /** * @param \Doctrine\DBAL\Platforms\AbstractPlatform $platform * @@ -132,6 +166,14 @@ public function setLastInsertId($id) $this->_lastInsertId = $id; } + /** + * @param Statement $result + */ + public function setQueryResult(Statement $result) + { + $this->_queryResult = $result; + } + /** * @return array */ @@ -153,7 +195,7 @@ public function getExecuteUpdates() */ public function reset() { - $this->_inserts = array(); + $this->_inserts = []; $this->_lastInsertId = 0; } } diff --git a/tests/Doctrine/Tests/Mocks/DriverMock.php b/tests/Doctrine/Tests/Mocks/DriverMock.php index 15a37c17dd6..21ae4e3bbab 100644 --- a/tests/Doctrine/Tests/Mocks/DriverMock.php +++ b/tests/Doctrine/Tests/Mocks/DriverMock.php @@ -25,7 +25,7 @@ class DriverMock implements Driver /** * {@inheritdoc} */ - public function connect(array $params, $username = null, $password = null, array $driverOptions = array()) + public function connect(array $params, $username = null, $password = null, array $driverOptions = []) { return new DriverConnectionMock(); } @@ -48,9 +48,9 @@ public function getSchemaManager(Connection $conn) { if ($this->_schemaManagerMock == null) { return new SchemaManagerMock($conn); - } else { - return $this->_schemaManagerMock; } + + return $this->_schemaManagerMock; } /* MOCK API */ diff --git a/tests/Doctrine/Tests/Mocks/EntityManagerMock.php b/tests/Doctrine/Tests/Mocks/EntityManagerMock.php index 24ecb59efe3..f7af70227dd 100644 --- a/tests/Doctrine/Tests/Mocks/EntityManagerMock.php +++ b/tests/Doctrine/Tests/Mocks/EntityManagerMock.php @@ -1,23 +1,4 @@ . - */ namespace Doctrine\Tests\Mocks; @@ -91,7 +72,7 @@ public static function create($conn, Configuration $config = null, EventManager $config = new Configuration(); $config->setProxyDir(__DIR__ . '/../Proxies'); $config->setProxyNamespace('Doctrine\Tests\Proxies'); - $config->setMetadataDriverImpl($config->newDefaultAnnotationDriver(array(), true)); + $config->setMetadataDriverImpl($config->newDefaultAnnotationDriver([], true)); } if (null === $eventManager) { $eventManager = new EventManager(); diff --git a/tests/Doctrine/Tests/Mocks/EntityPersisterMock.php b/tests/Doctrine/Tests/Mocks/EntityPersisterMock.php index 6130f58f301..63be3397e68 100644 --- a/tests/Doctrine/Tests/Mocks/EntityPersisterMock.php +++ b/tests/Doctrine/Tests/Mocks/EntityPersisterMock.php @@ -14,17 +14,17 @@ class EntityPersisterMock extends BasicEntityPersister /** * @var array */ - private $inserts = array(); + private $inserts = []; /** * @var array */ - private $updates = array(); + private $updates = []; /** * @var array */ - private $deletes = array(); + private $deletes = []; /** * @var int @@ -39,7 +39,7 @@ class EntityPersisterMock extends BasicEntityPersister /** * @var array */ - private $postInsertIds = array(); + private $postInsertIds = []; /** * @var bool @@ -57,10 +57,10 @@ public function addInsert($entity) if ( ! is_null($this->mockIdGeneratorType) && $this->mockIdGeneratorType == ClassMetadata::GENERATOR_TYPE_IDENTITY || $this->class->isIdGeneratorIdentity()) { $id = $this->identityColumnValueCounter++; - $this->postInsertIds[] = array( + $this->postInsertIds[] = [ 'generatedId' => $id, 'entity' => $entity, - ); + ]; return $id; } return null; @@ -139,9 +139,9 @@ public function reset() { $this->existsCalled = false; $this->identityColumnValueCounter = 0; - $this->inserts = array(); - $this->updates = array(); - $this->deletes = array(); + $this->inserts = []; + $this->updates = []; + $this->deletes = []; } /** diff --git a/tests/Doctrine/Tests/Mocks/HydratorMockStatement.php b/tests/Doctrine/Tests/Mocks/HydratorMockStatement.php index 7afec2c607e..4f6df40e59d 100644 --- a/tests/Doctrine/Tests/Mocks/HydratorMockStatement.php +++ b/tests/Doctrine/Tests/Mocks/HydratorMockStatement.php @@ -30,13 +30,12 @@ public function __construct(array $resultSet) /** * Fetches all rows from the result set. * - * @param int|null $fetchStyle - * @param int|null $columnIndex + * @param int|null $fetchMode + * @param int|null $fetchArgument * @param array|null $ctorArgs - * * @return array */ - public function fetchAll($fetchStyle = null, $columnIndex = null, array $ctorArgs = null) + public function fetchAll($fetchMode = null, $fetchArgument = null, $ctorArgs = null) { return $this->_resultSet; } @@ -55,7 +54,7 @@ public function fetchColumn($columnNumber = 0) /** * {@inheritdoc} */ - public function fetch($fetchStyle = null) + public function fetch($fetchStyle = null, $cursorOrientation = \PDO::FETCH_ORI_NEXT, $cursorOffset = 0) { $current = current($this->_resultSet); next($this->_resultSet); @@ -108,7 +107,7 @@ public function errorInfo() /** * {@inheritdoc} */ - public function execute($params = array()) + public function execute($params = null) { } diff --git a/tests/Doctrine/Tests/Mocks/MetadataDriverMock.php b/tests/Doctrine/Tests/Mocks/MetadataDriverMock.php index b691ec02c3a..f14c256b19e 100644 --- a/tests/Doctrine/Tests/Mocks/MetadataDriverMock.php +++ b/tests/Doctrine/Tests/Mocks/MetadataDriverMock.php @@ -30,6 +30,6 @@ public function isTransient($className) */ public function getAllClassNames() { - return array(); + return []; } } diff --git a/tests/Doctrine/Tests/Mocks/StatementArrayMock.php b/tests/Doctrine/Tests/Mocks/StatementArrayMock.php index 4054b9a9ebd..0f1747c42dc 100644 --- a/tests/Doctrine/Tests/Mocks/StatementArrayMock.php +++ b/tests/Doctrine/Tests/Mocks/StatementArrayMock.php @@ -1,10 +1,4 @@ _result; } - public function fetch($fetchStyle = null) + public function fetch($fetchMode = null, $cursorOrientation = \PDO::FETCH_ORI_NEXT, $cursorOffset = 0) { $current = current($this->_result); next($this->_result); @@ -59,13 +53,13 @@ public function fetchColumn($columnIndex = 0) if ($current) { next($this->_result); return reset($current); - } else { - return false; } + + return false; } public function rowCount() { return count($this->_result); } -} \ No newline at end of file +} diff --git a/tests/Doctrine/Tests/Mocks/StatementMock.php b/tests/Doctrine/Tests/Mocks/StatementMock.php index 8107ff1beb1..efba7d841b4 100644 --- a/tests/Doctrine/Tests/Mocks/StatementMock.php +++ b/tests/Doctrine/Tests/Mocks/StatementMock.php @@ -75,14 +75,14 @@ public function setFetchMode($fetchStyle, $arg2 = null, $arg3 = null) /** * {@inheritdoc} */ - public function fetch($fetchStyle = null) + public function fetch($fetchMode = null, $cursorOrientation = \PDO::FETCH_ORI_NEXT, $cursorOffset = 0) { } /** * {@inheritdoc} */ - public function fetchAll($fetchStyle = null) + public function fetchAll($fetchMode = null, $fetchArgument = null, $ctorArgs = null) { } diff --git a/tests/Doctrine/Tests/Mocks/TaskMock.php b/tests/Doctrine/Tests/Mocks/TaskMock.php index 22676f67aaf..f6ce095add1 100644 --- a/tests/Doctrine/Tests/Mocks/TaskMock.php +++ b/tests/Doctrine/Tests/Mocks/TaskMock.php @@ -1,23 +1,4 @@ . - */ namespace Doctrine\Tests\Mocks; @@ -36,7 +17,7 @@ class TaskMock extends \Doctrine\Common\Cli\Tasks\AbstractTask * * @var array (TaskMock) */ - static public $instances = array(); + static public $instances = []; /** * @var int diff --git a/tests/Doctrine/Tests/Mocks/TimestampRegionMock.php b/tests/Doctrine/Tests/Mocks/TimestampRegionMock.php index b55c7c5e31d..3f088a4e492 100644 --- a/tests/Doctrine/Tests/Mocks/TimestampRegionMock.php +++ b/tests/Doctrine/Tests/Mocks/TimestampRegionMock.php @@ -14,6 +14,6 @@ class TimestampRegionMock extends CacheRegionMock implements TimestampRegion { public function update(CacheKey $key) { - $this->calls[__FUNCTION__][] = array('key' => $key); + $this->calls[__FUNCTION__][] = ['key' => $key]; } } diff --git a/tests/Doctrine/Tests/Mocks/UnitOfWorkMock.php b/tests/Doctrine/Tests/Mocks/UnitOfWorkMock.php index 3d7361e7f8e..f11f7152322 100644 --- a/tests/Doctrine/Tests/Mocks/UnitOfWorkMock.php +++ b/tests/Doctrine/Tests/Mocks/UnitOfWorkMock.php @@ -12,7 +12,7 @@ class UnitOfWorkMock extends UnitOfWork /** * @var array */ - private $_mockDataChangeSets = array(); + private $_mockDataChangeSets = []; /** * @var array|null diff --git a/tests/Doctrine/Tests/Models/CMS/CmsAddress.php b/tests/Doctrine/Tests/Models/CMS/CmsAddress.php index aaf4956d3d0..f5c0b9af766 100644 --- a/tests/Doctrine/Tests/Models/CMS/CmsAddress.php +++ b/tests/Doctrine/Tests/Models/CMS/CmsAddress.php @@ -124,91 +124,115 @@ public function setUser(CmsUser $user) { public static function loadMetadata(\Doctrine\ORM\Mapping\ClassMetadataInfo $metadata) { - $metadata->setPrimaryTable(array( + $metadata->setPrimaryTable( + [ 'name' => 'company_person', - )); + ] + ); - $metadata->mapField(array ( + $metadata->mapField( + [ 'id' => true, 'fieldName' => 'id', 'type' => 'integer', - )); + ] + ); - $metadata->mapField(array ( + $metadata->mapField( + [ 'fieldName' => 'zip', 'length' => 50, - )); + ] + ); - $metadata->mapField(array ( + $metadata->mapField( + [ 'fieldName' => 'city', 'length' => 50, - )); + ] + ); - $metadata->mapOneToOne(array( + $metadata->mapOneToOne( + [ 'fieldName' => 'user', 'targetEntity' => 'CmsUser', - 'joinColumns' => array(array('referencedColumnName' => 'id')) - )); + 'joinColumns' => [['referencedColumnName' => 'id']] + ] + ); - $metadata->addNamedNativeQuery(array ( + $metadata->addNamedNativeQuery( + [ 'name' => 'find-all', 'query' => 'SELECT id, country, city FROM cms_addresses', 'resultSetMapping' => 'mapping-find-all', - )); + ] + ); - $metadata->addNamedNativeQuery(array ( + $metadata->addNamedNativeQuery( + [ 'name' => 'find-by-id', 'query' => 'SELECT * FROM cms_addresses WHERE id = ?', - 'resultClass' => 'Doctrine\\Tests\\Models\\CMS\\CmsAddress', - )); + 'resultClass' => CmsAddress::class, + ] + ); - $metadata->addNamedNativeQuery(array ( + $metadata->addNamedNativeQuery( + [ 'name' => 'count', 'query' => 'SELECT COUNT(*) AS count FROM cms_addresses', 'resultSetMapping' => 'mapping-count', - )); + ] + ); - $metadata->addSqlResultSetMapping(array ( + $metadata->addSqlResultSetMapping( + [ 'name' => 'mapping-find-all', - 'columns' => array(), - 'entities' => array ( array ( - 'fields' => array ( - array ( + 'columns' => [], + 'entities' => [ + [ + 'fields' => [ + [ 'name' => 'id', 'column' => 'id', - ), - array ( + ], + [ 'name' => 'city', 'column' => 'city', - ), - array ( + ], + [ 'name' => 'country', 'column' => 'country', - ), - ), - 'entityClass' => 'Doctrine\Tests\Models\CMS\CmsAddress', - ), - ), - )); - - $metadata->addSqlResultSetMapping(array ( + ], + ], + 'entityClass' => CmsAddress::class, + ], + ], + ] + ); + + $metadata->addSqlResultSetMapping( + [ 'name' => 'mapping-without-fields', - 'columns' => array(), - 'entities' => array(array ( - 'entityClass' => 'Doctrine\\Tests\\Models\\CMS\\CmsAddress', - 'fields' => array() - ) - ) - )); - - $metadata->addSqlResultSetMapping(array ( + 'columns' => [], + 'entities' => [ + [ + 'entityClass' => CmsAddress::class, + 'fields' => [] + ] + ] + ] + ); + + $metadata->addSqlResultSetMapping( + [ 'name' => 'mapping-count', - 'columns' =>array ( - array ( + 'columns' => [ + [ 'name' => 'count', - ), - ) - )); + ], + ] + ] + ); $metadata->addEntityListener(\Doctrine\ORM\Events::postPersist, 'CmsAddressListener', 'postPersist'); $metadata->addEntityListener(\Doctrine\ORM\Events::prePersist, 'CmsAddressListener', 'prePersist'); @@ -222,4 +246,4 @@ public static function loadMetadata(\Doctrine\ORM\Mapping\ClassMetadataInfo $met $metadata->addEntityListener(\Doctrine\ORM\Events::preFlush, 'CmsAddressListener', 'preFlush'); $metadata->addEntityListener(\Doctrine\ORM\Events::postLoad, 'CmsAddressListener', 'postLoad'); } -} \ No newline at end of file +} diff --git a/tests/Doctrine/Tests/Models/CMS/CmsGroup.php b/tests/Doctrine/Tests/Models/CMS/CmsGroup.php index b65ae8557d2..9707d8cc280 100644 --- a/tests/Doctrine/Tests/Models/CMS/CmsGroup.php +++ b/tests/Doctrine/Tests/Models/CMS/CmsGroup.php @@ -1,8 +1,4 @@ setPrimaryTable(array( + $metadata->setPrimaryTable( + [ 'name' => 'cms_users', - )); + ] + ); - $metadata->addNamedNativeQuery(array ( + $metadata->addNamedNativeQuery( + [ 'name' => 'fetchIdAndUsernameWithResultClass', 'query' => 'SELECT id, username FROM cms_users WHERE username = ?', - 'resultClass' => 'Doctrine\\Tests\\Models\\CMS\\CmsUser', - )); + 'resultClass' => CmsUser::class, + ] + ); - $metadata->addNamedNativeQuery(array ( + $metadata->addNamedNativeQuery( + [ 'name' => 'fetchAllColumns', 'query' => 'SELECT * FROM cms_users WHERE username = ?', - 'resultClass' => 'Doctrine\\Tests\\Models\\CMS\\CmsUser', - )); + 'resultClass' => CmsUser::class, + ] + ); - $metadata->addNamedNativeQuery(array ( + $metadata->addNamedNativeQuery( + [ 'name' => 'fetchJoinedAddress', 'query' => 'SELECT u.id, u.name, u.status, a.id AS a_id, a.country, a.zip, a.city FROM cms_users u INNER JOIN cms_addresses a ON u.id = a.user_id WHERE u.username = ?', 'resultSetMapping' => 'mappingJoinedAddress', - )); + ] + ); - $metadata->addNamedNativeQuery(array ( + $metadata->addNamedNativeQuery( + [ 'name' => 'fetchJoinedPhonenumber', 'query' => 'SELECT id, name, status, phonenumber AS number FROM cms_users INNER JOIN cms_phonenumbers ON id = user_id WHERE username = ?', 'resultSetMapping' => 'mappingJoinedPhonenumber', - )); + ] + ); - $metadata->addNamedNativeQuery(array ( + $metadata->addNamedNativeQuery( + [ 'name' => 'fetchUserPhonenumberCount', 'query' => 'SELECT id, name, status, COUNT(phonenumber) AS numphones FROM cms_users INNER JOIN cms_phonenumbers ON id = user_id WHERE username IN (?) GROUP BY id, name, status, username ORDER BY username', 'resultSetMapping' => 'mappingUserPhonenumberCount', - )); + ] + ); - $metadata->addNamedNativeQuery(array ( + $metadata->addNamedNativeQuery( + [ "name" => "fetchMultipleJoinsEntityResults", "resultSetMapping" => "mappingMultipleJoinsEntityResults", "query" => "SELECT u.id AS u_id, u.name AS u_name, u.status AS u_status, a.id AS a_id, a.zip AS a_zip, a.country AS a_country, COUNT(p.phonenumber) AS numphones FROM cms_users u INNER JOIN cms_addresses a ON u.id = a.user_id INNER JOIN cms_phonenumbers p ON u.id = p.user_id GROUP BY u.id, u.name, u.status, u.username, a.id, a.zip, a.country ORDER BY u.username" - )); + ] + ); - $metadata->addSqlResultSetMapping(array ( + $metadata->addSqlResultSetMapping( + [ 'name' => 'mappingJoinedAddress', - 'columns' => array(), - 'entities' => array(array ( - 'fields'=> array ( - array ( + 'columns' => [], + 'entities' => [ + [ + 'fields'=> [ + [ 'name' => 'id', 'column' => 'id', - ), - array ( + ], + [ 'name' => 'name', 'column' => 'name', - ), - array ( + ], + [ 'name' => 'status', 'column' => 'status', - ), - array ( + ], + [ 'name' => 'address.zip', 'column' => 'zip', - ), - array ( + ], + [ 'name' => 'address.city', 'column' => 'city', - ), - array ( + ], + [ 'name' => 'address.country', 'column' => 'country', - ), - array ( + ], + [ 'name' => 'address.id', 'column' => 'a_id', - ), - ), - 'entityClass' => 'Doctrine\Tests\Models\CMS\CmsUser', + ], + ], + 'entityClass' => CmsUser::class, 'discriminatorColumn' => null - ), - ), - )); + ], + ], + ] + ); - $metadata->addSqlResultSetMapping(array ( + $metadata->addSqlResultSetMapping( + [ 'name' => 'mappingJoinedPhonenumber', - 'columns' => array(), - 'entities' => array(array( - 'fields'=> array ( - array ( + 'columns' => [], + 'entities' => [ + [ + 'fields'=> [ + [ 'name' => 'id', 'column' => 'id', - ), - array ( + ], + [ 'name' => 'name', 'column' => 'name', - ), - array ( + ], + [ 'name' => 'status', 'column' => 'status', - ), - array ( + ], + [ 'name' => 'phonenumbers.phonenumber', 'column' => 'number', - ), - ), - 'entityClass' => 'Doctrine\\Tests\\Models\\CMS\\CmsUser', + ], + ], + 'entityClass' => CmsUser::class, 'discriminatorColumn' => null - ), - ), - )); + ], + ], + ] + ); - $metadata->addSqlResultSetMapping(array ( + $metadata->addSqlResultSetMapping( + [ 'name' => 'mappingUserPhonenumberCount', - 'columns' => array(), - 'entities' => array ( - array( - 'fields' => array ( - array ( + 'columns' => [], + 'entities' => [ + [ + 'fields' => [ + [ 'name' => 'id', 'column' => 'id', - ), - array ( + ], + [ 'name' => 'name', 'column' => 'name', - ), - array ( + ], + [ 'name' => 'status', 'column' => 'status', - ) - ), - 'entityClass' => 'Doctrine\Tests\Models\CMS\CmsUser', + ] + ], + 'entityClass' => CmsUser::class, 'discriminatorColumn' => null - ) - ), - 'columns' => array ( - array ( + ] + ], + 'columns' => [ + [ 'name' => 'numphones', - ) - ) - )); + ] + ] + ] + ); - $metadata->addSqlResultSetMapping(array( + $metadata->addSqlResultSetMapping( + [ 'name' => 'mappingMultipleJoinsEntityResults', - 'entities' => array(array( - 'fields' => array( - array( + 'entities' => [ + [ + 'fields' => [ + [ 'name' => 'id', 'column' => 'u_id', - ), - array( + ], + [ 'name' => 'name', 'column' => 'u_name', - ), - array( + ], + [ 'name' => 'status', 'column' => 'u_status', - ) - ), - 'entityClass' => 'Doctrine\Tests\Models\CMS\CmsUser', + ] + ], + 'entityClass' => CmsUser::class, 'discriminatorColumn' => null, - ), - array( - 'fields' => array( - array( + ], + [ + 'fields' => [ + [ 'name' => 'id', 'column' => 'a_id', - ), - array( + ], + [ 'name' => 'zip', 'column' => 'a_zip', - ), - array( + ], + [ 'name' => 'country', 'column' => 'a_country', - ), - ), - 'entityClass' => 'Doctrine\Tests\Models\CMS\CmsAddress', + ], + ], + 'entityClass' => CmsAddress::class, 'discriminatorColumn' => null, - ), - ), - 'columns' => array(array( + ], + ], + 'columns' => [ + [ 'name' => 'numphones', - ) - ) - )); + ] + ] + ] + ); } } diff --git a/tests/Doctrine/Tests/Models/Cache/Action.php b/tests/Doctrine/Tests/Models/Cache/Action.php index 25609abedb5..72bbba4c173 100644 --- a/tests/Doctrine/Tests/Models/Cache/Action.php +++ b/tests/Doctrine/Tests/Models/Cache/Action.php @@ -10,17 +10,10 @@ */ class Action { - const CLASSNAME = __CLASS__; - /** * @Id - * @GeneratedValue - * @Column(type="integer") - */ - public $id; - - /** - * @Column + * @Column(type="string") + * @GeneratedValue(strategy="NONE") */ public $name; diff --git a/tests/Doctrine/Tests/Models/Cache/Address.php b/tests/Doctrine/Tests/Models/Cache/Address.php index fa5363560fa..5ccb349d0a0 100644 --- a/tests/Doctrine/Tests/Models/Cache/Address.php +++ b/tests/Doctrine/Tests/Models/Cache/Address.php @@ -8,8 +8,6 @@ */ class Address { - const CLASSNAME = __CLASS__; - /** * @Id * @GeneratedValue diff --git a/tests/Doctrine/Tests/Models/Cache/Attraction.php b/tests/Doctrine/Tests/Models/Cache/Attraction.php index cbd62f84163..f53786dde7a 100644 --- a/tests/Doctrine/Tests/Models/Cache/Attraction.php +++ b/tests/Doctrine/Tests/Models/Cache/Attraction.php @@ -17,8 +17,6 @@ */ abstract class Attraction { - const CLASSNAME = __CLASS__; - /** * @Id * @GeneratedValue @@ -92,4 +90,4 @@ public function addInfo(AttractionInfo $info) $this->infos->add($info); } } -} \ No newline at end of file +} diff --git a/tests/Doctrine/Tests/Models/Cache/AttractionContactInfo.php b/tests/Doctrine/Tests/Models/Cache/AttractionContactInfo.php index 76ef305a41c..e25665528ad 100644 --- a/tests/Doctrine/Tests/Models/Cache/AttractionContactInfo.php +++ b/tests/Doctrine/Tests/Models/Cache/AttractionContactInfo.php @@ -8,8 +8,6 @@ */ class AttractionContactInfo extends AttractionInfo { - const CLASSNAME = __CLASS__; - /** * @Column(unique=true) */ @@ -30,4 +28,4 @@ public function setFone($fone) { $this->fone = $fone; } -} \ No newline at end of file +} diff --git a/tests/Doctrine/Tests/Models/Cache/AttractionInfo.php b/tests/Doctrine/Tests/Models/Cache/AttractionInfo.php index 418ef49b06c..978d8587e25 100644 --- a/tests/Doctrine/Tests/Models/Cache/AttractionInfo.php +++ b/tests/Doctrine/Tests/Models/Cache/AttractionInfo.php @@ -14,8 +14,6 @@ */ abstract class AttractionInfo { - const CLASSNAME = __CLASS__; - /** * @Id * @GeneratedValue @@ -51,4 +49,4 @@ public function setAttraction(Attraction $attraction) $attraction->addInfo($this); } -} \ No newline at end of file +} diff --git a/tests/Doctrine/Tests/Models/Cache/AttractionLocationInfo.php b/tests/Doctrine/Tests/Models/Cache/AttractionLocationInfo.php index ebdb592aea9..e7419fb4a67 100644 --- a/tests/Doctrine/Tests/Models/Cache/AttractionLocationInfo.php +++ b/tests/Doctrine/Tests/Models/Cache/AttractionLocationInfo.php @@ -8,8 +8,6 @@ */ class AttractionLocationInfo extends AttractionInfo { - const CLASSNAME = __CLASS__; - /** * @Column(unique=true) */ @@ -30,4 +28,4 @@ public function setAddress($address) { $this->address = $address; } -} \ No newline at end of file +} diff --git a/tests/Doctrine/Tests/Models/Cache/Bar.php b/tests/Doctrine/Tests/Models/Cache/Bar.php index f0d0931270d..cc54d547c90 100644 --- a/tests/Doctrine/Tests/Models/Cache/Bar.php +++ b/tests/Doctrine/Tests/Models/Cache/Bar.php @@ -7,5 +7,4 @@ */ class Bar extends Attraction { - const CLASSNAME = __CLASS__; -} \ No newline at end of file +} diff --git a/tests/Doctrine/Tests/Models/Cache/Beach.php b/tests/Doctrine/Tests/Models/Cache/Beach.php index 61e623dc573..dcabe5935ab 100644 --- a/tests/Doctrine/Tests/Models/Cache/Beach.php +++ b/tests/Doctrine/Tests/Models/Cache/Beach.php @@ -7,5 +7,4 @@ */ class Beach extends Attraction { - const CLASSNAME = __CLASS__; -} \ No newline at end of file +} diff --git a/tests/Doctrine/Tests/Models/Cache/City.php b/tests/Doctrine/Tests/Models/Cache/City.php index f755e07aec9..b3769fbe779 100644 --- a/tests/Doctrine/Tests/Models/Cache/City.php +++ b/tests/Doctrine/Tests/Models/Cache/City.php @@ -11,8 +11,6 @@ */ class City { - const CLASSNAME = __CLASS__; - /** * @Id * @GeneratedValue @@ -106,4 +104,4 @@ public static function loadMetadata(\Doctrine\ORM\Mapping\ClassMetadataInfo $met { include __DIR__ . '/../../ORM/Mapping/php/Doctrine.Tests.Models.Cache.City.php'; } -} \ No newline at end of file +} diff --git a/tests/Doctrine/Tests/Models/Cache/Client.php b/tests/Doctrine/Tests/Models/Cache/Client.php index 70544256bf1..dfbc60e30cf 100644 --- a/tests/Doctrine/Tests/Models/Cache/Client.php +++ b/tests/Doctrine/Tests/Models/Cache/Client.php @@ -8,8 +8,6 @@ */ class Client { - const CLASSNAME = __CLASS__; - /** * @Id * @GeneratedValue diff --git a/tests/Doctrine/Tests/Models/Cache/ComplexAction.php b/tests/Doctrine/Tests/Models/Cache/ComplexAction.php index 46d0414d3a2..9c0a0abd9fb 100644 --- a/tests/Doctrine/Tests/Models/Cache/ComplexAction.php +++ b/tests/Doctrine/Tests/Models/Cache/ComplexAction.php @@ -10,8 +10,6 @@ */ class ComplexAction { - const CLASSNAME = __CLASS__; - /** * @Column */ @@ -20,14 +18,14 @@ class ComplexAction /** * @Id * @OneToOne(targetEntity="Action", cascade={"persist", "remove"}) - * @JoinColumn(name="action1_id", referencedColumnName="id") + * @JoinColumn(name="action1_name", referencedColumnName="name") */ public $action1; /** * @Id * @OneToOne(targetEntity="Action", cascade={"persist", "remove"}) - * @JoinColumn(name="action2_id", referencedColumnName="id") + * @JoinColumn(name="action2_name", referencedColumnName="name") */ public $action2; diff --git a/tests/Doctrine/Tests/Models/Cache/Country.php b/tests/Doctrine/Tests/Models/Cache/Country.php index 33a9cf40cfd..f4179f63e75 100644 --- a/tests/Doctrine/Tests/Models/Cache/Country.php +++ b/tests/Doctrine/Tests/Models/Cache/Country.php @@ -9,8 +9,6 @@ */ class Country { - const CLASSNAME = __CLASS__; - /** * @Id * @GeneratedValue @@ -47,4 +45,4 @@ public function setName($name) { $this->name = $name; } -} \ No newline at end of file +} diff --git a/tests/Doctrine/Tests/Models/Cache/Flight.php b/tests/Doctrine/Tests/Models/Cache/Flight.php index a95caab241c..f109c34da38 100644 --- a/tests/Doctrine/Tests/Models/Cache/Flight.php +++ b/tests/Doctrine/Tests/Models/Cache/Flight.php @@ -9,8 +9,6 @@ */ class Flight { - const CLASSNAME = __CLASS__; - /** * @Id * @Cache @@ -62,4 +60,4 @@ public function setDeparture($departure) { $this->departure = $departure; } -} \ No newline at end of file +} diff --git a/tests/Doctrine/Tests/Models/Cache/Login.php b/tests/Doctrine/Tests/Models/Cache/Login.php index 8de766d38c5..24e5b133dac 100644 --- a/tests/Doctrine/Tests/Models/Cache/Login.php +++ b/tests/Doctrine/Tests/Models/Cache/Login.php @@ -8,8 +8,6 @@ */ class Login { - const CLASSNAME = __CLASS__; - /** * @Id * @GeneratedValue diff --git a/tests/Doctrine/Tests/Models/Cache/Person.php b/tests/Doctrine/Tests/Models/Cache/Person.php index 9cbe00c57d8..01ab416aac4 100644 --- a/tests/Doctrine/Tests/Models/Cache/Person.php +++ b/tests/Doctrine/Tests/Models/Cache/Person.php @@ -9,8 +9,6 @@ */ class Person { - const CLASSNAME = __CLASS__; - /** * @Id * @GeneratedValue diff --git a/tests/Doctrine/Tests/Models/Cache/Restaurant.php b/tests/Doctrine/Tests/Models/Cache/Restaurant.php index 00d3ac06183..c4bf94cbc7d 100644 --- a/tests/Doctrine/Tests/Models/Cache/Restaurant.php +++ b/tests/Doctrine/Tests/Models/Cache/Restaurant.php @@ -7,5 +7,4 @@ */ class Restaurant extends Attraction { - const CLASSNAME = __CLASS__; -} \ No newline at end of file +} diff --git a/tests/Doctrine/Tests/Models/Cache/State.php b/tests/Doctrine/Tests/Models/Cache/State.php index 0d37e4d8faa..77dd0122c13 100644 --- a/tests/Doctrine/Tests/Models/Cache/State.php +++ b/tests/Doctrine/Tests/Models/Cache/State.php @@ -11,8 +11,6 @@ */ class State { - const CLASSNAME = __CLASS__; - /** * @Id * @GeneratedValue @@ -89,4 +87,4 @@ public function addCity(City $city) { $this->cities[] = $city; } -} \ No newline at end of file +} diff --git a/tests/Doctrine/Tests/Models/Cache/Token.php b/tests/Doctrine/Tests/Models/Cache/Token.php index f6c712e3624..bcfbb1b9121 100644 --- a/tests/Doctrine/Tests/Models/Cache/Token.php +++ b/tests/Doctrine/Tests/Models/Cache/Token.php @@ -10,8 +10,6 @@ */ class Token { - const CLASSNAME = __CLASS__; - /** * @Id * @Column(type="string") @@ -36,7 +34,7 @@ class Token /** * @ManyToOne(targetEntity="Action", cascade={"persist", "remove"}, inversedBy="tokens") - * @JoinColumn(name="action_id", referencedColumnName="id") + * @JoinColumn(name="action_name", referencedColumnName="name") * @var array */ public $action; @@ -44,8 +42,8 @@ class Token /** * @ManyToOne(targetEntity="ComplexAction", cascade={"persist", "remove"}, inversedBy="tokens") * @JoinColumns({ - * @JoinColumn(name="complex_action1_id", referencedColumnName="action1_id"), - * @JoinColumn(name="complex_action2_id", referencedColumnName="action2_id") + * @JoinColumn(name="complex_action1_name", referencedColumnName="action1_name"), + * @JoinColumn(name="complex_action2_name", referencedColumnName="action2_name") * }) * @var ComplexAction */ diff --git a/tests/Doctrine/Tests/Models/Cache/Travel.php b/tests/Doctrine/Tests/Models/Cache/Travel.php index 75e3275a489..1e0240066a5 100644 --- a/tests/Doctrine/Tests/Models/Cache/Travel.php +++ b/tests/Doctrine/Tests/Models/Cache/Travel.php @@ -11,8 +11,6 @@ */ class Travel { - const CLASSNAME = __CLASS__; - /** * @Id * @GeneratedValue @@ -109,4 +107,4 @@ public function getCreatedAt() { return $this->createdAt; } -} \ No newline at end of file +} diff --git a/tests/Doctrine/Tests/Models/Cache/Traveler.php b/tests/Doctrine/Tests/Models/Cache/Traveler.php index 3f720b46595..c8b68565b99 100644 --- a/tests/Doctrine/Tests/Models/Cache/Traveler.php +++ b/tests/Doctrine/Tests/Models/Cache/Traveler.php @@ -11,8 +11,6 @@ */ class Traveler { - const CLASSNAME = __CLASS__; - /** * @Id * @GeneratedValue diff --git a/tests/Doctrine/Tests/Models/Cache/TravelerProfile.php b/tests/Doctrine/Tests/Models/Cache/TravelerProfile.php index d4bea245714..03b9c7d3d9e 100644 --- a/tests/Doctrine/Tests/Models/Cache/TravelerProfile.php +++ b/tests/Doctrine/Tests/Models/Cache/TravelerProfile.php @@ -9,8 +9,6 @@ */ class TravelerProfile { - const CLASSNAME = __CLASS__; - /** * @Id * @GeneratedValue @@ -63,4 +61,4 @@ public function setInfo(TravelerProfileInfo $info) { $this->info = $info; } -} \ No newline at end of file +} diff --git a/tests/Doctrine/Tests/Models/Cache/TravelerProfileInfo.php b/tests/Doctrine/Tests/Models/Cache/TravelerProfileInfo.php index b7a23bea002..154ce9600dd 100644 --- a/tests/Doctrine/Tests/Models/Cache/TravelerProfileInfo.php +++ b/tests/Doctrine/Tests/Models/Cache/TravelerProfileInfo.php @@ -9,8 +9,6 @@ */ class TravelerProfileInfo { - const CLASSNAME = __CLASS__; - /** * @Id * @GeneratedValue @@ -65,4 +63,4 @@ public function setProfile(TravelerProfile $profile) { $this->profile = $profile; } -} \ No newline at end of file +} diff --git a/tests/Doctrine/Tests/Models/Company/CompanyContract.php b/tests/Doctrine/Tests/Models/Company/CompanyContract.php index 1390982740e..15e691ba087 100644 --- a/tests/Doctrine/Tests/Models/Company/CompanyContract.php +++ b/tests/Doctrine/Tests/Models/Company/CompanyContract.php @@ -134,28 +134,36 @@ static public function loadMetadata(\Doctrine\ORM\Mapping\ClassMetadataInfo $met { $metadata->setInheritanceType(\Doctrine\ORM\Mapping\ClassMetadata::INHERITANCE_TYPE_JOINED); $metadata->setTableName( 'company_contracts'); - $metadata->setDiscriminatorColumn(array( + $metadata->setDiscriminatorColumn( + [ 'name' => 'discr', 'type' => 'string', - )); + ] + ); - $metadata->mapField(array( + $metadata->mapField( + [ 'id' => true, 'name' => 'id', 'fieldName' => 'id', - )); + ] + ); - $metadata->mapField(array( + $metadata->mapField( + [ 'type' => 'boolean', 'name' => 'completed', 'fieldName' => 'completed', - )); + ] + ); - $metadata->setDiscriminatorMap(array( + $metadata->setDiscriminatorMap( + [ "fix" => "CompanyFixContract", "flexible" => "CompanyFlexContract", "flexultra" => "CompanyFlexUltraContract" - )); + ] + ); $metadata->addEntityListener(\Doctrine\ORM\Events::postPersist, 'CompanyContractListener', 'postPersistHandler'); $metadata->addEntityListener(\Doctrine\ORM\Events::prePersist, 'CompanyContractListener', 'prePersistHandler'); diff --git a/tests/Doctrine/Tests/Models/Company/CompanyContractListener.php b/tests/Doctrine/Tests/Models/Company/CompanyContractListener.php index 61c1d4719f2..23714f32983 100644 --- a/tests/Doctrine/Tests/Models/Company/CompanyContractListener.php +++ b/tests/Doctrine/Tests/Models/Company/CompanyContractListener.php @@ -6,17 +6,17 @@ class CompanyContractListener { public $postPersistCalls; public $prePersistCalls; - + public $postUpdateCalls; public $preUpdateCalls; - + public $postRemoveCalls; public $preRemoveCalls; public $preFlushCalls; - + public $postLoadCalls; - + /** * @PostPersist */ @@ -80,5 +80,4 @@ public function postLoadHandler(CompanyContract $contract) { $this->postLoadCalls[] = func_get_args(); } - } diff --git a/tests/Doctrine/Tests/Models/Company/CompanyFixContract.php b/tests/Doctrine/Tests/Models/Company/CompanyFixContract.php index 87f3ce9529a..8fe94e2584d 100644 --- a/tests/Doctrine/Tests/Models/Company/CompanyFixContract.php +++ b/tests/Doctrine/Tests/Models/Company/CompanyFixContract.php @@ -30,10 +30,12 @@ public function setFixPrice($fixPrice) static public function loadMetadata(\Doctrine\ORM\Mapping\ClassMetadataInfo $metadata) { - $metadata->mapField(array( + $metadata->mapField( + [ 'type' => 'integer', 'name' => 'fixPrice', 'fieldName' => 'fixPrice', - )); + ] + ); } -} \ No newline at end of file +} diff --git a/tests/Doctrine/Tests/Models/Company/CompanyFlexContract.php b/tests/Doctrine/Tests/Models/Company/CompanyFlexContract.php index 86e6b330cef..978e8d5e6cd 100644 --- a/tests/Doctrine/Tests/Models/Company/CompanyFlexContract.php +++ b/tests/Doctrine/Tests/Models/Company/CompanyFlexContract.php @@ -110,16 +110,20 @@ public function removeManager(CompanyManager $manager) static public function loadMetadata(\Doctrine\ORM\Mapping\ClassMetadataInfo $metadata) { - $metadata->mapField(array( + $metadata->mapField( + [ 'type' => 'integer', 'name' => 'hoursWorked', 'fieldName' => 'hoursWorked', - )); + ] + ); - $metadata->mapField(array( + $metadata->mapField( + [ 'type' => 'integer', 'name' => 'pricePerHour', 'fieldName' => 'pricePerHour', - )); + ] + ); } } diff --git a/tests/Doctrine/Tests/Models/Company/CompanyFlexUltraContract.php b/tests/Doctrine/Tests/Models/Company/CompanyFlexUltraContract.php index 85126bd0edd..47313d032e7 100644 --- a/tests/Doctrine/Tests/Models/Company/CompanyFlexUltraContract.php +++ b/tests/Doctrine/Tests/Models/Company/CompanyFlexUltraContract.php @@ -31,11 +31,13 @@ public function setMaxPrice($maxPrice) static public function loadMetadata(\Doctrine\ORM\Mapping\ClassMetadataInfo $metadata) { - $metadata->mapField(array( + $metadata->mapField( + [ 'type' => 'integer', 'name' => 'maxPrice', 'fieldName' => 'maxPrice', - )); + ] + ); $metadata->addEntityListener(\Doctrine\ORM\Events::postPersist, 'CompanyContractListener', 'postPersistHandler'); $metadata->addEntityListener(\Doctrine\ORM\Events::prePersist, 'CompanyContractListener', 'prePersistHandler'); @@ -47,8 +49,8 @@ static public function loadMetadata(\Doctrine\ORM\Mapping\ClassMetadataInfo $met $metadata->addEntityListener(\Doctrine\ORM\Events::preFlush, 'CompanyContractListener', 'preFlushHandler'); $metadata->addEntityListener(\Doctrine\ORM\Events::postLoad, 'CompanyContractListener', 'postLoadHandler'); - + $metadata->addEntityListener(\Doctrine\ORM\Events::prePersist, 'CompanyFlexUltraContractListener', 'prePersistHandler1'); $metadata->addEntityListener(\Doctrine\ORM\Events::prePersist, 'CompanyFlexUltraContractListener', 'prePersistHandler2'); } -} \ No newline at end of file +} diff --git a/tests/Doctrine/Tests/Models/Company/CompanyPerson.php b/tests/Doctrine/Tests/Models/Company/CompanyPerson.php index 4636fa4e30a..ca80c953dcb 100644 --- a/tests/Doctrine/Tests/Models/Company/CompanyPerson.php +++ b/tests/Doctrine/Tests/Models/Company/CompanyPerson.php @@ -120,41 +120,50 @@ public function setSpouse(CompanyPerson $spouse) { public static function loadMetadata(\Doctrine\ORM\Mapping\ClassMetadataInfo $metadata) { - $metadata->setPrimaryTable(array( + $metadata->setPrimaryTable( + [ 'name' => 'company_person', - )); + ] + ); - $metadata->addNamedNativeQuery(array ( + $metadata->addNamedNativeQuery( + [ 'name' => 'fetchAllWithResultClass', 'query' => 'SELECT id, name, discr FROM company_persons ORDER BY name', - 'resultClass' => 'Doctrine\\Tests\\Models\\Company\\CompanyPerson', - )); + 'resultClass' => CompanyPerson::class, + ] + ); - $metadata->addNamedNativeQuery(array ( + $metadata->addNamedNativeQuery( + [ 'name' => 'fetchAllWithSqlResultSetMapping', 'query' => 'SELECT id, name, discr AS discriminator FROM company_persons ORDER BY name', 'resultSetMapping' => 'mappingFetchAll', - )); + ] + ); - $metadata->addSqlResultSetMapping(array ( + $metadata->addSqlResultSetMapping( + [ 'name' => 'mappingFetchAll', - 'columns' => array(), - 'entities' => array ( array ( - 'fields' => array ( - array ( + 'columns' => [], + 'entities' => [ + [ + 'fields' => [ + [ 'name' => 'id', 'column' => 'id', - ), - array ( + ], + [ 'name' => 'name', 'column' => 'name', - ), - ), - 'entityClass' => 'Doctrine\Tests\Models\Company\CompanyPerson', + ], + ], + 'entityClass' => CompanyPerson::class, 'discriminatorColumn' => 'discriminator', - ), - ), - )); + ], + ], + ] + ); } } diff --git a/tests/Doctrine/Tests/Models/CompositeKeyInheritance/JoinedDerivedChildClass.php b/tests/Doctrine/Tests/Models/CompositeKeyInheritance/JoinedDerivedChildClass.php new file mode 100644 index 00000000000..8b48361992b --- /dev/null +++ b/tests/Doctrine/Tests/Models/CompositeKeyInheritance/JoinedDerivedChildClass.php @@ -0,0 +1,22 @@ +. - */ namespace Doctrine\Tests\Models\CustomType; @@ -27,8 +10,6 @@ */ class CustomIdObjectTypeChild { - const CLASSNAME = __CLASS__; - /** * @Id @Column(type="CustomIdObject") * diff --git a/tests/Doctrine/Tests/Models/CustomType/CustomIdObjectTypeParent.php b/tests/Doctrine/Tests/Models/CustomType/CustomIdObjectTypeParent.php index 3045c647bbf..21ce535b8a8 100644 --- a/tests/Doctrine/Tests/Models/CustomType/CustomIdObjectTypeParent.php +++ b/tests/Doctrine/Tests/Models/CustomType/CustomIdObjectTypeParent.php @@ -1,21 +1,4 @@ . - */ namespace Doctrine\Tests\Models\CustomType; @@ -28,8 +11,6 @@ */ class CustomIdObjectTypeParent { - const CLASSNAME = __CLASS__; - /** * @Id @Column(type="CustomIdObject") * diff --git a/tests/Doctrine/Tests/Models/DDC1476/DDC1476EntityWithDefaultFieldType.php b/tests/Doctrine/Tests/Models/DDC1476/DDC1476EntityWithDefaultFieldType.php index 58afe8128c5..b543b0fe589 100644 --- a/tests/Doctrine/Tests/Models/DDC1476/DDC1476EntityWithDefaultFieldType.php +++ b/tests/Doctrine/Tests/Models/DDC1476/DDC1476EntityWithDefaultFieldType.php @@ -1,23 +1,5 @@ . - */ - namespace Doctrine\Tests\Models\DDC1476; /** @@ -62,15 +44,19 @@ public function setName($name) public static function loadMetadata(\Doctrine\ORM\Mapping\ClassMetadataInfo $metadata) { - $metadata->mapField(array( + $metadata->mapField( + [ 'id' => true, 'fieldName' => 'id', - )); - $metadata->mapField(array( + ] + ); + $metadata->mapField( + [ 'fieldName' => 'name', - )); + ] + ); $metadata->setIdGeneratorType(\Doctrine\ORM\Mapping\ClassMetadataInfo::GENERATOR_TYPE_NONE); } -} \ No newline at end of file +} diff --git a/tests/Doctrine/Tests/Models/DDC2504/DDC2504ChildClass.php b/tests/Doctrine/Tests/Models/DDC2504/DDC2504ChildClass.php index 08a4605b62f..a43de5bbfe7 100644 --- a/tests/Doctrine/Tests/Models/DDC2504/DDC2504ChildClass.php +++ b/tests/Doctrine/Tests/Models/DDC2504/DDC2504ChildClass.php @@ -7,5 +7,4 @@ */ class DDC2504ChildClass extends DDC2504RootClass { - const CLASSNAME = __CLASS__; } diff --git a/tests/Doctrine/Tests/Models/DDC2504/DDC2504OtherClass.php b/tests/Doctrine/Tests/Models/DDC2504/DDC2504OtherClass.php index a855cdf8aa9..c90ff2a0c4e 100644 --- a/tests/Doctrine/Tests/Models/DDC2504/DDC2504OtherClass.php +++ b/tests/Doctrine/Tests/Models/DDC2504/DDC2504OtherClass.php @@ -9,8 +9,6 @@ */ class DDC2504OtherClass { - const CLASSNAME = __CLASS__; - /** * @Column(type="integer") * @Id @GeneratedValue diff --git a/tests/Doctrine/Tests/Models/DDC2825/ExplicitSchemaAndTable.php b/tests/Doctrine/Tests/Models/DDC2825/ExplicitSchemaAndTable.php index 60b5d562501..3b6957653cd 100644 --- a/tests/Doctrine/Tests/Models/DDC2825/ExplicitSchemaAndTable.php +++ b/tests/Doctrine/Tests/Models/DDC2825/ExplicitSchemaAndTable.php @@ -5,8 +5,6 @@ /** @Entity @Table(name="explicit_table", schema="explicit_schema") */ class ExplicitSchemaAndTable { - const CLASSNAME = __CLASS__; - /** @Id @Column(type="integer") @GeneratedValue(strategy="AUTO") */ public $id; } diff --git a/tests/Doctrine/Tests/Models/DDC2825/SchemaAndTableInTableName.php b/tests/Doctrine/Tests/Models/DDC2825/SchemaAndTableInTableName.php index bd22c2b232e..151e577ec56 100644 --- a/tests/Doctrine/Tests/Models/DDC2825/SchemaAndTableInTableName.php +++ b/tests/Doctrine/Tests/Models/DDC2825/SchemaAndTableInTableName.php @@ -10,8 +10,6 @@ */ class SchemaAndTableInTableName { - const CLASSNAME = __CLASS__; - /** @Id @Column(type="integer") @GeneratedValue(strategy="AUTO") */ public $id; -} \ No newline at end of file +} diff --git a/tests/Doctrine/Tests/Models/DDC3346/DDC3346Article.php b/tests/Doctrine/Tests/Models/DDC3346/DDC3346Article.php index dc8a876c512..8b26c639724 100644 --- a/tests/Doctrine/Tests/Models/DDC3346/DDC3346Article.php +++ b/tests/Doctrine/Tests/Models/DDC3346/DDC3346Article.php @@ -8,8 +8,6 @@ */ class DDC3346Article { - const CLASSNAME = __CLASS__; - /** * @Id * @Column(type="integer") diff --git a/tests/Doctrine/Tests/Models/DDC3346/DDC3346Author.php b/tests/Doctrine/Tests/Models/DDC3346/DDC3346Author.php index 5229ee280a2..4611bbdd758 100644 --- a/tests/Doctrine/Tests/Models/DDC3346/DDC3346Author.php +++ b/tests/Doctrine/Tests/Models/DDC3346/DDC3346Author.php @@ -8,8 +8,6 @@ */ class DDC3346Author { - const CLASSNAME = __CLASS__; - /** * @Id @Column(type="integer") * @GeneratedValue @@ -24,5 +22,5 @@ class DDC3346Author /** * @OneToMany(targetEntity="DDC3346Article", mappedBy="user", fetch="EAGER", cascade={"detach"}) */ - public $articles = array(); + public $articles = []; } diff --git a/tests/Doctrine/Tests/Models/DDC3579/DDC3579Admin.php b/tests/Doctrine/Tests/Models/DDC3579/DDC3579Admin.php index effedc3c4b1..85383994cb0 100644 --- a/tests/Doctrine/Tests/Models/DDC3579/DDC3579Admin.php +++ b/tests/Doctrine/Tests/Models/DDC3579/DDC3579Admin.php @@ -15,8 +15,9 @@ class DDC3579Admin extends DDC3579User { public static function loadMetadata($metadata) { - $metadata->setAssociationOverride('groups', array( + $metadata->setAssociationOverride('groups', [ 'inversedBy' => 'admins' - )); + ] + ); } } diff --git a/tests/Doctrine/Tests/Models/DDC3579/DDC3579User.php b/tests/Doctrine/Tests/Models/DDC3579/DDC3579User.php index 7a7ea5de657..8b6193cdc3f 100644 --- a/tests/Doctrine/Tests/Models/DDC3579/DDC3579User.php +++ b/tests/Doctrine/Tests/Models/DDC3579/DDC3579User.php @@ -81,27 +81,33 @@ public function getGroups() public static function loadMetadata($metadata) { - $metadata->mapField(array( + $metadata->mapField( + [ 'id' => true, 'fieldName' => 'id', 'type' => 'integer', 'columnName' => 'user_id', 'length' => 150, - )); + ] + ); - $metadata->mapField(array( + $metadata->mapField( + [ 'fieldName' => 'name', 'type' => 'string', 'columnName'=> 'user_name', 'nullable' => true, 'unique' => false, 'length' => 250, - )); + ] + ); - $metadata->mapManyToMany(array( + $metadata->mapManyToMany( + [ 'fieldName' => 'groups', 'targetEntity' => 'DDC3579Group' - )); + ] + ); $metadata->setIdGeneratorType(\Doctrine\ORM\Mapping\ClassMetadataInfo::GENERATOR_TYPE_AUTO); } diff --git a/tests/Doctrine/Tests/Models/DDC3597/DDC3597Image.php b/tests/Doctrine/Tests/Models/DDC3597/DDC3597Image.php index 2254b4243a9..5d1acfeb6ad 100644 --- a/tests/Doctrine/Tests/Models/DDC3597/DDC3597Image.php +++ b/tests/Doctrine/Tests/Models/DDC3597/DDC3597Image.php @@ -12,8 +12,6 @@ */ class DDC3597Image extends DDC3597Media { - const CLASSNAME = __CLASS__; - /** * @var DDC3597Dimension * @Embedded(class = "Doctrine\Tests\Models\DDC3597\Embeddable\DDC3597Dimension", columnPrefix = false) @@ -34,4 +32,4 @@ function __construct($distributionHash) { public function getDimension() { return $this->dimension; } -} \ No newline at end of file +} diff --git a/tests/Doctrine/Tests/Models/DDC3597/DDC3597Media.php b/tests/Doctrine/Tests/Models/DDC3597/DDC3597Media.php index 751f7dac170..c285b3c40e6 100644 --- a/tests/Doctrine/Tests/Models/DDC3597/DDC3597Media.php +++ b/tests/Doctrine/Tests/Models/DDC3597/DDC3597Media.php @@ -4,14 +4,12 @@ /** * Description of Media - * + * * @author Volker von Hoesslin * @Entity */ abstract class DDC3597Media extends DDC3597Root { - const CLASSNAME = __CLASS__; - /** * @var string * @@ -73,4 +71,4 @@ public function setFormat($format) { -} \ No newline at end of file +} diff --git a/tests/Doctrine/Tests/Models/DDC3597/DDC3597Root.php b/tests/Doctrine/Tests/Models/DDC3597/DDC3597Root.php index d7f86dfba6a..3bdb67f13d7 100644 --- a/tests/Doctrine/Tests/Models/DDC3597/DDC3597Root.php +++ b/tests/Doctrine/Tests/Models/DDC3597/DDC3597Root.php @@ -15,8 +15,6 @@ */ abstract class DDC3597Root { - const CLASSNAME = __CLASS__; - /** * @var int * @@ -77,4 +75,4 @@ public function getCreatedAt() { public function getUpdatedAt() { return $this->updatedAt; } -} \ No newline at end of file +} diff --git a/tests/Doctrine/Tests/Models/DDC3699/DDC3699Child.php b/tests/Doctrine/Tests/Models/DDC3699/DDC3699Child.php index 320f73138eb..dc2ccfddde1 100644 --- a/tests/Doctrine/Tests/Models/DDC3699/DDC3699Child.php +++ b/tests/Doctrine/Tests/Models/DDC3699/DDC3699Child.php @@ -5,8 +5,6 @@ /** @Entity @Table(name="ddc3699_child") */ class DDC3699Child extends DDC3699Parent { - const CLASSNAME = __CLASS__; - /** @Id @Column(type="integer") */ public $id; @@ -18,4 +16,4 @@ class DDC3699Child extends DDC3699Parent /** @OneToMany(targetEntity="DDC3699RelationMany", mappedBy="child") */ public $relations; -} \ No newline at end of file +} diff --git a/tests/Doctrine/Tests/Models/DDC3699/DDC3699Parent.php b/tests/Doctrine/Tests/Models/DDC3699/DDC3699Parent.php index 09cfedaefdf..2e5e7ab363e 100644 --- a/tests/Doctrine/Tests/Models/DDC3699/DDC3699Parent.php +++ b/tests/Doctrine/Tests/Models/DDC3699/DDC3699Parent.php @@ -5,8 +5,6 @@ /** @MappedSuperclass */ abstract class DDC3699Parent { - const CLASSNAME = __CLASS__; - /** @Column(type="string") */ public $parentField; -} \ No newline at end of file +} diff --git a/tests/Doctrine/Tests/Models/DDC3699/DDC3699RelationMany.php b/tests/Doctrine/Tests/Models/DDC3699/DDC3699RelationMany.php index 3e0c06a67b2..1b907bb9863 100644 --- a/tests/Doctrine/Tests/Models/DDC3699/DDC3699RelationMany.php +++ b/tests/Doctrine/Tests/Models/DDC3699/DDC3699RelationMany.php @@ -8,8 +8,6 @@ */ class DDC3699RelationMany { - const CLASSNAME = __CLASS__; - /** @Id @Column(type="integer") */ public $id; diff --git a/tests/Doctrine/Tests/Models/DDC3699/DDC3699RelationOne.php b/tests/Doctrine/Tests/Models/DDC3699/DDC3699RelationOne.php index c63558d351c..22807aafc82 100644 --- a/tests/Doctrine/Tests/Models/DDC3699/DDC3699RelationOne.php +++ b/tests/Doctrine/Tests/Models/DDC3699/DDC3699RelationOne.php @@ -8,8 +8,6 @@ */ class DDC3699RelationOne { - const CLASSNAME = __CLASS__; - /** @Id @Column(type="integer") */ public $id; diff --git a/tests/Doctrine/Tests/Models/DDC3711/DDC3711EntityA.php b/tests/Doctrine/Tests/Models/DDC3711/DDC3711EntityA.php index 3146969ed57..ecbfd52773c 100644 --- a/tests/Doctrine/Tests/Models/DDC3711/DDC3711EntityA.php +++ b/tests/Doctrine/Tests/Models/DDC3711/DDC3711EntityA.php @@ -1,12 +1,13 @@ - */ + namespace Doctrine\Tests\Models\DDC3711; use Doctrine\Common\Collections\ArrayCollection; +/** + * @author Marc Pantel + */ class DDC3711EntityA { /** @@ -75,4 +76,4 @@ public function addEntityB($entityB) return $this; } -} \ No newline at end of file +} diff --git a/tests/Doctrine/Tests/Models/DDC3711/DDC3711EntityB.php b/tests/Doctrine/Tests/Models/DDC3711/DDC3711EntityB.php index ff589e0923a..48c4fd8602d 100644 --- a/tests/Doctrine/Tests/Models/DDC3711/DDC3711EntityB.php +++ b/tests/Doctrine/Tests/Models/DDC3711/DDC3711EntityB.php @@ -1,12 +1,13 @@ - */ + namespace Doctrine\Tests\Models\DDC3711; use Doctrine\Common\Collections\ArrayCollection; +/** + * @author Marc Pantel + */ class DDC3711EntityB { /** @@ -72,4 +73,4 @@ public function addEntityA($entityA) $this->entityA[] = $entityA; } -} \ No newline at end of file +} diff --git a/tests/Doctrine/Tests/Models/DDC5934/DDC5934BaseContract.php b/tests/Doctrine/Tests/Models/DDC5934/DDC5934BaseContract.php new file mode 100644 index 00000000000..84970c270b3 --- /dev/null +++ b/tests/Doctrine/Tests/Models/DDC5934/DDC5934BaseContract.php @@ -0,0 +1,53 @@ +members = new ArrayCollection(); + } + + public static function loadMetadata(ClassMetadata $metadata) + { + $metadata->mapField([ + 'id' => true, + 'fieldName' => 'id', + 'type' => 'integer', + 'columnName' => 'id', + ]); + + $metadata->mapManyToMany([ + 'fieldName' => 'members', + 'targetEntity' => 'DDC5934Member', + ]); + + $metadata->setIdGeneratorType(ClassMetadata::GENERATOR_TYPE_AUTO); + } +} diff --git a/tests/Doctrine/Tests/Models/DDC5934/DDC5934Contract.php b/tests/Doctrine/Tests/Models/DDC5934/DDC5934Contract.php new file mode 100644 index 00000000000..e26c4d66501 --- /dev/null +++ b/tests/Doctrine/Tests/Models/DDC5934/DDC5934Contract.php @@ -0,0 +1,24 @@ +setAssociationOverride('members', [ + 'fetch' => ClassMetadata::FETCH_EXTRA_LAZY, + ]); + } +} diff --git a/tests/Doctrine/Tests/Models/DDC5934/DDC5934Member.php b/tests/Doctrine/Tests/Models/DDC5934/DDC5934Member.php new file mode 100644 index 00000000000..ff85d6c6613 --- /dev/null +++ b/tests/Doctrine/Tests/Models/DDC5934/DDC5934Member.php @@ -0,0 +1,24 @@ +contracts = new ArrayCollection(); + } +} diff --git a/tests/Doctrine/Tests/Models/DDC6412/DDC6412File.php b/tests/Doctrine/Tests/Models/DDC6412/DDC6412File.php new file mode 100644 index 00000000000..64551cdf4fb --- /dev/null +++ b/tests/Doctrine/Tests/Models/DDC6412/DDC6412File.php @@ -0,0 +1,21 @@ +. - */ - namespace Doctrine\Tests\Models\DDC753; use Doctrine\ORM\EntityRepository; @@ -33,4 +15,4 @@ public function isCustomRepository() return true; } -} \ No newline at end of file +} diff --git a/tests/Doctrine/Tests/Models/DDC753/DDC753DefaultRepository.php b/tests/Doctrine/Tests/Models/DDC753/DDC753DefaultRepository.php index 5be9aa522e6..1a3e071fa7b 100644 --- a/tests/Doctrine/Tests/Models/DDC753/DDC753DefaultRepository.php +++ b/tests/Doctrine/Tests/Models/DDC753/DDC753DefaultRepository.php @@ -1,23 +1,5 @@ . - */ - namespace Doctrine\Tests\Models\DDC753; use Doctrine\ORM\EntityRepository; @@ -32,4 +14,4 @@ public function isDefaultRepository() return true; } -} \ No newline at end of file +} diff --git a/tests/Doctrine/Tests/Models/DDC753/DDC753EntityWithCustomRepository.php b/tests/Doctrine/Tests/Models/DDC753/DDC753EntityWithCustomRepository.php index 7b92e66ac73..7a9ce8d835b 100644 --- a/tests/Doctrine/Tests/Models/DDC753/DDC753EntityWithCustomRepository.php +++ b/tests/Doctrine/Tests/Models/DDC753/DDC753EntityWithCustomRepository.php @@ -1,23 +1,5 @@ . - */ - namespace Doctrine\Tests\Models\DDC753; /** @@ -36,4 +18,4 @@ class DDC753EntityWithCustomRepository /** @column(type="string") */ protected $name; -} \ No newline at end of file +} diff --git a/tests/Doctrine/Tests/Models/DDC753/DDC753EntityWithDefaultCustomRepository.php b/tests/Doctrine/Tests/Models/DDC753/DDC753EntityWithDefaultCustomRepository.php index 8ca2a2c9467..6f448755fde 100644 --- a/tests/Doctrine/Tests/Models/DDC753/DDC753EntityWithDefaultCustomRepository.php +++ b/tests/Doctrine/Tests/Models/DDC753/DDC753EntityWithDefaultCustomRepository.php @@ -1,23 +1,5 @@ . - */ - namespace Doctrine\Tests\Models\DDC753; /** @@ -36,4 +18,4 @@ class DDC753EntityWithDefaultCustomRepository /** @column(type="string") */ protected $name; -} \ No newline at end of file +} diff --git a/tests/Doctrine/Tests/Models/DDC753/DDC753EntityWithInvalidRepository.php b/tests/Doctrine/Tests/Models/DDC753/DDC753EntityWithInvalidRepository.php index d12660cf4a2..e480e912c4d 100644 --- a/tests/Doctrine/Tests/Models/DDC753/DDC753EntityWithInvalidRepository.php +++ b/tests/Doctrine/Tests/Models/DDC753/DDC753EntityWithInvalidRepository.php @@ -1,23 +1,5 @@ . - */ - namespace Doctrine\Tests\Models\DDC753; /** @@ -36,4 +18,4 @@ class DDC753EntityWithInvalidRepository /** @column(type="string") */ protected $name; -} \ No newline at end of file +} diff --git a/tests/Doctrine/Tests/Models/DDC753/DDC753InvalidRepository.php b/tests/Doctrine/Tests/Models/DDC753/DDC753InvalidRepository.php index decc07078a4..4e8c7bad7bb 100644 --- a/tests/Doctrine/Tests/Models/DDC753/DDC753InvalidRepository.php +++ b/tests/Doctrine/Tests/Models/DDC753/DDC753InvalidRepository.php @@ -1,26 +1,8 @@ . - */ - namespace Doctrine\Tests\Models\DDC753; class DDC753InvalidRepository { -} \ No newline at end of file +} diff --git a/tests/Doctrine/Tests/Models/DDC869/DDC869ChequePayment.php b/tests/Doctrine/Tests/Models/DDC869/DDC869ChequePayment.php index a9f548ffca6..4690e068a4c 100644 --- a/tests/Doctrine/Tests/Models/DDC869/DDC869ChequePayment.php +++ b/tests/Doctrine/Tests/Models/DDC869/DDC869ChequePayment.php @@ -1,23 +1,5 @@ . - */ - namespace Doctrine\Tests\Models\DDC869; /** @@ -31,10 +13,12 @@ class DDC869ChequePayment extends DDC869Payment public static function loadMetadata(\Doctrine\ORM\Mapping\ClassMetadataInfo $metadata) { - $metadata->mapField(array( + $metadata->mapField( + [ 'fieldName' => 'serialNumber', 'type' => 'string', - )); + ] + ); } -} \ No newline at end of file +} diff --git a/tests/Doctrine/Tests/Models/DDC869/DDC869CreditCardPayment.php b/tests/Doctrine/Tests/Models/DDC869/DDC869CreditCardPayment.php index cd637b3c07d..6f314e31889 100644 --- a/tests/Doctrine/Tests/Models/DDC869/DDC869CreditCardPayment.php +++ b/tests/Doctrine/Tests/Models/DDC869/DDC869CreditCardPayment.php @@ -1,23 +1,5 @@ . - */ - namespace Doctrine\Tests\Models\DDC869; /** @@ -31,10 +13,12 @@ class DDC869CreditCardPayment extends DDC869Payment public static function loadMetadata(\Doctrine\ORM\Mapping\ClassMetadataInfo $metadata) { - $metadata->mapField(array( + $metadata->mapField( + [ 'fieldName' => 'creditCardNumber', 'type' => 'string', - )); + ] + ); } -} \ No newline at end of file +} diff --git a/tests/Doctrine/Tests/Models/DDC869/DDC869Payment.php b/tests/Doctrine/Tests/Models/DDC869/DDC869Payment.php index 01e7fbefde4..992c53ae27a 100644 --- a/tests/Doctrine/Tests/Models/DDC869/DDC869Payment.php +++ b/tests/Doctrine/Tests/Models/DDC869/DDC869Payment.php @@ -1,23 +1,5 @@ . - */ - namespace Doctrine\Tests\Models\DDC869; /** @@ -39,19 +21,23 @@ class DDC869Payment public static function loadMetadata(\Doctrine\ORM\Mapping\ClassMetadataInfo $metadata) { - $metadata->mapField(array( + $metadata->mapField( + [ 'id' => true, 'fieldName' => 'id', 'type' => 'integer', 'columnName' => 'id', - )); - $metadata->mapField(array( + ] + ); + $metadata->mapField( + [ 'fieldName' => 'value', 'type' => 'float', - )); + ] + ); $metadata->isMappedSuperclass = true; - $metadata->setCustomRepositoryClass("Doctrine\Tests\Models\DDC869\DDC869PaymentRepository"); + $metadata->setCustomRepositoryClass(DDC869PaymentRepository::class); $metadata->setIdGeneratorType(\Doctrine\ORM\Mapping\ClassMetadataInfo::GENERATOR_TYPE_AUTO); } -} \ No newline at end of file +} diff --git a/tests/Doctrine/Tests/Models/DDC869/DDC869PaymentRepository.php b/tests/Doctrine/Tests/Models/DDC869/DDC869PaymentRepository.php index f950df0e064..3c11b154bce 100644 --- a/tests/Doctrine/Tests/Models/DDC869/DDC869PaymentRepository.php +++ b/tests/Doctrine/Tests/Models/DDC869/DDC869PaymentRepository.php @@ -1,23 +1,5 @@ . - */ - namespace Doctrine\Tests\Models\DDC869; use Doctrine\ORM\EntityRepository; @@ -34,4 +16,4 @@ public function isTrue() { return true; } -} \ No newline at end of file +} diff --git a/tests/Doctrine/Tests/Models/DDC889/DDC889Class.php b/tests/Doctrine/Tests/Models/DDC889/DDC889Class.php index 7520568b038..089261a83ba 100644 --- a/tests/Doctrine/Tests/Models/DDC889/DDC889Class.php +++ b/tests/Doctrine/Tests/Models/DDC889/DDC889Class.php @@ -1,23 +1,5 @@ . - */ - namespace Doctrine\Tests\Models\DDC889; class DDC889Class extends DDC889SuperClass @@ -33,14 +15,16 @@ class DDC889Class extends DDC889SuperClass public static function loadMetadata(\Doctrine\ORM\Mapping\ClassMetadataInfo $metadata) { - $metadata->mapField(array( + $metadata->mapField( + [ 'id' => true, 'fieldName' => 'id', 'type' => 'integer', 'columnName' => 'id', - )); + ] + ); $metadata->setIdGeneratorType(\Doctrine\ORM\Mapping\ClassMetadataInfo::GENERATOR_TYPE_AUTO); } -} \ No newline at end of file +} diff --git a/tests/Doctrine/Tests/Models/DDC889/DDC889Entity.php b/tests/Doctrine/Tests/Models/DDC889/DDC889Entity.php index 59cd21a61eb..43884435fa7 100644 --- a/tests/Doctrine/Tests/Models/DDC889/DDC889Entity.php +++ b/tests/Doctrine/Tests/Models/DDC889/DDC889Entity.php @@ -1,23 +1,5 @@ . - */ - namespace Doctrine\Tests\Models\DDC889; /** @@ -30,4 +12,4 @@ public static function loadMetadata(\Doctrine\ORM\Mapping\ClassMetadataInfo $met { } -} \ No newline at end of file +} diff --git a/tests/Doctrine/Tests/Models/DDC889/DDC889SuperClass.php b/tests/Doctrine/Tests/Models/DDC889/DDC889SuperClass.php index 7cffe488bc9..8408a9ad74b 100644 --- a/tests/Doctrine/Tests/Models/DDC889/DDC889SuperClass.php +++ b/tests/Doctrine/Tests/Models/DDC889/DDC889SuperClass.php @@ -1,23 +1,5 @@ . - */ - namespace Doctrine\Tests\Models\DDC889; /** @@ -31,11 +13,13 @@ class DDC889SuperClass public static function loadMetadata(\Doctrine\ORM\Mapping\ClassMetadataInfo $metadata) { - $metadata->mapField(array( + $metadata->mapField( + [ 'fieldName' => 'name', - )); + ] + ); $metadata->isMappedSuperclass = true; $metadata->setIdGeneratorType(\Doctrine\ORM\Mapping\ClassMetadataInfo::GENERATOR_TYPE_NONE); } -} \ No newline at end of file +} diff --git a/tests/Doctrine/Tests/Models/DDC964/DDC964Admin.php b/tests/Doctrine/Tests/Models/DDC964/DDC964Admin.php index 110326b2c93..29ea4dd4e14 100644 --- a/tests/Doctrine/Tests/Models/DDC964/DDC964Admin.php +++ b/tests/Doctrine/Tests/Models/DDC964/DDC964Admin.php @@ -23,23 +23,31 @@ class DDC964Admin extends DDC964User { public static function loadMetadata(\Doctrine\ORM\Mapping\ClassMetadataInfo $metadata) { - $metadata->setAssociationOverride('address',array( - 'joinColumns'=>array(array( + $metadata->setAssociationOverride('address', + [ + 'joinColumns'=> [ + [ 'name' => 'adminaddress_id', 'referencedColumnName' => 'id', - )) - )); + ] + ] + ] + ); - $metadata->setAssociationOverride('groups',array( - 'joinTable' => array( + $metadata->setAssociationOverride('groups', + [ + 'joinTable' => [ 'name' => 'ddc964_users_admingroups', - 'joinColumns' => array(array( + 'joinColumns' => [ + [ 'name' => 'adminuser_id', - )), - 'inverseJoinColumns' =>array (array ( + ] + ], + 'inverseJoinColumns' => [[ 'name' => 'admingroup_id', - )) - ) - )); + ]] + ] + ] + ); } -} \ No newline at end of file +} diff --git a/tests/Doctrine/Tests/Models/DDC964/DDC964Guest.php b/tests/Doctrine/Tests/Models/DDC964/DDC964Guest.php index cb64d15fae8..23486b0fd6d 100644 --- a/tests/Doctrine/Tests/Models/DDC964/DDC964Guest.php +++ b/tests/Doctrine/Tests/Models/DDC964/DDC964Guest.php @@ -26,17 +26,20 @@ class DDC964Guest extends DDC964User { public static function loadMetadata(\Doctrine\ORM\Mapping\ClassMetadataInfo $metadata) { - $metadata->setAttributeOverride('id', array( + $metadata->setAttributeOverride('id', [ 'columnName' => 'guest_id', 'type' => 'integer', 'length' => 140, - )); + ] + ); - $metadata->setAttributeOverride('name',array( + $metadata->setAttributeOverride('name', + [ 'columnName' => 'guest_name', 'nullable' => false, 'unique' => true, 'length' => 240, - )); + ] + ); } -} \ No newline at end of file +} diff --git a/tests/Doctrine/Tests/Models/DDC964/DDC964User.php b/tests/Doctrine/Tests/Models/DDC964/DDC964User.php index f1bfdae394d..a9f15c8c948 100644 --- a/tests/Doctrine/Tests/Models/DDC964/DDC964User.php +++ b/tests/Doctrine/Tests/Models/DDC964/DDC964User.php @@ -109,47 +109,59 @@ public function setAddress(DDC964Address $address) public static function loadMetadata(\Doctrine\ORM\Mapping\ClassMetadataInfo $metadata) { - $metadata->mapField(array( + $metadata->mapField( + [ 'id' => true, 'fieldName' => 'id', 'type' => 'integer', 'columnName' => 'user_id', 'length' => 150, - )); - $metadata->mapField(array( + ] + ); + $metadata->mapField( + [ 'fieldName' => 'name', 'type' => 'string', 'columnName'=> 'user_name', 'nullable' => true, 'unique' => false, 'length' => 250, - )); + ] + ); - $metadata->mapManyToOne(array( + $metadata->mapManyToOne( + [ 'fieldName' => 'address', 'targetEntity' => 'DDC964Address', - 'cascade' => array('persist','merge'), - 'joinColumn' => array('name'=>'address_id', 'referencedColumnMame'=>'id'), - )); + 'cascade' => ['persist','merge'], + 'joinColumn' => ['name'=>'address_id', 'referencedColumnMame'=>'id'], + ] + ); - $metadata->mapManyToMany(array( + $metadata->mapManyToMany( + [ 'fieldName' => 'groups', 'targetEntity' => 'DDC964Group', 'inversedBy' => 'users', - 'cascade' => array('persist','merge','detach'), - 'joinTable' => array( + 'cascade' => ['persist','merge','detach'], + 'joinTable' => [ 'name' => 'ddc964_users_groups', - 'joinColumns' => array(array( + 'joinColumns' => [ + [ 'name'=>'user_id', 'referencedColumnName'=>'id', - )), - 'inverseJoinColumns'=>array(array( + ] + ], + 'inverseJoinColumns'=> [ + [ 'name'=>'group_id', 'referencedColumnName'=>'id', - )) - ) - )); + ] + ] + ] + ] + ); $metadata->setIdGeneratorType(\Doctrine\ORM\Mapping\ClassMetadataInfo::GENERATOR_TYPE_AUTO); } -} \ No newline at end of file +} diff --git a/tests/Doctrine/Tests/Models/DirectoryTree/AbstractContentItem.php b/tests/Doctrine/Tests/Models/DirectoryTree/AbstractContentItem.php index d2ba439a072..41798724b20 100644 --- a/tests/Doctrine/Tests/Models/DirectoryTree/AbstractContentItem.php +++ b/tests/Doctrine/Tests/Models/DirectoryTree/AbstractContentItem.php @@ -1,21 +1,4 @@ . - */ namespace Doctrine\Tests\Models\DirectoryTree; @@ -24,8 +7,6 @@ */ abstract class AbstractContentItem { - const CLASSNAME = __CLASS__; - /** * @Id @Column(type="integer") @GeneratedValue */ diff --git a/tests/Doctrine/Tests/Models/DirectoryTree/Directory.php b/tests/Doctrine/Tests/Models/DirectoryTree/Directory.php index f0db778b813..cb3729974bc 100644 --- a/tests/Doctrine/Tests/Models/DirectoryTree/Directory.php +++ b/tests/Doctrine/Tests/Models/DirectoryTree/Directory.php @@ -1,21 +1,4 @@ . - */ namespace Doctrine\Tests\Models\DirectoryTree; diff --git a/tests/Doctrine/Tests/Models/DirectoryTree/File.php b/tests/Doctrine/Tests/Models/DirectoryTree/File.php index 428daad8b5c..f6cbace23ca 100644 --- a/tests/Doctrine/Tests/Models/DirectoryTree/File.php +++ b/tests/Doctrine/Tests/Models/DirectoryTree/File.php @@ -1,21 +1,4 @@ . - */ namespace Doctrine\Tests\Models\DirectoryTree; @@ -25,8 +8,6 @@ */ class File extends AbstractContentItem { - const CLASSNAME = __CLASS__; - /** @Column(type="string") */ protected $extension = "html"; diff --git a/tests/Doctrine/Tests/Models/GH7141/GH7141Article.php b/tests/Doctrine/Tests/Models/GH7141/GH7141Article.php new file mode 100644 index 00000000000..5af97c62ef5 --- /dev/null +++ b/tests/Doctrine/Tests/Models/GH7141/GH7141Article.php @@ -0,0 +1,15 @@ +tags = new ArrayCollection(); + } +} diff --git a/tests/Doctrine/Tests/Models/GH7316/GH7316Article.php b/tests/Doctrine/Tests/Models/GH7316/GH7316Article.php new file mode 100644 index 00000000000..a832cd70d4c --- /dev/null +++ b/tests/Doctrine/Tests/Models/GH7316/GH7316Article.php @@ -0,0 +1,15 @@ +tags = new ArrayCollection(); + } +} diff --git a/tests/Doctrine/Tests/Models/Generic/DateTimeModel.php b/tests/Doctrine/Tests/Models/Generic/DateTimeModel.php index 92ebe5e5deb..7ef61ea278c 100644 --- a/tests/Doctrine/Tests/Models/Generic/DateTimeModel.php +++ b/tests/Doctrine/Tests/Models/Generic/DateTimeModel.php @@ -8,8 +8,6 @@ */ class DateTimeModel { - const CLASSNAME = __CLASS__; - /** * @Id @Column(type="integer") * @GeneratedValue @@ -27,4 +25,4 @@ class DateTimeModel * @Column(name="col_time", type="time", nullable=true) */ public $time; -} \ No newline at end of file +} diff --git a/tests/Doctrine/Tests/Models/GeoNames/Admin1.php b/tests/Doctrine/Tests/Models/GeoNames/Admin1.php index 15a0147edd2..11b9d8e8582 100644 --- a/tests/Doctrine/Tests/Models/GeoNames/Admin1.php +++ b/tests/Doctrine/Tests/Models/GeoNames/Admin1.php @@ -28,7 +28,7 @@ class Admin1 * @OneToMany(targetEntity="Admin1AlternateName", mappedBy="admin1") * @Cache */ - public $names = array(); + public $names = []; /** * @Column(type="string", length=255); diff --git a/tests/Doctrine/Tests/Models/Hydration/EntityWithArrayDefaultArrayValueM2M.php b/tests/Doctrine/Tests/Models/Hydration/EntityWithArrayDefaultArrayValueM2M.php index 8ba57db685a..ff927968eeb 100644 --- a/tests/Doctrine/Tests/Models/Hydration/EntityWithArrayDefaultArrayValueM2M.php +++ b/tests/Doctrine/Tests/Models/Hydration/EntityWithArrayDefaultArrayValueM2M.php @@ -5,8 +5,6 @@ /** @Entity */ class EntityWithArrayDefaultArrayValueM2M { - const CLASSNAME = __CLASS__; - /** @Id @Column(type="integer") @GeneratedValue(strategy="AUTO") */ public $id; diff --git a/tests/Doctrine/Tests/Models/Hydration/SimpleEntity.php b/tests/Doctrine/Tests/Models/Hydration/SimpleEntity.php index dda00eb3b65..7ec75174de1 100644 --- a/tests/Doctrine/Tests/Models/Hydration/SimpleEntity.php +++ b/tests/Doctrine/Tests/Models/Hydration/SimpleEntity.php @@ -5,8 +5,6 @@ /** @Entity */ class SimpleEntity { - const CLASSNAME = __CLASS__; - /** @Id @Column(type="integer") @GeneratedValue(strategy="AUTO") */ public $id; } diff --git a/tests/Doctrine/Tests/Models/Issue5989/Issue5989Employee.php b/tests/Doctrine/Tests/Models/Issue5989/Issue5989Employee.php new file mode 100644 index 00000000000..9f5e248d8c6 --- /dev/null +++ b/tests/Doctrine/Tests/Models/Issue5989/Issue5989Employee.php @@ -0,0 +1,17 @@ +id1 = $id1; + $this->otherParent = $otherParent; + $this->parents = new ArrayCollection(); + } +} diff --git a/tests/Doctrine/Tests/Models/ManyToManyPersister/OtherParentClass.php b/tests/Doctrine/Tests/Models/ManyToManyPersister/OtherParentClass.php new file mode 100644 index 00000000000..04e27e616d2 --- /dev/null +++ b/tests/Doctrine/Tests/Models/ManyToManyPersister/OtherParentClass.php @@ -0,0 +1,23 @@ +id = $id; + } +} diff --git a/tests/Doctrine/Tests/Models/ManyToManyPersister/ParentClass.php b/tests/Doctrine/Tests/Models/ManyToManyPersister/ParentClass.php new file mode 100644 index 00000000000..3007a1013db --- /dev/null +++ b/tests/Doctrine/Tests/Models/ManyToManyPersister/ParentClass.php @@ -0,0 +1,39 @@ +id = $id; + $this->children = new ArrayCollection(); + } +} diff --git a/tests/Doctrine/Tests/Models/MixedToOneIdentity/CompositeToOneKeyState.php b/tests/Doctrine/Tests/Models/MixedToOneIdentity/CompositeToOneKeyState.php index b4b02e158c3..09bab229ef6 100644 --- a/tests/Doctrine/Tests/Models/MixedToOneIdentity/CompositeToOneKeyState.php +++ b/tests/Doctrine/Tests/Models/MixedToOneIdentity/CompositeToOneKeyState.php @@ -5,8 +5,6 @@ /** @Entity */ class CompositeToOneKeyState { - const CLASSNAME = __CLASS__; - /** * @Id * @Column(type="string") @@ -20,4 +18,4 @@ class CompositeToOneKeyState * @JoinColumn(referencedColumnName="country") */ public $country; -} \ No newline at end of file +} diff --git a/tests/Doctrine/Tests/Models/MixedToOneIdentity/Country.php b/tests/Doctrine/Tests/Models/MixedToOneIdentity/Country.php index bbdc237f792..629cde160ec 100644 --- a/tests/Doctrine/Tests/Models/MixedToOneIdentity/Country.php +++ b/tests/Doctrine/Tests/Models/MixedToOneIdentity/Country.php @@ -5,8 +5,6 @@ /** @Entity */ class Country { - const CLASSNAME = __CLASS__; - /** @Id @Column(type="string") @GeneratedValue(strategy="NONE") */ public $country; } diff --git a/tests/Doctrine/Tests/Models/NonPublicSchemaJoins/User.php b/tests/Doctrine/Tests/Models/NonPublicSchemaJoins/User.php index 1c40a5e433c..be80cea33c4 100644 --- a/tests/Doctrine/Tests/Models/NonPublicSchemaJoins/User.php +++ b/tests/Doctrine/Tests/Models/NonPublicSchemaJoins/User.php @@ -10,8 +10,6 @@ */ class User { - const CLASSNAME = __CLASS__; - /** * @Column(type="integer") * @Id diff --git a/tests/Doctrine/Tests/Models/OneToOneInverseSideLoad/InverseSide.php b/tests/Doctrine/Tests/Models/OneToOneInverseSideLoad/InverseSide.php new file mode 100644 index 00000000000..1b7d844b270 --- /dev/null +++ b/tests/Doctrine/Tests/Models/OneToOneInverseSideLoad/InverseSide.php @@ -0,0 +1,26 @@ +user; } -} \ No newline at end of file +} diff --git a/tests/Doctrine/Tests/Models/Quote/City.php b/tests/Doctrine/Tests/Models/Quote/City.php new file mode 100644 index 00000000000..74503ea0858 --- /dev/null +++ b/tests/Doctrine/Tests/Models/Quote/City.php @@ -0,0 +1,27 @@ +name = $name; + } +} diff --git a/tests/Doctrine/Tests/Models/Quote/FullAddress.php b/tests/Doctrine/Tests/Models/Quote/FullAddress.php new file mode 100644 index 00000000000..b73cda5bd4a --- /dev/null +++ b/tests/Doctrine/Tests/Models/Quote/FullAddress.php @@ -0,0 +1,17 @@ +legs = new ArrayCollection(); } -} \ No newline at end of file +} diff --git a/tests/Doctrine/Tests/Models/Tweet/Tweet.php b/tests/Doctrine/Tests/Models/Tweet/Tweet.php index 8a315df9ef0..5455452c2b6 100644 --- a/tests/Doctrine/Tests/Models/Tweet/Tweet.php +++ b/tests/Doctrine/Tests/Models/Tweet/Tweet.php @@ -8,8 +8,6 @@ */ class Tweet { - const CLASSNAME = __CLASS__; - /** * @Id * @GeneratedValue diff --git a/tests/Doctrine/Tests/Models/Tweet/User.php b/tests/Doctrine/Tests/Models/Tweet/User.php index 68cf137f2b0..4efd6193e4f 100644 --- a/tests/Doctrine/Tests/Models/Tweet/User.php +++ b/tests/Doctrine/Tests/Models/Tweet/User.php @@ -10,8 +10,6 @@ */ class User { - const CLASSNAME = __CLASS__; - /** * @Id * @GeneratedValue diff --git a/tests/Doctrine/Tests/Models/Tweet/UserList.php b/tests/Doctrine/Tests/Models/Tweet/UserList.php index 1eb3e141f03..0f20f94b938 100644 --- a/tests/Doctrine/Tests/Models/Tweet/UserList.php +++ b/tests/Doctrine/Tests/Models/Tweet/UserList.php @@ -8,8 +8,6 @@ */ class UserList { - const CLASSNAME = __CLASS__; - /** * @Id * @GeneratedValue diff --git a/tests/Doctrine/Tests/Models/ValueConversionType/OwningManyToOneCompositeIdForeignKeyEntity.php b/tests/Doctrine/Tests/Models/ValueConversionType/OwningManyToOneCompositeIdForeignKeyEntity.php index b6787a41854..7b94a110d73 100644 --- a/tests/Doctrine/Tests/Models/ValueConversionType/OwningManyToOneCompositeIdForeignKeyEntity.php +++ b/tests/Doctrine/Tests/Models/ValueConversionType/OwningManyToOneCompositeIdForeignKeyEntity.php @@ -1,5 +1,7 @@ 1, 'name' => 'bar'))), - array(new CacheKeyMock('key.2'), new CacheEntryMock(array('id'=>2, 'name' => 'foo'))), - ); + return [ + [new CacheKeyMock('key.1'), new CacheEntryMock(['id'=>1, 'name' => 'bar'])], + [new CacheKeyMock('key.2'), new CacheEntryMock(['id'=>2, 'name' => 'foo'])], + ]; } /** @@ -57,7 +57,7 @@ public function testPutGetContainsEvict($key, $value) $actual = $this->region->get($key); $this->assertEquals($value, $actual); - + $this->region->evict($key); $this->assertFalse($this->region->contains($key)); @@ -71,8 +71,8 @@ public function testEvictAll() $this->assertFalse($this->region->contains($key1)); $this->assertFalse($this->region->contains($key2)); - $this->region->put($key1, new CacheEntryMock(array('value' => 'foo'))); - $this->region->put($key2, new CacheEntryMock(array('value' => 'bar'))); + $this->region->put($key1, new CacheEntryMock(['value' => 'foo'])); + $this->region->put($key2, new CacheEntryMock(['value' => 'bar'])); $this->assertTrue($this->region->contains($key1)); $this->assertTrue($this->region->contains($key2)); @@ -82,4 +82,4 @@ public function testEvictAll() $this->assertFalse($this->region->contains($key1)); $this->assertFalse($this->region->contains($key2)); } -} \ No newline at end of file +} diff --git a/tests/Doctrine/Tests/ORM/Cache/CacheConfigTest.php b/tests/Doctrine/Tests/ORM/Cache/CacheConfigTest.php index 321207c39ba..4c016df1fc7 100644 --- a/tests/Doctrine/Tests/ORM/Cache/CacheConfigTest.php +++ b/tests/Doctrine/Tests/ORM/Cache/CacheConfigTest.php @@ -6,6 +6,8 @@ use Doctrine\ORM\Cache\CacheFactory; use Doctrine\ORM\Cache\QueryCacheValidator; use Doctrine\ORM\Cache\Logging\CacheLogger; +use Doctrine\ORM\Cache\TimestampQueryCacheValidator; +use Doctrine\ORM\Cache\TimestampRegion; use Doctrine\Tests\DoctrineTestCase; /** @@ -67,12 +69,17 @@ public function testSetGetCacheFactory() public function testSetGetQueryValidator() { + $factory = $this->createMock(CacheFactory::class); + $factory->method('getTimestampRegion')->willReturn($this->createMock(TimestampRegion::class)); + + $this->config->setCacheFactory($factory); + $validator = $this->createMock(QueryCacheValidator::class); - $this->assertInstanceOf('Doctrine\ORM\Cache\TimestampQueryCacheValidator', $this->config->getQueryValidator()); + $this->assertInstanceOf(TimestampQueryCacheValidator::class, $this->config->getQueryValidator()); $this->config->setQueryValidator($validator); $this->assertEquals($validator, $this->config->getQueryValidator()); } -} \ No newline at end of file +} diff --git a/tests/Doctrine/Tests/ORM/Cache/CacheKeyTest.php b/tests/Doctrine/Tests/ORM/Cache/CacheKeyTest.php index 39c28af1e35..63c86d7f1af 100644 --- a/tests/Doctrine/Tests/ORM/Cache/CacheKeyTest.php +++ b/tests/Doctrine/Tests/ORM/Cache/CacheKeyTest.php @@ -13,57 +13,57 @@ class CacheKeyTest extends DoctrineTestCase { public function testEntityCacheKeyIdentifierCollision() { - $key1 = new EntityCacheKey('Foo', array('id'=>1)); - $key2 = new EntityCacheKey('Bar', array('id'=>1)); + $key1 = new EntityCacheKey('Foo', ['id'=>1]); + $key2 = new EntityCacheKey('Bar', ['id'=>1]); $this->assertNotEquals($key1->hash, $key2->hash); } public function testEntityCacheKeyIdentifierType() { - $key1 = new EntityCacheKey('Foo', array('id'=>1)); - $key2 = new EntityCacheKey('Foo', array('id'=>'1')); + $key1 = new EntityCacheKey('Foo', ['id'=>1]); + $key2 = new EntityCacheKey('Foo', ['id'=>'1']); $this->assertEquals($key1->hash, $key2->hash); } public function testEntityCacheKeyIdentifierOrder() { - $key1 = new EntityCacheKey('Foo', array('foo_bar'=>1, 'bar_foo'=> 2)); - $key2 = new EntityCacheKey('Foo', array('bar_foo'=>2, 'foo_bar'=> 1)); + $key1 = new EntityCacheKey('Foo', ['foo_bar'=>1, 'bar_foo'=> 2]); + $key2 = new EntityCacheKey('Foo', ['bar_foo'=>2, 'foo_bar'=> 1]); $this->assertEquals($key1->hash, $key2->hash); } public function testCollectionCacheKeyIdentifierType() { - $key1 = new CollectionCacheKey('Foo', 'assoc', array('id'=>1)); - $key2 = new CollectionCacheKey('Foo', 'assoc', array('id'=>'1')); + $key1 = new CollectionCacheKey('Foo', 'assoc', ['id'=>1]); + $key2 = new CollectionCacheKey('Foo', 'assoc', ['id'=>'1']); $this->assertEquals($key1->hash, $key2->hash); } public function testCollectionCacheKeyIdentifierOrder() { - $key1 = new CollectionCacheKey('Foo', 'assoc', array('foo_bar'=>1, 'bar_foo'=> 2)); - $key2 = new CollectionCacheKey('Foo', 'assoc', array('bar_foo'=>2, 'foo_bar'=> 1)); + $key1 = new CollectionCacheKey('Foo', 'assoc', ['foo_bar'=>1, 'bar_foo'=> 2]); + $key2 = new CollectionCacheKey('Foo', 'assoc', ['bar_foo'=>2, 'foo_bar'=> 1]); $this->assertEquals($key1->hash, $key2->hash); } public function testCollectionCacheKeyIdentifierCollision() { - $key1 = new CollectionCacheKey('Foo', 'assoc', array('id'=>1)); - $key2 = new CollectionCacheKey('Bar', 'assoc', array('id'=>1)); + $key1 = new CollectionCacheKey('Foo', 'assoc', ['id'=>1]); + $key2 = new CollectionCacheKey('Bar', 'assoc', ['id'=>1]); $this->assertNotEquals($key1->hash, $key2->hash); } public function testCollectionCacheKeyAssociationCollision() { - $key1 = new CollectionCacheKey('Foo', 'assoc1', array('id'=>1)); - $key2 = new CollectionCacheKey('Foo', 'assoc2', array('id'=>1)); + $key1 = new CollectionCacheKey('Foo', 'assoc1', ['id'=>1]); + $key2 = new CollectionCacheKey('Foo', 'assoc2', ['id'=>1]); $this->assertNotEquals($key1->hash, $key2->hash); } -} \ No newline at end of file +} diff --git a/tests/Doctrine/Tests/ORM/Cache/CacheLoggerChainTest.php b/tests/Doctrine/Tests/ORM/Cache/CacheLoggerChainTest.php index 0af90cb072c..a070237a200 100644 --- a/tests/Doctrine/Tests/ORM/Cache/CacheLoggerChainTest.php +++ b/tests/Doctrine/Tests/ORM/Cache/CacheLoggerChainTest.php @@ -42,13 +42,13 @@ public function testGetAndSetLogger() $this->logger->setLogger('mock', $this->mock); $this->assertSame($this->mock, $this->logger->getLogger('mock')); - $this->assertEquals(array('mock' => $this->mock), $this->logger->getLoggers()); + $this->assertEquals(['mock' => $this->mock], $this->logger->getLoggers()); } public function testEntityCacheChain() { $name = 'my_entity_region'; - $key = new EntityCacheKey(State::CLASSNAME, array('id' => 1)); + $key = new EntityCacheKey(State::class, ['id' => 1]); $this->logger->setLogger('mock', $this->mock); @@ -72,7 +72,7 @@ public function testEntityCacheChain() public function testCollectionCacheChain() { $name = 'my_collection_region'; - $key = new CollectionCacheKey(State::CLASSNAME, 'cities', array('id' => 1)); + $key = new CollectionCacheKey(State::class, 'cities', ['id' => 1]); $this->logger->setLogger('mock', $this->mock); @@ -116,4 +116,4 @@ public function testQueryCacheChain() $this->logger->queryCachePut($name, $key); $this->logger->queryCacheMiss($name, $key); } -} \ No newline at end of file +} diff --git a/tests/Doctrine/Tests/ORM/Cache/DefaultCacheFactoryTest.php b/tests/Doctrine/Tests/ORM/Cache/DefaultCacheFactoryTest.php index 40c997d4217..4ff2edc1cf9 100644 --- a/tests/Doctrine/Tests/ORM/Cache/DefaultCacheFactoryTest.php +++ b/tests/Doctrine/Tests/ORM/Cache/DefaultCacheFactoryTest.php @@ -4,14 +4,28 @@ use Doctrine\Common\Cache\Cache; use Doctrine\Common\Cache\CacheProvider; -use \Doctrine\Tests\OrmTestCase; -use Doctrine\ORM\Mapping\ClassMetadata; +use Doctrine\ORM\Cache\CacheFactory; use Doctrine\ORM\Cache\DefaultCacheFactory; +use Doctrine\ORM\Cache\Persister\Collection\CachedCollectionPersister; +use Doctrine\ORM\Cache\Persister\Collection\NonStrictReadWriteCachedCollectionPersister; +use Doctrine\ORM\Cache\Persister\Collection\ReadOnlyCachedCollectionPersister; +use Doctrine\ORM\Cache\Persister\Collection\ReadWriteCachedCollectionPersister; +use Doctrine\ORM\Cache\Persister\Entity\CachedEntityPersister; +use Doctrine\ORM\Cache\Persister\Entity\NonStrictReadWriteCachedEntityPersister; +use Doctrine\ORM\Cache\Persister\Entity\ReadOnlyCachedEntityPersister; +use Doctrine\ORM\Cache\Persister\Entity\ReadWriteCachedEntityPersister; +use Doctrine\ORM\Cache\Region\DefaultMultiGetRegion; use Doctrine\ORM\Cache\Region\DefaultRegion; -use Doctrine\Tests\Mocks\ConcurrentRegionMock; -use Doctrine\ORM\Persisters\Entity\BasicEntityPersister; -use Doctrine\ORM\Persisters\Collection\OneToManyPersister; use Doctrine\ORM\Cache\RegionsConfiguration; +use Doctrine\ORM\Mapping\ClassMetadata; +use Doctrine\ORM\Persisters\Collection\OneToManyPersister; +use Doctrine\ORM\Persisters\Entity\BasicEntityPersister; +use Doctrine\Tests\Mocks\ConcurrentRegionMock; +use Doctrine\Tests\Models\Cache\AttractionContactInfo; +use Doctrine\Tests\Models\Cache\AttractionLocationInfo; +use Doctrine\Tests\Models\Cache\City; +use Doctrine\Tests\Models\Cache\State; +use Doctrine\Tests\OrmTestCase; /** * @group DDC-2183 @@ -38,27 +52,26 @@ protected function setUp() $this->enableSecondLevelCache(); parent::setUp(); - $this->em = $this->_getTestEntityManager(); - $this->regionsConfig = new RegionsConfiguration; - $arguments = array($this->regionsConfig, $this->getSharedSecondLevelCacheDriverImpl()); - $this->factory = $this->getMockBuilder(DefaultCacheFactory::class) - ->setMethods(array('getRegion')) - ->setConstructorArgs($arguments) - ->getMock(); + $this->em = $this->_getTestEntityManager(); + $this->regionsConfig = new RegionsConfiguration; + $arguments = [$this->regionsConfig, $this->getSharedSecondLevelCacheDriverImpl()]; + $this->factory = $this->getMockBuilder(DefaultCacheFactory::class) + ->setMethods(['getRegion']) + ->setConstructorArgs($arguments) + ->getMock(); } public function testImplementsCacheFactory() { - $this->assertInstanceOf('Doctrine\ORM\Cache\CacheFactory', $this->factory); + $this->assertInstanceOf(CacheFactory::class, $this->factory); } public function testBuildCachedEntityPersisterReadOnly() { - $em = $this->em; - $entityName = 'Doctrine\Tests\Models\Cache\State'; - $metadata = clone $em->getClassMetadata($entityName); - $persister = new BasicEntityPersister($em, $metadata); - $region = new ConcurrentRegionMock(new DefaultRegion('regionName', $this->getSharedSecondLevelCacheDriverImpl())); + $em = $this->em; + $metadata = clone $em->getClassMetadata(State::class); + $persister = new BasicEntityPersister($em, $metadata); + $region = new ConcurrentRegionMock(new DefaultRegion('regionName', $this->getSharedSecondLevelCacheDriverImpl())); $metadata->cache['usage'] = ClassMetadata::CACHE_USAGE_READ_ONLY; @@ -69,17 +82,16 @@ public function testBuildCachedEntityPersisterReadOnly() $cachedPersister = $this->factory->buildCachedEntityPersister($em, $persister, $metadata); - $this->assertInstanceOf('Doctrine\ORM\Cache\Persister\Entity\CachedEntityPersister', $cachedPersister); - $this->assertInstanceOf('Doctrine\ORM\Cache\Persister\Entity\ReadOnlyCachedEntityPersister', $cachedPersister); + $this->assertInstanceOf(CachedEntityPersister::class, $cachedPersister); + $this->assertInstanceOf(ReadOnlyCachedEntityPersister::class, $cachedPersister); } public function testBuildCachedEntityPersisterReadWrite() { - $em = $this->em; - $entityName = 'Doctrine\Tests\Models\Cache\State'; - $metadata = clone $em->getClassMetadata($entityName); - $persister = new BasicEntityPersister($em, $metadata); - $region = new ConcurrentRegionMock(new DefaultRegion('regionName', $this->getSharedSecondLevelCacheDriverImpl())); + $em = $this->em; + $metadata = clone $em->getClassMetadata(State::class); + $persister = new BasicEntityPersister($em, $metadata); + $region = new ConcurrentRegionMock(new DefaultRegion('regionName', $this->getSharedSecondLevelCacheDriverImpl())); $metadata->cache['usage'] = ClassMetadata::CACHE_USAGE_READ_WRITE; @@ -90,17 +102,16 @@ public function testBuildCachedEntityPersisterReadWrite() $cachedPersister = $this->factory->buildCachedEntityPersister($em, $persister, $metadata); - $this->assertInstanceOf('Doctrine\ORM\Cache\Persister\Entity\CachedEntityPersister', $cachedPersister); - $this->assertInstanceOf('Doctrine\ORM\Cache\Persister\Entity\ReadWriteCachedEntityPersister', $cachedPersister); + $this->assertInstanceOf(CachedEntityPersister::class, $cachedPersister); + $this->assertInstanceOf(ReadWriteCachedEntityPersister::class, $cachedPersister); } public function testBuildCachedEntityPersisterNonStrictReadWrite() { - $em = $this->em; - $entityName = 'Doctrine\Tests\Models\Cache\State'; - $metadata = clone $em->getClassMetadata($entityName); - $persister = new BasicEntityPersister($em, $metadata); - $region = new ConcurrentRegionMock(new DefaultRegion('regionName', $this->getSharedSecondLevelCacheDriverImpl())); + $em = $this->em; + $metadata = clone $em->getClassMetadata(State::class); + $persister = new BasicEntityPersister($em, $metadata); + $region = new ConcurrentRegionMock(new DefaultRegion('regionName', $this->getSharedSecondLevelCacheDriverImpl())); $metadata->cache['usage'] = ClassMetadata::CACHE_USAGE_NONSTRICT_READ_WRITE; @@ -111,18 +122,17 @@ public function testBuildCachedEntityPersisterNonStrictReadWrite() $cachedPersister = $this->factory->buildCachedEntityPersister($em, $persister, $metadata); - $this->assertInstanceOf('Doctrine\ORM\Cache\Persister\Entity\CachedEntityPersister', $cachedPersister); - $this->assertInstanceOf('Doctrine\ORM\Cache\Persister\Entity\NonStrictReadWriteCachedEntityPersister', $cachedPersister); + $this->assertInstanceOf(CachedEntityPersister::class, $cachedPersister); + $this->assertInstanceOf(NonStrictReadWriteCachedEntityPersister::class, $cachedPersister); } public function testBuildCachedCollectionPersisterReadOnly() { - $em = $this->em; - $entityName = 'Doctrine\Tests\Models\Cache\State'; - $metadata = $em->getClassMetadata($entityName); - $mapping = $metadata->associationMappings['cities']; - $persister = new OneToManyPersister($em); - $region = new ConcurrentRegionMock(new DefaultRegion('regionName', $this->getSharedSecondLevelCacheDriverImpl())); + $em = $this->em; + $metadata = $em->getClassMetadata(State::class); + $mapping = $metadata->associationMappings['cities']; + $persister = new OneToManyPersister($em); + $region = new ConcurrentRegionMock(new DefaultRegion('regionName', $this->getSharedSecondLevelCacheDriverImpl())); $mapping['cache']['usage'] = ClassMetadata::CACHE_USAGE_READ_ONLY; @@ -134,18 +144,17 @@ public function testBuildCachedCollectionPersisterReadOnly() $cachedPersister = $this->factory->buildCachedCollectionPersister($em, $persister, $mapping); - $this->assertInstanceOf('Doctrine\ORM\Cache\Persister\Collection\CachedCollectionPersister', $cachedPersister); - $this->assertInstanceOf('Doctrine\ORM\Cache\Persister\Collection\ReadOnlyCachedCollectionPersister', $cachedPersister); + $this->assertInstanceOf(CachedCollectionPersister::class, $cachedPersister); + $this->assertInstanceOf(ReadOnlyCachedCollectionPersister::class, $cachedPersister); } public function testBuildCachedCollectionPersisterReadWrite() { - $em = $this->em; - $entityName = 'Doctrine\Tests\Models\Cache\State'; - $metadata = $em->getClassMetadata($entityName); - $mapping = $metadata->associationMappings['cities']; - $persister = new OneToManyPersister($em); - $region = new ConcurrentRegionMock(new DefaultRegion('regionName', $this->getSharedSecondLevelCacheDriverImpl())); + $em = $this->em; + $metadata = $em->getClassMetadata(State::class); + $mapping = $metadata->associationMappings['cities']; + $persister = new OneToManyPersister($em); + $region = new ConcurrentRegionMock(new DefaultRegion('regionName', $this->getSharedSecondLevelCacheDriverImpl())); $mapping['cache']['usage'] = ClassMetadata::CACHE_USAGE_READ_WRITE; @@ -156,18 +165,17 @@ public function testBuildCachedCollectionPersisterReadWrite() $cachedPersister = $this->factory->buildCachedCollectionPersister($em, $persister, $mapping); - $this->assertInstanceOf('Doctrine\ORM\Cache\Persister\Collection\CachedCollectionPersister', $cachedPersister); - $this->assertInstanceOf('Doctrine\ORM\Cache\Persister\Collection\ReadWriteCachedCollectionPersister', $cachedPersister); + $this->assertInstanceOf(CachedCollectionPersister::class, $cachedPersister); + $this->assertInstanceOf(ReadWriteCachedCollectionPersister::class, $cachedPersister); } public function testBuildCachedCollectionPersisterNonStrictReadWrite() { - $em = $this->em; - $entityName = 'Doctrine\Tests\Models\Cache\State'; - $metadata = $em->getClassMetadata($entityName); - $mapping = $metadata->associationMappings['cities']; - $persister = new OneToManyPersister($em); - $region = new ConcurrentRegionMock(new DefaultRegion('regionName', $this->getSharedSecondLevelCacheDriverImpl())); + $em = $this->em; + $metadata = $em->getClassMetadata(State::class); + $mapping = $metadata->associationMappings['cities']; + $persister = new OneToManyPersister($em); + $region = new ConcurrentRegionMock(new DefaultRegion('regionName', $this->getSharedSecondLevelCacheDriverImpl())); $mapping['cache']['usage'] = ClassMetadata::CACHE_USAGE_NONSTRICT_READ_WRITE; @@ -178,15 +186,15 @@ public function testBuildCachedCollectionPersisterNonStrictReadWrite() $cachedPersister = $this->factory->buildCachedCollectionPersister($em, $persister, $mapping); - $this->assertInstanceOf('Doctrine\ORM\Cache\Persister\Collection\CachedCollectionPersister', $cachedPersister); - $this->assertInstanceOf('Doctrine\ORM\Cache\Persister\Collection\NonStrictReadWriteCachedCollectionPersister', $cachedPersister); + $this->assertInstanceOf(CachedCollectionPersister::class, $cachedPersister); + $this->assertInstanceOf(NonStrictReadWriteCachedCollectionPersister::class, $cachedPersister); } public function testInheritedEntityCacheRegion() { $em = $this->em; - $metadata1 = clone $em->getClassMetadata('Doctrine\Tests\Models\Cache\AttractionContactInfo'); - $metadata2 = clone $em->getClassMetadata('Doctrine\Tests\Models\Cache\AttractionLocationInfo'); + $metadata1 = clone $em->getClassMetadata(AttractionContactInfo::class); + $metadata2 = clone $em->getClassMetadata(AttractionLocationInfo::class); $persister1 = new BasicEntityPersister($em, $metadata1); $persister2 = new BasicEntityPersister($em, $metadata2); $factory = new DefaultCacheFactory($this->regionsConfig, $this->getSharedSecondLevelCacheDriverImpl()); @@ -194,8 +202,8 @@ public function testInheritedEntityCacheRegion() $cachedPersister1 = $factory->buildCachedEntityPersister($em, $persister1, $metadata1); $cachedPersister2 = $factory->buildCachedEntityPersister($em, $persister2, $metadata2); - $this->assertInstanceOf('Doctrine\ORM\Cache\Persister\Entity\CachedEntityPersister', $cachedPersister1); - $this->assertInstanceOf('Doctrine\ORM\Cache\Persister\Entity\CachedEntityPersister', $cachedPersister2); + $this->assertInstanceOf(CachedEntityPersister::class, $cachedPersister1); + $this->assertInstanceOf(CachedEntityPersister::class, $cachedPersister2); $this->assertNotSame($cachedPersister1, $cachedPersister2); $this->assertSame($cachedPersister1->getCacheRegion(), $cachedPersister2->getCacheRegion()); @@ -204,8 +212,8 @@ public function testInheritedEntityCacheRegion() public function testCreateNewCacheDriver() { $em = $this->em; - $metadata1 = clone $em->getClassMetadata('Doctrine\Tests\Models\Cache\State'); - $metadata2 = clone $em->getClassMetadata('Doctrine\Tests\Models\Cache\City'); + $metadata1 = clone $em->getClassMetadata(State::class); + $metadata2 = clone $em->getClassMetadata(City::class); $persister1 = new BasicEntityPersister($em, $metadata1); $persister2 = new BasicEntityPersister($em, $metadata2); $factory = new DefaultCacheFactory($this->regionsConfig, $this->getSharedSecondLevelCacheDriverImpl()); @@ -213,77 +221,127 @@ public function testCreateNewCacheDriver() $cachedPersister1 = $factory->buildCachedEntityPersister($em, $persister1, $metadata1); $cachedPersister2 = $factory->buildCachedEntityPersister($em, $persister2, $metadata2); - $this->assertInstanceOf('Doctrine\ORM\Cache\Persister\Entity\CachedEntityPersister', $cachedPersister1); - $this->assertInstanceOf('Doctrine\ORM\Cache\Persister\Entity\CachedEntityPersister', $cachedPersister2); + $this->assertInstanceOf(CachedEntityPersister::class, $cachedPersister1); + $this->assertInstanceOf(CachedEntityPersister::class, $cachedPersister2); $this->assertNotSame($cachedPersister1, $cachedPersister2); $this->assertNotSame($cachedPersister1->getCacheRegion(), $cachedPersister2->getCacheRegion()); } - /** - * @expectedException InvalidArgumentException - * @expectedExceptionMessage Unrecognized access strategy type [-1] - */ public function testBuildCachedEntityPersisterNonStrictException() { - $em = $this->em; - $entityName = 'Doctrine\Tests\Models\Cache\State'; - $metadata = clone $em->getClassMetadata($entityName); - $persister = new BasicEntityPersister($em, $metadata); + $em = $this->em; + $metadata = clone $em->getClassMetadata(State::class); + $persister = new BasicEntityPersister($em, $metadata); $metadata->cache['usage'] = -1; + $this->expectException(\InvalidArgumentException::class); + $this->expectExceptionMessage('Unrecognized access strategy type [-1]'); + $this->factory->buildCachedEntityPersister($em, $persister, $metadata); } - /** - * @expectedException InvalidArgumentException - * @expectedExceptionMessage Unrecognized access strategy type [-1] - */ public function testBuildCachedCollectionPersisterException() { - $em = $this->em; - $entityName = 'Doctrine\Tests\Models\Cache\State'; - $metadata = $em->getClassMetadata($entityName); - $mapping = $metadata->associationMappings['cities']; - $persister = new OneToManyPersister($em); + $em = $this->em; + $metadata = $em->getClassMetadata(State::class); + $mapping = $metadata->associationMappings['cities']; + $persister = new OneToManyPersister($em); $mapping['cache']['usage'] = -1; + $this->expectException(\InvalidArgumentException::class); + $this->expectExceptionMessage('Unrecognized access strategy type [-1]'); + $this->factory->buildCachedCollectionPersister($em, $persister, $mapping); } - /** - * @expectedException LogicException - * @expectedExceptionMessage If you want to use a "READ_WRITE" cache an implementation of "Doctrine\ORM\Cache\ConcurrentRegion" is required, The default implementation provided by doctrine is "Doctrine\ORM\Cache\Region\FileLockRegion" if you want to use it please provide a valid directory - */ public function testInvalidFileLockRegionDirectoryException() { $factory = new DefaultCacheFactory($this->regionsConfig, $this->getSharedSecondLevelCacheDriverImpl()); - $factory->getRegion(array( - 'usage' => ClassMetadata::CACHE_USAGE_READ_WRITE, - 'region' => 'foo' - )); + $this->expectException(\LogicException::class); + $this->expectExceptionMessage( + 'If you want to use a "READ_WRITE" cache an implementation of "Doctrine\ORM\Cache\ConcurrentRegion" ' + . 'is required, The default implementation provided by doctrine is ' + . '"Doctrine\ORM\Cache\Region\FileLockRegion" if you want to use it please provide a valid directory' + ); + + $factory->getRegion( + [ + 'usage' => ClassMetadata::CACHE_USAGE_READ_WRITE, + 'region' => 'foo' + ] + ); + } + + public function testInvalidFileLockRegionDirectoryExceptionWithEmptyString() + { + $factory = new DefaultCacheFactory($this->regionsConfig, $this->getSharedSecondLevelCacheDriverImpl()); + + $factory->setFileLockRegionDirectory(''); + + $this->expectException(\LogicException::class); + $this->expectExceptionMessage( + 'If you want to use a "READ_WRITE" cache an implementation of "Doctrine\ORM\Cache\ConcurrentRegion" ' + . 'is required, The default implementation provided by doctrine is ' + . '"Doctrine\ORM\Cache\Region\FileLockRegion" if you want to use it please provide a valid directory' + ); + + $factory->getRegion( + [ + 'usage' => ClassMetadata::CACHE_USAGE_READ_WRITE, + 'region' => 'foo' + ] + ); } public function testBuildsNewNamespacedCacheInstancePerRegionInstance() { $factory = new DefaultCacheFactory($this->regionsConfig, $this->getSharedSecondLevelCacheDriverImpl()); - $fooRegion = $factory->getRegion(array( - 'region' => 'foo', - 'usage' => ClassMetadata::CACHE_USAGE_READ_ONLY, - )); - $barRegion = $factory->getRegion(array( - 'region' => 'bar', - 'usage' => ClassMetadata::CACHE_USAGE_READ_ONLY, - )); + $fooRegion = $factory->getRegion( + [ + 'region' => 'foo', + 'usage' => ClassMetadata::CACHE_USAGE_READ_ONLY, + ] + ); + $barRegion = $factory->getRegion( + [ + 'region' => 'bar', + 'usage' => ClassMetadata::CACHE_USAGE_READ_ONLY, + ] + ); $this->assertSame('foo', $fooRegion->getCache()->getNamespace()); $this->assertSame('bar', $barRegion->getCache()->getNamespace()); } + public function testAppendsNamespacedCacheInstancePerRegionInstanceWhenItsAlreadySet() + { + $cache = clone $this->getSharedSecondLevelCacheDriverImpl(); + $cache->setNamespace('testing'); + + $factory = new DefaultCacheFactory($this->regionsConfig, $cache); + + $fooRegion = $factory->getRegion( + [ + 'region' => 'foo', + 'usage' => ClassMetadata::CACHE_USAGE_READ_ONLY, + ] + ); + $barRegion = $factory->getRegion( + [ + 'region' => 'bar', + 'usage' => ClassMetadata::CACHE_USAGE_READ_ONLY, + ] + ); + + $this->assertSame('testing:foo', $fooRegion->getCache()->getNamespace()); + $this->assertSame('testing:bar', $barRegion->getCache()->getNamespace()); + } + public function testBuildsDefaultCacheRegionFromGenericCacheRegion() { /* @var $cache \Doctrine\Common\Cache\Cache */ @@ -292,11 +350,13 @@ public function testBuildsDefaultCacheRegionFromGenericCacheRegion() $factory = new DefaultCacheFactory($this->regionsConfig, $cache); $this->assertInstanceOf( - 'Doctrine\ORM\Cache\Region\DefaultRegion', - $factory->getRegion(array( - 'region' => 'bar', - 'usage' => ClassMetadata::CACHE_USAGE_READ_ONLY, - )) + DefaultRegion::class, + $factory->getRegion( + [ + 'region' => 'bar', + 'usage' => ClassMetadata::CACHE_USAGE_READ_ONLY, + ] + ) ); } @@ -308,11 +368,13 @@ public function testBuildsMultiGetCacheRegionFromGenericCacheRegion() $factory = new DefaultCacheFactory($this->regionsConfig, $cache); $this->assertInstanceOf( - 'Doctrine\ORM\Cache\Region\DefaultMultiGetRegion', - $factory->getRegion(array( - 'region' => 'bar', - 'usage' => ClassMetadata::CACHE_USAGE_READ_ONLY, - )) + DefaultMultiGetRegion::class, + $factory->getRegion( + [ + 'region' => 'bar', + 'usage' => ClassMetadata::CACHE_USAGE_READ_ONLY, + ] + ) ); } diff --git a/tests/Doctrine/Tests/ORM/Cache/DefaultCacheTest.php b/tests/Doctrine/Tests/ORM/Cache/DefaultCacheTest.php index c33d0839b92..cbc9d8e8b73 100644 --- a/tests/Doctrine/Tests/ORM/Cache/DefaultCacheTest.php +++ b/tests/Doctrine/Tests/ORM/Cache/DefaultCacheTest.php @@ -2,6 +2,8 @@ namespace Doctrine\Tests\ORM\Cache; +use Doctrine\ORM\Cache; +use Doctrine\Tests\Models\CMS\CmsUser; use Doctrine\Tests\OrmTestCase; use Doctrine\ORM\Cache\DefaultCache; use Doctrine\Tests\Models\Cache\State; @@ -26,8 +28,6 @@ class DefaultCacheTest extends OrmTestCase */ private $em; - const NON_CACHEABLE_ENTITY = 'Doctrine\Tests\Models\CMS\CmsUser'; - protected function setUp() { parent::enableSecondLevelCache(); @@ -70,157 +70,157 @@ private function putCollectionCacheEntry($className, $association, array $ownerI public function testImplementsCache() { - $this->assertInstanceOf('Doctrine\ORM\Cache', $this->cache); + $this->assertInstanceOf(Cache::class, $this->cache); } - + public function testGetEntityCacheRegionAccess() { - $this->assertInstanceOf('Doctrine\ORM\Cache\Region', $this->cache->getEntityCacheRegion(State::CLASSNAME)); - $this->assertNull($this->cache->getEntityCacheRegion(self::NON_CACHEABLE_ENTITY)); + $this->assertInstanceOf(Cache\Region::class, $this->cache->getEntityCacheRegion(State::class)); + $this->assertNull($this->cache->getEntityCacheRegion(CmsUser::class)); } public function testGetCollectionCacheRegionAccess() { - $this->assertInstanceOf('Doctrine\ORM\Cache\Region', $this->cache->getCollectionCacheRegion(State::CLASSNAME, 'cities')); - $this->assertNull($this->cache->getCollectionCacheRegion(self::NON_CACHEABLE_ENTITY, 'phonenumbers')); + $this->assertInstanceOf(Cache\Region::class, $this->cache->getCollectionCacheRegion(State::class, 'cities')); + $this->assertNull($this->cache->getCollectionCacheRegion(CmsUser::class, 'phonenumbers')); } public function testContainsEntity() { - $identifier = array('id'=>1); - $className = Country::CLASSNAME; - $cacheEntry = array_merge($identifier, array('name' => 'Brazil')); + $identifier = ['id'=>1]; + $className = Country::class; + $cacheEntry = array_merge($identifier, ['name' => 'Brazil']); - $this->assertFalse($this->cache->containsEntity(Country::CLASSNAME, 1)); + $this->assertFalse($this->cache->containsEntity(Country::class, 1)); $this->putEntityCacheEntry($className, $identifier, $cacheEntry); - $this->assertTrue($this->cache->containsEntity(Country::CLASSNAME, 1)); - $this->assertFalse($this->cache->containsEntity(self::NON_CACHEABLE_ENTITY, 1)); + $this->assertTrue($this->cache->containsEntity(Country::class, 1)); + $this->assertFalse($this->cache->containsEntity(CmsUser::class, 1)); } public function testEvictEntity() { - $identifier = array('id'=>1); - $className = Country::CLASSNAME; - $cacheEntry = array_merge($identifier, array('name' => 'Brazil')); + $identifier = ['id'=>1]; + $className = Country::class; + $cacheEntry = array_merge($identifier, ['name' => 'Brazil']); $this->putEntityCacheEntry($className, $identifier, $cacheEntry); - $this->assertTrue($this->cache->containsEntity(Country::CLASSNAME, 1)); + $this->assertTrue($this->cache->containsEntity(Country::class, 1)); - $this->cache->evictEntity(Country::CLASSNAME, 1); - $this->cache->evictEntity(self::NON_CACHEABLE_ENTITY, 1); + $this->cache->evictEntity(Country::class, 1); + $this->cache->evictEntity(CmsUser::class, 1); - $this->assertFalse($this->cache->containsEntity(Country::CLASSNAME, 1)); + $this->assertFalse($this->cache->containsEntity(Country::class, 1)); } public function testEvictEntityRegion() { - $identifier = array('id'=>1); - $className = Country::CLASSNAME; - $cacheEntry = array_merge($identifier, array('name' => 'Brazil')); + $identifier = ['id'=>1]; + $className = Country::class; + $cacheEntry = array_merge($identifier, ['name' => 'Brazil']); $this->putEntityCacheEntry($className, $identifier, $cacheEntry); - $this->assertTrue($this->cache->containsEntity(Country::CLASSNAME, 1)); + $this->assertTrue($this->cache->containsEntity(Country::class, 1)); - $this->cache->evictEntityRegion(Country::CLASSNAME); - $this->cache->evictEntityRegion(self::NON_CACHEABLE_ENTITY); + $this->cache->evictEntityRegion(Country::class); + $this->cache->evictEntityRegion(CmsUser::class); - $this->assertFalse($this->cache->containsEntity(Country::CLASSNAME, 1)); + $this->assertFalse($this->cache->containsEntity(Country::class, 1)); } public function testEvictEntityRegions() { - $identifier = array('id'=>1); - $className = Country::CLASSNAME; - $cacheEntry = array_merge($identifier, array('name' => 'Brazil')); + $identifier = ['id'=>1]; + $className = Country::class; + $cacheEntry = array_merge($identifier, ['name' => 'Brazil']); $this->putEntityCacheEntry($className, $identifier, $cacheEntry); - $this->assertTrue($this->cache->containsEntity(Country::CLASSNAME, 1)); + $this->assertTrue($this->cache->containsEntity(Country::class, 1)); $this->cache->evictEntityRegions(); - $this->assertFalse($this->cache->containsEntity(Country::CLASSNAME, 1)); + $this->assertFalse($this->cache->containsEntity(Country::class, 1)); } public function testContainsCollection() { - $ownerId = array('id'=>1); - $className = State::CLASSNAME; + $ownerId = ['id'=>1]; + $className = State::class; $association = 'cities'; - $cacheEntry = array( - array('id' => 11), - array('id' => 12), - ); + $cacheEntry = [ + ['id' => 11], + ['id' => 12], + ]; - $this->assertFalse($this->cache->containsCollection(State::CLASSNAME, $association, 1)); + $this->assertFalse($this->cache->containsCollection(State::class, $association, 1)); $this->putCollectionCacheEntry($className, $association, $ownerId, $cacheEntry); - $this->assertTrue($this->cache->containsCollection(State::CLASSNAME, $association, 1)); - $this->assertFalse($this->cache->containsCollection(self::NON_CACHEABLE_ENTITY, 'phonenumbers', 1)); + $this->assertTrue($this->cache->containsCollection(State::class, $association, 1)); + $this->assertFalse($this->cache->containsCollection(CmsUser::class, 'phonenumbers', 1)); } public function testEvictCollection() { - $ownerId = array('id'=>1); - $className = State::CLASSNAME; + $ownerId = ['id'=>1]; + $className = State::class; $association = 'cities'; - $cacheEntry = array( - array('id' => 11), - array('id' => 12), - ); + $cacheEntry = [ + ['id' => 11], + ['id' => 12], + ]; $this->putCollectionCacheEntry($className, $association, $ownerId, $cacheEntry); - $this->assertTrue($this->cache->containsCollection(State::CLASSNAME, $association, 1)); + $this->assertTrue($this->cache->containsCollection(State::class, $association, 1)); $this->cache->evictCollection($className, $association, $ownerId); - $this->cache->evictCollection(self::NON_CACHEABLE_ENTITY, 'phonenumbers', 1); + $this->cache->evictCollection(CmsUser::class, 'phonenumbers', 1); - $this->assertFalse($this->cache->containsCollection(State::CLASSNAME, $association, 1)); + $this->assertFalse($this->cache->containsCollection(State::class, $association, 1)); } public function testEvictCollectionRegion() { - $ownerId = array('id'=>1); - $className = State::CLASSNAME; + $ownerId = ['id'=>1]; + $className = State::class; $association = 'cities'; - $cacheEntry = array( - array('id' => 11), - array('id' => 12), - ); + $cacheEntry = [ + ['id' => 11], + ['id' => 12], + ]; $this->putCollectionCacheEntry($className, $association, $ownerId, $cacheEntry); - $this->assertTrue($this->cache->containsCollection(State::CLASSNAME, $association, 1)); + $this->assertTrue($this->cache->containsCollection(State::class, $association, 1)); $this->cache->evictCollectionRegion($className, $association); - $this->cache->evictCollectionRegion(self::NON_CACHEABLE_ENTITY, 'phonenumbers'); + $this->cache->evictCollectionRegion(CmsUser::class, 'phonenumbers'); - $this->assertFalse($this->cache->containsCollection(State::CLASSNAME, $association, 1)); + $this->assertFalse($this->cache->containsCollection(State::class, $association, 1)); } public function testEvictCollectionRegions() { - $ownerId = array('id'=>1); - $className = State::CLASSNAME; + $ownerId = ['id'=>1]; + $className = State::class; $association = 'cities'; - $cacheEntry = array( - array('id' => 11), - array('id' => 12), - ); + $cacheEntry = [ + ['id' => 11], + ['id' => 12], + ]; $this->putCollectionCacheEntry($className, $association, $ownerId, $cacheEntry); - $this->assertTrue($this->cache->containsCollection(State::CLASSNAME, $association, 1)); + $this->assertTrue($this->cache->containsCollection(State::class, $association, 1)); $this->cache->evictCollectionRegions(); - $this->assertFalse($this->cache->containsCollection(State::CLASSNAME, $association, 1)); + $this->assertFalse($this->cache->containsCollection(State::class, $association, 1)); } public function testQueryCache() @@ -230,8 +230,8 @@ public function testQueryCache() $defaultQueryCache = $this->cache->getQueryCache(); $fooQueryCache = $this->cache->getQueryCache('foo'); - $this->assertInstanceOf('Doctrine\ORM\Cache\QueryCache', $defaultQueryCache); - $this->assertInstanceOf('Doctrine\ORM\Cache\QueryCache', $fooQueryCache); + $this->assertInstanceOf(Cache\QueryCache::class, $defaultQueryCache); + $this->assertInstanceOf(Cache\QueryCache::class, $fooQueryCache); $this->assertSame($defaultQueryCache, $this->cache->getQueryCache()); $this->assertSame($fooQueryCache, $this->cache->getQueryCache('foo')); @@ -249,7 +249,7 @@ public function testToIdentifierArrayShouldLookupForEntityIdentifier() { $identifier = 123; $entity = new Country('Foo'); - $metadata = $this->em->getClassMetadata(Country::CLASSNAME); + $metadata = $this->em->getClassMetadata(Country::class); $method = new \ReflectionMethod($this->cache, 'toIdentifierArray'); $property = new \ReflectionProperty($entity, 'id'); @@ -257,7 +257,7 @@ public function testToIdentifierArrayShouldLookupForEntityIdentifier() $method->setAccessible(true); $property->setValue($entity, $identifier); - $this->assertEquals(array('id'=>$identifier), $method->invoke($this->cache, $metadata, $identifier)); + $this->assertEquals(['id'=>$identifier], $method->invoke($this->cache, $metadata, $identifier)); } -} \ No newline at end of file +} diff --git a/tests/Doctrine/Tests/ORM/Cache/DefaultCollectionHydratorTest.php b/tests/Doctrine/Tests/ORM/Cache/DefaultCollectionHydratorTest.php index ed0456e3908..f2a35b16a95 100644 --- a/tests/Doctrine/Tests/ORM/Cache/DefaultCollectionHydratorTest.php +++ b/tests/Doctrine/Tests/ORM/Cache/DefaultCollectionHydratorTest.php @@ -2,17 +2,17 @@ namespace Doctrine\Tests\ORM\Cache; -use Doctrine\ORM\UnitOfWork; +use Doctrine\Common\Collections\ArrayCollection; +use Doctrine\ORM\Cache\CollectionCacheEntry; +use Doctrine\ORM\Cache\CollectionCacheKey; +use Doctrine\ORM\Cache\DefaultCollectionHydrator; +use Doctrine\ORM\Cache\EntityCacheEntry; +use Doctrine\ORM\Cache\EntityCacheKey; use Doctrine\ORM\PersistentCollection; -use Doctrine\Tests\Models\Cache\State; +use Doctrine\ORM\UnitOfWork; use Doctrine\Tests\Models\Cache\City; +use Doctrine\Tests\Models\Cache\State; use Doctrine\Tests\OrmFunctionalTestCase; -use Doctrine\ORM\Cache\EntityCacheKey; -use Doctrine\ORM\Cache\EntityCacheEntry; -use Doctrine\ORM\Cache\CollectionCacheKey; -use Doctrine\ORM\Cache\CollectionCacheEntry; -use Doctrine\Common\Collections\ArrayCollection; -use Doctrine\ORM\Cache\DefaultCollectionHydrator; /** * @group DDC-2183 @@ -29,29 +29,33 @@ protected function setUp() $this->enableSecondLevelCache(); parent::setUp(); - $targetPersister = $this->_em->getUnitOfWork()->getEntityPersister(City::CLASSNAME); + $targetPersister = $this->_em->getUnitOfWork()->getEntityPersister(City::class); $this->structure = new DefaultCollectionHydrator($this->_em, $targetPersister); } public function testImplementsCollectionEntryStructure() { - $this->assertInstanceOf('Doctrine\ORM\Cache\DefaultCollectionHydrator', $this->structure); + $this->assertInstanceOf(DefaultCollectionHydrator::class, $this->structure); } public function testLoadCacheCollection() { - $targetRegion = $this->_em->getCache()->getEntityCacheRegion(City::CLASSNAME); - $entry = new CollectionCacheEntry(array( - new EntityCacheKey(City::CLASSNAME, array('id'=>31)), - new EntityCacheKey(City::CLASSNAME, array('id'=>32)), - )); + $targetRegion = $this->_em->getCache()->getEntityCacheRegion(City::class); + $entry = new CollectionCacheEntry( + [ + new EntityCacheKey(City::class, ['id'=>31]), + new EntityCacheKey(City::class, ['id'=>32]), + ] + ); - $targetRegion->put(new EntityCacheKey(City::CLASSNAME, array('id'=>31)), new EntityCacheEntry(City::CLASSNAME, array('id'=>31, 'name'=>'Foo'))); - $targetRegion->put(new EntityCacheKey(City::CLASSNAME, array('id'=>32)), new EntityCacheEntry(City::CLASSNAME, array('id'=>32, 'name'=>'Bar'))); + $targetRegion->put(new EntityCacheKey(City::class, ['id'=>31]), new EntityCacheEntry(City::class, ['id'=>31, 'name'=>'Foo'] + )); + $targetRegion->put(new EntityCacheKey(City::class, ['id'=>32]), new EntityCacheEntry(City::class, ['id'=>32, 'name'=>'Bar'] + )); - $sourceClass = $this->_em->getClassMetadata(State::CLASSNAME); - $targetClass = $this->_em->getClassMetadata(City::CLASSNAME); - $key = new CollectionCacheKey($sourceClass->name, 'cities', array('id'=>21)); + $sourceClass = $this->_em->getClassMetadata(State::class); + $targetClass = $this->_em->getClassMetadata(City::class); + $key = new CollectionCacheKey($sourceClass->name, 'cities', ['id'=>21]); $collection = new PersistentCollection($this->_em, $targetClass, new ArrayCollection()); $list = $this->structure->loadCacheEntry($sourceClass, $key, $entry, $collection); @@ -75,4 +79,4 @@ public function testLoadCacheCollection() $this->assertEquals(UnitOfWork::STATE_MANAGED, $this->_em->getUnitOfWork()->getEntityState($collection[1])); } -} \ No newline at end of file +} diff --git a/tests/Doctrine/Tests/ORM/Cache/DefaultEntityHydratorTest.php b/tests/Doctrine/Tests/ORM/Cache/DefaultEntityHydratorTest.php index 73878ee46d9..d58ab8a0527 100644 --- a/tests/Doctrine/Tests/ORM/Cache/DefaultEntityHydratorTest.php +++ b/tests/Doctrine/Tests/ORM/Cache/DefaultEntityHydratorTest.php @@ -2,15 +2,15 @@ namespace Doctrine\Tests\ORM\Cache; -use Doctrine\Tests\OrmTestCase; -use Doctrine\Tests\Models\Cache\State; -use Doctrine\Tests\Models\Cache\Country; - -use Doctrine\ORM\UnitOfWork; -use Doctrine\ORM\Cache\EntityCacheKey; -use Doctrine\ORM\Cache\EntityCacheEntry; -use Doctrine\ORM\Cache\DefaultEntityHydrator; use Doctrine\ORM\Cache\AssociationCacheEntry; +use Doctrine\ORM\Cache\CacheEntry; +use Doctrine\ORM\Cache\DefaultEntityHydrator; +use Doctrine\ORM\Cache\EntityCacheEntry; +use Doctrine\ORM\Cache\EntityCacheKey; +use Doctrine\ORM\UnitOfWork; +use Doctrine\Tests\Models\Cache\Country; +use Doctrine\Tests\Models\Cache\State; +use Doctrine\Tests\OrmTestCase; /** * @group DDC-2183 @@ -42,9 +42,9 @@ public function testImplementsEntityEntryStructure() public function testCreateEntity() { - $metadata = $this->em->getClassMetadata(Country::CLASSNAME); - $key = new EntityCacheKey($metadata->name, array('id'=>1)); - $entry = new EntityCacheEntry($metadata->name, array('id'=>1, 'name'=>'Foo')); + $metadata = $this->em->getClassMetadata(Country::class); + $key = new EntityCacheKey($metadata->name, ['id'=>1]); + $entry = new EntityCacheEntry($metadata->name, ['id'=>1, 'name'=>'Foo']); $entity = $this->structure->loadCacheEntry($metadata, $key, $entry); $this->assertInstanceOf($metadata->name, $entity); @@ -56,9 +56,9 @@ public function testCreateEntity() public function testLoadProxy() { - $metadata = $this->em->getClassMetadata(Country::CLASSNAME); - $key = new EntityCacheKey($metadata->name, array('id'=>1)); - $entry = new EntityCacheEntry($metadata->name, array('id'=>1, 'name'=>'Foo')); + $metadata = $this->em->getClassMetadata(Country::class); + $key = new EntityCacheKey($metadata->name, ['id'=>1]); + $entry = new EntityCacheEntry($metadata->name, ['id'=>1, 'name'=>'Foo']); $proxy = $this->em->getReference($metadata->name, $key->identifier); $entity = $this->structure->loadCacheEntry($metadata, $key, $entry, $proxy); @@ -74,24 +74,25 @@ public function testBuildCacheEntry() { $entity = new Country('Foo'); $uow = $this->em->getUnitOfWork(); - $data = array('id'=>1, 'name'=>'Foo'); - $metadata = $this->em->getClassMetadata(Country::CLASSNAME); - $key = new EntityCacheKey($metadata->name, array('id'=>1)); + $data = ['id'=>1, 'name'=>'Foo']; + $metadata = $this->em->getClassMetadata(Country::class); + $key = new EntityCacheKey($metadata->name, ['id'=>1]); $entity->setId(1); $uow->registerManaged($entity, $key->identifier, $data); $cache = $this->structure->buildCacheEntry($metadata, $key, $entity); - $this->assertInstanceOf('Doctrine\ORM\Cache\CacheEntry', $cache); - $this->assertInstanceOf('Doctrine\ORM\Cache\EntityCacheEntry', $cache); + $this->assertInstanceOf(CacheEntry::class, $cache); + $this->assertInstanceOf(EntityCacheEntry::class, $cache); $this->assertArrayHasKey('id', $cache->data); $this->assertArrayHasKey('name', $cache->data); - $this->assertEquals(array( + $this->assertEquals( + [ 'id' => 1, 'name' => 'Foo', - ), $cache->data); + ], $cache->data); } public function testBuildCacheEntryAssociation() @@ -99,87 +100,90 @@ public function testBuildCacheEntryAssociation() $country = new Country('Foo'); $state = new State('Bat', $country); $uow = $this->em->getUnitOfWork(); - $countryData = array('id'=>11, 'name'=>'Foo'); - $stateData = array('id'=>12, 'name'=>'Bar', 'country' => $country); - $metadata = $this->em->getClassMetadata(State::CLASSNAME); - $key = new EntityCacheKey($metadata->name, array('id'=>11)); + $countryData = ['id'=>11, 'name'=>'Foo']; + $stateData = ['id'=>12, 'name'=>'Bar', 'country' => $country]; + $metadata = $this->em->getClassMetadata(State::class); + $key = new EntityCacheKey($metadata->name, ['id'=>11]); $country->setId(11); $state->setId(12); - $uow->registerManaged($country, array('id'=>11), $countryData); - $uow->registerManaged($state, array('id'=>12), $stateData); + $uow->registerManaged($country, ['id'=>11], $countryData); + $uow->registerManaged($state, ['id'=>12], $stateData); $cache = $this->structure->buildCacheEntry($metadata, $key, $state); - $this->assertInstanceOf('Doctrine\ORM\Cache\CacheEntry', $cache); - $this->assertInstanceOf('Doctrine\ORM\Cache\EntityCacheEntry', $cache); + $this->assertInstanceOf(CacheEntry::class, $cache); + $this->assertInstanceOf(EntityCacheEntry::class, $cache); $this->assertArrayHasKey('id', $cache->data); $this->assertArrayHasKey('name', $cache->data); $this->assertArrayHasKey('country', $cache->data); - $this->assertEquals(array( + $this->assertEquals( + [ 'id' => 12, 'name' => 'Bar', - 'country' => new AssociationCacheEntry(Country::CLASSNAME, array('id' => 11)), - ), $cache->data); + 'country' => new AssociationCacheEntry(Country::class, ['id' => 11]), + ], $cache->data); } public function testBuildCacheEntryNonInitializedAssocProxy() { - $proxy = $this->em->getReference(Country::CLASSNAME, 11); + $proxy = $this->em->getReference(Country::class, 11); $entity = new State('Bat', $proxy); $uow = $this->em->getUnitOfWork(); - $entityData = array('id'=>12, 'name'=>'Bar', 'country' => $proxy); - $metadata = $this->em->getClassMetadata(State::CLASSNAME); - $key = new EntityCacheKey($metadata->name, array('id'=>11)); + $entityData = ['id'=>12, 'name'=>'Bar', 'country' => $proxy]; + $metadata = $this->em->getClassMetadata(State::class); + $key = new EntityCacheKey($metadata->name, ['id'=>11]); $entity->setId(12); - $uow->registerManaged($entity, array('id'=>12), $entityData); + $uow->registerManaged($entity, ['id'=>12], $entityData); $cache = $this->structure->buildCacheEntry($metadata, $key, $entity); - $this->assertInstanceOf('Doctrine\ORM\Cache\CacheEntry', $cache); - $this->assertInstanceOf('Doctrine\ORM\Cache\EntityCacheEntry', $cache); + $this->assertInstanceOf(CacheEntry::class, $cache); + $this->assertInstanceOf(EntityCacheEntry::class, $cache); $this->assertArrayHasKey('id', $cache->data); $this->assertArrayHasKey('name', $cache->data); $this->assertArrayHasKey('country', $cache->data); - $this->assertEquals(array( + $this->assertEquals( + [ 'id' => 12, 'name' => 'Bar', - 'country' => new AssociationCacheEntry(Country::CLASSNAME, array('id' => 11)), - ), $cache->data); + 'country' => new AssociationCacheEntry(Country::class, ['id' => 11]), + ], $cache->data); } public function testCacheEntryWithWrongIdentifierType() { - $proxy = $this->em->getReference(Country::CLASSNAME, 11); + $proxy = $this->em->getReference(Country::class, 11); $entity = new State('Bat', $proxy); $uow = $this->em->getUnitOfWork(); - $entityData = array('id'=> 12, 'name'=>'Bar', 'country' => $proxy); - $metadata = $this->em->getClassMetadata(State::CLASSNAME); - $key = new EntityCacheKey($metadata->name, array('id'=>'12')); + $entityData = ['id'=> 12, 'name'=>'Bar', 'country' => $proxy]; + $metadata = $this->em->getClassMetadata(State::class); + $key = new EntityCacheKey($metadata->name, ['id'=>'12']); $entity->setId(12); - $uow->registerManaged($entity, array('id'=>12), $entityData); + $uow->registerManaged($entity, ['id'=>12], $entityData); $cache = $this->structure->buildCacheEntry($metadata, $key, $entity); - $this->assertInstanceOf('Doctrine\ORM\Cache\CacheEntry', $cache); - $this->assertInstanceOf('Doctrine\ORM\Cache\EntityCacheEntry', $cache); + $this->assertInstanceOf(CacheEntry::class, $cache); + $this->assertInstanceOf(EntityCacheEntry::class, $cache); $this->assertArrayHasKey('id', $cache->data); $this->assertArrayHasKey('name', $cache->data); $this->assertArrayHasKey('country', $cache->data); $this->assertSame($entity->getId(), $cache->data['id']); - $this->assertEquals(array( + $this->assertEquals( + [ 'id' => 12, 'name' => 'Bar', - 'country' => new AssociationCacheEntry(Country::CLASSNAME, array('id' => 11)), - ), $cache->data); + 'country' => new AssociationCacheEntry(Country::class, ['id' => 11]), + ], $cache->data); } } diff --git a/tests/Doctrine/Tests/ORM/Cache/DefaultQueryCacheTest.php b/tests/Doctrine/Tests/ORM/Cache/DefaultQueryCacheTest.php index b183eaed4dc..ecfcc5207ff 100644 --- a/tests/Doctrine/Tests/ORM/Cache/DefaultQueryCacheTest.php +++ b/tests/Doctrine/Tests/ORM/Cache/DefaultQueryCacheTest.php @@ -2,6 +2,9 @@ namespace Doctrine\Tests\ORM\Cache; +use Doctrine\Common\Collections\Collection; +use Doctrine\ORM\Cache\EntityCacheKey; +use Doctrine\ORM\Cache\QueryCache; use Doctrine\Tests\Mocks\TimestampRegionMock; use Doctrine\Tests\OrmTestCase; use Doctrine\Tests\Mocks\CacheRegionMock; @@ -61,7 +64,7 @@ protected function setUp() public function testImplementQueryCache() { - $this->assertInstanceOf('Doctrine\ORM\Cache\QueryCache', $this->queryCache); + $this->assertInstanceOf(QueryCache::class, $this->queryCache); } public function testGetRegion() @@ -79,12 +82,12 @@ public function testClearShouldEvictRegion() public function testPutBasicQueryResult() { - $result = array(); + $result = []; $key = new QueryCacheKey('query.key1', 0); $rsm = new ResultSetMappingBuilder($this->em); - $metadata = $this->em->getClassMetadata(Country::CLASSNAME); + $metadata = $this->em->getClassMetadata(Country::class); - $rsm->addRootEntityFromClassMetadata(Country::CLASSNAME, 'c'); + $rsm->addRootEntityFromClassMetadata(Country::class, 'c'); for ($i = 0; $i < 4; $i++) { $name = "Country $i"; @@ -92,37 +95,37 @@ public function testPutBasicQueryResult() $result[] = $entity; $metadata->setFieldValue($entity, 'id', $i); - $this->em->getUnitOfWork()->registerManaged($entity, array('id' => $i), array('name' => $name)); + $this->em->getUnitOfWork()->registerManaged($entity, ['id' => $i], ['name' => $name]); } $this->assertTrue($this->queryCache->put($key, $rsm, $result)); $this->assertArrayHasKey('put', $this->region->calls); $this->assertCount(5, $this->region->calls['put']); - $this->assertInstanceOf('Doctrine\ORM\Cache\EntityCacheKey', $this->region->calls['put'][0]['key']); - $this->assertInstanceOf('Doctrine\ORM\Cache\EntityCacheKey', $this->region->calls['put'][1]['key']); - $this->assertInstanceOf('Doctrine\ORM\Cache\EntityCacheKey', $this->region->calls['put'][2]['key']); - $this->assertInstanceOf('Doctrine\ORM\Cache\EntityCacheKey', $this->region->calls['put'][3]['key']); - $this->assertInstanceOf('Doctrine\ORM\Cache\QueryCacheKey', $this->region->calls['put'][4]['key']); - - $this->assertInstanceOf('Doctrine\ORM\Cache\EntityCacheEntry', $this->region->calls['put'][0]['entry']); - $this->assertInstanceOf('Doctrine\ORM\Cache\EntityCacheEntry', $this->region->calls['put'][1]['entry']); - $this->assertInstanceOf('Doctrine\ORM\Cache\EntityCacheEntry', $this->region->calls['put'][2]['entry']); - $this->assertInstanceOf('Doctrine\ORM\Cache\EntityCacheEntry', $this->region->calls['put'][3]['entry']); - $this->assertInstanceOf('Doctrine\ORM\Cache\QueryCacheEntry', $this->region->calls['put'][4]['entry']); + $this->assertInstanceOf(EntityCacheKey::class, $this->region->calls['put'][0]['key']); + $this->assertInstanceOf(EntityCacheKey::class, $this->region->calls['put'][1]['key']); + $this->assertInstanceOf(EntityCacheKey::class, $this->region->calls['put'][2]['key']); + $this->assertInstanceOf(EntityCacheKey::class, $this->region->calls['put'][3]['key']); + $this->assertInstanceOf(QueryCacheKey::class, $this->region->calls['put'][4]['key']); + + $this->assertInstanceOf(EntityCacheEntry::class, $this->region->calls['put'][0]['entry']); + $this->assertInstanceOf(EntityCacheEntry::class, $this->region->calls['put'][1]['entry']); + $this->assertInstanceOf(EntityCacheEntry::class, $this->region->calls['put'][2]['entry']); + $this->assertInstanceOf(EntityCacheEntry::class, $this->region->calls['put'][3]['entry']); + $this->assertInstanceOf(QueryCacheEntry::class, $this->region->calls['put'][4]['entry']); } public function testPutToOneAssociationQueryResult() { - $result = array(); + $result = []; $uow = $this->em->getUnitOfWork(); $key = new QueryCacheKey('query.key1', 0); $rsm = new ResultSetMappingBuilder($this->em); - $cityClass = $this->em->getClassMetadata(City::CLASSNAME); - $stateClass = $this->em->getClassMetadata(State::CLASSNAME); + $cityClass = $this->em->getClassMetadata(City::class); + $stateClass = $this->em->getClassMetadata(State::class); - $rsm->addRootEntityFromClassMetadata(City::CLASSNAME, 'c'); - $rsm->addJoinedEntityFromClassMetadata(State::CLASSNAME, 's', 'c', 'state', array('id'=>'state_id', 'name'=>'state_name')); + $rsm->addRootEntityFromClassMetadata(City::class, 'c'); + $rsm->addJoinedEntityFromClassMetadata(State::class, 's', 'c', 'state', ['id'=>'state_id', 'name'=>'state_name']); for ($i = 0; $i < 4; $i++) { $state = new State("State $i"); @@ -132,38 +135,40 @@ public function testPutToOneAssociationQueryResult() $cityClass->setFieldValue($city, 'id', $i); $stateClass->setFieldValue($state, 'id', $i*2); - $uow->registerManaged($state, array('id' => $state->getId()), array('name' => $city->getName())); - $uow->registerManaged($city, array('id' => $city->getId()), array('name' => $city->getName(), 'state' => $state)); + $uow->registerManaged($state, ['id' => $state->getId()], ['name' => $city->getName()]); + $uow->registerManaged($city, ['id' => $city->getId()], ['name' => $city->getName(), 'state' => $state]); } $this->assertTrue($this->queryCache->put($key, $rsm, $result)); $this->assertArrayHasKey('put', $this->region->calls); $this->assertCount(9, $this->region->calls['put']); - $this->assertInstanceOf('Doctrine\ORM\Cache\EntityCacheKey', $this->region->calls['put'][0]['key']); - $this->assertInstanceOf('Doctrine\ORM\Cache\EntityCacheKey', $this->region->calls['put'][1]['key']); - $this->assertInstanceOf('Doctrine\ORM\Cache\EntityCacheKey', $this->region->calls['put'][2]['key']); - $this->assertInstanceOf('Doctrine\ORM\Cache\EntityCacheKey', $this->region->calls['put'][3]['key']); - $this->assertInstanceOf('Doctrine\ORM\Cache\EntityCacheKey', $this->region->calls['put'][4]['key']); - $this->assertInstanceOf('Doctrine\ORM\Cache\EntityCacheKey', $this->region->calls['put'][5]['key']); - $this->assertInstanceOf('Doctrine\ORM\Cache\EntityCacheKey', $this->region->calls['put'][6]['key']); - $this->assertInstanceOf('Doctrine\ORM\Cache\EntityCacheKey', $this->region->calls['put'][7]['key']); - $this->assertInstanceOf('Doctrine\ORM\Cache\QueryCacheKey', $this->region->calls['put'][8]['key']); + $this->assertInstanceOf(EntityCacheKey::class, $this->region->calls['put'][0]['key']); + $this->assertInstanceOf(EntityCacheKey::class, $this->region->calls['put'][1]['key']); + $this->assertInstanceOf(EntityCacheKey::class, $this->region->calls['put'][2]['key']); + $this->assertInstanceOf(EntityCacheKey::class, $this->region->calls['put'][3]['key']); + $this->assertInstanceOf(EntityCacheKey::class, $this->region->calls['put'][4]['key']); + $this->assertInstanceOf(EntityCacheKey::class, $this->region->calls['put'][5]['key']); + $this->assertInstanceOf(EntityCacheKey::class, $this->region->calls['put'][6]['key']); + $this->assertInstanceOf(EntityCacheKey::class, $this->region->calls['put'][7]['key']); + $this->assertInstanceOf(QueryCacheKey::class, $this->region->calls['put'][8]['key']); } public function testPutToOneAssociation2LevelsQueryResult() { - $result = array(); + $result = []; $uow = $this->em->getUnitOfWork(); $key = new QueryCacheKey('query.key1', 0); $rsm = new ResultSetMappingBuilder($this->em); - $cityClass = $this->em->getClassMetadata(City::CLASSNAME); - $stateClass = $this->em->getClassMetadata(State::CLASSNAME); - $countryClass = $this->em->getClassMetadata(Country::CLASSNAME); + $cityClass = $this->em->getClassMetadata(City::class); + $stateClass = $this->em->getClassMetadata(State::class); + $countryClass = $this->em->getClassMetadata(Country::class); - $rsm->addRootEntityFromClassMetadata(City::CLASSNAME, 'c'); - $rsm->addJoinedEntityFromClassMetadata(State::CLASSNAME, 's', 'c', 'state', array('id'=>'state_id', 'name'=>'state_name')); - $rsm->addJoinedEntityFromClassMetadata(Country::CLASSNAME, 'co', 's', 'country', array('id'=>'country_id', 'name'=>'country_name')); + $rsm->addRootEntityFromClassMetadata(City::class, 'c'); + $rsm->addJoinedEntityFromClassMetadata(State::class, 's', 'c', 'state', ['id'=>'state_id', 'name'=>'state_name'] + ); + $rsm->addJoinedEntityFromClassMetadata(Country::class, 'co', 's', 'country', ['id'=>'country_id', 'name'=>'country_name'] + ); for ($i = 0; $i < 4; $i++) { $country = new Country("Country $i"); @@ -176,40 +181,42 @@ public function testPutToOneAssociation2LevelsQueryResult() $stateClass->setFieldValue($state, 'id', $i*2); $countryClass->setFieldValue($country, 'id', $i*3); - $uow->registerManaged($country, array('id' => $country->getId()), array('name' => $country->getName())); - $uow->registerManaged($state, array('id' => $state->getId()), array('name' => $state->getName(), 'country' => $country)); - $uow->registerManaged($city, array('id' => $city->getId()), array('name' => $city->getName(), 'state' => $state)); + $uow->registerManaged($country, ['id' => $country->getId()], ['name' => $country->getName()]); + $uow->registerManaged($state, ['id' => $state->getId()], ['name' => $state->getName(), 'country' => $country] + ); + $uow->registerManaged($city, ['id' => $city->getId()], ['name' => $city->getName(), 'state' => $state]); } $this->assertTrue($this->queryCache->put($key, $rsm, $result)); $this->assertArrayHasKey('put', $this->region->calls); $this->assertCount(13, $this->region->calls['put']); - $this->assertInstanceOf('Doctrine\ORM\Cache\EntityCacheKey', $this->region->calls['put'][0]['key']); - $this->assertInstanceOf('Doctrine\ORM\Cache\EntityCacheKey', $this->region->calls['put'][1]['key']); - $this->assertInstanceOf('Doctrine\ORM\Cache\EntityCacheKey', $this->region->calls['put'][2]['key']); - $this->assertInstanceOf('Doctrine\ORM\Cache\EntityCacheKey', $this->region->calls['put'][3]['key']); - $this->assertInstanceOf('Doctrine\ORM\Cache\EntityCacheKey', $this->region->calls['put'][4]['key']); - $this->assertInstanceOf('Doctrine\ORM\Cache\EntityCacheKey', $this->region->calls['put'][5]['key']); - $this->assertInstanceOf('Doctrine\ORM\Cache\EntityCacheKey', $this->region->calls['put'][6]['key']); - $this->assertInstanceOf('Doctrine\ORM\Cache\EntityCacheKey', $this->region->calls['put'][7]['key']); - $this->assertInstanceOf('Doctrine\ORM\Cache\EntityCacheKey', $this->region->calls['put'][8]['key']); - $this->assertInstanceOf('Doctrine\ORM\Cache\EntityCacheKey', $this->region->calls['put'][9]['key']); - $this->assertInstanceOf('Doctrine\ORM\Cache\EntityCacheKey', $this->region->calls['put'][10]['key']); - $this->assertInstanceOf('Doctrine\ORM\Cache\EntityCacheKey', $this->region->calls['put'][11]['key']); - $this->assertInstanceOf('Doctrine\ORM\Cache\QueryCacheKey', $this->region->calls['put'][12]['key']); + $this->assertInstanceOf(EntityCacheKey::class, $this->region->calls['put'][0]['key']); + $this->assertInstanceOf(EntityCacheKey::class, $this->region->calls['put'][1]['key']); + $this->assertInstanceOf(EntityCacheKey::class, $this->region->calls['put'][2]['key']); + $this->assertInstanceOf(EntityCacheKey::class, $this->region->calls['put'][3]['key']); + $this->assertInstanceOf(EntityCacheKey::class, $this->region->calls['put'][4]['key']); + $this->assertInstanceOf(EntityCacheKey::class, $this->region->calls['put'][5]['key']); + $this->assertInstanceOf(EntityCacheKey::class, $this->region->calls['put'][6]['key']); + $this->assertInstanceOf(EntityCacheKey::class, $this->region->calls['put'][7]['key']); + $this->assertInstanceOf(EntityCacheKey::class, $this->region->calls['put'][8]['key']); + $this->assertInstanceOf(EntityCacheKey::class, $this->region->calls['put'][9]['key']); + $this->assertInstanceOf(EntityCacheKey::class, $this->region->calls['put'][10]['key']); + $this->assertInstanceOf(EntityCacheKey::class, $this->region->calls['put'][11]['key']); + $this->assertInstanceOf(QueryCacheKey::class, $this->region->calls['put'][12]['key']); } public function testPutToOneAssociationNullQueryResult() { - $result = array(); + $result = []; $uow = $this->em->getUnitOfWork(); $key = new QueryCacheKey('query.key1', 0); $rsm = new ResultSetMappingBuilder($this->em); - $cityClass = $this->em->getClassMetadata(City::CLASSNAME); + $cityClass = $this->em->getClassMetadata(City::class); - $rsm->addRootEntityFromClassMetadata(City::CLASSNAME, 'c'); - $rsm->addJoinedEntityFromClassMetadata(State::CLASSNAME, 's', 'c', 'state', array('id'=>'state_id', 'name'=>'state_name')); + $rsm->addRootEntityFromClassMetadata(City::class, 'c'); + $rsm->addJoinedEntityFromClassMetadata(State::class, 's', 'c', 'state', ['id'=>'state_id', 'name'=>'state_name'] + ); for ($i = 0; $i < 4; $i++) { $city = new City("City $i", null); @@ -217,31 +224,31 @@ public function testPutToOneAssociationNullQueryResult() $cityClass->setFieldValue($city, 'id', $i); - $uow->registerManaged($city, array('id' => $city->getId()), array('name' => $city->getName(), 'state' => null)); + $uow->registerManaged($city, ['id' => $city->getId()], ['name' => $city->getName(), 'state' => null]); } $this->assertTrue($this->queryCache->put($key, $rsm, $result)); $this->assertArrayHasKey('put', $this->region->calls); $this->assertCount(5, $this->region->calls['put']); - $this->assertInstanceOf('Doctrine\ORM\Cache\EntityCacheKey', $this->region->calls['put'][0]['key']); - $this->assertInstanceOf('Doctrine\ORM\Cache\EntityCacheKey', $this->region->calls['put'][1]['key']); - $this->assertInstanceOf('Doctrine\ORM\Cache\EntityCacheKey', $this->region->calls['put'][2]['key']); - $this->assertInstanceOf('Doctrine\ORM\Cache\EntityCacheKey', $this->region->calls['put'][3]['key']); - $this->assertInstanceOf('Doctrine\ORM\Cache\QueryCacheKey', $this->region->calls['put'][4]['key']); + $this->assertInstanceOf(EntityCacheKey::class, $this->region->calls['put'][0]['key']); + $this->assertInstanceOf(EntityCacheKey::class, $this->region->calls['put'][1]['key']); + $this->assertInstanceOf(EntityCacheKey::class, $this->region->calls['put'][2]['key']); + $this->assertInstanceOf(EntityCacheKey::class, $this->region->calls['put'][3]['key']); + $this->assertInstanceOf(QueryCacheKey::class, $this->region->calls['put'][4]['key']); } public function testPutToManyAssociationQueryResult() { - $result = array(); + $result = []; $uow = $this->em->getUnitOfWork(); $key = new QueryCacheKey('query.key1', 0); $rsm = new ResultSetMappingBuilder($this->em); - $cityClass = $this->em->getClassMetadata(City::CLASSNAME); - $stateClass = $this->em->getClassMetadata(State::CLASSNAME); + $cityClass = $this->em->getClassMetadata(City::class); + $stateClass = $this->em->getClassMetadata(State::class); - $rsm->addRootEntityFromClassMetadata(State::CLASSNAME, 's'); - $rsm->addJoinedEntityFromClassMetadata(City::CLASSNAME, 'c', 's', 'cities', array('id'=>'c_id', 'name'=>'c_name')); + $rsm->addRootEntityFromClassMetadata(State::class, 's'); + $rsm->addJoinedEntityFromClassMetadata(City::class, 'c', 's', 'cities', ['id'=>'c_id', 'name'=>'c_name']); for ($i = 0; $i < 4; $i++) { $state = new State("State $i"); @@ -256,9 +263,12 @@ public function testPutToManyAssociationQueryResult() $state->addCity($city1); $state->addCity($city2); - $uow->registerManaged($city1, array('id' => $city1->getId()), array('name' => $city1->getName(), 'state' => $state)); - $uow->registerManaged($city2, array('id' => $city2->getId()), array('name' => $city2->getName(), 'state' => $state)); - $uow->registerManaged($state, array('id' => $state->getId()), array('name' => $state->getName(), 'cities' => $state->getCities())); + $uow->registerManaged($city1, ['id' => $city1->getId()], ['name' => $city1->getName(), 'state' => $state] + ); + $uow->registerManaged($city2, ['id' => $city2->getId()], ['name' => $city2->getName(), 'state' => $state] + ); + $uow->registerManaged($state, ['id' => $state->getId()], ['name' => $state->getName(), 'cities' => $state->getCities()] + ); } $this->assertTrue($this->queryCache->put($key, $rsm, $result)); @@ -270,41 +280,116 @@ public function testGetBasicQueryResult() { $rsm = new ResultSetMappingBuilder($this->em); $key = new QueryCacheKey('query.key1', 0); - $entry = new QueryCacheEntry(array( - array('identifier' => array('id' => 1)), - array('identifier' => array('id' => 2)) - )); - - $data = array( - array('id'=>1, 'name' => 'Foo'), - array('id'=>2, 'name' => 'Bar') + $entry = new QueryCacheEntry( + [ + ['identifier' => ['id' => 1]], + ['identifier' => ['id' => 2]] + ] + ); + + $data = [ + ['id'=>1, 'name' => 'Foo'], + ['id'=>2, 'name' => 'Bar'] + ]; + + $this->region->addReturn('get', $entry); + + $this->region->addReturn( + 'getMultiple', + [ + new EntityCacheEntry(Country::class, $data[0]), + new EntityCacheEntry(Country::class, $data[1]) + ] + ); + + $rsm->addRootEntityFromClassMetadata(Country::class, 'c'); + + $result = $this->queryCache->get($key, $rsm); + + $this->assertCount(2, $result); + $this->assertInstanceOf(Country::class, $result[0]); + $this->assertInstanceOf(Country::class, $result[1]); + $this->assertEquals(1, $result[0]->getId()); + $this->assertEquals(2, $result[1]->getId()); + $this->assertEquals('Foo', $result[0]->getName()); + $this->assertEquals('Bar', $result[1]->getName()); + } + + public function testGetWithAssociation() + { + $rsm = new ResultSetMappingBuilder($this->em); + $key = new QueryCacheKey('query.key1', 0); + $entry = new QueryCacheEntry( + [ + ['identifier' => ['id' => 1]], + ['identifier' => ['id' => 2]] + ] ); + $data = [ + ['id'=>1, 'name' => 'Foo'], + ['id'=>2, 'name' => 'Bar'] + ]; + $this->region->addReturn('get', $entry); - $this->region->addReturn('get', new EntityCacheEntry(Country::CLASSNAME, $data[0])); - $this->region->addReturn('get', new EntityCacheEntry(Country::CLASSNAME, $data[1])); - $rsm->addRootEntityFromClassMetadata(Country::CLASSNAME, 'c'); + $this->region->addReturn( + 'getMultiple', + [ + new EntityCacheEntry(Country::class, $data[0]), + new EntityCacheEntry(Country::class, $data[1]) + ] + ); + + $rsm->addRootEntityFromClassMetadata(Country::class, 'c'); $result = $this->queryCache->get($key, $rsm); $this->assertCount(2, $result); - $this->assertInstanceOf(Country::CLASSNAME, $result[0]); - $this->assertInstanceOf(Country::CLASSNAME, $result[1]); + $this->assertInstanceOf(Country::class, $result[0]); + $this->assertInstanceOf(Country::class, $result[1]); $this->assertEquals(1, $result[0]->getId()); $this->assertEquals(2, $result[1]->getId()); $this->assertEquals('Foo', $result[0]->getName()); $this->assertEquals('Bar', $result[1]->getName()); } + public function testGetWithAssociationCacheMiss() : void + { + $rsm = new ResultSetMappingBuilder($this->em); + $key = new QueryCacheKey('query.key1', 0); + $entry = new QueryCacheEntry( + [ + ['identifier' => ['id' => 1]], + ['identifier' => ['id' => 2]], + ] + ); + + $this->region->addReturn('get', $entry); + + $this->region->addReturn( + 'getMultiple', + [ + new EntityCacheEntry(Country::class, ['id' => 1, 'name' => 'Foo']), + false, + ] + ); + + $rsm->addRootEntityFromClassMetadata(Country::class, 'c'); + + $result = $this->queryCache->get($key, $rsm); + + self::assertNull($result); + } + public function testCancelPutResultIfEntityPutFails() { - $result = array(); + $result = []; $key = new QueryCacheKey('query.key1', 0); $rsm = new ResultSetMappingBuilder($this->em); - $metadata = $this->em->getClassMetadata(Country::CLASSNAME); + $metadata = $this->em->getClassMetadata(Country::class); - $rsm->addRootEntityFromClassMetadata(Country::CLASSNAME, 'c'); + $rsm->addRootEntityFromClassMetadata(Country::class, 'c'); for ($i = 0; $i < 4; $i++) { $name = "Country $i"; @@ -312,7 +397,7 @@ public function testCancelPutResultIfEntityPutFails() $result[] = $entity; $metadata->setFieldValue($entity, 'id', $i); - $this->em->getUnitOfWork()->registerManaged($entity, array('id' => $i), array('name' => $name)); + $this->em->getUnitOfWork()->registerManaged($entity, ['id' => $i], ['name' => $name]); } $this->region->addReturn('put', false); @@ -324,15 +409,16 @@ public function testCancelPutResultIfEntityPutFails() public function testCancelPutResultIfAssociationEntityPutFails() { - $result = array(); + $result = []; $uow = $this->em->getUnitOfWork(); $key = new QueryCacheKey('query.key1', 0); $rsm = new ResultSetMappingBuilder($this->em); - $cityClass = $this->em->getClassMetadata(City::CLASSNAME); - $stateClass = $this->em->getClassMetadata(State::CLASSNAME); + $cityClass = $this->em->getClassMetadata(City::class); + $stateClass = $this->em->getClassMetadata(State::class); - $rsm->addRootEntityFromClassMetadata(City::CLASSNAME, 'c'); - $rsm->addJoinedEntityFromClassMetadata(State::CLASSNAME, 's', 'c', 'state', array('id'=>'state_id', 'name'=>'state_name')); + $rsm->addRootEntityFromClassMetadata(City::class, 'c'); + $rsm->addJoinedEntityFromClassMetadata(State::class, 's', 'c', 'state', ['id'=>'state_id', 'name'=>'state_name'] + ); $state = new State("State 1"); $city = new City("City 2", $state); @@ -341,8 +427,8 @@ public function testCancelPutResultIfAssociationEntityPutFails() $cityClass->setFieldValue($city, 'id', 1); $stateClass->setFieldValue($state, 'id', 11); - $uow->registerManaged($state, array('id' => $state->getId()), array('name' => $city->getName())); - $uow->registerManaged($city, array('id' => $city->getId()), array('name' => $city->getName(), 'state' => $state)); + $uow->registerManaged($state, ['id' => $state->getId()], ['name' => $city->getName()]); + $uow->registerManaged($city, ['id' => $city->getId()], ['name' => $city->getName(), 'state' => $state]); $this->region->addReturn('put', true); // put root entity $this->region->addReturn('put', false); // association fails @@ -352,15 +438,15 @@ public function testCancelPutResultIfAssociationEntityPutFails() public function testCancelPutToManyAssociationQueryResult() { - $result = array(); + $result = []; $uow = $this->em->getUnitOfWork(); $key = new QueryCacheKey('query.key1', 0); $rsm = new ResultSetMappingBuilder($this->em); - $cityClass = $this->em->getClassMetadata(City::CLASSNAME); - $stateClass = $this->em->getClassMetadata(State::CLASSNAME); + $cityClass = $this->em->getClassMetadata(City::class); + $stateClass = $this->em->getClassMetadata(State::class); - $rsm->addRootEntityFromClassMetadata(State::CLASSNAME, 's'); - $rsm->addJoinedEntityFromClassMetadata(City::CLASSNAME, 'c', 's', 'cities', array('id'=>'c_id', 'name'=>'c_name')); + $rsm->addRootEntityFromClassMetadata(State::class, 's'); + $rsm->addJoinedEntityFromClassMetadata(City::class, 'c', 's', 'cities', ['id'=>'c_id', 'name'=>'c_name']); $state = new State("State"); $city1 = new City("City 1", $state); @@ -374,9 +460,10 @@ public function testCancelPutToManyAssociationQueryResult() $state->addCity($city1); $state->addCity($city2); - $uow->registerManaged($city1, array('id' => $city1->getId()), array('name' => $city1->getName(), 'state' => $state)); - $uow->registerManaged($city2, array('id' => $city2->getId()), array('name' => $city2->getName(), 'state' => $state)); - $uow->registerManaged($state, array('id' => $state->getId()), array('name' => $state->getName(), 'cities' => $state->getCities())); + $uow->registerManaged($city1, ['id' => $city1->getId()], ['name' => $city1->getName(), 'state' => $state]); + $uow->registerManaged($city2, ['id' => $city2->getId()], ['name' => $city2->getName(), 'state' => $state]); + $uow->registerManaged($state, ['id' => $state->getId()], ['name' => $state->getName(), 'cities' => $state->getCities()] + ); $this->region->addReturn('put', true); // put root entity $this->region->addReturn('put', false); // collection association fails @@ -390,12 +477,14 @@ public function testIgnoreCacheNonGetMode() { $rsm = new ResultSetMappingBuilder($this->em); $key = new QueryCacheKey('query.key1', 0, Cache::MODE_PUT); - $entry = new QueryCacheEntry(array( - array('identifier' => array('id' => 1)), - array('identifier' => array('id' => 2)) - )); + $entry = new QueryCacheEntry( + [ + ['identifier' => ['id' => 1]], + ['identifier' => ['id' => 2]] + ] + ); - $rsm->addRootEntityFromClassMetadata(Country::CLASSNAME, 'c'); + $rsm->addRootEntityFromClassMetadata(Country::class, 'c'); $this->region->addReturn('get', $entry); @@ -404,12 +493,12 @@ public function testIgnoreCacheNonGetMode() public function testIgnoreCacheNonPutMode() { - $result = array(); + $result = []; $rsm = new ResultSetMappingBuilder($this->em); - $metadata = $this->em->getClassMetadata(Country::CLASSNAME); + $metadata = $this->em->getClassMetadata(Country::class); $key = new QueryCacheKey('query.key1', 0, Cache::MODE_GET); - $rsm->addRootEntityFromClassMetadata(Country::CLASSNAME, 'c'); + $rsm->addRootEntityFromClassMetadata(Country::class, 'c'); for ($i = 0; $i < 4; $i++) { $name = "Country $i"; @@ -417,7 +506,7 @@ public function testIgnoreCacheNonPutMode() $result[] = $entity; $metadata->setFieldValue($entity, 'id', $i); - $this->em->getUnitOfWork()->registerManaged($entity, array('id' => $i), array('name' => $name)); + $this->em->getUnitOfWork()->registerManaged($entity, ['id' => $i], ['name' => $name]); } $this->assertFalse($this->queryCache->put($key, $rsm, $result)); @@ -427,22 +516,30 @@ public function testGetShouldIgnoreOldQueryCacheEntryResult() { $rsm = new ResultSetMappingBuilder($this->em); $key = new QueryCacheKey('query.key1', 50); - $entry = new QueryCacheEntry(array( - array('identifier' => array('id' => 1)), - array('identifier' => array('id' => 2)) - )); - $entities = array( - array('id'=>1, 'name' => 'Foo'), - array('id'=>2, 'name' => 'Bar') + $entry = new QueryCacheEntry( + [ + ['identifier' => ['id' => 1]], + ['identifier' => ['id' => 2]] + ] ); + $entities = [ + ['id'=>1, 'name' => 'Foo'], + ['id'=>2, 'name' => 'Bar'] + ]; - $entry->time = time() - 100; + $entry->time = microtime(true) - 100; $this->region->addReturn('get', $entry); - $this->region->addReturn('get', new EntityCacheEntry(Country::CLASSNAME, $entities[0])); - $this->region->addReturn('get', new EntityCacheEntry(Country::CLASSNAME, $entities[1])); - $rsm->addRootEntityFromClassMetadata(Country::CLASSNAME, 'c'); + $this->region->addReturn( + 'getMultiple', + [ + new EntityCacheEntry(Country::class, $entities[0]), + new EntityCacheEntry(Country::class, $entities[1]) + ] + ); + + $rsm->addRootEntityFromClassMetadata(Country::class, 'c'); $this->assertNull($this->queryCache->get($key, $rsm)); } @@ -451,21 +548,29 @@ public function testGetShouldIgnoreNonQueryCacheEntryResult() { $rsm = new ResultSetMappingBuilder($this->em); $key = new QueryCacheKey('query.key1', 0); - $entry = new \ArrayObject(array( - array('identifier' => array('id' => 1)), - array('identifier' => array('id' => 2)) - )); - - $data = array( - array('id'=>1, 'name' => 'Foo'), - array('id'=>2, 'name' => 'Bar') + $entry = new \ArrayObject( + [ + ['identifier' => ['id' => 1]], + ['identifier' => ['id' => 2]] + ] ); + $data = [ + ['id'=>1, 'name' => 'Foo'], + ['id'=>2, 'name' => 'Bar'] + ]; + $this->region->addReturn('get', $entry); - $this->region->addReturn('get', new EntityCacheEntry(Country::CLASSNAME, $data[0])); - $this->region->addReturn('get', new EntityCacheEntry(Country::CLASSNAME, $data[1])); - $rsm->addRootEntityFromClassMetadata(Country::CLASSNAME, 'c'); + $this->region->addReturn( + 'getMultiple', + [ + new EntityCacheEntry(Country::class, $data[0]), + new EntityCacheEntry(Country::class, $data[1]) + ] + ); + + $rsm->addRootEntityFromClassMetadata(Country::class, 'c'); $this->assertNull($this->queryCache->get($key, $rsm)); } @@ -474,15 +579,17 @@ public function testGetShouldIgnoreMissingEntityQueryCacheEntry() { $rsm = new ResultSetMappingBuilder($this->em); $key = new QueryCacheKey('query.key1', 0); - $entry = new QueryCacheEntry(array( - array('identifier' => array('id' => 1)), - array('identifier' => array('id' => 2)) - )); + $entry = new QueryCacheEntry( + [ + ['identifier' => ['id' => 1]], + ['identifier' => ['id' => 2]] + ] + ); $this->region->addReturn('get', $entry); - $this->region->addReturn('get', null); + $this->region->addReturn('getMultiple', [null]); - $rsm->addRootEntityFromClassMetadata(Country::CLASSNAME, 'c'); + $rsm->addRootEntityFromClassMetadata(Country::class, 'c'); $this->assertNull($this->queryCache->get($key, $rsm)); } @@ -507,15 +614,17 @@ public function testGetAssociationValue() $munich->addAttraction(new Restaurant('Schneider Weisse', $munich)); $wurzburg->addAttraction(new Restaurant('Fischers Fritz', $wurzburg)); - $rsm->addRootEntityFromClassMetadata(State::CLASSNAME, 's'); - $rsm->addJoinedEntityFromClassMetadata(City::CLASSNAME, 'c', 's', 'cities', array( + $rsm->addRootEntityFromClassMetadata(State::class, 's'); + $rsm->addJoinedEntityFromClassMetadata(City::class, 'c', 's', 'cities', [ 'id' => 'c_id', 'name' => 'c_name' - )); - $rsm->addJoinedEntityFromClassMetadata(Restaurant::CLASSNAME, 'a', 'c', 'attractions', array( + ] + ); + $rsm->addJoinedEntityFromClassMetadata(Restaurant::class, 'a', 'c', 'attractions', [ 'id' => 'a_id', 'name' => 'a_name' - )); + ] + ); $cities = $reflection->invoke($this->queryCache, $rsm, 'c', $bavaria); $attractions = $reflection->invoke($this->queryCache, $rsm, 'a', $bavaria); @@ -523,9 +632,9 @@ public function testGetAssociationValue() $this->assertCount(2, $cities); $this->assertCount(2, $attractions); - $this->assertInstanceOf('Doctrine\Common\Collections\Collection', $cities); - $this->assertInstanceOf('Doctrine\Common\Collections\Collection', $attractions[0]); - $this->assertInstanceOf('Doctrine\Common\Collections\Collection', $attractions[1]); + $this->assertInstanceOf(Collection::class, $cities); + $this->assertInstanceOf(Collection::class, $attractions[0]); + $this->assertInstanceOf(Collection::class, $attractions[1]); $this->assertCount(2, $attractions[0]); $this->assertCount(1, $attractions[1]); @@ -537,7 +646,7 @@ public function testGetAssociationValue() */ public function testScalarResultException() { - $result = array(); + $result = []; $key = new QueryCacheKey('query.key1', 0); $rsm = new ResultSetMappingBuilder($this->em); @@ -552,12 +661,12 @@ public function testScalarResultException() */ public function testSupportMultipleRootEntitiesException() { - $result = array(); + $result = []; $key = new QueryCacheKey('query.key1', 0); $rsm = new ResultSetMappingBuilder($this->em); - $rsm->addEntityResult('Doctrine\Tests\Models\Cache\City', 'e1'); - $rsm->addEntityResult('Doctrine\Tests\Models\Cache\State', 'e2'); + $rsm->addEntityResult(City::class, 'e1'); + $rsm->addEntityResult(State::class, 'e2'); $this->queryCache->put($key, $rsm, $result); } @@ -568,12 +677,10 @@ public function testSupportMultipleRootEntitiesException() */ public function testNotCacheableEntityException() { - $result = array(); + $result = []; $key = new QueryCacheKey('query.key1', 0); $rsm = new ResultSetMappingBuilder($this->em); - $className = 'Doctrine\Tests\Models\Generic\BooleanModel'; - - $rsm->addRootEntityFromClassMetadata($className, 'c'); + $rsm->addRootEntityFromClassMetadata(BooleanModel::class, 'c'); for ($i = 0; $i < 4; $i++) { $entity = new BooleanModel(); @@ -583,7 +690,7 @@ public function testNotCacheableEntityException() $entity->booleanField = $boolean; $result[] = $entity; - $this->em->getUnitOfWork()->registerManaged($entity, array('id' => $i), array('booleanField' => $boolean)); + $this->em->getUnitOfWork()->registerManaged($entity, ['id' => $i], ['booleanField' => $boolean]); } $this->assertFalse($this->queryCache->put($key, $rsm, $result)); diff --git a/tests/Doctrine/Tests/ORM/Cache/DefaultRegionTest.php b/tests/Doctrine/Tests/ORM/Cache/DefaultRegionTest.php index 2bcc1fc21f2..e50c2a55c3d 100644 --- a/tests/Doctrine/Tests/ORM/Cache/DefaultRegionTest.php +++ b/tests/Doctrine/Tests/ORM/Cache/DefaultRegionTest.php @@ -2,9 +2,9 @@ namespace Doctrine\Tests\ORM\Cache; -use Doctrine\Common\Cache\ApcCache; use Doctrine\Common\Cache\ArrayCache; use Doctrine\Common\Cache\Cache; +use Doctrine\Common\Cache\CacheProvider; use Doctrine\ORM\Cache\CollectionCacheEntry; use Doctrine\ORM\Cache\Region\DefaultRegion; use Doctrine\Tests\Mocks\CacheEntryMock; @@ -28,14 +28,11 @@ public function testGetters() public function testSharedRegion() { - if ( ! extension_loaded('apc') || false === @apc_cache_info()) { - $this->markTestSkipped('The ' . __CLASS__ .' requires the use of APC'); - } - + $cache = new SharedArrayCache(); $key = new CacheKeyMock('key'); - $entry = new CacheEntryMock(array('value' => 'foo')); - $region1 = new DefaultRegion('region1', new ApcCache()); - $region2 = new DefaultRegion('region2', new ApcCache()); + $entry = new CacheEntryMock(['value' => 'foo']); + $region1 = new DefaultRegion('region1', $cache->createChild()); + $region2 = new DefaultRegion('region2', $cache->createChild()); $this->assertFalse($region1->contains($key)); $this->assertFalse($region2->contains($key)); @@ -79,10 +76,10 @@ public function testEvictAllWithGenericCacheThrowsUnsupportedException() public function testGetMulti() { $key1 = new CacheKeyMock('key.1'); - $value1 = new CacheEntryMock(array('id' => 1, 'name' => 'bar')); + $value1 = new CacheEntryMock(['id' => 1, 'name' => 'bar']); $key2 = new CacheKeyMock('key.2'); - $value2 = new CacheEntryMock(array('id' => 2, 'name' => 'bar')); + $value2 = new CacheEntryMock(['id' => 2, 'name' => 'bar']); $this->assertFalse($this->region->contains($key1)); $this->assertFalse($this->region->contains($key2)); @@ -93,9 +90,92 @@ public function testGetMulti() $this->assertTrue($this->region->contains($key1)); $this->assertTrue($this->region->contains($key2)); - $actual = $this->region->getMultiple(new CollectionCacheEntry(array($key1, $key2))); + $actual = $this->region->getMultiple(new CollectionCacheEntry([$key1, $key2])); $this->assertEquals($value1, $actual[0]); $this->assertEquals($value2, $actual[1]); } -} \ No newline at end of file + + /** + * @test + * @group GH7266 + */ + public function corruptedDataDoesNotLeakIntoApplicationWhenGettingSingleEntry() : void + { + $key1 = new CacheKeyMock('key.1'); + $this->cache->save($this->region->getName() . '_' . $key1->hash, 'a-very-invalid-value'); + + self::assertTrue($this->region->contains($key1)); + self::assertNull($this->region->get($key1)); + } + + /** + * @test + * @group GH7266 + */ + public function corruptedDataDoesNotLeakIntoApplicationWhenGettingMultipleEntries() : void + { + $key1 = new CacheKeyMock('key.1'); + $this->cache->save($this->region->getName() . '_' . $key1->hash, 'a-very-invalid-value'); + + self::assertTrue($this->region->contains($key1)); + self::assertNull($this->region->getMultiple(new CollectionCacheEntry([$key1]))); + } +} + +/** + * Cache provider that offers child cache items (sharing the same array) + * + * Declared as a different class for readability purposes and kept in this file + * to keep its monstrosity contained. + * + * @internal + */ +final class SharedArrayCache extends ArrayCache +{ + public function createChild(): Cache + { + return new class ($this) extends CacheProvider + { + /** + * @var ArrayCache + */ + private $parent; + + public function __construct(ArrayCache $parent) + { + $this->parent = $parent; + } + + protected function doFetch($id) + { + return $this->parent->doFetch($id); + } + + protected function doContains($id) + { + return $this->parent->doContains($id); + } + + protected function doSave($id, $data, $lifeTime = 0) + { + return $this->parent->doSave($id, $data, $lifeTime); + } + + protected function doDelete($id) + { + return $this->parent->doDelete($id); + } + + protected function doFlush() + { + return $this->parent->doFlush(); + } + + protected function doGetStats() + { + return $this->parent->doGetStats(); + } + }; + } +} diff --git a/tests/Doctrine/Tests/ORM/Cache/FileLockRegionTest.php b/tests/Doctrine/Tests/ORM/Cache/FileLockRegionTest.php index 6fdef6feafb..1162f3c6aa6 100644 --- a/tests/Doctrine/Tests/ORM/Cache/FileLockRegionTest.php +++ b/tests/Doctrine/Tests/ORM/Cache/FileLockRegionTest.php @@ -2,15 +2,15 @@ namespace Doctrine\Tests\ORM\Cache; +use Doctrine\ORM\Cache\CacheKey; +use Doctrine\ORM\Cache\ConcurrentRegion; +use Doctrine\ORM\Cache\Lock; use Doctrine\ORM\Cache\Region\DefaultRegion; use Doctrine\ORM\Cache\Region\FileLockRegion; -use Doctrine\ORM\Cache\ConcurrentRegion; use Doctrine\Tests\Mocks\CacheEntryMock; use Doctrine\Tests\Mocks\CacheKeyMock; -use Doctrine\ORM\Cache\CacheKey; - -use RecursiveIteratorIterator; use RecursiveDirectoryIterator; +use RecursiveIteratorIterator; /** * @group DDC-2183 @@ -21,7 +21,7 @@ class FileLockRegionTest extends AbstractRegionTest * @var \Doctrine\ORM\Cache\ConcurrentRegion */ protected $region; - + /** * @var string */ @@ -67,7 +67,7 @@ public function testGetRegionName() public function testLockAndUnlock() { $key = new CacheKeyMock('key'); - $entry = new CacheEntryMock(array('foo' => 'bar')); + $entry = new CacheEntryMock(['foo' => 'bar']); $file = $this->getFileName($this->region, $key); $this->assertFalse($this->region->contains($key)); @@ -77,7 +77,7 @@ public function testLockAndUnlock() $lock = $this->region->lock($key); $this->assertFileExists($file); - $this->assertInstanceOf('Doctrine\ORM\Cache\Lock', $lock); + $this->assertInstanceOf(Lock::class, $lock); $this->assertEquals($lock->value, file_get_contents($file)); // should be not available after lock @@ -91,7 +91,7 @@ public function testLockAndUnlock() public function testLockWithExistingLock() { $key = new CacheKeyMock('key'); - $entry = new CacheEntryMock(array('foo' => 'bar')); + $entry = new CacheEntryMock(['foo' => 'bar']); $file = $this->getFileName($this->region, $key); $this->assertFalse($this->region->contains($key)); @@ -114,14 +114,14 @@ public function testLockWithExistingLock() public function testUnlockWithExistingLock() { $key = new CacheKeyMock('key'); - $entry = new CacheEntryMock(array('foo' => 'bar')); + $entry = new CacheEntryMock(['foo' => 'bar']); $file = $this->getFileName($this->region, $key); $this->assertFalse($this->region->contains($key)); $this->assertTrue($this->region->put($key, $entry)); $this->assertTrue($this->region->contains($key)); - $this->assertInstanceOf('Doctrine\ORM\Cache\Lock', $lock = $this->region->lock($key)); + $this->assertInstanceOf(Lock::class, $lock = $this->region->lock($key)); $this->assertEquals($lock->value, file_get_contents($file)); $this->assertFileExists($file); @@ -143,7 +143,7 @@ public function testUnlockWithExistingLock() public function testPutWithExistingLock() { $key = new CacheKeyMock('key'); - $entry = new CacheEntryMock(array('foo' => 'bar')); + $entry = new CacheEntryMock(['foo' => 'bar']); $file = $this->getFileName($this->region, $key); $this->assertFalse($this->region->contains($key)); @@ -166,14 +166,14 @@ public function testPutWithExistingLock() public function testLockedEvict() { $key = new CacheKeyMock('key'); - $entry = new CacheEntryMock(array('foo' => 'bar')); + $entry = new CacheEntryMock(['foo' => 'bar']); $file = $this->getFileName($this->region, $key); $this->assertFalse($this->region->contains($key)); $this->assertTrue($this->region->put($key, $entry)); $this->assertTrue($this->region->contains($key)); - $this->assertInstanceOf('Doctrine\ORM\Cache\Lock', $lock = $this->region->lock($key)); + $this->assertInstanceOf(Lock::class, $lock = $this->region->lock($key)); $this->assertEquals($lock->value, file_get_contents($file)); $this->assertFileExists($file); @@ -186,11 +186,11 @@ public function testLockedEvict() public function testLockedEvictAll() { $key1 = new CacheKeyMock('key1'); - $entry1 = new CacheEntryMock(array('foo1' => 'bar1')); + $entry1 = new CacheEntryMock(['foo1' => 'bar1']); $file1 = $this->getFileName($this->region, $key1); $key2 = new CacheKeyMock('key2'); - $entry2 = new CacheEntryMock(array('foo2' => 'bar2')); + $entry2 = new CacheEntryMock(['foo2' => 'bar2']); $file2 = $this->getFileName($this->region, $key2); $this->assertFalse($this->region->contains($key1)); @@ -201,8 +201,8 @@ public function testLockedEvictAll() $this->assertTrue($this->region->put($key2, $entry2)); $this->assertTrue($this->region->contains($key2)); - $this->assertInstanceOf('Doctrine\ORM\Cache\Lock', $lock1 = $this->region->lock($key1)); - $this->assertInstanceOf('Doctrine\ORM\Cache\Lock', $lock2 = $this->region->lock($key2)); + $this->assertInstanceOf(Lock::class, $lock1 = $this->region->lock($key1)); + $this->assertInstanceOf(Lock::class, $lock2 = $this->region->lock($key2)); $this->assertEquals($lock2->value, file_get_contents($file2)); $this->assertEquals($lock1->value, file_get_contents($file1)); @@ -222,7 +222,7 @@ public function testLockedEvictAll() public function testLockLifetime() { $key = new CacheKeyMock('key'); - $entry = new CacheEntryMock(array('foo' => 'bar')); + $entry = new CacheEntryMock(['foo' => 'bar']); $file = $this->getFileName($this->region, $key); $property = new \ReflectionProperty($this->region, 'lockLifetime'); @@ -233,7 +233,7 @@ public function testLockLifetime() $this->assertTrue($this->region->put($key, $entry)); $this->assertTrue($this->region->contains($key)); - $this->assertInstanceOf('Doctrine\ORM\Cache\Lock', $lock = $this->region->lock($key)); + $this->assertInstanceOf(Lock::class, $lock = $this->region->lock($key)); $this->assertEquals($lock->value, file_get_contents($file)); $this->assertFileExists($file); diff --git a/tests/Doctrine/Tests/ORM/Cache/MultiGetRegionTest.php b/tests/Doctrine/Tests/ORM/Cache/MultiGetRegionTest.php index 65d21b93fbe..5f45de47148 100644 --- a/tests/Doctrine/Tests/ORM/Cache/MultiGetRegionTest.php +++ b/tests/Doctrine/Tests/ORM/Cache/MultiGetRegionTest.php @@ -20,10 +20,10 @@ protected function createRegion() public function testGetMulti() { $key1 = new CacheKeyMock('key.1'); - $value1 = new CacheEntryMock(array('id' => 1, 'name' => 'bar')); + $value1 = new CacheEntryMock(['id' => 1, 'name' => 'bar']); $key2 = new CacheKeyMock('key.2'); - $value2 = new CacheEntryMock(array('id' => 2, 'name' => 'bar')); + $value2 = new CacheEntryMock(['id' => 2, 'name' => 'bar']); $this->assertFalse($this->region->contains($key1)); $this->assertFalse($this->region->contains($key2)); @@ -34,9 +34,22 @@ public function testGetMulti() $this->assertTrue($this->region->contains($key1)); $this->assertTrue($this->region->contains($key2)); - $actual = $this->region->getMultiple(new CollectionCacheEntry(array($key1, $key2))); + $actual = $this->region->getMultiple(new CollectionCacheEntry([$key1, $key2])); $this->assertEquals($value1, $actual[0]); $this->assertEquals($value2, $actual[1]); } + + /** + * @test + * @group GH7266 + */ + public function corruptedDataDoesNotLeakIntoApplication() : void + { + $key1 = new CacheKeyMock('key.1'); + $this->cache->save($this->region->getName() . '_' . $key1->hash, 'a-very-invalid-value'); + + self::assertTrue($this->region->contains($key1)); + self::assertNull($this->region->getMultiple(new CollectionCacheEntry([$key1]))); + } } diff --git a/tests/Doctrine/Tests/ORM/Cache/Persister/Collection/AbstractCollectionPersisterTest.php b/tests/Doctrine/Tests/ORM/Cache/Persister/Collection/AbstractCollectionPersisterTest.php index adc8ec0ba8a..c950cea70df 100644 --- a/tests/Doctrine/Tests/ORM/Cache/Persister/Collection/AbstractCollectionPersisterTest.php +++ b/tests/Doctrine/Tests/ORM/Cache/Persister/Collection/AbstractCollectionPersisterTest.php @@ -2,6 +2,8 @@ namespace Doctrine\Tests\ORM\Cache\Persister\Collection; +use Doctrine\ORM\Cache\Persister\CachedPersister; +use Doctrine\ORM\Cache\Persister\Collection\CachedCollectionPersister; use Doctrine\ORM\PersistentCollection; use Doctrine\Tests\OrmTestCase; @@ -35,7 +37,7 @@ abstract class AbstractCollectionPersisterTest extends OrmTestCase /** * @var array */ - protected $regionMockMethods = array( + protected $regionMockMethods = [ 'getName', 'contains', 'get', @@ -43,12 +45,12 @@ abstract class AbstractCollectionPersisterTest extends OrmTestCase 'put', 'evict', 'evictAll' - ); + ]; /** * @var array */ - protected $collectionPersisterMockMethods = array( + protected $collectionPersisterMockMethods = [ 'delete', 'update', 'count', @@ -60,7 +62,7 @@ abstract class AbstractCollectionPersisterTest extends OrmTestCase 'get', 'getMultiple', 'loadCriteria' - ); + ]; /** * @param \Doctrine\ORM\EntityManager $em @@ -101,7 +103,7 @@ protected function createRegion() protected function createCollection($owner, $assoc = null, $class = null, $elements = null) { $em = $this->em; - $class = $class ?: $this->em->getClassMetadata('Doctrine\Tests\Models\Cache\State'); + $class = $class ?: $this->em->getClassMetadata(State::class); $assoc = $assoc ?: $class->associationMappings['cities']; $coll = new PersistentCollection($em, $class, $elements ?: new ArrayCollection); @@ -113,7 +115,7 @@ protected function createCollection($owner, $assoc = null, $class = null, $eleme protected function createPersisterDefault() { - $assoc = $this->em->getClassMetadata('Doctrine\Tests\Models\Cache\State')->associationMappings['cities']; + $assoc = $this->em->getClassMetadata(State::class)->associationMappings['cities']; return $this->createPersister($this->em, $this->collectionPersister, $this->region, $assoc); } @@ -122,9 +124,9 @@ public function testImplementsEntityPersister() { $persister = $this->createPersisterDefault(); - $this->assertInstanceOf('Doctrine\ORM\Persisters\Collection\CollectionPersister', $persister); - $this->assertInstanceOf('Doctrine\ORM\Cache\Persister\CachedPersister', $persister); - $this->assertInstanceOf('Doctrine\ORM\Cache\Persister\Collection\CachedCollectionPersister', $persister); + $this->assertInstanceOf(CollectionPersister::class, $persister); + $this->assertInstanceOf(CachedPersister::class, $persister); + $this->assertInstanceOf(CachedCollectionPersister::class, $persister); } public function testInvokeDelete() @@ -133,7 +135,7 @@ public function testInvokeDelete() $persister = $this->createPersisterDefault(); $collection = $this->createCollection($entity); - $this->em->getUnitOfWork()->registerManaged($entity, array('id'=>1), array('id'=>1, 'name'=>'Foo')); + $this->em->getUnitOfWork()->registerManaged($entity, ['id'=>1], ['id'=>1, 'name'=>'Foo']); $this->collectionPersister->expects($this->once()) ->method('delete') @@ -150,7 +152,7 @@ public function testInvokeUpdate() $collection->setDirty(true); - $this->em->getUnitOfWork()->registerManaged($entity, array('id'=>1), array('id'=>1, 'name'=>'Foo')); + $this->em->getUnitOfWork()->registerManaged($entity, ['id'=>1], ['id'=>1, 'name'=>'Foo']); $this->collectionPersister->expects($this->once()) ->method('update') @@ -165,7 +167,7 @@ public function testInvokeCount() $persister = $this->createPersisterDefault(); $collection = $this->createCollection($entity); - $this->em->getUnitOfWork()->registerManaged($entity, array('id'=>1), array('id'=>1, 'name'=>'Foo')); + $this->em->getUnitOfWork()->registerManaged($entity, ['id'=>1], ['id'=>1, 'name'=>'Foo']); $this->collectionPersister->expects($this->once()) ->method('count') @@ -182,7 +184,7 @@ public function testInvokeSlice() $collection = $this->createCollection($entity); $slice = $this->createCollection($entity); - $this->em->getUnitOfWork()->registerManaged($entity, array('id'=>1), array('id'=>1, 'name'=>'Foo')); + $this->em->getUnitOfWork()->registerManaged($entity, ['id'=>1], ['id'=>1, 'name'=>'Foo']); $this->collectionPersister->expects($this->once()) ->method('slice') @@ -199,7 +201,7 @@ public function testInvokeContains() $persister = $this->createPersisterDefault(); $collection = $this->createCollection($entity); - $this->em->getUnitOfWork()->registerManaged($entity, array('id'=>1), array('id'=>1, 'name'=>'Foo')); + $this->em->getUnitOfWork()->registerManaged($entity, ['id'=>1], ['id'=>1, 'name'=>'Foo']); $this->collectionPersister->expects($this->once()) ->method('contains') @@ -215,7 +217,7 @@ public function testInvokeContainsKey() $persister = $this->createPersisterDefault(); $collection = $this->createCollection($entity); - $this->em->getUnitOfWork()->registerManaged($entity, array('id'=>1), array('id'=>1, 'name'=>'Foo')); + $this->em->getUnitOfWork()->registerManaged($entity, ['id'=>1], ['id'=>1, 'name'=>'Foo']); $this->collectionPersister->expects($this->once()) ->method('containsKey') @@ -232,7 +234,7 @@ public function testInvokeRemoveElement() $persister = $this->createPersisterDefault(); $collection = $this->createCollection($entity); - $this->em->getUnitOfWork()->registerManaged($entity, array('id'=>1), array('id'=>1, 'name'=>'Foo')); + $this->em->getUnitOfWork()->registerManaged($entity, ['id'=>1], ['id'=>1, 'name'=>'Foo']); $this->collectionPersister->expects($this->once()) ->method('removeElement') @@ -249,7 +251,7 @@ public function testInvokeGet() $persister = $this->createPersisterDefault(); $collection = $this->createCollection($entity); - $this->em->getUnitOfWork()->registerManaged($entity, array('id'=>1), array('id'=>1, 'name'=>'Foo')); + $this->em->getUnitOfWork()->registerManaged($entity, ['id'=>1], ['id'=>1, 'name'=>'Foo']); $this->collectionPersister->expects($this->once()) ->method('get') diff --git a/tests/Doctrine/Tests/ORM/Cache/Persister/Collection/ReadWriteCachedCollectionPersisterTest.php b/tests/Doctrine/Tests/ORM/Cache/Persister/Collection/ReadWriteCachedCollectionPersisterTest.php index b41d27ab170..6b7be1f751f 100644 --- a/tests/Doctrine/Tests/ORM/Cache/Persister/Collection/ReadWriteCachedCollectionPersisterTest.php +++ b/tests/Doctrine/Tests/ORM/Cache/Persister/Collection/ReadWriteCachedCollectionPersisterTest.php @@ -16,7 +16,7 @@ */ class ReadWriteCachedCollectionPersisterTest extends AbstractCollectionPersisterTest { - protected $regionMockMethods = array( + protected $regionMockMethods = [ 'getName', 'contains', 'get', @@ -26,7 +26,7 @@ class ReadWriteCachedCollectionPersisterTest extends AbstractCollectionPersister 'evictAll', 'lock', 'unlock', - ); + ]; /** * {@inheritdoc} @@ -52,14 +52,14 @@ public function testDeleteShouldLockItem() $lock = Lock::createLockRead(); $persister = $this->createPersisterDefault(); $collection = $this->createCollection($entity); - $key = new CollectionCacheKey(State::CLASSNAME, 'cities', array('id'=>1)); + $key = new CollectionCacheKey(State::class, 'cities', ['id'=>1]); $this->region->expects($this->once()) ->method('lock') ->with($this->equalTo($key)) ->will($this->returnValue($lock)); - $this->em->getUnitOfWork()->registerManaged($entity, array('id'=>1), array('id'=>1, 'name'=>'Foo')); + $this->em->getUnitOfWork()->registerManaged($entity, ['id'=>1], ['id'=>1, 'name'=>'Foo']); $persister->delete($collection); } @@ -70,14 +70,14 @@ public function testUpdateShouldLockItem() $lock = Lock::createLockRead(); $persister = $this->createPersisterDefault(); $collection = $this->createCollection($entity); - $key = new CollectionCacheKey(State::CLASSNAME, 'cities', array('id'=>1)); + $key = new CollectionCacheKey(State::class, 'cities', ['id'=>1]); $this->region->expects($this->once()) ->method('lock') ->with($this->equalTo($key)) ->will($this->returnValue($lock)); - $this->em->getUnitOfWork()->registerManaged($entity, array('id'=>1), array('id'=>1, 'name'=>'Foo')); + $this->em->getUnitOfWork()->registerManaged($entity, ['id'=>1], ['id'=>1, 'name'=>'Foo']); $persister->update($collection); } @@ -88,7 +88,7 @@ public function testUpdateTransactionRollBackShouldEvictItem() $lock = Lock::createLockRead(); $persister = $this->createPersisterDefault(); $collection = $this->createCollection($entity); - $key = new CollectionCacheKey(State::CLASSNAME, 'cities', array('id'=>1)); + $key = new CollectionCacheKey(State::class, 'cities', ['id'=>1]); $this->region->expects($this->once()) ->method('lock') @@ -100,7 +100,7 @@ public function testUpdateTransactionRollBackShouldEvictItem() ->with($this->equalTo($key)) ->will($this->returnValue($lock)); - $this->em->getUnitOfWork()->registerManaged($entity, array('id'=>1), array('id'=>1, 'name'=>'Foo')); + $this->em->getUnitOfWork()->registerManaged($entity, ['id'=>1], ['id'=>1, 'name'=>'Foo']); $persister->update($collection); $persister->afterTransactionRolledBack(); @@ -112,7 +112,7 @@ public function testDeleteTransactionRollBackShouldEvictItem() $lock = Lock::createLockRead(); $persister = $this->createPersisterDefault(); $collection = $this->createCollection($entity); - $key = new CollectionCacheKey(State::CLASSNAME, 'cities', array('id'=>1)); + $key = new CollectionCacheKey(State::class, 'cities', ['id'=>1]); $this->region->expects($this->once()) ->method('lock') @@ -123,7 +123,7 @@ public function testDeleteTransactionRollBackShouldEvictItem() ->method('evict') ->with($this->equalTo($key)); - $this->em->getUnitOfWork()->registerManaged($entity, array('id'=>1), array('id'=>1, 'name'=>'Foo')); + $this->em->getUnitOfWork()->registerManaged($entity, ['id'=>1], ['id'=>1, 'name'=>'Foo']); $persister->delete($collection); $persister->afterTransactionRolledBack(); @@ -135,8 +135,8 @@ public function testTransactionRollBackDeleteShouldClearQueue() $lock = Lock::createLockRead(); $persister = $this->createPersisterDefault(); $collection = $this->createCollection($entity); - $key = new CollectionCacheKey(State::CLASSNAME, 'cities', array('id'=>1)); - $property = new \ReflectionProperty('Doctrine\ORM\Cache\Persister\Collection\ReadWriteCachedCollectionPersister', 'queuedCache'); + $key = new CollectionCacheKey(State::class, 'cities', ['id'=>1]); + $property = new \ReflectionProperty(ReadWriteCachedCollectionPersister::class, 'queuedCache'); $property->setAccessible(true); @@ -149,7 +149,7 @@ public function testTransactionRollBackDeleteShouldClearQueue() ->method('evict') ->with($this->equalTo($key)); - $this->em->getUnitOfWork()->registerManaged($entity, array('id'=>1), array('id'=>1, 'name'=>'Foo')); + $this->em->getUnitOfWork()->registerManaged($entity, ['id'=>1], ['id'=>1, 'name'=>'Foo']); $persister->delete($collection); @@ -166,8 +166,8 @@ public function testTransactionRollBackUpdateShouldClearQueue() $lock = Lock::createLockRead(); $persister = $this->createPersisterDefault(); $collection = $this->createCollection($entity); - $key = new CollectionCacheKey(State::CLASSNAME, 'cities', array('id'=>1)); - $property = new \ReflectionProperty('Doctrine\ORM\Cache\Persister\Collection\ReadWriteCachedCollectionPersister', 'queuedCache'); + $key = new CollectionCacheKey(State::class, 'cities', ['id'=>1]); + $property = new \ReflectionProperty(ReadWriteCachedCollectionPersister::class, 'queuedCache'); $property->setAccessible(true); @@ -180,7 +180,7 @@ public function testTransactionRollBackUpdateShouldClearQueue() ->method('evict') ->with($this->equalTo($key)); - $this->em->getUnitOfWork()->registerManaged($entity, array('id'=>1), array('id'=>1, 'name'=>'Foo')); + $this->em->getUnitOfWork()->registerManaged($entity, ['id'=>1], ['id'=>1, 'name'=>'Foo']); $persister->update($collection); @@ -197,8 +197,8 @@ public function testTransactionRollCommitDeleteShouldClearQueue() $lock = Lock::createLockRead(); $persister = $this->createPersisterDefault(); $collection = $this->createCollection($entity); - $key = new CollectionCacheKey(State::CLASSNAME, 'cities', array('id'=>1)); - $property = new \ReflectionProperty('Doctrine\ORM\Cache\Persister\Collection\ReadWriteCachedCollectionPersister', 'queuedCache'); + $key = new CollectionCacheKey(State::class, 'cities', ['id'=>1]); + $property = new \ReflectionProperty(ReadWriteCachedCollectionPersister::class, 'queuedCache'); $property->setAccessible(true); @@ -211,7 +211,7 @@ public function testTransactionRollCommitDeleteShouldClearQueue() ->method('evict') ->with($this->equalTo($key)); - $this->em->getUnitOfWork()->registerManaged($entity, array('id'=>1), array('id'=>1, 'name'=>'Foo')); + $this->em->getUnitOfWork()->registerManaged($entity, ['id'=>1], ['id'=>1, 'name'=>'Foo']); $persister->delete($collection); @@ -228,8 +228,8 @@ public function testTransactionRollCommitUpdateShouldClearQueue() $lock = Lock::createLockRead(); $persister = $this->createPersisterDefault(); $collection = $this->createCollection($entity); - $key = new CollectionCacheKey(State::CLASSNAME, 'cities', array('id'=>1)); - $property = new \ReflectionProperty('Doctrine\ORM\Cache\Persister\Collection\ReadWriteCachedCollectionPersister', 'queuedCache'); + $key = new CollectionCacheKey(State::class, 'cities', ['id'=>1]); + $property = new \ReflectionProperty(ReadWriteCachedCollectionPersister::class, 'queuedCache'); $property->setAccessible(true); @@ -242,7 +242,7 @@ public function testTransactionRollCommitUpdateShouldClearQueue() ->method('evict') ->with($this->equalTo($key)); - $this->em->getUnitOfWork()->registerManaged($entity, array('id'=>1), array('id'=>1, 'name'=>'Foo')); + $this->em->getUnitOfWork()->registerManaged($entity, ['id'=>1], ['id'=>1, 'name'=>'Foo']); $persister->update($collection); @@ -258,8 +258,8 @@ public function testDeleteLockFailureShouldIgnoreQueue() $entity = new State("Foo"); $persister = $this->createPersisterDefault(); $collection = $this->createCollection($entity); - $key = new CollectionCacheKey(State::CLASSNAME, 'cities', array('id'=>1)); - $property = new \ReflectionProperty('Doctrine\ORM\Cache\Persister\Collection\ReadWriteCachedCollectionPersister', 'queuedCache'); + $key = new CollectionCacheKey(State::class, 'cities', ['id'=>1]); + $property = new \ReflectionProperty(ReadWriteCachedCollectionPersister::class, 'queuedCache'); $property->setAccessible(true); @@ -272,7 +272,7 @@ public function testDeleteLockFailureShouldIgnoreQueue() ->method('delete') ->with($this->equalTo($collection)); - $this->em->getUnitOfWork()->registerManaged($entity, array('id'=>1), array('id'=>1, 'name'=>'Foo')); + $this->em->getUnitOfWork()->registerManaged($entity, ['id'=>1], ['id'=>1, 'name'=>'Foo']); $persister->delete($collection); $this->assertCount(0, $property->getValue($persister)); @@ -283,8 +283,8 @@ public function testUpdateLockFailureShouldIgnoreQueue() $entity = new State("Foo"); $persister = $this->createPersisterDefault(); $collection = $this->createCollection($entity); - $key = new CollectionCacheKey(State::CLASSNAME, 'cities', array('id'=>1)); - $property = new \ReflectionProperty('Doctrine\ORM\Cache\Persister\Collection\ReadWriteCachedCollectionPersister', 'queuedCache'); + $key = new CollectionCacheKey(State::class, 'cities', ['id'=>1]); + $property = new \ReflectionProperty(ReadWriteCachedCollectionPersister::class, 'queuedCache'); $property->setAccessible(true); @@ -297,7 +297,7 @@ public function testUpdateLockFailureShouldIgnoreQueue() ->method('update') ->with($this->equalTo($collection)); - $this->em->getUnitOfWork()->registerManaged($entity, array('id'=>1), array('id'=>1, 'name'=>'Foo')); + $this->em->getUnitOfWork()->registerManaged($entity, ['id'=>1], ['id'=>1, 'name'=>'Foo']); $persister->update($collection); $this->assertCount(0, $property->getValue($persister)); diff --git a/tests/Doctrine/Tests/ORM/Cache/Persister/Entity/AbstractEntityPersisterTest.php b/tests/Doctrine/Tests/ORM/Cache/Persister/Entity/AbstractEntityPersisterTest.php index 83fd3ad8579..a0e3adbe51f 100644 --- a/tests/Doctrine/Tests/ORM/Cache/Persister/Entity/AbstractEntityPersisterTest.php +++ b/tests/Doctrine/Tests/ORM/Cache/Persister/Entity/AbstractEntityPersisterTest.php @@ -2,18 +2,18 @@ namespace Doctrine\Tests\ORM\Cache\Persister\Entity; -use Doctrine\Tests\OrmTestCase; - +use Doctrine\Common\Collections\ArrayCollection; +use Doctrine\Common\Collections\Criteria; +use Doctrine\ORM\Cache\Persister\CachedPersister; +use Doctrine\ORM\Cache\Persister\Entity\CachedEntityPersister; use Doctrine\ORM\Cache\Region; use Doctrine\ORM\EntityManager; use Doctrine\ORM\Mapping\ClassMetadata; +use Doctrine\ORM\PersistentCollection; use Doctrine\ORM\Persisters\Entity\EntityPersister; - -use Doctrine\Tests\Models\Cache\Country; -use Doctrine\Common\Collections\Criteria; -use Doctrine\Common\Collections\ArrayCollection; use Doctrine\ORM\Query\ResultSetMappingBuilder; -use Doctrine\ORM\PersistentCollection; +use Doctrine\Tests\Models\Cache\Country; +use Doctrine\Tests\OrmTestCase; /** * @group DDC-2183 @@ -35,52 +35,6 @@ abstract class AbstractEntityPersisterTest extends OrmTestCase */ protected $em; - /** - * @var array - */ - protected $regionMockMethods = array( - 'getName', - 'contains', - 'get', - 'getMultiple', - 'put', - 'evict', - 'evictAll' - ); - - /** - * @var array - */ - protected $entityPersisterMockMethods = array( - 'getClassMetadata', - 'getResultSetMapping', - 'getInserts', - 'getInsertSQL', - 'getSelectSQL', - 'getCountSQL', - 'expandParameters', - 'expandCriteriaParameters', - 'getSelectConditionStatementSQL', - 'addInsert', - 'executeInserts', - 'update', - 'delete', - 'getOwningTable', - 'load', - 'loadById', - 'loadOneToOneEntity', - 'count', - 'refresh', - 'loadCriteria', - 'loadAll', - 'getManyToManyCollection', - 'loadManyToManyCollection', - 'loadOneToManyCollection', - 'lock', - 'getOneToManyCollection', - 'exists' - ); - /** * @param \Doctrine\ORM\EntityManager $em * @param \Doctrine\ORM\Persisters\Entity\EntityPersister $persister @@ -97,11 +51,9 @@ protected function setUp() $this->enableSecondLevelCache(); parent::setUp(); - $this->em = $this->_getTestEntityManager(); - $this->region = $this->createRegion(); - $this->entityPersister = $this->getMockBuilder(EntityPersister::class) - ->setMethods($this->entityPersisterMockMethods) - ->getMock(); + $this->em = $this->_getTestEntityManager(); + $this->region = $this->createRegion(); + $this->entityPersister = $this->createMock(EntityPersister::class); } /** @@ -109,9 +61,7 @@ protected function setUp() */ protected function createRegion() { - return $this->getMockBuilder(Region::class) - ->setMethods($this->regionMockMethods) - ->getMock(); + return $this->createMock(Region::class); } /** @@ -119,16 +69,16 @@ protected function createRegion() */ protected function createPersisterDefault() { - return $this->createPersister($this->em, $this->entityPersister, $this->region, $this->em->getClassMetadata('Doctrine\Tests\Models\Cache\Country')); + return $this->createPersister($this->em, $this->entityPersister, $this->region, $this->em->getClassMetadata(Country::class)); } public function testImplementsEntityPersister() { $persister = $this->createPersisterDefault(); - $this->assertInstanceOf('Doctrine\ORM\Persisters\Entity\EntityPersister', $persister); - $this->assertInstanceOf('Doctrine\ORM\Cache\Persister\CachedPersister', $persister); - $this->assertInstanceOf('Doctrine\ORM\Cache\Persister\Entity\CachedEntityPersister', $persister); + $this->assertInstanceOf(EntityPersister::class, $persister); + $this->assertInstanceOf(CachedPersister::class, $persister); + $this->assertInstanceOf(CachedEntityPersister::class, $persister); } public function testInvokeAddInsert() @@ -150,9 +100,9 @@ public function testInvokeGetInserts() $this->entityPersister->expects($this->once()) ->method('getInserts') - ->will($this->returnValue(array($entity))); + ->will($this->returnValue([$entity])); - $this->assertEquals(array($entity), $persister->getInserts()); + $this->assertEquals([$entity], $persister->getInserts()); } public function testInvokeGetSelectSQL() @@ -161,10 +111,14 @@ public function testInvokeGetSelectSQL() $this->entityPersister->expects($this->once()) ->method('getSelectSQL') - ->with($this->equalTo(array('name'=>'Foo')), $this->equalTo(array(0)), $this->equalTo(1), $this->equalTo(2), $this->equalTo(3), $this->equalTo(array(4))) + ->with($this->equalTo(['name'=>'Foo']), $this->equalTo([0]), $this->equalTo(1), $this->equalTo(2), $this->equalTo(3), $this->equalTo( + [4] + )) ->will($this->returnValue('SELECT * FROM foo WERE name = ?')); - $this->assertEquals('SELECT * FROM foo WERE name = ?', $persister->getSelectSQL(array('name'=>'Foo'), array(0), 1, 2, 3, array(4))); + $this->assertEquals('SELECT * FROM foo WERE name = ?', $persister->getSelectSQL( + ['name'=>'Foo'], [0], 1, 2, 3, [4] + )); } public function testInvokeGetInsertSQL() @@ -184,10 +138,10 @@ public function testInvokeExpandParameters() $this->entityPersister->expects($this->once()) ->method('expandParameters') - ->with($this->equalTo(array('name'=>'Foo'))) - ->will($this->returnValue(array('name'=>'Foo'))); + ->with($this->equalTo(['name'=>'Foo'])) + ->will($this->returnValue(['name'=>'Foo'])); - $this->assertEquals(array('name'=>'Foo'), $persister->expandParameters(array('name'=>'Foo'))); + $this->assertEquals(['name'=>'Foo'], $persister->expandParameters(['name'=>'Foo'])); } public function testInvokeExpandCriteriaParameters() @@ -198,9 +152,9 @@ public function testInvokeExpandCriteriaParameters() $this->entityPersister->expects($this->once()) ->method('expandCriteriaParameters') ->with($this->equalTo($criteria)) - ->will($this->returnValue(array('name'=>'Foo'))); + ->will($this->returnValue(['name'=>'Foo'])); - $this->assertEquals(array('name'=>'Foo'), $persister->expandCriteriaParameters($criteria)); + $this->assertEquals(['name'=>'Foo'], $persister->expandCriteriaParameters($criteria)); } public function testInvokeSelectConditionStatementSQL() @@ -209,10 +163,10 @@ public function testInvokeSelectConditionStatementSQL() $this->entityPersister->expects($this->once()) ->method('getSelectConditionStatementSQL') - ->with($this->equalTo('id'), $this->equalTo(1), $this->equalTo(array()), $this->equalTo('=')) + ->with($this->equalTo('id'), $this->equalTo(1), $this->equalTo([]), $this->equalTo('=')) ->will($this->returnValue('name = 1')); - $this->assertEquals('name = 1', $persister->getSelectConditionStatementSQL('id', 1, array(), '=')); + $this->assertEquals('name = 1', $persister->getSelectConditionStatementSQL('id', 1, [], '=')); } public function testInvokeExecuteInserts() @@ -221,9 +175,9 @@ public function testInvokeExecuteInserts() $this->entityPersister->expects($this->once()) ->method('executeInserts') - ->will($this->returnValue(array('id' => 1))); + ->will($this->returnValue(['id' => 1])); - $this->assertEquals(array('id' => 1), $persister->executeInserts()); + $this->assertEquals(['id' => 1], $persister->executeInserts()); } public function testInvokeUpdate() @@ -235,7 +189,7 @@ public function testInvokeUpdate() ->method('update') ->with($this->equalTo($entity)); - $this->em->getUnitOfWork()->registerManaged($entity, array('id'=>1), array('id'=>1, 'name'=>'Foo')); + $this->em->getUnitOfWork()->registerManaged($entity, ['id'=>1], ['id'=>1, 'name'=>'Foo']); $this->assertNull($persister->update($entity)); } @@ -249,7 +203,7 @@ public function testInvokeDelete() ->method('delete') ->with($this->equalTo($entity)); - $this->em->getUnitOfWork()->registerManaged($entity, array('id'=>1), array('id'=>1, 'name'=>'Foo')); + $this->em->getUnitOfWork()->registerManaged($entity, ['id'=>1], ['id'=>1, 'name'=>'Foo']); $this->assertNull($persister->delete($entity)); } @@ -273,10 +227,14 @@ public function testInvokeLoad() $this->entityPersister->expects($this->once()) ->method('load') - ->with($this->equalTo(array('id' => 1)), $this->equalTo($entity), $this->equalTo(array(0)), $this->equalTo(array(1)), $this->equalTo(2), $this->equalTo(3), $this->equalTo(array(4))) + ->with($this->equalTo(['id' => 1]), $this->equalTo($entity), $this->equalTo([0]), $this->equalTo( + [1] + ), $this->equalTo(2), $this->equalTo(3), $this->equalTo( + [4] + )) ->will($this->returnValue($entity)); - $this->assertEquals($entity, $persister->load(array('id' => 1), $entity, array(0), array(1), 2, 3, array(4))); + $this->assertEquals($entity, $persister->load(['id' => 1], $entity, [0], [1], 2, 3, [4])); } public function testInvokeLoadAll() @@ -285,20 +243,20 @@ public function testInvokeLoadAll() $persister = $this->createPersisterDefault(); $entity = new Country("Foo"); - $rsm->addEntityResult(Country::CLASSNAME, 'c'); + $rsm->addEntityResult(Country::class, 'c'); - $this->em->getUnitOfWork()->registerManaged($entity, array('id'=>1), array('id'=>1, 'name'=>'Foo')); + $this->em->getUnitOfWork()->registerManaged($entity, ['id'=>1], ['id'=>1, 'name'=>'Foo']); $this->entityPersister->expects($this->once()) ->method('loadAll') - ->with($this->equalTo(array('id' => 1)), $this->equalTo(array(0)), $this->equalTo(1), $this->equalTo(2)) - ->will($this->returnValue(array($entity))); + ->with($this->equalTo(['id' => 1]), $this->equalTo([0]), $this->equalTo(1), $this->equalTo(2)) + ->will($this->returnValue([$entity])); $this->entityPersister->expects($this->once()) ->method('getResultSetMapping') ->will($this->returnValue($rsm)); - $this->assertEquals(array($entity), $persister->loadAll(array('id' => 1), array(0), 1, 2)); + $this->assertEquals([$entity], $persister->loadAll(['id' => 1], [0], 1, 2)); } public function testInvokeLoadById() @@ -308,10 +266,10 @@ public function testInvokeLoadById() $this->entityPersister->expects($this->once()) ->method('loadById') - ->with($this->equalTo(array('id' => 1)), $this->equalTo($entity)) + ->with($this->equalTo(['id' => 1]), $this->equalTo($entity)) ->will($this->returnValue($entity)); - $this->assertEquals($entity, $persister->loadById(array('id' => 1), $entity)); + $this->assertEquals($entity, $persister->loadById(['id' => 1], $entity)); } public function testInvokeLoadOneToOneEntity() @@ -321,10 +279,10 @@ public function testInvokeLoadOneToOneEntity() $this->entityPersister->expects($this->once()) ->method('loadOneToOneEntity') - ->with($this->equalTo(array()), $this->equalTo('foo'), $this->equalTo(array('id' => 11))) + ->with($this->equalTo([]), $this->equalTo('foo'), $this->equalTo(['id' => 11])) ->will($this->returnValue($entity)); - $this->assertEquals($entity, $persister->loadOneToOneEntity(array(), 'foo', array('id' => 11))); + $this->assertEquals($entity, $persister->loadOneToOneEntity([], 'foo', ['id' => 11])); } public function testInvokeRefresh() @@ -334,10 +292,10 @@ public function testInvokeRefresh() $this->entityPersister->expects($this->once()) ->method('refresh') - ->with($this->equalTo(array('id' => 1)), $this->equalTo($entity), $this->equalTo(0)) + ->with($this->equalTo(['id' => 1]), $this->equalTo($entity), $this->equalTo(0)) ->will($this->returnValue($entity)); - $this->assertNull($persister->refresh(array('id' => 1), $entity), 0); + $this->assertNull($persister->refresh(['id' => 1], $entity), 0); } public function testInvokeLoadCriteria() @@ -347,8 +305,8 @@ public function testInvokeLoadCriteria() $entity = new Country("Foo"); $criteria = new Criteria(); - $this->em->getUnitOfWork()->registerManaged($entity, array('id'=>1), array('id'=>1, 'name'=>'Foo')); - $rsm->addEntityResult(Country::CLASSNAME, 'c'); + $this->em->getUnitOfWork()->registerManaged($entity, ['id'=>1], ['id'=>1, 'name'=>'Foo']); + $rsm->addEntityResult(Country::class, 'c'); $this->entityPersister->expects($this->once()) ->method('getResultSetMapping') @@ -357,9 +315,9 @@ public function testInvokeLoadCriteria() $this->entityPersister->expects($this->once()) ->method('loadCriteria') ->with($this->equalTo($criteria)) - ->will($this->returnValue(array($entity))); + ->will($this->returnValue([$entity])); - $this->assertEquals(array($entity), $persister->loadCriteria($criteria)); + $this->assertEquals([$entity], $persister->loadCriteria($criteria)); } public function testInvokeGetManyToManyCollection() @@ -369,10 +327,10 @@ public function testInvokeGetManyToManyCollection() $this->entityPersister->expects($this->once()) ->method('getManyToManyCollection') - ->with($this->equalTo(array()), $this->equalTo('Foo'), $this->equalTo(1), $this->equalTo(2)) - ->will($this->returnValue(array($entity))); + ->with($this->equalTo([]), $this->equalTo('Foo'), $this->equalTo(1), $this->equalTo(2)) + ->will($this->returnValue([$entity])); - $this->assertEquals(array($entity), $persister->getManyToManyCollection(array(), 'Foo', 1 ,2)); + $this->assertEquals([$entity], $persister->getManyToManyCollection([], 'Foo', 1 ,2)); } public function testInvokeGetOneToManyCollection() @@ -382,16 +340,16 @@ public function testInvokeGetOneToManyCollection() $this->entityPersister->expects($this->once()) ->method('getOneToManyCollection') - ->with($this->equalTo(array()), $this->equalTo('Foo'), $this->equalTo(1), $this->equalTo(2)) - ->will($this->returnValue(array($entity))); + ->with($this->equalTo([]), $this->equalTo('Foo'), $this->equalTo(1), $this->equalTo(2)) + ->will($this->returnValue([$entity])); - $this->assertEquals(array($entity), $persister->getOneToManyCollection(array(), 'Foo', 1 ,2)); + $this->assertEquals([$entity], $persister->getOneToManyCollection([], 'Foo', 1 ,2)); } public function testInvokeLoadManyToManyCollection() { - $mapping = $this->em->getClassMetadata('Doctrine\Tests\Models\Cache\Country'); - $assoc = array('type' => 1); + $mapping = $this->em->getClassMetadata(Country::class); + $assoc = ['type' => 1]; $coll = new PersistentCollection($this->em, $mapping, new ArrayCollection()); $persister = $this->createPersisterDefault(); $entity = new Country("Foo"); @@ -399,15 +357,15 @@ public function testInvokeLoadManyToManyCollection() $this->entityPersister->expects($this->once()) ->method('loadManyToManyCollection') ->with($this->equalTo($assoc), $this->equalTo('Foo'), $coll) - ->will($this->returnValue(array($entity))); + ->will($this->returnValue([$entity])); - $this->assertEquals(array($entity), $persister->loadManyToManyCollection($assoc, 'Foo', $coll)); + $this->assertEquals([$entity], $persister->loadManyToManyCollection($assoc, 'Foo', $coll)); } public function testInvokeLoadOneToManyCollection() { - $mapping = $this->em->getClassMetadata('Doctrine\Tests\Models\Cache\Country'); - $assoc = array('type' => 1); + $mapping = $this->em->getClassMetadata(Country::class); + $assoc = ['type' => 1]; $coll = new PersistentCollection($this->em, $mapping, new ArrayCollection()); $persister = $this->createPersisterDefault(); $entity = new Country("Foo"); @@ -415,14 +373,14 @@ public function testInvokeLoadOneToManyCollection() $this->entityPersister->expects($this->once()) ->method('loadOneToManyCollection') ->with($this->equalTo($assoc), $this->equalTo('Foo'), $coll) - ->will($this->returnValue(array($entity))); + ->will($this->returnValue([$entity])); - $this->assertEquals(array($entity), $persister->loadOneToManyCollection($assoc, 'Foo', $coll)); + $this->assertEquals([$entity], $persister->loadOneToManyCollection($assoc, 'Foo', $coll)); } public function testInvokeLock() { - $identifier = array('id' => 1); + $identifier = ['id' => 1]; $persister = $this->createPersisterDefault(); $this->entityPersister->expects($this->once()) diff --git a/tests/Doctrine/Tests/ORM/Cache/Persister/Entity/NonStrictReadWriteCachedEntityPersisterTest.php b/tests/Doctrine/Tests/ORM/Cache/Persister/Entity/NonStrictReadWriteCachedEntityPersisterTest.php index df1f6ac593c..0f1e67b0f63 100644 --- a/tests/Doctrine/Tests/ORM/Cache/Persister/Entity/NonStrictReadWriteCachedEntityPersisterTest.php +++ b/tests/Doctrine/Tests/ORM/Cache/Persister/Entity/NonStrictReadWriteCachedEntityPersisterTest.php @@ -32,7 +32,7 @@ public function testTransactionRollBackShouldClearQueue() $property->setAccessible(true); - $this->em->getUnitOfWork()->registerManaged($entity, array('id'=>1), array('id'=>1, 'name'=>'Foo')); + $this->em->getUnitOfWork()->registerManaged($entity, ['id'=>1], ['id'=>1, 'name'=>'Foo']); $persister->update($entity); $persister->delete($entity); @@ -48,8 +48,8 @@ public function testInsertTransactionCommitShouldPutCache() { $entity = new Country("Foo"); $persister = $this->createPersisterDefault(); - $key = new EntityCacheKey(Country::CLASSNAME, array('id'=>1)); - $entry = new EntityCacheEntry(Country::CLASSNAME, array('id'=>1, 'name'=>'Foo')); + $key = new EntityCacheKey(Country::class, ['id'=>1]); + $entry = new EntityCacheEntry(Country::class, ['id'=>1, 'name'=>'Foo']); $property = new \ReflectionProperty($persister, 'queuedCache'); $property->setAccessible(true); @@ -64,12 +64,12 @@ public function testInsertTransactionCommitShouldPutCache() $this->entityPersister->expects($this->once()) ->method('getInserts') - ->will($this->returnValue(array($entity))); + ->will($this->returnValue([$entity])); $this->entityPersister->expects($this->once()) ->method('executeInserts'); - $this->em->getUnitOfWork()->registerManaged($entity, array('id'=>1), array('id'=>1, 'name'=>'Foo')); + $this->em->getUnitOfWork()->registerManaged($entity, ['id'=>1], ['id'=>1, 'name'=>'Foo']); $persister->addInsert($entity); $persister->executeInserts(); @@ -85,8 +85,8 @@ public function testUpdateTransactionCommitShouldPutCache() { $entity = new Country("Foo"); $persister = $this->createPersisterDefault(); - $key = new EntityCacheKey(Country::CLASSNAME, array('id'=>1)); - $entry = new EntityCacheEntry(Country::CLASSNAME, array('id'=>1, 'name'=>'Foo')); + $key = new EntityCacheKey(Country::class, ['id'=>1]); + $entry = new EntityCacheEntry(Country::class, ['id'=>1, 'name'=>'Foo']); $property = new \ReflectionProperty($persister, 'queuedCache'); $property->setAccessible(true); @@ -99,7 +99,7 @@ public function testUpdateTransactionCommitShouldPutCache() ->method('update') ->with($this->equalTo($entity)); - $this->em->getUnitOfWork()->registerManaged($entity, array('id'=>1), array('id'=>1, 'name'=>'Foo')); + $this->em->getUnitOfWork()->registerManaged($entity, ['id'=>1], ['id'=>1, 'name'=>'Foo']); $persister->update($entity); @@ -114,7 +114,7 @@ public function testDeleteTransactionCommitShouldEvictCache() { $entity = new Country("Foo"); $persister = $this->createPersisterDefault(); - $key = new EntityCacheKey(Country::CLASSNAME, array('id'=>1)); + $key = new EntityCacheKey(Country::class, ['id'=>1]); $property = new \ReflectionProperty($persister, 'queuedCache'); $property->setAccessible(true); @@ -127,7 +127,7 @@ public function testDeleteTransactionCommitShouldEvictCache() ->method('delete') ->with($this->equalTo($entity)); - $this->em->getUnitOfWork()->registerManaged($entity, array('id'=>1), array('id'=>1, 'name'=>'Foo')); + $this->em->getUnitOfWork()->registerManaged($entity, ['id'=>1], ['id'=>1, 'name'=>'Foo']); $persister->delete($entity); diff --git a/tests/Doctrine/Tests/ORM/Cache/Persister/Entity/ReadWriteCachedEntityPersisterTest.php b/tests/Doctrine/Tests/ORM/Cache/Persister/Entity/ReadWriteCachedEntityPersisterTest.php index dc9fef43a0a..ee9d1433393 100644 --- a/tests/Doctrine/Tests/ORM/Cache/Persister/Entity/ReadWriteCachedEntityPersisterTest.php +++ b/tests/Doctrine/Tests/ORM/Cache/Persister/Entity/ReadWriteCachedEntityPersisterTest.php @@ -17,18 +17,6 @@ */ class ReadWriteCachedEntityPersisterTest extends AbstractEntityPersisterTest { - protected $regionMockMethods = array( - 'getName', - 'contains', - 'get', - 'getMultiple', - 'put', - 'evict', - 'evictAll', - 'lock', - 'unlock', - ); - /** * {@inheritdoc} */ @@ -42,9 +30,7 @@ protected function createPersister(EntityManager $em, EntityPersister $persister */ protected function createRegion() { - return $this->getMockBuilder(ConcurrentRegion::class) - ->setConstructorArgs($this->regionMockMethods) - ->getMock(); + return $this->createMock(ConcurrentRegion::class); } public function testDeleteShouldLockItem() @@ -52,14 +38,14 @@ public function testDeleteShouldLockItem() $entity = new Country("Foo"); $lock = Lock::createLockRead(); $persister = $this->createPersisterDefault(); - $key = new EntityCacheKey(Country::CLASSNAME, array('id'=>1)); + $key = new EntityCacheKey(Country::class, ['id'=>1]); $this->region->expects($this->once()) ->method('lock') ->with($this->equalTo($key)) ->will($this->returnValue($lock)); - $this->em->getUnitOfWork()->registerManaged($entity, array('id'=>1), array('id'=>1, 'name'=>'Foo')); + $this->em->getUnitOfWork()->registerManaged($entity, ['id'=>1], ['id'=>1, 'name'=>'Foo']); $persister->delete($entity); } @@ -69,14 +55,14 @@ public function testUpdateShouldLockItem() $entity = new Country("Foo"); $lock = Lock::createLockRead(); $persister = $this->createPersisterDefault(); - $key = new EntityCacheKey(Country::CLASSNAME, array('id'=>1)); + $key = new EntityCacheKey(Country::class, ['id'=>1]); $this->region->expects($this->once()) ->method('lock') ->with($this->equalTo($key)) ->will($this->returnValue($lock)); - $this->em->getUnitOfWork()->registerManaged($entity, array('id'=>1), array('id'=>1, 'name'=>'Foo')); + $this->em->getUnitOfWork()->registerManaged($entity, ['id'=>1], ['id'=>1, 'name'=>'Foo']); $persister->update($entity); } @@ -86,7 +72,7 @@ public function testUpdateTransactionRollBackShouldEvictItem() $entity = new Country("Foo"); $lock = Lock::createLockRead(); $persister = $this->createPersisterDefault(); - $key = new EntityCacheKey(Country::CLASSNAME, array('id'=>1)); + $key = new EntityCacheKey(Country::class, ['id'=>1]); $this->region->expects($this->once()) ->method('lock') @@ -98,7 +84,7 @@ public function testUpdateTransactionRollBackShouldEvictItem() ->with($this->equalTo($key)) ->will($this->returnValue($lock)); - $this->em->getUnitOfWork()->registerManaged($entity, array('id'=>1), array('id'=>1, 'name'=>'Foo')); + $this->em->getUnitOfWork()->registerManaged($entity, ['id'=>1], ['id'=>1, 'name'=>'Foo']); $persister->update($entity); $persister->afterTransactionRolledBack(); @@ -109,7 +95,7 @@ public function testDeleteTransactionRollBackShouldEvictItem() $entity = new Country("Foo"); $lock = Lock::createLockRead(); $persister = $this->createPersisterDefault(); - $key = new EntityCacheKey(Country::CLASSNAME, array('id'=>1)); + $key = new EntityCacheKey(Country::class, ['id'=>1]); $this->region->expects($this->once()) ->method('lock') @@ -120,7 +106,7 @@ public function testDeleteTransactionRollBackShouldEvictItem() ->method('evict') ->with($this->equalTo($key)); - $this->em->getUnitOfWork()->registerManaged($entity, array('id'=>1), array('id'=>1, 'name'=>'Foo')); + $this->em->getUnitOfWork()->registerManaged($entity, ['id'=>1], ['id'=>1, 'name'=>'Foo']); $persister->delete($entity); $persister->afterTransactionRolledBack(); @@ -131,8 +117,8 @@ public function testTransactionRollBackShouldClearQueue() $entity = new Country("Foo"); $lock = Lock::createLockRead(); $persister = $this->createPersisterDefault(); - $key = new EntityCacheKey(Country::CLASSNAME, array('id'=>1)); - $property = new \ReflectionProperty('Doctrine\ORM\Cache\Persister\Entity\ReadWriteCachedEntityPersister', 'queuedCache'); + $key = new EntityCacheKey(Country::class, ['id'=>1]); + $property = new \ReflectionProperty(ReadWriteCachedEntityPersister::class, 'queuedCache'); $property->setAccessible(true); @@ -145,7 +131,7 @@ public function testTransactionRollBackShouldClearQueue() ->method('evict') ->with($this->equalTo($key)); - $this->em->getUnitOfWork()->registerManaged($entity, array('id'=>1), array('id'=>1, 'name'=>'Foo')); + $this->em->getUnitOfWork()->registerManaged($entity, ['id'=>1], ['id'=>1, 'name'=>'Foo']); $persister->update($entity); $persister->delete($entity); @@ -162,8 +148,8 @@ public function testTransactionCommitShouldClearQueue() $entity = new Country("Foo"); $lock = Lock::createLockRead(); $persister = $this->createPersisterDefault(); - $key = new EntityCacheKey(Country::CLASSNAME, array('id'=>1)); - $property = new \ReflectionProperty('Doctrine\ORM\Cache\Persister\Entity\ReadWriteCachedEntityPersister', 'queuedCache'); + $key = new EntityCacheKey(Country::class, ['id'=>1]); + $property = new \ReflectionProperty(ReadWriteCachedEntityPersister::class, 'queuedCache'); $property->setAccessible(true); @@ -176,7 +162,7 @@ public function testTransactionCommitShouldClearQueue() ->method('evict') ->with($this->equalTo($key)); - $this->em->getUnitOfWork()->registerManaged($entity, array('id'=>1), array('id'=>1, 'name'=>'Foo')); + $this->em->getUnitOfWork()->registerManaged($entity, ['id'=>1], ['id'=>1, 'name'=>'Foo']); $persister->update($entity); $persister->delete($entity); @@ -192,8 +178,8 @@ public function testDeleteLockFailureShouldIgnoreQueue() { $entity = new Country("Foo"); $persister = $this->createPersisterDefault(); - $key = new EntityCacheKey(Country::CLASSNAME, array('id'=>1)); - $property = new \ReflectionProperty('Doctrine\ORM\Cache\Persister\Entity\ReadWriteCachedEntityPersister', 'queuedCache'); + $key = new EntityCacheKey(Country::class, ['id'=>1]); + $property = new \ReflectionProperty(ReadWriteCachedEntityPersister::class, 'queuedCache'); $property->setAccessible(true); @@ -206,7 +192,7 @@ public function testDeleteLockFailureShouldIgnoreQueue() ->method('delete') ->with($this->equalTo($entity)); - $this->em->getUnitOfWork()->registerManaged($entity, array('id'=>1), array('id'=>1, 'name'=>'Foo')); + $this->em->getUnitOfWork()->registerManaged($entity, ['id'=>1], ['id'=>1, 'name'=>'Foo']); $persister->delete($entity); $this->assertCount(0, $property->getValue($persister)); @@ -216,8 +202,8 @@ public function testUpdateLockFailureShouldIgnoreQueue() { $entity = new Country("Foo"); $persister = $this->createPersisterDefault(); - $key = new EntityCacheKey(Country::CLASSNAME, array('id'=>1)); - $property = new \ReflectionProperty('Doctrine\ORM\Cache\Persister\Entity\ReadWriteCachedEntityPersister', 'queuedCache'); + $key = new EntityCacheKey(Country::class, ['id'=>1]); + $property = new \ReflectionProperty(ReadWriteCachedEntityPersister::class, 'queuedCache'); $property->setAccessible(true); @@ -230,7 +216,7 @@ public function testUpdateLockFailureShouldIgnoreQueue() ->method('update') ->with($this->equalTo($entity)); - $this->em->getUnitOfWork()->registerManaged($entity, array('id'=>1), array('id'=>1, 'name'=>'Foo')); + $this->em->getUnitOfWork()->registerManaged($entity, ['id'=>1], ['id'=>1, 'name'=>'Foo']); $persister->update($entity); $this->assertCount(0, $property->getValue($persister)); diff --git a/tests/Doctrine/Tests/ORM/Cache/StatisticsCacheLoggerTest.php b/tests/Doctrine/Tests/ORM/Cache/StatisticsCacheLoggerTest.php index 16c91729b22..e9f04f350ed 100644 --- a/tests/Doctrine/Tests/ORM/Cache/StatisticsCacheLoggerTest.php +++ b/tests/Doctrine/Tests/ORM/Cache/StatisticsCacheLoggerTest.php @@ -29,7 +29,7 @@ protected function setUp() public function testEntityCache() { $name = 'my_entity_region'; - $key = new EntityCacheKey(State::CLASSNAME, array('id' => 1)); + $key = new EntityCacheKey(State::class, ['id' => 1]); $this->logger->entityCacheHit($name, $key); $this->logger->entityCachePut($name, $key); @@ -46,7 +46,7 @@ public function testEntityCache() public function testCollectionCache() { $name = 'my_collection_region'; - $key = new CollectionCacheKey(State::CLASSNAME, 'cities', array('id' => 1)); + $key = new CollectionCacheKey(State::class, 'cities', ['id' => 1]); $this->logger->collectionCacheHit($name, $key); $this->logger->collectionCachePut($name, $key); @@ -83,8 +83,8 @@ public function testMultipleCaches() $entityRegion = 'my_entity_region'; $queryRegion = 'my_query_region'; - $coolKey = new CollectionCacheKey(State::CLASSNAME, 'cities', array('id' => 1)); - $entityKey = new EntityCacheKey(State::CLASSNAME, array('id' => 1)); + $coolKey = new CollectionCacheKey(State::class, 'cities', ['id' => 1]); + $entityKey = new EntityCacheKey(State::class, ['id' => 1]); $queryKey = new QueryCacheKey('my_query_hash'); $this->logger->queryCacheHit($queryRegion, $queryKey); @@ -131,4 +131,4 @@ public function testMultipleCaches() $this->assertArrayHasKey($queryRegion, $hit); $this->assertArrayHasKey($entityRegion, $hit); } -} \ No newline at end of file +} diff --git a/tests/Doctrine/Tests/ORM/CommitOrderCalculatorTest.php b/tests/Doctrine/Tests/ORM/CommitOrderCalculatorTest.php index 770ec7deb21..c967beb8b62 100644 --- a/tests/Doctrine/Tests/ORM/CommitOrderCalculatorTest.php +++ b/tests/Doctrine/Tests/ORM/CommitOrderCalculatorTest.php @@ -24,11 +24,11 @@ protected function setUp() public function testCommitOrdering1() { - $class1 = new ClassMetadata(__NAMESPACE__ . '\NodeClass1'); - $class2 = new ClassMetadata(__NAMESPACE__ . '\NodeClass2'); - $class3 = new ClassMetadata(__NAMESPACE__ . '\NodeClass3'); - $class4 = new ClassMetadata(__NAMESPACE__ . '\NodeClass4'); - $class5 = new ClassMetadata(__NAMESPACE__ . '\NodeClass5'); + $class1 = new ClassMetadata(NodeClass1::class); + $class2 = new ClassMetadata(NodeClass2::class); + $class3 = new ClassMetadata(NodeClass3::class); + $class4 = new ClassMetadata(NodeClass4::class); + $class5 = new ClassMetadata(NodeClass5::class); $this->_calc->addNode($class1->name, $class1); $this->_calc->addNode($class2->name, $class2); @@ -44,15 +44,15 @@ public function testCommitOrdering1() $sorted = $this->_calc->sort(); // There is only 1 valid ordering for this constellation - $correctOrder = array($class5, $class1, $class2, $class3, $class4); + $correctOrder = [$class5, $class1, $class2, $class3, $class4]; $this->assertSame($correctOrder, $sorted); } public function testCommitOrdering2() { - $class1 = new ClassMetadata(__NAMESPACE__ . '\NodeClass1'); - $class2 = new ClassMetadata(__NAMESPACE__ . '\NodeClass2'); + $class1 = new ClassMetadata(NodeClass1::class); + $class2 = new ClassMetadata(NodeClass2::class); $this->_calc->addNode($class1->name, $class1); $this->_calc->addNode($class2->name, $class2); @@ -63,10 +63,43 @@ public function testCommitOrdering2() $sorted = $this->_calc->sort(); // There is only 1 valid ordering for this constellation - $correctOrder = array($class2, $class1); + $correctOrder = [$class2, $class1]; $this->assertSame($correctOrder, $sorted); } + + public function testCommitOrdering3() + { + // this test corresponds to the GH7259Test::testPersistFileBeforeVersion functional test + $class1 = new ClassMetadata(NodeClass1::class); + $class2 = new ClassMetadata(NodeClass2::class); + $class3 = new ClassMetadata(NodeClass3::class); + $class4 = new ClassMetadata(NodeClass4::class); + + $this->_calc->addNode($class1->name, $class1); + $this->_calc->addNode($class2->name, $class2); + $this->_calc->addNode($class3->name, $class3); + $this->_calc->addNode($class4->name, $class4); + + $this->_calc->addDependency($class4->name, $class1->name, 1); + $this->_calc->addDependency($class1->name, $class2->name, 1); + $this->_calc->addDependency($class4->name, $class3->name, 1); + $this->_calc->addDependency($class1->name, $class4->name, 0); + + $sorted = $this->_calc->sort(); + + // There is only multiple valid ordering for this constellation, but + // the class4, class1, class2 ordering is important to break the cycle + // on the nullable link. + $correctOrders = [ + [$class4, $class1, $class2, $class3], + [$class4, $class1, $class3, $class2], + [$class4, $class3, $class1, $class2], + ]; + + // We want to perform a strict comparison of the array + $this->assertContains($sorted, $correctOrders, '', false, true, true); + } } class NodeClass1 {} diff --git a/tests/Doctrine/Tests/ORM/ConfigurationTest.php b/tests/Doctrine/Tests/ORM/ConfigurationTest.php index d99d2b1e84e..92a2eeaea70 100644 --- a/tests/Doctrine/Tests/ORM/ConfigurationTest.php +++ b/tests/Doctrine/Tests/ORM/ConfigurationTest.php @@ -7,6 +7,7 @@ use Doctrine\Common\Proxy\AbstractProxyFactory; use Doctrine\Common\Cache\ArrayCache; use Doctrine\ORM\Cache\CacheConfiguration; +use Doctrine\ORM\EntityRepository; use Doctrine\ORM\Mapping as AnnotationNamespace; use Doctrine\ORM\Configuration; use Doctrine\ORM\Mapping\EntityListenerResolver; @@ -14,14 +15,15 @@ use Doctrine\ORM\Mapping\QuoteStrategy; use Doctrine\ORM\ORMException; use Doctrine\ORM\Query\ResultSetMapping; +use Doctrine\Tests\Models\DDC753\DDC753CustomRepository; use ReflectionClass; -use PHPUnit_Framework_TestCase; +use PHPUnit\Framework\TestCase; /** * Tests for the Configuration object * @author Marco Pivetta */ -class ConfigurationTest extends PHPUnit_Framework_TestCase +class ConfigurationTest extends TestCase { /** * @var Configuration @@ -75,34 +77,34 @@ public function testSetGetMetadataDriverImpl() public function testNewDefaultAnnotationDriver() { - $paths = array(__DIR__); - $reflectionClass = new ReflectionClass(__NAMESPACE__ . '\ConfigurationTestAnnotationReaderChecker'); + $paths = [__DIR__]; + $reflectionClass = new ReflectionClass(ConfigurationTestAnnotationReaderChecker::class); $annotationDriver = $this->configuration->newDefaultAnnotationDriver($paths, false); $reader = $annotationDriver->getReader(); $annotation = $reader->getMethodAnnotation( $reflectionClass->getMethod('namespacedAnnotationMethod'), - 'Doctrine\ORM\Mapping\PrePersist' + AnnotationNamespace\PrePersist::class ); - $this->assertInstanceOf('Doctrine\ORM\Mapping\PrePersist', $annotation); + $this->assertInstanceOf(AnnotationNamespace\PrePersist::class, $annotation); $annotationDriver = $this->configuration->newDefaultAnnotationDriver($paths); $reader = $annotationDriver->getReader(); $annotation = $reader->getMethodAnnotation( $reflectionClass->getMethod('simpleAnnotationMethod'), - 'Doctrine\ORM\Mapping\PrePersist' + AnnotationNamespace\PrePersist::class ); - $this->assertInstanceOf('Doctrine\ORM\Mapping\PrePersist', $annotation); + $this->assertInstanceOf(AnnotationNamespace\PrePersist::class, $annotation); } public function testSetGetEntityNamespace() { $this->configuration->addEntityNamespace('TestNamespace', __NAMESPACE__); $this->assertSame(__NAMESPACE__, $this->configuration->getEntityNamespace('TestNamespace')); - $namespaces = array('OtherNamespace' => __NAMESPACE__); + $namespaces = ['OtherNamespace' => __NAMESPACE__]; $this->configuration->setEntityNamespaces($namespaces); $this->assertSame($namespaces, $this->configuration->getEntityNamespaces()); - $this->expectException(\Doctrine\ORM\ORMException::class); + $this->expectException(ORMException::class); $this->configuration->getEntityNamespace('NonExistingNamespace'); } @@ -135,7 +137,8 @@ public function testAddGetNamedQuery() $dql = 'SELECT u FROM User u'; $this->configuration->addNamedQuery('QueryName', $dql); $this->assertSame($dql, $this->configuration->getNamedQuery('QueryName')); - $this->expectException(\Doctrine\ORM\ORMException::class); + $this->expectException(ORMException::class); + $this->expectExceptionMessage('a named query'); $this->configuration->getNamedQuery('NonExistingQuery'); } @@ -147,8 +150,9 @@ public function testAddGetNamedNativeQuery() $fetched = $this->configuration->getNamedNativeQuery('QueryName'); $this->assertSame($sql, $fetched[0]); $this->assertSame($rsm, $fetched[1]); - $this->expectException(\Doctrine\ORM\ORMException::class); - $this->configuration->getNamedQuery('NonExistingQuery'); + $this->expectException(ORMException::class); + $this->expectExceptionMessage('a named native query'); + $this->configuration->getNamedNativeQuery('NonExistingQuery'); } /** @@ -175,6 +179,8 @@ public function testEnsureProductionSettings() { $this->setProductionSettings(); $this->configuration->ensureProductionSettings(); + + $this->addToAssertionCount(1); } public function testEnsureProductionSettingsQueryCache() @@ -257,10 +263,8 @@ public function testAddGetCustomStringFunction() $this->configuration->addCustomStringFunction('FunctionName', __CLASS__); $this->assertSame(__CLASS__, $this->configuration->getCustomStringFunction('FunctionName')); $this->assertSame(null, $this->configuration->getCustomStringFunction('NonExistingFunction')); - $this->configuration->setCustomStringFunctions(array('OtherFunctionName' => __CLASS__)); + $this->configuration->setCustomStringFunctions(['OtherFunctionName' => __CLASS__]); $this->assertSame(__CLASS__, $this->configuration->getCustomStringFunction('OtherFunctionName')); - $this->expectException(\Doctrine\ORM\ORMException::class); - $this->configuration->addCustomStringFunction('concat', __CLASS__); } public function testAddGetCustomNumericFunction() @@ -268,10 +272,8 @@ public function testAddGetCustomNumericFunction() $this->configuration->addCustomNumericFunction('FunctionName', __CLASS__); $this->assertSame(__CLASS__, $this->configuration->getCustomNumericFunction('FunctionName')); $this->assertSame(null, $this->configuration->getCustomNumericFunction('NonExistingFunction')); - $this->configuration->setCustomNumericFunctions(array('OtherFunctionName' => __CLASS__)); + $this->configuration->setCustomNumericFunctions(['OtherFunctionName' => __CLASS__]); $this->assertSame(__CLASS__, $this->configuration->getCustomNumericFunction('OtherFunctionName')); - $this->expectException(\Doctrine\ORM\ORMException::class); - $this->configuration->addCustomNumericFunction('abs', __CLASS__); } public function testAddGetCustomDatetimeFunction() @@ -279,10 +281,8 @@ public function testAddGetCustomDatetimeFunction() $this->configuration->addCustomDatetimeFunction('FunctionName', __CLASS__); $this->assertSame(__CLASS__, $this->configuration->getCustomDatetimeFunction('FunctionName')); $this->assertSame(null, $this->configuration->getCustomDatetimeFunction('NonExistingFunction')); - $this->configuration->setCustomDatetimeFunctions(array('OtherFunctionName' => __CLASS__)); + $this->configuration->setCustomDatetimeFunctions(['OtherFunctionName' => __CLASS__]); $this->assertSame(__CLASS__, $this->configuration->getCustomDatetimeFunction('OtherFunctionName')); - $this->expectException(\Doctrine\ORM\ORMException::class); - $this->configuration->addCustomDatetimeFunction('date_add', __CLASS__); } public function testAddGetCustomHydrationMode() @@ -298,9 +298,9 @@ public function testSetCustomHydrationModes() $this->assertSame(__CLASS__, $this->configuration->getCustomHydrationMode('HydrationModeName')); $this->configuration->setCustomHydrationModes( - array( + [ 'AnotherHydrationModeName' => __CLASS__ - ) + ] ); $this->assertNull($this->configuration->getCustomHydrationMode('HydrationModeName')); @@ -309,7 +309,7 @@ public function testSetCustomHydrationModes() public function testSetGetClassMetadataFactoryName() { - $this->assertSame('Doctrine\ORM\Mapping\ClassMetadataFactory', $this->configuration->getClassMetadataFactoryName()); + $this->assertSame(AnnotationNamespace\ClassMetadataFactory::class, $this->configuration->getClassMetadataFactoryName()); $this->configuration->setClassMetadataFactoryName(__CLASS__); $this->assertSame(__CLASS__, $this->configuration->getClassMetadataFactoryName()); } @@ -323,17 +323,16 @@ public function testAddGetFilters() public function setDefaultRepositoryClassName() { - $this->assertSame('Doctrine\ORM\EntityRepository', $this->configuration->getDefaultRepositoryClassName()); - $repositoryClass = 'Doctrine\Tests\Models\DDC753\DDC753CustomRepository'; - $this->configuration->setDefaultRepositoryClassName($repositoryClass); - $this->assertSame($repositoryClass, $this->configuration->getDefaultRepositoryClassName()); - $this->expectException(\Doctrine\ORM\ORMException::class); + $this->assertSame(EntityRepository::class, $this->configuration->getDefaultRepositoryClassName()); + $this->configuration->setDefaultRepositoryClassName(DDC753CustomRepository::class); + $this->assertSame(DDC753CustomRepository::class, $this->configuration->getDefaultRepositoryClassName()); + $this->expectException(ORMException::class); $this->configuration->setDefaultRepositoryClassName(__CLASS__); } public function testSetGetNamingStrategy() { - $this->assertInstanceOf('Doctrine\ORM\Mapping\NamingStrategy', $this->configuration->getNamingStrategy()); + $this->assertInstanceOf(NamingStrategy::class, $this->configuration->getNamingStrategy()); $namingStrategy = $this->createMock(NamingStrategy::class); $this->configuration->setNamingStrategy($namingStrategy); $this->assertSame($namingStrategy, $this->configuration->getNamingStrategy()); @@ -341,7 +340,7 @@ public function testSetGetNamingStrategy() public function testSetGetQuoteStrategy() { - $this->assertInstanceOf('Doctrine\ORM\Mapping\QuoteStrategy', $this->configuration->getQuoteStrategy()); + $this->assertInstanceOf(QuoteStrategy::class, $this->configuration->getQuoteStrategy()); $quoteStrategy = $this->createMock(QuoteStrategy::class); $this->configuration->setQuoteStrategy($quoteStrategy); $this->assertSame($quoteStrategy, $this->configuration->getQuoteStrategy()); @@ -352,8 +351,8 @@ public function testSetGetQuoteStrategy() */ public function testSetGetEntityListenerResolver() { - $this->assertInstanceOf('Doctrine\ORM\Mapping\EntityListenerResolver', $this->configuration->getEntityListenerResolver()); - $this->assertInstanceOf('Doctrine\ORM\Mapping\DefaultEntityListenerResolver', $this->configuration->getEntityListenerResolver()); + $this->assertInstanceOf(EntityListenerResolver::class, $this->configuration->getEntityListenerResolver()); + $this->assertInstanceOf(AnnotationNamespace\DefaultEntityListenerResolver::class, $this->configuration->getEntityListenerResolver()); $resolver = $this->createMock(EntityListenerResolver::class); $this->configuration->setEntityListenerResolver($resolver); $this->assertSame($resolver, $this->configuration->getEntityListenerResolver()); diff --git a/tests/Doctrine/Tests/ORM/Decorator/EntityManagerDecoratorTest.php b/tests/Doctrine/Tests/ORM/Decorator/EntityManagerDecoratorTest.php index c52ce550cbf..14b06893b8b 100644 --- a/tests/Doctrine/Tests/ORM/Decorator/EntityManagerDecoratorTest.php +++ b/tests/Doctrine/Tests/ORM/Decorator/EntityManagerDecoratorTest.php @@ -2,64 +2,97 @@ namespace Doctrine\Tests\ORM\Decorator; +use Doctrine\ORM\Decorator\EntityManagerDecorator; use Doctrine\ORM\EntityManagerInterface; use Doctrine\ORM\Query\ResultSetMapping; +use Doctrine\Tests\VerifyDeprecations; +use PHPUnit\Framework\TestCase; +use function in_array; -class EntityManagerDecoratorTest extends \PHPUnit_Framework_TestCase +class EntityManagerDecoratorTest extends TestCase { + use VerifyDeprecations; + + const VOID_METHODS = [ + 'persist', + 'remove', + 'clear', + 'detach', + 'refresh', + 'flush', + 'initializeObject', + ]; + + /** + * @var EntityManagerInterface|\PHPUnit_Framework_MockObject_MockObject + */ private $wrapped; - private $decorator; public function setUp() { $this->wrapped = $this->createMock(EntityManagerInterface::class); - $this->decorator = $this->getMockBuilder('Doctrine\ORM\Decorator\EntityManagerDecorator') - ->setConstructorArgs(array($this->wrapped)) - ->setMethods(null) - ->getMock(); } public function getMethodParameters() { - $class = new \ReflectionClass('Doctrine\ORM\EntityManager'); + $class = new \ReflectionClass(EntityManagerInterface::class); + $methods = []; - $methods = array(); foreach ($class->getMethods() as $method) { if ($method->isConstructor() || $method->isStatic() || !$method->isPublic()) { continue; } - /** Special case EntityManager::createNativeQuery() */ - if ($method->getName() === 'createNativeQuery') { - $methods[] = array($method->getName(), array('name', new ResultSetMapping())); - continue; - } - - 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()); - } + $methods[$method->getName()] = $this->getParameters($method); } return $methods; } + private function getParameters(\ReflectionMethod $method) + { + /** Special case EntityManager::createNativeQuery() */ + if ($method->getName() === 'createNativeQuery') { + return [$method->getName(), ['name', new ResultSetMapping()]]; + } + + if ($method->getNumberOfRequiredParameters() === 0) { + return [$method->getName(), []]; + } + + if ($method->getNumberOfRequiredParameters() > 0) { + return [$method->getName(), array_fill(0, $method->getNumberOfRequiredParameters(), 'req') ?: []]; + } + + if ($method->getNumberOfParameters() != $method->getNumberOfRequiredParameters()) { + return [$method->getName(), array_fill(0, $method->getNumberOfParameters(), 'all') ?: []]; + } + + return []; + } + /** * @dataProvider getMethodParameters */ public function testAllMethodCallsAreDelegatedToTheWrappedInstance($method, array $parameters) { - $stub = $this->wrapped - ->expects($this->once()) + $return = !in_array($method, self::VOID_METHODS) ? 'INNER VALUE FROM ' . $method : null; + + $this->wrapped->expects($this->once()) ->method($method) - ->will($this->returnValue('INNER VALUE FROM ' . $method)); + ->with(...$parameters) + ->willReturn($return); - call_user_func_array(array($stub, 'with'), $parameters); + $decorator = new class ($this->wrapped) extends EntityManagerDecorator { + }; + + $this->assertSame($return, $decorator->$method(...$parameters)); + + if (in_array($method, ['copy', 'merge', 'detach', 'getHydrator'], true)) { + $this->assertHasDeprecationMessages(); + return; + } - $this->assertSame('INNER VALUE FROM ' . $method, call_user_func_array(array($this->decorator, $method), $parameters)); + $this->assertNotHasDeprecationMessages(); } } diff --git a/tests/Doctrine/Tests/ORM/EntityManagerTest.php b/tests/Doctrine/Tests/ORM/EntityManagerTest.php index cf6fc99a439..3eaf47d9f5f 100644 --- a/tests/Doctrine/Tests/ORM/EntityManagerTest.php +++ b/tests/Doctrine/Tests/ORM/EntityManagerTest.php @@ -2,13 +2,33 @@ namespace Doctrine\Tests\ORM; +use Doctrine\Common\EventManager; +use Doctrine\Common\Persistence\Mapping\Driver\MappingDriver; +use Doctrine\Common\Persistence\Mapping\MappingException; +use Doctrine\DBAL\Connection; +use Doctrine\ORM\Configuration; +use Doctrine\ORM\EntityManager; +use Doctrine\ORM\Mapping\ClassMetadataFactory; +use Doctrine\ORM\NativeQuery; use Doctrine\ORM\ORMException; use Doctrine\ORM\ORMInvalidArgumentException; +use Doctrine\ORM\Proxy\ProxyFactory; +use Doctrine\ORM\Query; use Doctrine\ORM\Query\ResultSetMapping; +use Doctrine\ORM\QueryBuilder; +use Doctrine\ORM\UnitOfWork; +use Doctrine\Tests\Models\CMS\CmsUser; +use Doctrine\Tests\Models\GeoNames\Country; use Doctrine\Tests\OrmTestCase; +use Doctrine\Tests\VerifyDeprecations; class EntityManagerTest extends OrmTestCase { + use VerifyDeprecations; + + /** + * @var EntityManager + */ private $_em; function setUp() @@ -29,32 +49,32 @@ public function testIsOpen() public function testGetConnection() { - $this->assertInstanceOf('Doctrine\DBAL\Connection', $this->_em->getConnection()); + $this->assertInstanceOf(Connection::class, $this->_em->getConnection()); } public function testGetMetadataFactory() { - $this->assertInstanceOf('Doctrine\ORM\Mapping\ClassMetadataFactory', $this->_em->getMetadataFactory()); + $this->assertInstanceOf(ClassMetadataFactory::class, $this->_em->getMetadataFactory()); } public function testGetConfiguration() { - $this->assertInstanceOf('Doctrine\ORM\Configuration', $this->_em->getConfiguration()); + $this->assertInstanceOf(Configuration::class, $this->_em->getConfiguration()); } public function testGetUnitOfWork() { - $this->assertInstanceOf('Doctrine\ORM\UnitOfWork', $this->_em->getUnitOfWork()); + $this->assertInstanceOf(UnitOfWork::class, $this->_em->getUnitOfWork()); } public function testGetProxyFactory() { - $this->assertInstanceOf('Doctrine\ORM\Proxy\ProxyFactory', $this->_em->getProxyFactory()); + $this->assertInstanceOf(ProxyFactory::class, $this->_em->getProxyFactory()); } public function testGetEventManager() { - $this->assertInstanceOf('Doctrine\Common\EventManager', $this->_em->getEventManager()); + $this->assertInstanceOf(EventManager::class, $this->_em->getEventManager()); } public function testCreateNativeQuery() @@ -66,27 +86,27 @@ public function testCreateNativeQuery() } /** - * @covers Doctrine\ORM\EntityManager::createNamedNativeQuery + * @covers \Doctrine\ORM\EntityManager::createNamedNativeQuery */ public function testCreateNamedNativeQuery() { $rsm = new ResultSetMapping(); $this->_em->getConfiguration()->addNamedNativeQuery('foo', 'SELECT foo', $rsm); - + $query = $this->_em->createNamedNativeQuery('foo'); - - $this->assertInstanceOf('Doctrine\ORM\NativeQuery', $query); + + $this->assertInstanceOf(NativeQuery::class, $query); } public function testCreateQueryBuilder() { - $this->assertInstanceOf('Doctrine\ORM\QueryBuilder', $this->_em->createQueryBuilder()); + $this->assertInstanceOf(QueryBuilder::class, $this->_em->createQueryBuilder()); } public function testCreateQueryBuilderAliasValid() { $q = $this->_em->createQueryBuilder() - ->select('u')->from('Doctrine\Tests\Models\CMS\CmsUser', 'u'); + ->select('u')->from(CmsUser::class, 'u'); $q2 = clone $q; $this->assertEquals('SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u', $q->getQuery()->getDql()); @@ -99,12 +119,12 @@ public function testCreateQueryBuilderAliasValid() public function testCreateQuery_DqlIsOptional() { - $this->assertInstanceOf('Doctrine\ORM\Query', $this->_em->createQuery()); + $this->assertInstanceOf(Query::class, $this->_em->createQuery()); } public function testGetPartialReference() { - $user = $this->_em->getPartialReference('Doctrine\Tests\Models\CMS\CmsUser', 42); + $user = $this->_em->getPartialReference(CmsUser::class, 42); $this->assertTrue($this->_em->contains($user)); $this->assertEquals(42, $user->id); $this->assertNull($user->getName()); @@ -113,31 +133,31 @@ public function testGetPartialReference() public function testCreateQuery() { $q = $this->_em->createQuery('SELECT 1'); - $this->assertInstanceOf('Doctrine\ORM\Query', $q); + $this->assertInstanceOf(Query::class, $q); $this->assertEquals('SELECT 1', $q->getDql()); } - + /** * @covers Doctrine\ORM\EntityManager::createNamedQuery */ public function testCreateNamedQuery() { $this->_em->getConfiguration()->addNamedQuery('foo', 'SELECT 1'); - + $query = $this->_em->createNamedQuery('foo'); - $this->assertInstanceOf('Doctrine\ORM\Query', $query); + $this->assertInstanceOf(Query::class, $query); $this->assertEquals('SELECT 1', $query->getDql()); } static public function dataMethodsAffectedByNoObjectArguments() { - return array( - array('persist'), - array('remove'), - array('merge'), - array('refresh'), - array('detach') - ); + return [ + ['persist'], + ['remove'], + ['merge'], + ['refresh'], + ['detach'] + ]; } /** @@ -152,13 +172,13 @@ public function testThrowsExceptionOnNonObjectValues($methodName) { static public function dataAffectedByErrorIfClosedException() { - return array( - array('flush'), - array('persist'), - array('remove'), - array('merge'), - array('refresh'), - ); + return [ + ['flush'], + ['persist'], + ['remove'], + ['merge'], + ['refresh'], + ]; } /** @@ -188,7 +208,7 @@ public function testTransactionalAcceptsReturn() public function testTransactionalAcceptsVariousCallables() { - $this->assertSame('callback', $this->_em->transactional(array($this, 'transactionalCallback'))); + $this->assertSame('callback', $this->_em->transactional([$this, 'transactionalCallback'])); } public function testTransactionalThrowsInvalidArgumentExceptionIfNonCallablePassed() @@ -204,4 +224,137 @@ public function transactionalCallback($em) $this->assertSame($this->_em, $em); return 'callback'; } + + public function testCreateInvalidConnection() + { + $this->expectException(\InvalidArgumentException::class); + $this->expectExceptionMessage('Invalid $connection argument of type integer given: "1".'); + + $config = new Configuration(); + $config->setMetadataDriverImpl($this->createMock(MappingDriver::class)); + EntityManager::create(1, $config); + } + + /** + * @group #5796 + */ + public function testTransactionalReThrowsThrowables() + { + try { + $this->_em->transactional(function () { + (function (array $value) { + // this only serves as an IIFE that throws a `TypeError` + })(null); + }); + + self::fail('TypeError expected to be thrown'); + } catch (\TypeError $ignored) { + self::assertFalse($this->_em->isOpen()); + } + } + + /** + * @group 6017 + */ + public function testClearManagerWithObject() + { + $entity = new Country(456, 'United Kingdom'); + + $this->expectException(ORMInvalidArgumentException::class); + + $this->_em->clear($entity); + } + + /** + * @group 6017 + */ + public function testClearManagerWithUnknownEntityName() + { + $this->expectException(MappingException::class); + + $this->_em->clear(uniqid('nonExisting', true)); + } + + /** + * @group 6017 + */ + public function testClearManagerWithProxyClassName() + { + $proxy = $this->_em->getReference(Country::class, ['id' => random_int(457, 100000)]); + + $entity = new Country(456, 'United Kingdom'); + + $this->_em->persist($entity); + + $this->assertTrue($this->_em->contains($entity)); + + $this->_em->clear(get_class($proxy)); + + $this->assertFalse($this->_em->contains($entity)); + } + + /** + * @group 6017 + */ + public function testClearManagerWithNullValue() + { + $entity = new Country(456, 'United Kingdom'); + + $this->_em->persist($entity); + + $this->assertTrue($this->_em->contains($entity)); + + $this->_em->clear(null); + + $this->assertFalse($this->_em->contains($entity)); + } + + public function testDeprecatedClearWithArguments() : void + { + $entity = new Country(456, 'United Kingdom'); + $this->_em->persist($entity); + + $this->expectDeprecationMessage('Calling Doctrine\ORM\EntityManager::clear() with any arguments to clear specific entities is deprecated and will not be supported in Doctrine ORM 3.0.'); + $this->_em->clear(Country::class); + } + + public function testDeprecatedFlushWithArguments() : void + { + $entity = new Country(456, 'United Kingdom'); + $this->_em->persist($entity); + + $this->expectDeprecationMessage('Calling Doctrine\ORM\EntityManager::flush() with any arguments to flush specific entities is deprecated and will not be supported in Doctrine ORM 3.0.'); + $this->_em->flush($entity); + } + + public function testDeprecatedMerge() : void + { + $entity = new Country(456, 'United Kingdom'); + $this->_em->persist($entity); + + $this->expectDeprecationMessage('Method Doctrine\ORM\EntityManager::merge() is deprecated and will be removed in Doctrine ORM 3.0.'); + $this->_em->merge($entity); + } + + public function testDeprecatedDetach() : void + { + $entity = new Country(456, 'United Kingdom'); + $this->_em->persist($entity); + + $this->expectDeprecationMessage('Method Doctrine\ORM\EntityManager::detach() is deprecated and will be removed in Doctrine ORM 3.0.'); + $this->_em->detach($entity); + } + + public function testDeprecatedCopy() : void + { + $entity = new Country(456, 'United Kingdom'); + $this->_em->persist($entity); + + try { + $this->expectDeprecationMessage('Method Doctrine\ORM\EntityManager::copy() is deprecated and will be removed in Doctrine ORM 3.0.'); + $this->_em->copy($entity); + } catch (\BadMethodCallException $e) { + // do nothing + } + } } diff --git a/tests/Doctrine/Tests/ORM/EntityNotFoundExceptionTest.php b/tests/Doctrine/Tests/ORM/EntityNotFoundExceptionTest.php index 7dce1b17169..ec1cfbfc99c 100644 --- a/tests/Doctrine/Tests/ORM/EntityNotFoundExceptionTest.php +++ b/tests/Doctrine/Tests/ORM/EntityNotFoundExceptionTest.php @@ -3,31 +3,31 @@ namespace Doctrine\Tests\ORM; use Doctrine\ORM\EntityNotFoundException; -use PHPUnit_Framework_TestCase; +use PHPUnit\Framework\TestCase; /** * Tests for {@see \Doctrine\ORM\EntityNotFoundException} * * @covers \Doctrine\ORM\EntityNotFoundException */ -class EntityNotFoundExceptionTest extends PHPUnit_Framework_TestCase +class EntityNotFoundExceptionTest extends TestCase { public function testFromClassNameAndIdentifier() { $exception = EntityNotFoundException::fromClassNameAndIdentifier( 'foo', - array('foo' => 'bar') + ['foo' => 'bar'] ); - $this->assertInstanceOf('Doctrine\ORM\EntityNotFoundException', $exception); + $this->assertInstanceOf(EntityNotFoundException::class, $exception); $this->assertSame('Entity of type \'foo\' for IDs foo(bar) was not found', $exception->getMessage()); $exception = EntityNotFoundException::fromClassNameAndIdentifier( 'foo', - array() + [] ); - $this->assertInstanceOf('Doctrine\ORM\EntityNotFoundException', $exception); + $this->assertInstanceOf(EntityNotFoundException::class, $exception); $this->assertSame('Entity of type \'foo\' was not found', $exception->getMessage()); } } diff --git a/tests/Doctrine/Tests/ORM/Event/OnClassMetadataNotFoundEventArgsTest.php b/tests/Doctrine/Tests/ORM/Event/OnClassMetadataNotFoundEventArgsTest.php index 54f2feb0dd8..e5f62bd26ae 100644 --- a/tests/Doctrine/Tests/ORM/Event/OnClassMetadataNotFoundEventArgsTest.php +++ b/tests/Doctrine/Tests/ORM/Event/OnClassMetadataNotFoundEventArgsTest.php @@ -5,14 +5,14 @@ use Doctrine\Common\Persistence\Mapping\ClassMetadata; use Doctrine\Common\Persistence\ObjectManager; use Doctrine\ORM\Event\OnClassMetadataNotFoundEventArgs; -use PHPUnit_Framework_TestCase; +use PHPUnit\Framework\TestCase; /** * Tests for {@see \Doctrine\ORM\Event\OnClassMetadataNotFoundEventArgs} * * @covers \Doctrine\ORM\Event\OnClassMetadataNotFoundEventArgs */ -class OnClassMetadataNotFoundEventArgsTest extends PHPUnit_Framework_TestCase +class OnClassMetadataNotFoundEventArgsTest extends TestCase { public function testEventArgsMutability() { diff --git a/tests/Doctrine/Tests/ORM/Functional/AbstractManyToManyAssociationTestCase.php b/tests/Doctrine/Tests/ORM/Functional/AbstractManyToManyAssociationTestCase.php index 37f0fcd2982..26445c1417a 100644 --- a/tests/Doctrine/Tests/ORM/Functional/AbstractManyToManyAssociationTestCase.php +++ b/tests/Doctrine/Tests/ORM/Functional/AbstractManyToManyAssociationTestCase.php @@ -31,7 +31,8 @@ protected function _countForeignKeys($firstId, $secondId) FROM {$this->_table} WHERE {$this->_firstField} = ? AND {$this->_secondField} = ? - ", array($firstId, $secondId))->fetchAll()); + ", [$firstId, $secondId] + )->fetchAll()); } public function assertCollectionEquals(Collection $first, Collection $second) diff --git a/tests/Doctrine/Tests/ORM/Functional/AdvancedAssociationTest.php b/tests/Doctrine/Tests/ORM/Functional/AdvancedAssociationTest.php index 5546b285e86..e6714500cd5 100644 --- a/tests/Doctrine/Tests/ORM/Functional/AdvancedAssociationTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/AdvancedAssociationTest.php @@ -3,7 +3,7 @@ namespace Doctrine\Tests\ORM\Functional; use Doctrine\Common\Collections\ArrayCollection; -use Doctrine\ORM\Query; +use Doctrine\ORM\PersistentCollection; use Doctrine\Tests\OrmFunctionalTestCase; /** @@ -16,13 +16,15 @@ class AdvancedAssociationTest extends OrmFunctionalTestCase protected function setUp() { parent::setUp(); try { - $this->_schemaTool->createSchema(array( - $this->_em->getClassMetadata('Doctrine\Tests\ORM\Functional\Phrase'), - $this->_em->getClassMetadata('Doctrine\Tests\ORM\Functional\PhraseType'), - $this->_em->getClassMetadata('Doctrine\Tests\ORM\Functional\Definition'), - $this->_em->getClassMetadata('Doctrine\Tests\ORM\Functional\Lemma'), - $this->_em->getClassMetadata('Doctrine\Tests\ORM\Functional\Type') - )); + $this->_schemaTool->createSchema( + [ + $this->_em->getClassMetadata(Phrase::class), + $this->_em->getClassMetadata(PhraseType::class), + $this->_em->getClassMetadata(Definition::class), + $this->_em->getClassMetadata(Lemma::class), + $this->_em->getClassMetadata(Type::class) + ] + ); } catch (\Exception $e) { // Swallow all exceptions. We do not test the schema tool here. } @@ -55,7 +57,7 @@ public function testIssue() //end setup // test1 - lazy-loading many-to-one after find() - $phrase2 = $this->_em->find('Doctrine\Tests\ORM\Functional\Phrase', $phrase->getId()); + $phrase2 = $this->_em->find(Phrase::class, $phrase->getId()); $this->assertTrue(is_numeric($phrase2->getType()->getId())); $this->_em->clear(); @@ -64,8 +66,8 @@ public function testIssue() $query = $this->_em->createQuery("SELECT p,t FROM Doctrine\Tests\ORM\Functional\Phrase p JOIN p.type t"); $res = $query->getResult(); $this->assertEquals(1, count($res)); - $this->assertInstanceOf('Doctrine\Tests\ORM\Functional\PhraseType', $res[0]->getType()); - $this->assertInstanceOf('Doctrine\ORM\PersistentCollection', $res[0]->getType()->getPhrases()); + $this->assertInstanceOf(PhraseType::class, $res[0]->getType()); + $this->assertInstanceOf(PersistentCollection::class, $res[0]->getType()->getPhrases()); $this->assertFalse($res[0]->getType()->getPhrases()->isInitialized()); $this->_em->clear(); @@ -74,17 +76,17 @@ public function testIssue() $query = $this->_em->createQuery("SELECT p,t,pp FROM Doctrine\Tests\ORM\Functional\Phrase p JOIN p.type t JOIN t.phrases pp"); $res = $query->getResult(); $this->assertEquals(1, count($res)); - $this->assertInstanceOf('Doctrine\Tests\ORM\Functional\PhraseType', $res[0]->getType()); - $this->assertInstanceOf('Doctrine\ORM\PersistentCollection', $res[0]->getType()->getPhrases()); + $this->assertInstanceOf(PhraseType::class, $res[0]->getType()); + $this->assertInstanceOf(PersistentCollection::class, $res[0]->getType()->getPhrases()); $this->assertTrue($res[0]->getType()->getPhrases()->isInitialized()); $this->_em->clear(); // test3 - lazy-loading one-to-many after find() - $phrase3 = $this->_em->find('Doctrine\Tests\ORM\Functional\Phrase', $phrase->getId()); + $phrase3 = $this->_em->find(Phrase::class, $phrase->getId()); $definitions = $phrase3->getDefinitions(); - $this->assertInstanceOf('Doctrine\ORM\PersistentCollection', $definitions); - $this->assertInstanceOf('Doctrine\Tests\ORM\Functional\Definition', $definitions[0]); + $this->assertInstanceOf(PersistentCollection::class, $definitions); + $this->assertInstanceOf(Definition::class, $definitions[0]); $this->_em->clear(); @@ -95,7 +97,7 @@ public function testIssue() $this->assertEquals(1, count($res)); - $this->assertInstanceOf('Doctrine\Tests\ORM\Functional\Definition', $definitions[0]); + $this->assertInstanceOf(Definition::class, $definitions[0]); $this->assertEquals(2, $definitions->count()); } @@ -119,7 +121,7 @@ public function testManyToMany() $res = $query->getResult(); $types = $res[0]->getTypes(); - $this->assertInstanceOf('Doctrine\Tests\ORM\Functional\Type', $types[0]); + $this->assertInstanceOf(Type::class, $types[0]); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/BasicFunctionalTest.php b/tests/Doctrine/Tests/ORM/Functional/BasicFunctionalTest.php index bee055f84ee..7f19fa83010 100644 --- a/tests/Doctrine/Tests/ORM/Functional/BasicFunctionalTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/BasicFunctionalTest.php @@ -6,17 +6,22 @@ use Doctrine\ORM\EntityNotFoundException; use Doctrine\ORM\Mapping\ClassMetadata; use Doctrine\ORM\ORMInvalidArgumentException; +use Doctrine\ORM\PersistentCollection; +use Doctrine\ORM\Proxy\Proxy; use Doctrine\ORM\Query; use Doctrine\ORM\UnitOfWork; -use Doctrine\Tests\Models\CMS\CmsUser; -use Doctrine\Tests\Models\CMS\CmsPhonenumber; use Doctrine\Tests\Models\CMS\CmsAddress; use Doctrine\Tests\Models\CMS\CmsArticle; use Doctrine\Tests\Models\CMS\CmsComment; +use Doctrine\Tests\Models\CMS\CmsPhonenumber; +use Doctrine\Tests\Models\CMS\CmsUser; use Doctrine\Tests\OrmFunctionalTestCase; +use Doctrine\Tests\VerifyDeprecations; class BasicFunctionalTest extends OrmFunctionalTestCase { + use VerifyDeprecations; + protected function setUp() { $this->useModelSet('cms'); @@ -38,7 +43,7 @@ public function testBasicUnitsOfWorkWithOneToManyAssociation() $this->assertTrue($this->_em->contains($user)); // Read - $user2 = $this->_em->find('Doctrine\Tests\Models\CMS\CmsUser', $user->id); + $user2 = $this->_em->find(CmsUser::class, $user->id); $this->assertTrue($user === $user2); // Add a phonenumber @@ -48,7 +53,6 @@ public function testBasicUnitsOfWorkWithOneToManyAssociation() $this->_em->flush(); $this->assertTrue($this->_em->contains($ph)); $this->assertTrue($this->_em->contains($user)); - //$this->assertInstanceOf('Doctrine\ORM\PersistentCollection', $user->phonenumbers); // Update name $user->name = 'guilherme'; @@ -94,8 +98,6 @@ public function testOneToManyAssociationModification() $this->_em->persist($user); $this->_em->flush(); - //$this->assertInstanceOf('Doctrine\ORM\PersistentCollection', $user->phonenumbers); - // Remove the first element from the collection unset($user->phonenumbers[0]); $ph1->user = null; // owning side! @@ -127,7 +129,7 @@ public function testBasicOneToOne() // Check that the foreign key has been set $userId = $this->_em->getConnection()->executeQuery( - "SELECT user_id FROM cms_addresses WHERE id=?", array($address->id) + "SELECT user_id FROM cms_addresses WHERE id=?", [$address->id] )->fetchColumn(); $this->assertTrue(is_numeric($userId)); @@ -138,8 +140,8 @@ public function testBasicOneToOne() ->getSingleResult(); // Address has been eager-loaded because it cant be lazy - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsAddress', $user2->address); - $this->assertNotInstanceOf('Doctrine\ORM\Proxy\Proxy', $user2->address); + $this->assertInstanceOf(CmsAddress::class, $user2->address); + $this->assertNotInstanceOf(Proxy::class, $user2->address); } /** @@ -173,7 +175,7 @@ public function testRemove() $this->assertEquals(UnitOfWork::STATE_NEW, $this->_em->getUnitOfWork()->getEntityState($user), "State should be UnitOfWork::STATE_NEW"); - $this->assertNull($this->_em->find('Doctrine\Tests\Models\CMS\CmsUser', $id)); + $this->assertNull($this->_em->find(CmsUser::class, $id)); } public function testOneToManyOrphanRemoval() @@ -278,10 +280,9 @@ public function testBasicOneToManyLeftJoin() $this->assertEquals('Guilherme', $users[0]->name); $this->assertEquals('gblanco', $users[0]->username); $this->assertEquals('developer', $users[0]->status); - $this->assertInstanceOf('Doctrine\ORM\PersistentCollection', $users[0]->phonenumbers); + $this->assertInstanceOf(PersistentCollection::class, $users[0]->phonenumbers); $this->assertTrue($users[0]->phonenumbers->isInitialized()); $this->assertEquals(0, $users[0]->phonenumbers->count()); - //$this->assertNull($users[0]->articles); } public function testBasicRefresh() @@ -395,7 +396,7 @@ public function testCreateEntityOfProxy() $this->_em->clear(); $userId = $user->id; - $user = $this->_em->getReference('Doctrine\Tests\Models\CMS\CmsUser', $user->id); + $user = $this->_em->getReference(CmsUser::class, $user->id); $dql = "SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.id = ?1"; $user = $this->_em->createQuery($dql) @@ -501,17 +502,14 @@ public function testSetSetAssociationWithGetReference() $this->_em->persist($address); $this->_em->flush(); - $this->_em->detach($address); + $this->_em->clear(CmsAddress::class); $this->assertFalse($this->_em->contains($address)); $this->assertTrue($this->_em->contains($user)); // Assume we only got the identifier of the address and now want to attach // that address to the user without actually loading it, using getReference(). - $addressRef = $this->_em->getReference('Doctrine\Tests\Models\CMS\CmsAddress', $address->getId()); - - //$addressRef->getId(); - //\Doctrine\Common\Util\Debug::dump($addressRef); + $addressRef = $this->_em->getReference(CmsAddress::class, $address->getId()); $user->setAddress($addressRef); // Ugh! Initializes address 'cause of $address->setUser($user)! @@ -522,8 +520,8 @@ public function testSetSetAssociationWithGetReference() $query = $this->_em->createQuery("select u, a from Doctrine\Tests\Models\CMS\CmsUser u join u.address a where u.username='gblanco'"); $gblanco = $query->getSingleResult(); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsUser', $gblanco); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsAddress', $gblanco->getAddress()); + $this->assertInstanceOf(CmsUser::class, $gblanco); + $this->assertInstanceOf(CmsAddress::class, $gblanco->getAddress()); $this->assertEquals('Berlin', $gblanco->getAddress()->getCity()); } @@ -594,7 +592,7 @@ public function testTextColumnSaveAndRetrieve() $this->_em->flush(); $this->_em->clear(); - $articleNew = $this->_em->find('Doctrine\Tests\Models\CMS\CmsArticle', $articleId); + $articleNew = $this->_em->find(CmsArticle::class, $articleId); $this->assertEquals("Lorem ipsum dolor sunt. And stuff!", $articleNew->text); $this->assertTrue($this->_em->contains($articleNew)); } @@ -631,7 +629,7 @@ public function testFlushDoesNotIssueUnnecessaryUpdates() $user2 = $query->getSingleResult(); $this->assertEquals(1, count($user2->articles)); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsAddress', $user2->address); + $this->assertInstanceOf(CmsAddress::class, $user2->address); $oldLogger = $this->_em->getConnection()->getConfiguration()->getSQLLogger(); $debugStack = new DebugStack(); @@ -656,7 +654,7 @@ public function testRemoveEntityByReference() $this->_em->flush(); $this->_em->clear(); - $userRef = $this->_em->getReference('Doctrine\Tests\Models\CMS\CmsUser', $user->getId()); + $userRef = $this->_em->getReference(CmsUser::class, $user->getId()); $this->_em->remove($userRef); $this->_em->flush(); $this->_em->clear(); @@ -687,12 +685,12 @@ public function testQueryEntityByReference() //$this->_em->getConnection()->getConfiguration()->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger); - $userRef = $this->_em->getReference('Doctrine\Tests\Models\CMS\CmsUser', $user->getId()); + $userRef = $this->_em->getReference(CmsUser::class, $user->getId()); $address2 = $this->_em->createQuery('select a from Doctrine\Tests\Models\CMS\CmsAddress a where a.user = :user') ->setParameter('user', $userRef) ->getSingleResult(); - $this->assertInstanceOf('Doctrine\ORM\Proxy\Proxy', $address2->getUser()); + $this->assertInstanceOf(Proxy::class, $address2->getUser()); $this->assertTrue($userRef === $address2->getUser()); $this->assertFalse($userRef->__isInitialized__); $this->assertEquals('Germany', $address2->country); @@ -732,7 +730,6 @@ public function testOneToOneNullUpdate() */ public function testNewAssociatedEntityDuringFlushThrowsException() { - //$this->_em->getConnection()->getConfiguration()->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger); $user = new CmsUser(); $user->username = "beberlei"; $user->name = "Benjamin E."; @@ -746,11 +743,10 @@ public function testNewAssociatedEntityDuringFlushThrowsException() $address->user = $user; $this->_em->persist($address); - // pretend we forgot to persist $user - try { - $this->_em->flush(); // should raise an exception - $this->fail(); - } catch (\InvalidArgumentException $expected) {} + + // flushing without persisting $user should raise an exception + $this->expectException(\InvalidArgumentException::class); + $this->_em->flush(); } /** @@ -759,7 +755,6 @@ public function testNewAssociatedEntityDuringFlushThrowsException() */ public function testNewAssociatedEntityDuringFlushThrowsException2() { - //$this->_em->getConnection()->getConfiguration()->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger); $user = new CmsUser(); $user->username = "beberlei"; $user->name = "Benjamin E."; @@ -781,11 +776,10 @@ public function testNewAssociatedEntityDuringFlushThrowsException2() $u2->name = "Benjamin E."; $u2->status = 'inactive'; $address->user = $u2; - // pretend we forgot to persist $u2 - try { - $this->_em->flush(); // should raise an exception - $this->fail(); - } catch (\InvalidArgumentException $expected) {} + + // flushing without persisting $u2 should raise an exception + $this->expectException(\InvalidArgumentException::class); + $this->_em->flush(); } /** @@ -794,7 +788,6 @@ public function testNewAssociatedEntityDuringFlushThrowsException2() */ public function testNewAssociatedEntityDuringFlushThrowsException3() { - //$this->_em->getConnection()->getConfiguration()->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger); $art = new CmsArticle(); $art->topic = 'topic'; $art->text = 'the text'; @@ -805,11 +798,10 @@ public function testNewAssociatedEntityDuringFlushThrowsException3() $art->addComment($com); $this->_em->persist($art); - // pretend we forgot to persist $com - try { - $this->_em->flush(); // should raise an exception - $this->fail(); - } catch (\InvalidArgumentException $expected) {} + + // flushing without persisting $com should raise an exception + $this->expectException(\InvalidArgumentException::class); + $this->_em->flush(); } public function testOneToOneOrphanRemoval() @@ -872,7 +864,7 @@ public function testGetPartialReferenceToUpdateObjectWithoutLoadingIt() $userId = $user->id; $this->_em->clear(); - $user = $this->_em->getPartialReference('Doctrine\Tests\Models\CMS\CmsUser', $userId); + $user = $this->_em->getPartialReference(CmsUser::class, $userId); $this->assertTrue($this->_em->contains($user)); $this->assertNull($user->getName()); $this->assertEquals($userId, $user->id); @@ -904,7 +896,8 @@ public function testMergePersistsNewEntities() $this->_em->clear(); $user2 = $this->_em->find(get_class($managedUser), $userId); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsUser', $user2); + $this->assertInstanceOf(CmsUser::class, $user2); + $this->assertHasDeprecationMessages(); } public function testMergeNonPersistedProperties() @@ -932,6 +925,7 @@ public function testMergeNonPersistedProperties() $this->assertNull($user2->nonPersistedProperty); $this->assertNull($user2->nonPersistedPropertyObject); $this->assertEquals('active', $user2->status); + $this->assertHasDeprecationMessages(); } public function testMergeThrowsExceptionIfEntityWithGeneratedIdentifierDoesNotExist() @@ -941,10 +935,10 @@ public function testMergeThrowsExceptionIfEntityWithGeneratedIdentifierDoesNotEx $user->name = "Benjamin E."; $user->status = 'active'; $user->id = 42; - try { - $this->_em->merge($user); - $this->fail(); - } catch (EntityNotFoundException $enfe) {} + + $this->expectException(EntityNotFoundException::class); + $this->_em->merge($user); + $this->assertHasDeprecationMessages(); } /** @@ -952,7 +946,6 @@ public function testMergeThrowsExceptionIfEntityWithGeneratedIdentifierDoesNotEx */ public function testOneToOneMergeSetNull() { - //$this->_em->getConnection()->getConfiguration()->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger); $user = new CmsUser(); $user->username = "beberlei"; $user->name = "Benjamin E."; @@ -975,6 +968,7 @@ public function testOneToOneMergeSetNull() $this->_em->clear(); $this->assertNull($this->_em->find(get_class($ph), $ph->phonenumber)->getUser()); + $this->assertHasDeprecationMessages(); } /** @@ -1001,9 +995,9 @@ public function testManyToOneFetchModeQuery() $dql = "SELECT a FROM Doctrine\Tests\Models\CMS\CmsArticle a WHERE a.id = ?1"; $article = $this->_em->createQuery($dql) ->setParameter(1, $article->id) - ->setFetchMode('Doctrine\Tests\Models\CMS\CmsArticle', 'user', ClassMetadata::FETCH_EAGER) + ->setFetchMode(CmsArticle::class, 'user', ClassMetadata::FETCH_EAGER) ->getSingleResult(); - $this->assertInstanceOf('Doctrine\ORM\Proxy\Proxy', $article->user, "It IS a proxy, ..."); + $this->assertInstanceOf(Proxy::class, $article->user, "It IS a proxy, ..."); $this->assertTrue($article->user->__isInitialized__, "...but its initialized!"); $this->assertEquals($qc+2, $this->getCurrentQueryCount()); } @@ -1045,7 +1039,7 @@ public function testClearWithEntityName() $unitOfWork = $this->_em->getUnitOfWork(); - $this->_em->clear('Doctrine\Tests\Models\CMS\CmsUser'); + $this->_em->clear(CmsUser::class); $this->assertEquals(UnitOfWork::STATE_DETACHED, $unitOfWork->getEntityState($user)); $this->assertEquals(UnitOfWork::STATE_DETACHED, $unitOfWork->getEntityState($article1)); @@ -1075,17 +1069,18 @@ public function testFlushManyExplicitEntities() $this->_em->persist($userB); $this->_em->persist($userC); - $this->_em->flush(array($userA, $userB, $userB)); + $this->_em->flush([$userA, $userB, $userB]); $userC->name = 'changed name'; - $this->_em->flush(array($userA, $userB)); + $this->_em->flush([$userA, $userB]); $this->_em->refresh($userC); $this->assertTrue($userA->id > 0, 'user a has an id'); $this->assertTrue($userB->id > 0, 'user b has an id'); $this->assertTrue($userC->id > 0, 'user c has an id'); $this->assertEquals('UserC', $userC->name, 'name has not changed because we did not flush it'); + $this->assertHasDeprecationMessages(); } /** @@ -1107,6 +1102,7 @@ public function testFlushSingleManagedEntity() $user = $this->_em->find(get_class($user), $user->id); $this->assertEquals('administrator', $user->status); + $this->assertHasDeprecationMessages(); } /** @@ -1150,6 +1146,7 @@ public function testFlushSingleAndNewEntity() $this->assertTrue($this->_em->contains($otherUser), "Other user is contained in EntityManager"); $this->assertTrue($otherUser->id > 0, "other user has an id"); + $this->assertHasDeprecationMessages(); } /** @@ -1177,6 +1174,7 @@ public function testFlushAndCascadePersist() $this->assertTrue($this->_em->contains($address), "Other user is contained in EntityManager"); $this->assertTrue($address->id > 0, "other user has an id"); + $this->assertHasDeprecationMessages(); } /** @@ -1226,6 +1224,7 @@ public function testFlushSingleNewEntityThenRemove() $this->_em->clear(); $this->assertNull($this->_em->find(get_class($user), $userId)); + $this->assertHasDeprecationMessages(); } /** @@ -1254,6 +1253,7 @@ public function testProxyIsIgnored() $this->assertTrue($this->_em->contains($otherUser), "Other user is contained in EntityManager"); $this->assertTrue($otherUser->id > 0, "other user has an id"); + $this->assertHasDeprecationMessages(); } /** @@ -1283,6 +1283,7 @@ public function testFlushSingleSaveOnlySingle() $user2 = $this->_em->find(get_class($user2), $user2->id); $this->assertEquals('developer', $user2->status); + $this->assertHasDeprecationMessages(); } /** diff --git a/tests/Doctrine/Tests/ORM/Functional/CascadeRemoveOrderTest.php b/tests/Doctrine/Tests/ORM/Functional/CascadeRemoveOrderTest.php index a2392a3e86d..8908e51e009 100644 --- a/tests/Doctrine/Tests/ORM/Functional/CascadeRemoveOrderTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/CascadeRemoveOrderTest.php @@ -14,20 +14,24 @@ protected function setUp() { parent::setUp(); - $this->_schemaTool->createSchema(array( - $this->_em->getClassMetadata(__NAMESPACE__ . '\CascadeRemoveOrderEntityO'), - $this->_em->getClassMetadata(__NAMESPACE__ . '\CascadeRemoveOrderEntityG'), - )); + $this->_schemaTool->createSchema( + [ + $this->_em->getClassMetadata(CascadeRemoveOrderEntityO::class), + $this->_em->getClassMetadata(CascadeRemoveOrderEntityG::class), + ] + ); } protected function tearDown() { parent::tearDown(); - $this->_schemaTool->dropSchema(array( - $this->_em->getClassMetadata(__NAMESPACE__ . '\CascadeRemoveOrderEntityO'), - $this->_em->getClassMetadata(__NAMESPACE__ . '\CascadeRemoveOrderEntityG'), - )); + $this->_schemaTool->dropSchema( + [ + $this->_em->getClassMetadata(CascadeRemoveOrderEntityO::class), + $this->_em->getClassMetadata(CascadeRemoveOrderEntityG::class), + ] + ); } public function testSingle() @@ -39,10 +43,12 @@ public function testSingle() $this->_em->flush(); $this->_em->clear(); - $eOloaded = $this->_em->find('Doctrine\Tests\ORM\Functional\CascadeRemoveOrderEntityO', $eO->getId()); + $eOloaded = $this->_em->find(CascadeRemoveOrderEntityO::class, $eO->getId()); $this->_em->remove($eOloaded); $this->_em->flush(); + + self::assertNull($this->_em->find(CascadeRemoveOrderEntityG::class, $eG->getId())); } public function testMany() @@ -58,10 +64,14 @@ public function testMany() $this->_em->flush(); $this->_em->clear(); - $eOloaded = $this->_em->find('Doctrine\Tests\ORM\Functional\CascadeRemoveOrderEntityO', $eO->getId()); + $eOloaded = $this->_em->find(CascadeRemoveOrderEntityO::class, $eO->getId()); $this->_em->remove($eOloaded); $this->_em->flush(); + + self::assertNull($this->_em->find(CascadeRemoveOrderEntityG::class, $eG1->getId())); + self::assertNull($this->_em->find(CascadeRemoveOrderEntityG::class, $eG2->getId())); + self::assertNull($this->_em->find(CascadeRemoveOrderEntityG::class, $eG3->getId())); } } @@ -153,4 +163,4 @@ public function getId() { return $this->id; } -} \ No newline at end of file +} diff --git a/tests/Doctrine/Tests/ORM/Functional/ClassTableInheritanceTest.php b/tests/Doctrine/Tests/ORM/Functional/ClassTableInheritanceTest.php index 697f568ffb5..4ece24fa773 100644 --- a/tests/Doctrine/Tests/ORM/Functional/ClassTableInheritanceTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/ClassTableInheritanceTest.php @@ -2,14 +2,16 @@ namespace Doctrine\Tests\ORM\Functional; -use Doctrine\Tests\Models\Company\CompanyPerson, - Doctrine\Tests\Models\Company\CompanyEmployee, - Doctrine\Tests\Models\Company\CompanyManager, - Doctrine\Tests\Models\Company\CompanyOrganization, - Doctrine\Tests\Models\Company\CompanyAuction, - Doctrine\Tests\Models\Company\CompanyRaffle; - use Doctrine\Common\Collections\Criteria; +use Doctrine\ORM\PersistentCollection; +use Doctrine\ORM\Proxy\Proxy; +use Doctrine\Tests\Models\Company\CompanyAuction; +use Doctrine\Tests\Models\Company\CompanyEmployee; +use Doctrine\Tests\Models\Company\CompanyEvent; +use Doctrine\Tests\Models\Company\CompanyManager; +use Doctrine\Tests\Models\Company\CompanyOrganization; +use Doctrine\Tests\Models\Company\CompanyPerson; +use Doctrine\Tests\Models\Company\CompanyRaffle; use Doctrine\Tests\OrmFunctionalTestCase; /** @@ -22,8 +24,8 @@ class ClassTableInheritanceTest extends OrmFunctionalTestCase protected function setUp() { $this->useModelSet('company'); + parent::setUp(); - //$this->_em->getConnection()->getConfiguration()->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger); } public function testCRUD() @@ -45,13 +47,13 @@ public function testCRUD() $this->_em->clear(); - $query = $this->_em->createQuery("select p from Doctrine\Tests\Models\Company\CompanyPerson p order by p.name desc"); + $query = $this->_em->createQuery('select p from ' . CompanyPerson::class . ' p order by p.name desc'); $entities = $query->getResult(); - $this->assertEquals(2, count($entities)); - $this->assertInstanceOf('Doctrine\Tests\Models\Company\CompanyPerson', $entities[0]); - $this->assertInstanceOf('Doctrine\Tests\Models\Company\CompanyEmployee', $entities[1]); + $this->assertCount(2, $entities); + $this->assertInstanceOf(CompanyPerson::class, $entities[0]); + $this->assertInstanceOf(CompanyEmployee::class, $entities[1]); $this->assertTrue(is_numeric($entities[0]->getId())); $this->assertTrue(is_numeric($entities[1]->getId())); $this->assertEquals('Roman S. Borschel', $entities[0]->getName()); @@ -60,25 +62,25 @@ public function testCRUD() $this->_em->clear(); - $query = $this->_em->createQuery("select p from Doctrine\Tests\Models\Company\CompanyEmployee p"); + $query = $this->_em->createQuery('select p from ' . CompanyEmployee::class . ' p'); $entities = $query->getResult(); - $this->assertEquals(1, count($entities)); - $this->assertInstanceOf('Doctrine\Tests\Models\Company\CompanyEmployee', $entities[0]); + $this->assertCount(1, $entities); + $this->assertInstanceOf(CompanyEmployee::class, $entities[0]); $this->assertTrue(is_numeric($entities[0]->getId())); $this->assertEquals('Guilherme Blanco', $entities[0]->getName()); $this->assertEquals(100000, $entities[0]->getSalary()); $this->_em->clear(); - $guilherme = $this->_em->getRepository(get_class($employee))->findOneBy(array('name' => 'Guilherme Blanco')); - $this->assertInstanceOf('Doctrine\Tests\Models\Company\CompanyEmployee', $guilherme); + $guilherme = $this->_em->getRepository(get_class($employee))->findOneBy(['name' => 'Guilherme Blanco']); + $this->assertInstanceOf(CompanyEmployee::class, $guilherme); $this->assertEquals('Guilherme Blanco', $guilherme->getName()); $this->_em->clear(); - $query = $this->_em->createQuery("update Doctrine\Tests\Models\Company\CompanyEmployee p set p.name = ?1, p.department = ?2 where p.name='Guilherme Blanco' and p.salary = ?3"); + $query = $this->_em->createQuery("update " . CompanyEmployee::class . " p set p.name = ?1, p.department = ?2 where p.name='Guilherme Blanco' and p.salary = ?3"); $query->setParameter(1, 'NewName', 'string'); $query->setParameter(2, 'NewDepartment'); $query->setParameter(3, 100000); @@ -86,12 +88,13 @@ public function testCRUD() $numUpdated = $query->execute(); $this->assertEquals(1, $numUpdated); - $query = $this->_em->createQuery("delete from Doctrine\Tests\Models\Company\CompanyPerson p"); + $query = $this->_em->createQuery('delete from ' . CompanyPerson::class . ' p'); $numDeleted = $query->execute(); $this->assertEquals(2, $numDeleted); } - public function testMultiLevelUpdateAndFind() { + public function testMultiLevelUpdateAndFind() + { $manager = new CompanyManager; $manager->setName('Roman S. Borschel'); $manager->setSalary(100000); @@ -108,16 +111,17 @@ public function testMultiLevelUpdateAndFind() { $this->_em->clear(); - $manager = $this->_em->find('Doctrine\Tests\Models\Company\CompanyManager', $manager->getId()); + $manager = $this->_em->find(CompanyManager::class, $manager->getId()); - $this->assertInstanceOf('Doctrine\Tests\Models\Company\CompanyManager', $manager); + $this->assertInstanceOf(CompanyManager::class, $manager); $this->assertEquals('Roman B.', $manager->getName()); $this->assertEquals(119000, $manager->getSalary()); $this->assertEquals('CEO', $manager->getTitle()); $this->assertTrue(is_numeric($manager->getId())); } - public function testFindOnBaseClass() { + public function testFindOnBaseClass() + { $manager = new CompanyManager; $manager->setName('Roman S. Borschel'); $manager->setSalary(100000); @@ -128,17 +132,17 @@ public function testFindOnBaseClass() { $this->_em->clear(); - $person = $this->_em->find('Doctrine\Tests\Models\Company\CompanyPerson', $manager->getId()); + $person = $this->_em->find(CompanyPerson::class, $manager->getId()); - $this->assertInstanceOf('Doctrine\Tests\Models\Company\CompanyManager', $person); + $this->assertInstanceOf(CompanyManager::class, $person); $this->assertEquals('Roman S. Borschel', $person->getName()); $this->assertEquals(100000, $person->getSalary()); $this->assertEquals('CTO', $person->getTitle()); $this->assertTrue(is_numeric($person->getId())); - //$this->assertInstanceOf('Doctrine\Tests\Models\Company\CompanyCar', $person->getCar()); } - public function testSelfReferencingOneToOne() { + public function testSelfReferencingOneToOne() + { $manager = new CompanyManager; $manager->setName('John Smith'); $manager->setSalary(100000); @@ -154,22 +158,16 @@ public function testSelfReferencingOneToOne() { $this->_em->persist($manager); $this->_em->persist($wife); - $this->_em->flush(); - - //var_dump($this->_em->getConnection()->fetchAll('select * from company_persons')); - //var_dump($this->_em->getConnection()->fetchAll('select * from company_employees')); - //var_dump($this->_em->getConnection()->fetchAll('select * from company_managers')); - $this->_em->clear(); - $query = $this->_em->createQuery('select p, s from Doctrine\Tests\Models\Company\CompanyPerson p join p.spouse s where p.name=\'Mary Smith\''); + $query = $this->_em->createQuery('select p, s from ' . CompanyPerson::class . ' p join p.spouse s where p.name=\'Mary Smith\''); $result = $query->getResult(); - $this->assertEquals(1, count($result)); - $this->assertInstanceOf('Doctrine\Tests\Models\Company\CompanyPerson', $result[0]); + $this->assertCount(1, $result); + $this->assertInstanceOf(CompanyPerson::class, $result[0]); $this->assertEquals('Mary Smith', $result[0]->getName()); - $this->assertInstanceOf('Doctrine\Tests\Models\Company\CompanyEmployee', $result[0]->getSpouse()); + $this->assertInstanceOf(CompanyEmployee::class, $result[0]->getSpouse()); $this->assertEquals('John Smith', $result[0]->getSpouse()->getName()); $this->assertSame($result[0], $result[0]->getSpouse()->getSpouse()); } @@ -184,8 +182,8 @@ public function testSelfReferencingManyToMany() $person1->addFriend($person2); - $this->assertEquals(1, count($person1->getFriends())); - $this->assertEquals(1, count($person2->getFriends())); + $this->assertCount(1, $person1->getFriends()); + $this->assertCount(1, $person2->getFriends()); $this->_em->persist($person1); @@ -195,12 +193,12 @@ public function testSelfReferencingManyToMany() $this->_em->clear(); - $query = $this->_em->createQuery('select p, f from Doctrine\Tests\Models\Company\CompanyPerson p join p.friends f where p.name=?1'); + $query = $this->_em->createQuery('select p, f from ' . CompanyPerson::class . ' p join p.friends f where p.name=?1'); $query->setParameter(1, 'Roman'); $result = $query->getResult(); - $this->assertEquals(1, count($result)); - $this->assertEquals(1, count($result[0]->getFriends())); + $this->assertCount(1, $result); + $this->assertCount(1, $result[0]->getFriends()); $this->assertEquals('Roman', $result[0]->getName()); $friends = $result[0]->getFriends(); @@ -228,25 +226,24 @@ public function testLazyLoading1() $result = $q->getResult(); - $this->assertEquals(1, count($result)); - $this->assertInstanceOf('Doctrine\Tests\Models\Company\CompanyOrganization', $result[0]); + $this->assertCount(1, $result); + $this->assertInstanceOf(CompanyOrganization::class, $result[0]); $this->assertNull($result[0]->getMainEvent()); $events = $result[0]->getEvents(); - $this->assertInstanceOf('Doctrine\ORM\PersistentCollection', $events); + $this->assertInstanceOf(PersistentCollection::class, $events); $this->assertFalse($events->isInitialized()); - $this->assertEquals(2, count($events)); + $this->assertCount(2, $events); if ($events[0] instanceof CompanyAuction) { - $this->assertInstanceOf('Doctrine\Tests\Models\Company\CompanyRaffle', $events[1]); + $this->assertInstanceOf(CompanyRaffle::class, $events[1]); } else { - $this->assertInstanceOf('Doctrine\Tests\Models\Company\CompanyRaffle', $events[0]); - $this->assertInstanceOf('Doctrine\Tests\Models\Company\CompanyAuction', $events[1]); + $this->assertInstanceOf(CompanyRaffle::class, $events[0]); + $this->assertInstanceOf(CompanyAuction::class, $events[1]); } } - public function testLazyLoading2() { $org = new CompanyOrganization; @@ -258,27 +255,27 @@ public function testLazyLoading2() $this->_em->flush(); $this->_em->clear(); - $q = $this->_em->createQuery('select a from Doctrine\Tests\Models\Company\CompanyEvent a where a.id = ?1'); + $q = $this->_em->createQuery('select a from ' . CompanyEvent::class . ' a where a.id = ?1'); $q->setParameter(1, $event1->getId()); $result = $q->getResult(); - $this->assertEquals(1, count($result)); - $this->assertInstanceOf('Doctrine\Tests\Models\Company\CompanyAuction', $result[0], sprintf("Is of class %s",get_class($result[0]))); + $this->assertCount(1, $result); + $this->assertInstanceOf(CompanyAuction::class, $result[0], sprintf("Is of class %s", get_class($result[0]))); $this->_em->clear(); - $q = $this->_em->createQuery('select a from Doctrine\Tests\Models\Company\CompanyOrganization a where a.id = ?1'); + $q = $this->_em->createQuery('select a from ' . CompanyOrganization::class . ' a where a.id = ?1'); $q->setParameter(1, $org->getId()); $result = $q->getResult(); - $this->assertEquals(1, count($result)); - $this->assertInstanceOf('Doctrine\Tests\Models\Company\CompanyOrganization', $result[0]); + $this->assertCount(1, $result); + $this->assertInstanceOf(CompanyOrganization::class, $result[0]); $mainEvent = $result[0]->getMainEvent(); // mainEvent should have been loaded because it can't be lazy - $this->assertInstanceOf('Doctrine\Tests\Models\Company\CompanyAuction', $mainEvent); - $this->assertNotInstanceOf('Doctrine\ORM\Proxy\Proxy', $mainEvent); + $this->assertInstanceOf(CompanyAuction::class, $mainEvent); + $this->assertNotInstanceOf(Proxy::class, $mainEvent); } /** @@ -286,12 +283,13 @@ public function testLazyLoading2() */ public function testBulkUpdateIssueDDC368() { - $dql = 'UPDATE Doctrine\Tests\Models\Company\CompanyEmployee AS p SET p.salary = 1'; - $this->_em->createQuery($dql)->execute(); + $this->_em->createQuery('UPDATE ' . CompanyEmployee::class . ' AS p SET p.salary = 1') + ->execute(); + + $result = $this->_em->createQuery('SELECT count(p.id) FROM ' . CompanyEmployee::class . ' p WHERE p.salary = 1') + ->getResult(); - $this->assertTrue(count($this->_em->createQuery( - 'SELECT count(p.id) FROM Doctrine\Tests\Models\Company\CompanyEmployee p WHERE p.salary = 1') - ->getResult()) > 0); + $this->assertGreaterThan(0, count($result)); } /** @@ -299,13 +297,12 @@ public function testBulkUpdateIssueDDC368() */ public function testBulkUpdateNonScalarParameterDDC1341() { - $dql = 'UPDATE Doctrine\Tests\Models\Company\CompanyEmployee AS p SET p.startDate = ?0 WHERE p.department = ?1'; - $query = $this->_em->createQuery($dql) - ->setParameter(0, new \DateTime()) - ->setParameter(1, 'IT'); - - $result = $query->execute(); + $this->_em->createQuery('UPDATE ' . CompanyEmployee::class . ' AS p SET p.startDate = ?0 WHERE p.department = ?1') + ->setParameter(0, new \DateTime()) + ->setParameter(1, 'IT') + ->execute(); + $this->addToAssertionCount(1); } /** @@ -313,8 +310,6 @@ public function testBulkUpdateNonScalarParameterDDC1341() */ public function testDeleteJoinTableRecords() { - #$this->markTestSkipped('Nightmare! friends adds both ID 6-7 and 7-6 into two rows of the join table. How to detect this?'); - $employee1 = new CompanyEmployee(); $employee1->setName('gblanco'); $employee1->setSalary(0); @@ -360,8 +355,9 @@ public function testQueryForInheritedSingleValuedAssociation() $this->_em->flush(); $this->_em->clear(); - $dql = "SELECT m FROM Doctrine\Tests\Models\Company\CompanyManager m WHERE m.spouse = ?1"; - $dqlManager = $this->_em->createQuery($dql)->setParameter(1, $person->getId())->getSingleResult(); + $dqlManager = $this->_em->createQuery('SELECT m FROM ' . CompanyManager::class . ' m WHERE m.spouse = ?1') + ->setParameter(1, $person->getId()) + ->getSingleResult(); $this->assertEquals($manager->getId(), $dqlManager->getId()); $this->assertEquals($person->getId(), $dqlManager->getSpouse()->getId()); @@ -388,13 +384,13 @@ public function testFindByAssociation() $this->_em->flush(); $this->_em->clear(); - $repos = $this->_em->getRepository('Doctrine\Tests\Models\Company\CompanyManager'); - $pmanager = $repos->findOneBy(array('spouse' => $person->getId())); + $repos = $this->_em->getRepository(CompanyManager::class); + $pmanager = $repos->findOneBy(['spouse' => $person->getId()]); $this->assertEquals($manager->getId(), $pmanager->getId()); - $repos = $this->_em->getRepository('Doctrine\Tests\Models\Company\CompanyPerson'); - $pmanager = $repos->findOneBy(array('spouse' => $person->getId())); + $repos = $this->_em->getRepository(CompanyPerson::class); + $pmanager = $repos->findOneBy(['spouse' => $person->getId()]); $this->assertEquals($manager->getId(), $pmanager->getId()); } @@ -414,14 +410,14 @@ public function testGetReferenceEntityWithSubclasses() $this->_em->flush(); $this->_em->clear(); - $ref = $this->_em->getReference('Doctrine\Tests\Models\Company\CompanyPerson', $manager->getId()); - $this->assertNotInstanceOf('Doctrine\ORM\Proxy\Proxy', $ref, "Cannot Request a proxy from a class that has subclasses."); - $this->assertInstanceOf('Doctrine\Tests\Models\Company\CompanyPerson', $ref); - $this->assertInstanceOf('Doctrine\Tests\Models\Company\CompanyEmployee', $ref, "Direct fetch of the reference has to load the child class Employee directly."); + $ref = $this->_em->getReference(CompanyPerson::class, $manager->getId()); + $this->assertNotInstanceOf(Proxy::class, $ref, "Cannot Request a proxy from a class that has subclasses."); + $this->assertInstanceOf(CompanyPerson::class, $ref); + $this->assertInstanceOf(CompanyEmployee::class, $ref, "Direct fetch of the reference has to load the child class Employee directly."); $this->_em->clear(); - $ref = $this->_em->getReference('Doctrine\Tests\Models\Company\CompanyManager', $manager->getId()); - $this->assertInstanceOf('Doctrine\ORM\Proxy\Proxy', $ref, "A proxy can be generated only if no subclasses exists for the requested reference."); + $ref = $this->_em->getReference(CompanyManager::class, $manager->getId()); + $this->assertInstanceOf(Proxy::class, $ref, "A proxy can be generated only if no subclasses exists for the requested reference."); } /** @@ -445,8 +441,9 @@ public function testGetSubClassManyToManyCollection() $this->_em->flush(); $this->_em->clear(); - $manager = $this->_em->find('Doctrine\Tests\Models\Company\CompanyManager', $manager->getId()); - $this->assertEquals(1, count($manager->getFriends())); + $manager = $this->_em->find(CompanyManager::class, $manager->getId()); + + $this->assertCount(1, $manager->getFriends()); } /** @@ -482,16 +479,16 @@ public function testMatching() $this->_em->persist($manager); $this->_em->flush(); - $repository = $this->_em->getRepository("Doctrine\Tests\Models\Company\CompanyEmployee"); + $repository = $this->_em->getRepository(CompanyEmployee::class); $users = $repository->matching(new Criteria( Criteria::expr()->eq('department', 'IT') )); - $this->assertEquals(1, count($users)); + $this->assertCount(1, $users); - $repository = $this->_em->getRepository("Doctrine\Tests\Models\Company\CompanyManager"); + $repository = $this->_em->getRepository(CompanyManager::class); $users = $repository->matching(new Criteria( Criteria::expr()->eq('department', 'IT') )); - $this->assertEquals(1, count($users)); + $this->assertCount(1, $users); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/ClassTableInheritanceTest2.php b/tests/Doctrine/Tests/ORM/Functional/ClassTableInheritanceTest2.php index 5682bffe108..84949a6e3ed 100644 --- a/tests/Doctrine/Tests/ORM/Functional/ClassTableInheritanceTest2.php +++ b/tests/Doctrine/Tests/ORM/Functional/ClassTableInheritanceTest2.php @@ -2,6 +2,7 @@ namespace Doctrine\Tests\ORM\Functional; use Doctrine\Common\Collections\ArrayCollection; +use Doctrine\ORM\Proxy\Proxy; use Doctrine\Tests\OrmFunctionalTestCase; /** @@ -15,12 +16,14 @@ protected function setUp() { parent::setUp(); try { - $this->_schemaTool->createSchema(array( - $this->_em->getClassMetadata('Doctrine\Tests\ORM\Functional\CTIParent'), - $this->_em->getClassMetadata('Doctrine\Tests\ORM\Functional\CTIChild'), - $this->_em->getClassMetadata('Doctrine\Tests\ORM\Functional\CTIRelated'), - $this->_em->getClassMetadata('Doctrine\Tests\ORM\Functional\CTIRelated2') - )); + $this->_schemaTool->createSchema( + [ + $this->_em->getClassMetadata(CTIParent::class), + $this->_em->getClassMetadata(CTIChild::class), + $this->_em->getClassMetadata(CTIRelated::class), + $this->_em->getClassMetadata(CTIRelated2::class) + ] + ); } catch (\Exception $ignored) { // Swallow all exceptions. We do not test the schema tool here. } @@ -42,11 +45,11 @@ public function testOneToOneAssocToBaseTypeBidirectional() $relatedId = $related->getId(); - $related2 = $this->_em->find('Doctrine\Tests\ORM\Functional\CTIRelated', $relatedId); + $related2 = $this->_em->find(CTIRelated::class, $relatedId); - $this->assertInstanceOf('Doctrine\Tests\ORM\Functional\CTIRelated', $related2); - $this->assertInstanceOf('Doctrine\Tests\ORM\Functional\CTIChild', $related2->getCTIParent()); - $this->assertNotInstanceOf('Doctrine\ORM\Proxy\Proxy', $related2->getCTIParent()); + $this->assertInstanceOf(CTIRelated::class, $related2); + $this->assertInstanceOf(CTIChild::class, $related2->getCTIParent()); + $this->assertNotInstanceOf(Proxy::class, $related2->getCTIParent()); $this->assertEquals('hello', $related2->getCTIParent()->getData()); $this->assertSame($related2, $related2->getCTIParent()->getRelated()); @@ -70,7 +73,7 @@ public function testManyToManyToCTIHierarchy() $this->assertFalse($mmrel2->getCTIChildren()->isInitialized()); $this->assertEquals(1, count($mmrel2->getCTIChildren())); $this->assertTrue($mmrel2->getCTIChildren()->isInitialized()); - $this->assertInstanceOf('Doctrine\Tests\ORM\Functional\CTIChild', $mmrel2->getCTIChildren()->get(0)); + $this->assertInstanceOf(CTIChild::class, $mmrel2->getCTIChildren()->get(0)); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/CompositePrimaryKeyTest.php b/tests/Doctrine/Tests/ORM/Functional/CompositePrimaryKeyTest.php index 1df74636cc8..03bde6ba7cb 100644 --- a/tests/Doctrine/Tests/ORM/Functional/CompositePrimaryKeyTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/CompositePrimaryKeyTest.php @@ -30,7 +30,7 @@ public function putGermanysBrandenburderTor() public function putTripAroundEurope() { - $poi = $this->_em->find('Doctrine\Tests\Models\Navigation\NavPointOfInterest', array('lat' => 100, 'long' => 200)); + $poi = $this->_em->find(NavPointOfInterest::class, ['lat' => 100, 'long' => 200]); $tour = new NavTour("Trip around Europe"); $tour->addPointOfInterest($poi); @@ -46,9 +46,9 @@ public function testPersistCompositePkEntity() { $this->putGermanysBrandenburderTor(); - $poi = $this->_em->find('Doctrine\Tests\Models\Navigation\NavPointOfInterest', array('lat' => 100, 'long' => 200)); + $poi = $this->_em->find(NavPointOfInterest::class, ['lat' => 100, 'long' => 200]); - $this->assertInstanceOf('Doctrine\Tests\Models\Navigation\NavPointOfInterest', $poi); + $this->assertInstanceOf(NavPointOfInterest::class, $poi); $this->assertEquals(100, $poi->getLat()); $this->assertEquals(200, $poi->getLong()); $this->assertEquals('Brandenburger Tor', $poi->getName()); @@ -61,7 +61,7 @@ public function testSetParameterCompositeKeyObject() { $this->putGermanysBrandenburderTor(); - $poi = $this->_em->find('Doctrine\Tests\Models\Navigation\NavPointOfInterest', array('lat' => 100, 'long' => 200)); + $poi = $this->_em->find(NavPointOfInterest::class, ['lat' => 100, 'long' => 200]); $photo = new NavPhotos($poi, "asdf"); $this->_em->persist($photo); $this->_em->flush(); @@ -79,7 +79,7 @@ public function testIdentityFunctionWithCompositePrimaryKey() { $this->putGermanysBrandenburderTor(); - $poi = $this->_em->find('Doctrine\Tests\Models\Navigation\NavPointOfInterest', array('lat' => 100, 'long' => 200)); + $poi = $this->_em->find(NavPointOfInterest::class, ['lat' => 100, 'long' => 200]); $photo = new NavPhotos($poi, "asdf"); $this->_em->persist($photo); $this->_em->flush(); @@ -98,7 +98,7 @@ public function testManyToManyCompositeRelation() $this->putGermanysBrandenburderTor(); $tour = $this->putTripAroundEurope(); - $tour = $this->_em->find('Doctrine\Tests\Models\Navigation\NavTour', $tour->getId()); + $tour = $this->_em->find(NavTour::class, $tour->getId()); $this->assertEquals(1, count($tour->getPointOfInterests())); } @@ -140,7 +140,7 @@ public function testSpecifyUnknownIdentifierPrimaryKeyFails() $this->expectException(ORMException::class); $this->expectExceptionMessage('The identifier long is missing for a query of Doctrine\Tests\Models\Navigation\NavPointOfInterest'); - $poi = $this->_em->find('Doctrine\Tests\Models\Navigation\NavPointOfInterest', array('key1' => 100)); + $poi = $this->_em->find(NavPointOfInterest::class, ['key1' => 100]); } public function testUnrecognizedIdentifierFieldsOnGetReference() @@ -148,7 +148,8 @@ public function testUnrecognizedIdentifierFieldsOnGetReference() $this->expectException(ORMException::class); $this->expectExceptionMessage("Unrecognized identifier fields: 'key1'"); - $poi = $this->_em->getReference('Doctrine\Tests\Models\Navigation\NavPointOfInterest', array('lat' => 10, 'long' => 20, 'key1' => 100)); + $poi = $this->_em->getReference(NavPointOfInterest::class, ['lat' => 10, 'long' => 20, 'key1' => 100] + ); } /** @@ -158,7 +159,7 @@ public function testDeleteCompositePersistentCollection() { $this->putGermanysBrandenburderTor(); - $poi = $this->_em->find('Doctrine\Tests\Models\Navigation\NavPointOfInterest', array('lat' => 100, 'long' => 200)); + $poi = $this->_em->find(NavPointOfInterest::class, ['lat' => 100, 'long' => 200]); $poi->addVisitor(new NavUser("test1")); $poi->addVisitor(new NavUser("test2")); @@ -169,7 +170,7 @@ public function testDeleteCompositePersistentCollection() $this->_em->flush(); $this->_em->clear(); - $poi = $this->_em->find('Doctrine\Tests\Models\Navigation\NavPointOfInterest', array('lat' => 100, 'long' => 200)); + $poi = $this->_em->find(NavPointOfInterest::class, ['lat' => 100, 'long' => 200]); $this->assertEquals(0, count($poi->getVisitors())); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/CompositePrimaryKeyWithAssociationsTest.php b/tests/Doctrine/Tests/ORM/Functional/CompositePrimaryKeyWithAssociationsTest.php index b735925e63f..533f611d402 100644 --- a/tests/Doctrine/Tests/ORM/Functional/CompositePrimaryKeyWithAssociationsTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/CompositePrimaryKeyWithAssociationsTest.php @@ -41,16 +41,16 @@ public function setUp() public function testFindByAbleToGetCompositeEntitiesWithMixedTypeIdentifiers() { - $admin1Repo = $this->_em->getRepository('Doctrine\Tests\Models\GeoNames\Admin1'); - $admin1NamesRepo = $this->_em->getRepository('Doctrine\Tests\Models\GeoNames\Admin1AlternateName'); + $admin1Repo = $this->_em->getRepository(Admin1::class); + $admin1NamesRepo = $this->_em->getRepository(Admin1AlternateName::class); - $admin1Rome = $admin1Repo->findOneBy(array('country' => 'IT', 'id' => 1)); + $admin1Rome = $admin1Repo->findOneBy(['country' => 'IT', 'id' => 1]); - $names = $admin1NamesRepo->findBy(array('admin1' => $admin1Rome)); + $names = $admin1NamesRepo->findBy(['admin1' => $admin1Rome]); $this->assertCount(2, $names); - $name1 = $admin1NamesRepo->findOneBy(array('admin1' => $admin1Rome, 'id' => 1)); - $name2 = $admin1NamesRepo->findOneBy(array('admin1' => $admin1Rome, 'id' => 2)); + $name1 = $admin1NamesRepo->findOneBy(['admin1' => $admin1Rome, 'id' => 1]); + $name2 = $admin1NamesRepo->findOneBy(['admin1' => $admin1Rome, 'id' => 2]); $this->assertEquals(1, $name1->id); $this->assertEquals("Roma", $name1->name); diff --git a/tests/Doctrine/Tests/ORM/Functional/CustomFunctionsTest.php b/tests/Doctrine/Tests/ORM/Functional/CustomFunctionsTest.php index 63c3e4ee94f..79668b8f2cc 100644 --- a/tests/Doctrine/Tests/ORM/Functional/CustomFunctionsTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/CustomFunctionsTest.php @@ -47,6 +47,23 @@ public function testCustomFunctionDefinedWithCallback() $this->assertEquals(1, count($users)); $this->assertSame($user, $users[0]); } + + public function testCustomFunctionOverride() + { + $user = new CmsUser(); + $user->name = 'Bob'; + $user->username = 'Dylan'; + $this->_em->persist($user); + $this->_em->flush(); + + $this->_em->getConfiguration()->addCustomStringFunction('COUNT', 'Doctrine\Tests\ORM\Functional\CustomCount'); + + $query = $this->_em->createQuery('SELECT COUNT(DISTINCT u.id) FROM Doctrine\Tests\Models\CMS\CmsUser u'); + + $usersCount = $query->getSingleScalarResult(); + + $this->assertEquals(1, $usersCount); + } } class NoOp extends FunctionNode @@ -70,3 +87,20 @@ public function getSql(SqlWalker $sqlWalker) } } +class CustomCount extends FunctionNode +{ + /** + * @var Query\AST\AggregateExpression + */ + private $aggregateExpression; + + public function parse(Parser $parser): void + { + $this->aggregateExpression = $parser->AggregateExpression(); + } + + public function getSql(SqlWalker $sqlWalker): string + { + return $this->aggregateExpression->dispatch($sqlWalker); + } +} diff --git a/tests/Doctrine/Tests/ORM/Functional/CustomIdObjectTypeTest.php b/tests/Doctrine/Tests/ORM/Functional/CustomIdObjectTypeTest.php index 2e7abf76c2d..08d89fa8ec2 100644 --- a/tests/Doctrine/Tests/ORM/Functional/CustomIdObjectTypeTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/CustomIdObjectTypeTest.php @@ -1,21 +1,4 @@ . - */ namespace Doctrine\Tests\ORM\Functional; @@ -31,9 +14,9 @@ class CustomIdObjectTypeTest extends OrmFunctionalTestCase protected function setUp() { if (DBALType::hasType(CustomIdObjectType::NAME)) { - DBALType::overrideType(CustomIdObjectType::NAME, CustomIdObjectType::CLASSNAME); + DBALType::overrideType(CustomIdObjectType::NAME, CustomIdObjectType::class); } else { - DBALType::addType(CustomIdObjectType::NAME, CustomIdObjectType::CLASSNAME); + DBALType::addType(CustomIdObjectType::NAME, CustomIdObjectType::class); } $this->useModelSet('custom_id_object_type'); @@ -48,7 +31,7 @@ public function testFindByCustomIdObject() $this->_em->persist($parent); $this->_em->flush(); - $result = $this->_em->find(CustomIdObjectTypeParent::CLASSNAME, $parent->id); + $result = $this->_em->find(CustomIdObjectTypeParent::class, $parent->id); $this->assertSame($parent, $result); } @@ -70,7 +53,7 @@ public function testFetchJoinCustomIdObject() ->_em ->createQuery( 'SELECT parent, children FROM ' - . CustomIdObjectTypeParent::CLASSNAME + . CustomIdObjectTypeParent::class . ' parent LEFT JOIN parent.children children' ) ->getResult(); @@ -97,7 +80,7 @@ public function testFetchJoinWhereCustomIdObject() ->_em ->createQuery( 'SELECT parent, children FROM ' - . CustomIdObjectTypeParent::CLASSNAME + . CustomIdObjectTypeParent::class . ' parent LEFT JOIN parent.children children ' . 'WHERE children.id = ?1' ) diff --git a/tests/Doctrine/Tests/ORM/Functional/DatabaseDriverTest.php b/tests/Doctrine/Tests/ORM/Functional/DatabaseDriverTest.php index 37149abfd3a..5d08039e504 100644 --- a/tests/Doctrine/Tests/ORM/Functional/DatabaseDriverTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/DatabaseDriverTest.php @@ -33,15 +33,15 @@ public function testIssue2059() $user = new Table("ddc2059_user"); $user->addColumn('id', 'integer'); - $user->setPrimaryKey(array('id')); + $user->setPrimaryKey(['id']); $project = new Table("ddc2059_project"); $project->addColumn('id', 'integer'); $project->addColumn('user_id', 'integer'); $project->addColumn('user', 'string'); - $project->setPrimaryKey(array('id')); - $project->addForeignKeyConstraint('ddc2059_user', array('user_id'), array('id')); + $project->setPrimaryKey(['id']); + $project->addForeignKeyConstraint('ddc2059_user', ['user_id'], ['id']); - $metadata = $this->convertToClassMetadata(array($project, $user), array()); + $metadata = $this->convertToClassMetadata([$project, $user], []); $this->assertTrue(isset($metadata['Ddc2059Project']->fieldMappings['user'])); $this->assertTrue(isset($metadata['Ddc2059Project']->associationMappings['user2'])); @@ -55,12 +55,12 @@ public function testLoadMetadataFromDatabase() $table = new Table("dbdriver_foo"); $table->addColumn('id', 'integer'); - $table->setPrimaryKey(array('id')); - $table->addColumn('bar', 'string', array('notnull' => false, 'length' => 200)); + $table->setPrimaryKey(['id']); + $table->addColumn('bar', 'string', ['notnull' => false, 'length' => 200]); $this->_sm->dropAndCreateTable($table); - $metadatas = $this->extractClassMetadata(array("DbdriverFoo")); + $metadatas = $this->extractClassMetadata(["DbdriverFoo"]); $this->assertArrayHasKey('DbdriverFoo', $metadatas); $metadata = $metadatas['DbdriverFoo']; @@ -86,19 +86,19 @@ public function testLoadMetadataWithForeignKeyFromDatabase() $tableB = new Table("dbdriver_bar"); $tableB->addColumn('id', 'integer'); - $tableB->setPrimaryKey(array('id')); + $tableB->setPrimaryKey(['id']); $this->_sm->dropAndCreateTable($tableB); $tableA = new Table("dbdriver_baz"); $tableA->addColumn('id', 'integer'); - $tableA->setPrimaryKey(array('id')); + $tableA->setPrimaryKey(['id']); $tableA->addColumn('bar_id', 'integer'); - $tableA->addForeignKeyConstraint('dbdriver_bar', array('bar_id'), array('id')); + $tableA->addForeignKeyConstraint('dbdriver_bar', ['bar_id'], ['id']); $this->_sm->dropAndCreateTable($tableA); - $metadatas = $this->extractClassMetadata(array("DbdriverBar", "DbdriverBaz")); + $metadatas = $this->extractClassMetadata(["DbdriverBar", "DbdriverBaz"]); $this->assertArrayHasKey('DbdriverBaz', $metadatas); $bazMetadata = $metadatas['DbdriverBaz']; @@ -118,7 +118,7 @@ public function testDetectManyToManyTables() $this->markTestSkipped('Platform does not support foreign keys.'); } - $metadatas = $this->extractClassMetadata(array("CmsUsers", "CmsGroups", "CmsTags")); + $metadatas = $this->extractClassMetadata(["CmsUsers", "CmsGroups", "CmsTags"]); $this->assertArrayHasKey('CmsUsers', $metadatas, 'CmsUsers entity was not detected.'); $this->assertArrayHasKey('CmsGroups', $metadatas, 'CmsGroups entity was not detected.'); @@ -136,18 +136,18 @@ public function testIgnoreManyToManyTableWithoutFurtherForeignKeyDetails() { $tableB = new Table("dbdriver_bar"); $tableB->addColumn('id', 'integer'); - $tableB->setPrimaryKey(array('id')); + $tableB->setPrimaryKey(['id']); $tableA = new Table("dbdriver_baz"); $tableA->addColumn('id', 'integer'); - $tableA->setPrimaryKey(array('id')); + $tableA->setPrimaryKey(['id']); $tableMany = new Table("dbdriver_bar_baz"); $tableMany->addColumn('bar_id', 'integer'); $tableMany->addColumn('baz_id', 'integer'); - $tableMany->addForeignKeyConstraint('dbdriver_bar', array('bar_id'), array('id')); + $tableMany->addForeignKeyConstraint('dbdriver_bar', ['bar_id'], ['id']); - $metadatas = $this->convertToClassMetadata(array($tableA, $tableB), array($tableMany)); + $metadatas = $this->convertToClassMetadata([$tableA, $tableB], [$tableMany]); $this->assertEquals(0, count($metadatas['DbdriverBaz']->associationMappings), "no association mappings should be detected."); } @@ -160,24 +160,24 @@ public function testLoadMetadataFromDatabaseDetail() $table = new Table("dbdriver_foo"); - $table->addColumn('id', 'integer', array('unsigned' => true)); - $table->setPrimaryKey(array('id')); - $table->addColumn('column_unsigned', 'integer', array('unsigned' => true)); - $table->addColumn('column_comment', 'string', array('comment' => 'test_comment')); - $table->addColumn('column_default', 'string', array('default' => 'test_default')); - $table->addColumn('column_decimal', 'decimal', array('precision' => 4, 'scale' => 3)); + $table->addColumn('id', 'integer', ['unsigned' => true]); + $table->setPrimaryKey(['id']); + $table->addColumn('column_unsigned', 'integer', ['unsigned' => true]); + $table->addColumn('column_comment', 'string', ['comment' => 'test_comment']); + $table->addColumn('column_default', 'string', ['default' => 'test_default']); + $table->addColumn('column_decimal', 'decimal', ['precision' => 4, 'scale' => 3]); $table->addColumn('column_index1', 'string'); $table->addColumn('column_index2', 'string'); - $table->addIndex(array('column_index1','column_index2'), 'index1'); + $table->addIndex(['column_index1','column_index2'], 'index1'); $table->addColumn('column_unique_index1', 'string'); $table->addColumn('column_unique_index2', 'string'); - $table->addUniqueIndex(array('column_unique_index1', 'column_unique_index2'), 'unique_index1'); + $table->addUniqueIndex(['column_unique_index1', 'column_unique_index2'], 'unique_index1'); $this->_sm->dropAndCreateTable($table); - $metadatas = $this->extractClassMetadata(array("DbdriverFoo")); + $metadatas = $this->extractClassMetadata(["DbdriverFoo"]); $this->assertArrayHasKey('DbdriverFoo', $metadatas); @@ -208,13 +208,13 @@ public function testLoadMetadataFromDatabaseDetail() $this->assertTrue( ! empty($metadata->table['indexes']['index1']['columns'])); $this->assertEquals( - array('column_index1','column_index2'), + ['column_index1','column_index2'], $metadata->table['indexes']['index1']['columns'] ); $this->assertTrue( ! empty($metadata->table['uniqueConstraints']['unique_index1']['columns'])); $this->assertEquals( - array('column_unique_index1', 'column_unique_index2'), + ['column_unique_index1', 'column_unique_index2'], $metadata->table['uniqueConstraints']['unique_index1']['columns'] ); } diff --git a/tests/Doctrine/Tests/ORM/Functional/DatabaseDriverTestCase.php b/tests/Doctrine/Tests/ORM/Functional/DatabaseDriverTestCase.php index 03902c40ca9..89d3cd3583c 100644 --- a/tests/Doctrine/Tests/ORM/Functional/DatabaseDriverTestCase.php +++ b/tests/Doctrine/Tests/ORM/Functional/DatabaseDriverTestCase.php @@ -11,13 +11,13 @@ */ abstract class DatabaseDriverTestCase extends OrmFunctionalTestCase { - protected function convertToClassMetadata(array $entityTables, array $manyTables = array()) + protected function convertToClassMetadata(array $entityTables, array $manyTables = []) { $sm = $this->_em->getConnection()->getSchemaManager(); $driver = new DatabaseDriver($sm); $driver->setTables($entityTables, $manyTables); - $metadatas = array(); + $metadatas = []; foreach ($driver->getAllClassNames() AS $className) { $class = new ClassMetadataInfo($className); $driver->loadMetadataForClass($className, $class); @@ -34,7 +34,7 @@ protected function convertToClassMetadata(array $entityTables, array $manyTables protected function extractClassMetadata(array $classNames) { $classNames = array_map('strtolower', $classNames); - $metadatas = array(); + $metadatas = []; $sm = $this->_em->getConnection()->getSchemaManager(); $driver = new DatabaseDriver($sm); diff --git a/tests/Doctrine/Tests/ORM/Functional/DefaultValuesTest.php b/tests/Doctrine/Tests/ORM/Functional/DefaultValuesTest.php index e81bd7f8ac1..2797ba8337b 100644 --- a/tests/Doctrine/Tests/ORM/Functional/DefaultValuesTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/DefaultValuesTest.php @@ -1,6 +1,7 @@ _schemaTool->createSchema(array( - $this->_em->getClassMetadata('Doctrine\Tests\ORM\Functional\DefaultValueUser'), - $this->_em->getClassMetadata('Doctrine\Tests\ORM\Functional\DefaultValueAddress') - )); + $this->_schemaTool->createSchema( + [ + $this->_em->getClassMetadata(DefaultValueUser::class), + $this->_em->getClassMetadata(DefaultValueAddress::class) + ] + ); } catch (\Exception $e) { // Swallow all exceptions. We do not test the schema tool here. } @@ -53,7 +56,7 @@ public function testSimpleDetachMerge() { $this->_em->clear(); $a2 = $this->_em->find(get_class($a), $a->id); - $this->assertInstanceOf('Doctrine\Tests\ORM\Functional\DefaultValueUser', $a2->getUser()); + $this->assertInstanceOf(DefaultValueUser::class, $a2->getUser()); $this->assertEquals($userId, $a2->getUser()->getId()); $this->assertEquals('Poweruser', $a2->getUser()->type); } @@ -71,13 +74,13 @@ public function testGetPartialReferenceWithDefaultValueNotEvaluatedInFlush() $this->_em->flush(); $this->_em->clear(); - $user = $this->_em->getPartialReference('Doctrine\Tests\ORM\Functional\DefaultValueUser', $user->id); + $user = $this->_em->getPartialReference(DefaultValueUser::class, $user->id); $this->assertTrue($this->_em->getUnitOfWork()->isReadOnly($user)); $this->_em->flush(); $this->_em->clear(); - $user = $this->_em->find('Doctrine\Tests\ORM\Functional\DefaultValueUser', $user->id); + $user = $this->_em->find(DefaultValueUser::class, $user->id); $this->assertEquals('Normaluser', $user->type); } diff --git a/tests/Doctrine/Tests/ORM/Functional/DetachedEntityTest.php b/tests/Doctrine/Tests/ORM/Functional/DetachedEntityTest.php index d067836f7b1..b1a98530713 100644 --- a/tests/Doctrine/Tests/ORM/Functional/DetachedEntityTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/DetachedEntityTest.php @@ -2,12 +2,15 @@ namespace Doctrine\Tests\ORM\Functional; +use Doctrine\DBAL\Exception\UniqueConstraintViolationException; use Doctrine\ORM\OptimisticLockException; +use Doctrine\ORM\Proxy\Proxy; use Doctrine\Tests\Models\CMS\CmsUser; use Doctrine\Tests\Models\CMS\CmsPhonenumber; use Doctrine\Tests\Models\CMS\CmsAddress; use Doctrine\Tests\Models\CMS\CmsArticle; use Doctrine\Tests\OrmFunctionalTestCase; +use Doctrine\Tests\VerifyDeprecations; /** * Description of DetachedEntityTest @@ -16,13 +19,16 @@ */ class DetachedEntityTest extends OrmFunctionalTestCase { + use VerifyDeprecations; + protected function setUp() { $this->useModelSet('cms'); parent::setUp(); } - public function testSimpleDetachMerge() { + public function testSimpleDetachMerge() + { $user = new CmsUser; $user->name = 'Roman'; $user->username = 'romanb'; @@ -32,23 +38,20 @@ public function testSimpleDetachMerge() { $this->_em->clear(); // $user is now detached - $this->assertFalse($this->_em->contains($user)); $user->name = 'Roman B.'; - //$this->assertEquals(UnitOfWork::STATE_DETACHED, $this->_em->getUnitOfWork()->getEntityState($user)); - $user2 = $this->_em->merge($user); $this->assertFalse($user === $user2); $this->assertTrue($this->_em->contains($user2)); $this->assertEquals('Roman B.', $user2->name); + $this->assertHasDeprecationMessages(); } public function testSerializeUnserializeModifyMerge() { - //$this->_em->getConnection()->getConfiguration()->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger); $user = new CmsUser; $user->name = 'Guilherme'; $user->username = 'gblanco'; @@ -90,8 +93,8 @@ public function testSerializeUnserializeModifyMerge() // Merge back in $user = $this->_em->merge($user); // merge cascaded to phonenumbers - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsUser', $user->phonenumbers[0]->user); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsUser', $user->phonenumbers[1]->user); + $this->assertInstanceOf(CmsUser::class, $user->phonenumbers[0]->user); + $this->assertInstanceOf(CmsUser::class, $user->phonenumbers[1]->user); $im = $this->_em->getUnitOfWork()->getIdentityMap(); $this->_em->flush(); @@ -100,12 +103,13 @@ public function testSerializeUnserializeModifyMerge() $this->assertNotSame($oldPhonenumbers, $phonenumbers, "Merge should replace the Detached Collection with a new PersistentCollection."); $this->assertEquals(2, count($phonenumbers), "Failed to assert that two phonenumbers are contained in the merged users phonenumber collection."); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsPhonenumber', $phonenumbers[1]); + $this->assertInstanceOf(CmsPhonenumber::class, $phonenumbers[1]); $this->assertTrue($this->_em->contains($phonenumbers[1]), "Failed to assert that second phonenumber in collection is contained inside EntityManager persistence context."); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsPhonenumber', $phonenumbers[0]); + $this->assertInstanceOf(CmsPhonenumber::class, $phonenumbers[0]); $this->assertTrue($this->_em->getUnitOfWork()->isInIdentityMap($phonenumbers[0])); $this->assertTrue($this->_em->contains($phonenumbers[0]), "Failed to assert that first phonenumber in collection is contained inside EntityManager persistence context."); + $this->assertHasDeprecationMessages(); } /** @@ -115,14 +119,16 @@ public function testDetachedEntityThrowsExceptionOnFlush() { $ph = new CmsPhonenumber(); $ph->phonenumber = '12345'; + $this->_em->persist($ph); $this->_em->flush(); $this->_em->clear(); + $this->_em->persist($ph); - try { - $this->_em->flush(); - $this->fail(); - } catch (\Exception $expected) {} + + // since it tries to insert the object twice (with the same PK) + $this->expectException(UniqueConstraintViolationException::class); + $this->_em->flush(); } public function testUninitializedLazyAssociationsAreIgnoredOnMerge() @@ -145,16 +151,17 @@ public function testUninitializedLazyAssociationsAreIgnoredOnMerge() $this->_em->clear(); $address2 = $this->_em->find(get_class($address), $address->id); - $this->assertInstanceOf('Doctrine\ORM\Proxy\Proxy', $address2->user); + $this->assertInstanceOf(Proxy::class, $address2->user); $this->assertFalse($address2->user->__isInitialized__); $detachedAddress2 = unserialize(serialize($address2)); - $this->assertInstanceOf('Doctrine\ORM\Proxy\Proxy', $detachedAddress2->user); + $this->assertInstanceOf(Proxy::class, $detachedAddress2->user); $this->assertFalse($detachedAddress2->user->__isInitialized__); $managedAddress2 = $this->_em->merge($detachedAddress2); - $this->assertInstanceOf('Doctrine\ORM\Proxy\Proxy', $managedAddress2->user); + $this->assertInstanceOf(Proxy::class, $managedAddress2->user); $this->assertFalse($managedAddress2->user === $detachedAddress2->user); $this->assertFalse($managedAddress2->user->__isInitialized__); + $this->assertHasDeprecationMessages(); } /** @@ -172,14 +179,15 @@ public function testUseDetachedEntityAsQueryParameter() $this->_em->flush(); $this->_em->detach($user); - $dql = "SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.id = ?1"; + $dql = 'SELECT u FROM ' . CmsUser::class . ' u WHERE u.id = ?1'; $query = $this->_em->createQuery($dql); $query->setParameter(1, $user); $newUser = $query->getSingleResult(); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsUser', $newUser); + $this->assertInstanceOf(CmsUser::class, $newUser); $this->assertEquals('gblanco', $newUser->username); + $this->assertHasDeprecationMessages(); } /** @@ -199,6 +207,7 @@ public function testDetachManagedUnpersistedEntity() $this->assertFalse($this->_em->contains($user)); $this->assertFalse($this->_em->getUnitOfWork()->isInIdentityMap($user)); + $this->assertHasDeprecationMessages(); } /** @@ -215,13 +224,14 @@ public function testMergeArticleWrongVersion() $this->_em->detach($article); - $sql = "UPDATE cms_articles SET version = version+1 WHERE id = " . $article->id; + $sql = 'UPDATE cms_articles SET version = version + 1 WHERE id = ' . $article->id; $this->_em->getConnection()->executeUpdate($sql); $this->expectException(OptimisticLockException::class); $this->expectExceptionMessage('The optimistic lock failed, version 1 was expected, but is actually 2'); $this->_em->merge($article); + $this->assertHasDeprecationMessages(); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/EntityListenersTest.php b/tests/Doctrine/Tests/ORM/Functional/EntityListenersTest.php index 89901be1969..98457dd49db 100644 --- a/tests/Doctrine/Tests/ORM/Functional/EntityListenersTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/EntityListenersTest.php @@ -2,6 +2,10 @@ namespace Doctrine\Tests\ORM\Functional; +use Doctrine\Common\Persistence\Event\LifecycleEventArgs; +use Doctrine\ORM\Event\PreFlushEventArgs; +use Doctrine\ORM\Event\PreUpdateEventArgs; +use Doctrine\Tests\Models\Company\CompanyContractListener; use Doctrine\Tests\Models\Company\CompanyFixContract; use Doctrine\Tests\OrmFunctionalTestCase; @@ -23,7 +27,7 @@ protected function setUp() $this->listener = $this->_em->getConfiguration() ->getEntityListenerResolver() - ->resolve('Doctrine\Tests\Models\Company\CompanyContractListener'); + ->resolve(CompanyContractListener::class); } public function testPreFlushListeners() @@ -31,53 +35,35 @@ public function testPreFlushListeners() $fix = new CompanyFixContract(); $fix->setFixPrice(2000); - $this->listener->preFlushCalls = array(); + $this->listener->preFlushCalls = []; $this->_em->persist($fix); $this->_em->flush(); $this->assertCount(1,$this->listener->preFlushCalls); - $this->assertSame($fix, $this->listener->preFlushCalls[0][0]); - - $this->assertInstanceOf( - 'Doctrine\Tests\Models\Company\CompanyFixContract', - $this->listener->preFlushCalls[0][0] - ); - - $this->assertInstanceOf( - 'Doctrine\ORM\Event\PreFlushEventArgs', - $this->listener->preFlushCalls[0][1] - ); + $this->assertInstanceOf(CompanyFixContract::class, $this->listener->preFlushCalls[0][0]); + $this->assertInstanceOf(PreFlushEventArgs::class, $this->listener->preFlushCalls[0][1]); } public function testPostLoadListeners() { $fix = new CompanyFixContract(); $fix->setFixPrice(2000); - + $this->_em->persist($fix); $this->_em->flush(); $this->_em->clear(); - $this->listener->postLoadCalls = array(); + $this->listener->postLoadCalls = []; $dql = "SELECT f FROM Doctrine\Tests\Models\Company\CompanyFixContract f WHERE f.id = ?1"; $fix = $this->_em->createQuery($dql)->setParameter(1, $fix->getId())->getSingleResult(); $this->assertCount(1,$this->listener->postLoadCalls); - $this->assertSame($fix, $this->listener->postLoadCalls[0][0]); - - $this->assertInstanceOf( - 'Doctrine\Tests\Models\Company\CompanyFixContract', - $this->listener->postLoadCalls[0][0] - ); - - $this->assertInstanceOf( - 'Doctrine\ORM\Event\LifecycleEventArgs', - $this->listener->postLoadCalls[0][1] - ); + $this->assertInstanceOf(CompanyFixContract::class, $this->listener->postLoadCalls[0][0]); + $this->assertInstanceOf(LifecycleEventArgs::class, $this->listener->postLoadCalls[0][1]); } public function testPrePersistListeners() @@ -85,24 +71,15 @@ public function testPrePersistListeners() $fix = new CompanyFixContract(); $fix->setFixPrice(2000); - $this->listener->prePersistCalls = array(); + $this->listener->prePersistCalls = []; $this->_em->persist($fix); $this->_em->flush(); $this->assertCount(1,$this->listener->prePersistCalls); - $this->assertSame($fix, $this->listener->prePersistCalls[0][0]); - - $this->assertInstanceOf( - 'Doctrine\Tests\Models\Company\CompanyFixContract', - $this->listener->prePersistCalls[0][0] - ); - - $this->assertInstanceOf( - 'Doctrine\ORM\Event\LifecycleEventArgs', - $this->listener->prePersistCalls[0][1] - ); + $this->assertInstanceOf(CompanyFixContract::class, $this->listener->prePersistCalls[0][0]); + $this->assertInstanceOf(LifecycleEventArgs::class, $this->listener->prePersistCalls[0][1]); } public function testPostPersistListeners() @@ -110,24 +87,15 @@ public function testPostPersistListeners() $fix = new CompanyFixContract(); $fix->setFixPrice(2000); - $this->listener->postPersistCalls = array(); + $this->listener->postPersistCalls = []; $this->_em->persist($fix); $this->_em->flush(); $this->assertCount(1,$this->listener->postPersistCalls); - $this->assertSame($fix, $this->listener->postPersistCalls[0][0]); - - $this->assertInstanceOf( - 'Doctrine\Tests\Models\Company\CompanyFixContract', - $this->listener->postPersistCalls[0][0] - ); - - $this->assertInstanceOf( - 'Doctrine\ORM\Event\LifecycleEventArgs', - $this->listener->postPersistCalls[0][1] - ); + $this->assertInstanceOf(CompanyFixContract::class, $this->listener->postPersistCalls[0][0]); + $this->assertInstanceOf(LifecycleEventArgs::class, $this->listener->postPersistCalls[0][1]); } public function testPreUpdateListeners() @@ -138,26 +106,17 @@ public function testPreUpdateListeners() $this->_em->persist($fix); $this->_em->flush(); - $this->listener->preUpdateCalls = array(); - + $this->listener->preUpdateCalls = []; + $fix->setFixPrice(2000); $this->_em->persist($fix); $this->_em->flush(); $this->assertCount(1,$this->listener->preUpdateCalls); - $this->assertSame($fix, $this->listener->preUpdateCalls[0][0]); - - $this->assertInstanceOf( - 'Doctrine\Tests\Models\Company\CompanyFixContract', - $this->listener->preUpdateCalls[0][0] - ); - - $this->assertInstanceOf( - 'Doctrine\ORM\Event\PreUpdateEventArgs', - $this->listener->preUpdateCalls[0][1] - ); + $this->assertInstanceOf(CompanyFixContract::class, $this->listener->preUpdateCalls[0][0]); + $this->assertInstanceOf(PreUpdateEventArgs::class, $this->listener->preUpdateCalls[0][1]); } public function testPostUpdateListeners() @@ -168,7 +127,7 @@ public function testPostUpdateListeners() $this->_em->persist($fix); $this->_em->flush(); - $this->listener->postUpdateCalls = array(); + $this->listener->postUpdateCalls = []; $fix->setFixPrice(2000); @@ -176,18 +135,9 @@ public function testPostUpdateListeners() $this->_em->flush(); $this->assertCount(1,$this->listener->postUpdateCalls); - $this->assertSame($fix, $this->listener->postUpdateCalls[0][0]); - - $this->assertInstanceOf( - 'Doctrine\Tests\Models\Company\CompanyFixContract', - $this->listener->postUpdateCalls[0][0] - ); - - $this->assertInstanceOf( - 'Doctrine\ORM\Event\LifecycleEventArgs', - $this->listener->postUpdateCalls[0][1] - ); + $this->assertInstanceOf(CompanyFixContract::class, $this->listener->postUpdateCalls[0][0]); + $this->assertInstanceOf(LifecycleEventArgs::class, $this->listener->postUpdateCalls[0][1]); } public function testPreRemoveListeners() @@ -198,24 +148,15 @@ public function testPreRemoveListeners() $this->_em->persist($fix); $this->_em->flush(); - $this->listener->preRemoveCalls = array(); + $this->listener->preRemoveCalls = []; $this->_em->remove($fix); $this->_em->flush(); $this->assertCount(1,$this->listener->preRemoveCalls); - $this->assertSame($fix, $this->listener->preRemoveCalls[0][0]); - - $this->assertInstanceOf( - 'Doctrine\Tests\Models\Company\CompanyFixContract', - $this->listener->preRemoveCalls[0][0] - ); - - $this->assertInstanceOf( - 'Doctrine\ORM\Event\LifecycleEventArgs', - $this->listener->preRemoveCalls[0][1] - ); + $this->assertInstanceOf(CompanyFixContract::class, $this->listener->preRemoveCalls[0][0]); + $this->assertInstanceOf(LifecycleEventArgs::class, $this->listener->preRemoveCalls[0][1]); } public function testPostRemoveListeners() @@ -226,23 +167,14 @@ public function testPostRemoveListeners() $this->_em->persist($fix); $this->_em->flush(); - $this->listener->postRemoveCalls = array(); + $this->listener->postRemoveCalls = []; $this->_em->remove($fix); $this->_em->flush(); $this->assertCount(1,$this->listener->postRemoveCalls); - $this->assertSame($fix, $this->listener->postRemoveCalls[0][0]); - - $this->assertInstanceOf( - 'Doctrine\Tests\Models\Company\CompanyFixContract', - $this->listener->postRemoveCalls[0][0] - ); - - $this->assertInstanceOf( - 'Doctrine\ORM\Event\LifecycleEventArgs', - $this->listener->postRemoveCalls[0][1] - ); + $this->assertInstanceOf(CompanyFixContract::class, $this->listener->postRemoveCalls[0][0]); + $this->assertInstanceOf(LifecycleEventArgs::class, $this->listener->postRemoveCalls[0][1]); } -} \ No newline at end of file +} diff --git a/tests/Doctrine/Tests/ORM/Functional/EntityRepositoryCriteriaTest.php b/tests/Doctrine/Tests/ORM/Functional/EntityRepositoryCriteriaTest.php index 45f552d5949..700964b97da 100644 --- a/tests/Doctrine/Tests/ORM/Functional/EntityRepositoryCriteriaTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/EntityRepositoryCriteriaTest.php @@ -1,24 +1,8 @@ . - */ namespace Doctrine\Tests\ORM\Functional; +use Doctrine\ORM\LazyCriteriaCollection; use Doctrine\Tests\Models\Generic\DateTimeModel; use Doctrine\Common\Collections\Criteria; use Doctrine\Tests\Models\Tweet\Tweet; @@ -40,7 +24,7 @@ protected function setUp() public function tearDown() { if ($this->_em) { - $this->_em->getConfiguration()->setEntityNamespaces(array()); + $this->_em->getConfiguration()->setEntityNamespaces([]); } parent::tearDown(); } @@ -81,7 +65,7 @@ public function testLteDateComparison() { $this->loadFixture(); - $repository = $this->_em->getRepository('Doctrine\Tests\Models\Generic\DateTimeModel'); + $repository = $this->_em->getRepository(DateTimeModel::class); $dates = $repository->matching(new Criteria( Criteria::expr()->lte('datetime', new \DateTime('today')) )); @@ -112,7 +96,7 @@ private function loadNullFieldFixtures() public function testIsNullComparison() { $this->loadNullFieldFixtures(); - $repository = $this->_em->getRepository('Doctrine\Tests\Models\Generic\DateTimeModel'); + $repository = $this->_em->getRepository(DateTimeModel::class); $dates = $repository->matching(new Criteria( Criteria::expr()->isNull('time') @@ -124,7 +108,7 @@ public function testIsNullComparison() public function testEqNullComparison() { $this->loadNullFieldFixtures(); - $repository = $this->_em->getRepository('Doctrine\Tests\Models\Generic\DateTimeModel'); + $repository = $this->_em->getRepository(DateTimeModel::class); $dates = $repository->matching(new Criteria( Criteria::expr()->eq('time', null) @@ -136,7 +120,7 @@ public function testEqNullComparison() public function testNotEqNullComparison() { $this->loadNullFieldFixtures(); - $repository = $this->_em->getRepository('Doctrine\Tests\Models\Generic\DateTimeModel'); + $repository = $this->_em->getRepository(DateTimeModel::class); $dates = $repository->matching(new Criteria( Criteria::expr()->neq('time', null) @@ -148,7 +132,7 @@ public function testNotEqNullComparison() public function testCanCountWithoutLoadingCollection() { $this->loadFixture(); - $repository = $this->_em->getRepository('Doctrine\Tests\Models\Generic\DateTimeModel'); + $repository = $this->_em->getRepository(DateTimeModel::class); $dates = $repository->matching(new Criteria()); @@ -188,10 +172,10 @@ public function testCanContainsWithoutLoadingCollection() $criteria = new Criteria(); $criteria->andWhere($criteria->expr()->contains('content', 'Criteria')); - $user = $this->_em->find('Doctrine\Tests\Models\Tweet\User', $user->id); + $user = $this->_em->find(User::class, $user->id); $tweets = $user->tweets->matching($criteria); - $this->assertInstanceOf('Doctrine\ORM\LazyCriteriaCollection', $tweets); + $this->assertInstanceOf(LazyCriteriaCollection::class, $tweets); $this->assertFalse($tweets->isInitialized()); $tweets->contains($tweet); diff --git a/tests/Doctrine/Tests/ORM/Functional/EntityRepositoryTest.php b/tests/Doctrine/Tests/ORM/Functional/EntityRepositoryTest.php index ffca89ba0b8..b8158c17a01 100644 --- a/tests/Doctrine/Tests/ORM/Functional/EntityRepositoryTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/EntityRepositoryTest.php @@ -2,23 +2,33 @@ namespace Doctrine\Tests\ORM\Functional; +use Doctrine\Common\Collections\ArrayCollection; +use Doctrine\Common\Collections\Criteria; use Doctrine\DBAL\Connection; use Doctrine\DBAL\LockMode; +use Doctrine\ORM\EntityRepository; use Doctrine\ORM\OptimisticLockException; use Doctrine\ORM\ORMException; +use Doctrine\ORM\Query; use Doctrine\ORM\TransactionRequiredException; -use Doctrine\Tests\Models\CMS\CmsUser; -use Doctrine\Tests\Models\CMS\CmsEmail; use Doctrine\Tests\Models\CMS\CmsAddress; -use Doctrine\Common\Collections\Criteria; -use Doctrine\Common\Collections\ArrayCollection; +use Doctrine\Tests\Models\CMS\CmsEmail; +use Doctrine\Tests\Models\CMS\CmsUser; +use Doctrine\Tests\Models\DDC753\DDC753CustomRepository; +use Doctrine\Tests\Models\DDC753\DDC753DefaultRepository; +use Doctrine\Tests\Models\DDC753\DDC753EntityWithCustomRepository; +use Doctrine\Tests\Models\DDC753\DDC753EntityWithDefaultCustomRepository; +use Doctrine\Tests\Models\DDC753\DDC753InvalidRepository; use Doctrine\Tests\OrmFunctionalTestCase; +use Doctrine\Tests\VerifyDeprecations; /** * @author robo */ class EntityRepositoryTest extends OrmFunctionalTestCase { + use VerifyDeprecations; + protected function setUp() { $this->useModelSet('cms'); @@ -28,7 +38,7 @@ protected function setUp() public function tearDown() { if ($this->_em) { - $this->_em->getConfiguration()->setEntityNamespaces(array()); + $this->_em->getConfiguration()->setEntityNamespaces([]); } parent::tearDown(); } @@ -92,7 +102,7 @@ public function loadAssociatedFixture() $this->_em->flush(); $this->_em->clear(); - return array($user->id, $address->id); + return [$user->id, $address->id]; } public function loadFixtureUserEmail() @@ -136,7 +146,7 @@ public function loadFixtureUserEmail() $this->_em->flush(); $this->_em->clear(); - return array($user1, $user2, $user3); + return [$user1, $user2, $user3]; } public function buildUser($name, $username, $status, $address) @@ -170,10 +180,10 @@ public function buildAddress($country, $city, $street, $zip) public function testBasicFind() { $user1Id = $this->loadFixture(); - $repos = $this->_em->getRepository('Doctrine\Tests\Models\CMS\CmsUser'); + $repos = $this->_em->getRepository(CmsUser::class); $user = $repos->find($user1Id); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsUser',$user); + $this->assertInstanceOf(CmsUser::class,$user); $this->assertEquals('Roman', $user->name); $this->assertEquals('freak', $user->status); } @@ -181,11 +191,11 @@ public function testBasicFind() public function testFindByField() { $user1Id = $this->loadFixture(); - $repos = $this->_em->getRepository('Doctrine\Tests\Models\CMS\CmsUser'); + $repos = $this->_em->getRepository(CmsUser::class); - $users = $repos->findBy(array('status' => 'dev')); + $users = $repos->findBy(['status' => 'dev']); $this->assertEquals(2, count($users)); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsUser',$users[0]); + $this->assertInstanceOf(CmsUser::class,$users[0]); $this->assertEquals('Guilherme', $users[0]->name); $this->assertEquals('dev', $users[0]->status); } @@ -207,11 +217,11 @@ public function testFindByAssociationWithIntegerAsParameter() $this->_em->clear(); - $repository = $this->_em->getRepository('Doctrine\Tests\Models\CMS\CmsAddress'); - $addresses = $repository->findBy(array('user' => array($user1->getId(), $user2->getId()))); + $repository = $this->_em->getRepository(CmsAddress::class); + $addresses = $repository->findBy(['user' => [$user1->getId(), $user2->getId()]]); $this->assertEquals(2, count($addresses)); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsAddress',$addresses[0]); + $this->assertInstanceOf(CmsAddress::class,$addresses[0]); } public function testFindByAssociationWithObjectAsParameter() @@ -231,21 +241,21 @@ public function testFindByAssociationWithObjectAsParameter() $this->_em->clear(); - $repository = $this->_em->getRepository('Doctrine\Tests\Models\CMS\CmsAddress'); - $addresses = $repository->findBy(array('user' => array($user1, $user2))); + $repository = $this->_em->getRepository(CmsAddress::class); + $addresses = $repository->findBy(['user' => [$user1, $user2]]); $this->assertEquals(2, count($addresses)); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsAddress',$addresses[0]); + $this->assertInstanceOf(CmsAddress::class,$addresses[0]); } public function testFindFieldByMagicCall() { $user1Id = $this->loadFixture(); - $repos = $this->_em->getRepository('Doctrine\Tests\Models\CMS\CmsUser'); + $repos = $this->_em->getRepository(CmsUser::class); $users = $repos->findByStatus('dev'); $this->assertEquals(2, count($users)); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsUser',$users[0]); + $this->assertInstanceOf(CmsUser::class,$users[0]); $this->assertEquals('Guilherme', $users[0]->name); $this->assertEquals('dev', $users[0]->status); } @@ -253,7 +263,7 @@ public function testFindFieldByMagicCall() public function testFindAll() { $user1Id = $this->loadFixture(); - $repos = $this->_em->getRepository('Doctrine\Tests\Models\CMS\CmsUser'); + $repos = $this->_em->getRepository(CmsUser::class); $users = $repos->findAll(); $this->assertEquals(4, count($users)); @@ -262,7 +272,7 @@ public function testFindAll() public function testFindByAlias() { $user1Id = $this->loadFixture(); - $repos = $this->_em->getRepository('Doctrine\Tests\Models\CMS\CmsUser'); + $repos = $this->_em->getRepository(CmsUser::class); $this->_em->getConfiguration()->addEntityNamespace('CMS', 'Doctrine\Tests\Models\CMS'); @@ -272,11 +282,35 @@ public function testFindByAlias() $this->assertEquals(4, count($users)); } + public function testCount() + { + $this->loadFixture(); + $repos = $this->_em->getRepository(CmsUser::class); + + $userCount = $repos->count([]); + $this->assertSame(4, $userCount); + + $userCount = $repos->count(['status' => 'dev']); + $this->assertSame(2, $userCount); + + $userCount = $repos->count(['status' => 'nonexistent']); + $this->assertSame(0, $userCount); + } + + public function testCountBy() + { + $this->loadFixture(); + $repos = $this->_em->getRepository(CmsUser::class); + + $userCount = $repos->countByStatus('dev'); + $this->assertSame(2, $userCount); + } + /** * @expectedException \Doctrine\ORM\ORMException */ public function testExceptionIsThrownWhenCallingFindByWithoutParameter() { - $this->_em->getRepository('Doctrine\Tests\Models\CMS\CmsUser') + $this->_em->getRepository(CmsUser::class) ->findByStatus(); } @@ -284,7 +318,7 @@ public function testExceptionIsThrownWhenCallingFindByWithoutParameter() { * @expectedException \Doctrine\ORM\ORMException */ public function testExceptionIsThrownWhenUsingInvalidFieldName() { - $this->_em->getRepository('Doctrine\Tests\Models\CMS\CmsUser') + $this->_em->getRepository(CmsUser::class) ->findByThisFieldDoesNotExist('testvalue'); } @@ -296,7 +330,7 @@ public function testPessimisticReadLockWithoutTransaction_ThrowsException() { $this->expectException(TransactionRequiredException::class); - $this->_em->getRepository('Doctrine\Tests\Models\CMS\CmsUser') + $this->_em->getRepository(CmsUser::class) ->find(1, LockMode::PESSIMISTIC_READ); } @@ -308,7 +342,7 @@ public function testPessimisticWriteLockWithoutTransaction_ThrowsException() { $this->expectException(TransactionRequiredException::class); - $this->_em->getRepository('Doctrine\Tests\Models\CMS\CmsUser') + $this->_em->getRepository(CmsUser::class) ->find(1, LockMode::PESSIMISTIC_WRITE); } @@ -320,7 +354,7 @@ public function testOptimisticLockUnversionedEntity_ThrowsException() { $this->expectException(OptimisticLockException::class); - $this->_em->getRepository('Doctrine\Tests\Models\CMS\CmsUser') + $this->_em->getRepository(CmsUser::class) ->find(1, LockMode::OPTIMISTIC); } @@ -339,11 +373,11 @@ public function testIdentityMappedOptimisticLockUnversionedEntity_ThrowsExceptio $userId = $user->id; - $this->_em->find('Doctrine\Tests\Models\CMS\CmsUser', $userId); + $this->_em->find(CmsUser::class, $userId); $this->expectException(OptimisticLockException::class); - $this->_em->find('Doctrine\Tests\Models\CMS\CmsUser', $userId, LockMode::OPTIMISTIC); + $this->_em->find(CmsUser::class, $userId, LockMode::OPTIMISTIC); } /** @@ -353,7 +387,7 @@ public function testFindMagicCallByNullValue() { $this->loadFixture(); - $repos = $this->_em->getRepository('Doctrine\Tests\Models\CMS\CmsUser'); + $repos = $this->_em->getRepository(CmsUser::class); $users = $repos->findByStatus(null); $this->assertEquals(1, count($users)); @@ -366,7 +400,7 @@ public function testInvalidMagicCall() { $this->expectException(\BadMethodCallException::class); - $repos = $this->_em->getRepository('Doctrine\Tests\Models\CMS\CmsUser'); + $repos = $this->_em->getRepository(CmsUser::class); $repos->foo(); } @@ -376,12 +410,12 @@ public function testInvalidMagicCall() public function testFindByAssociationKey_ExceptionOnInverseSide() { list($userId, $addressId) = $this->loadAssociatedFixture(); - $repos = $this->_em->getRepository('Doctrine\Tests\Models\CMS\CmsUser'); + $repos = $this->_em->getRepository(CmsUser::class); $this->expectException(ORMException::class); $this->expectExceptionMessage("You cannot search for the association field 'Doctrine\Tests\Models\CMS\CmsUser#address', because it is the inverse side of an association. Find methods only work on owning side associations."); - $user = $repos->findBy(array('address' => $addressId)); + $user = $repos->findBy(['address' => $addressId]); } /** @@ -390,10 +424,10 @@ public function testFindByAssociationKey_ExceptionOnInverseSide() public function testFindOneByAssociationKey() { list($userId, $addressId) = $this->loadAssociatedFixture(); - $repos = $this->_em->getRepository('Doctrine\Tests\Models\CMS\CmsAddress'); - $address = $repos->findOneBy(array('user' => $userId)); + $repos = $this->_em->getRepository(CmsAddress::class); + $address = $repos->findOneBy(['user' => $userId]); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsAddress', $address); + $this->assertInstanceOf(CmsAddress::class, $address); $this->assertEquals($addressId, $address->id); } @@ -404,9 +438,9 @@ public function testFindOneByOrderBy() { $this->loadFixture(); - $repos = $this->_em->getRepository('Doctrine\Tests\Models\CMS\CmsUser'); - $userAsc = $repos->findOneBy(array(), array("username" => "ASC")); - $userDesc = $repos->findOneBy(array(), array("username" => "DESC")); + $repos = $this->_em->getRepository(CmsUser::class); + $userAsc = $repos->findOneBy([], ["username" => "ASC"]); + $userDesc = $repos->findOneBy([], ["username" => "DESC"]); $this->assertNotSame($userAsc, $userDesc); } @@ -417,10 +451,10 @@ public function testFindOneByOrderBy() public function testFindByAssociationKey() { list($userId, $addressId) = $this->loadAssociatedFixture(); - $repos = $this->_em->getRepository('Doctrine\Tests\Models\CMS\CmsAddress'); - $addresses = $repos->findBy(array('user' => $userId)); + $repos = $this->_em->getRepository(CmsAddress::class); + $addresses = $repos->findBy(['user' => $userId]); - $this->assertContainsOnly('Doctrine\Tests\Models\CMS\CmsAddress', $addresses); + $this->assertContainsOnly(CmsAddress::class, $addresses); $this->assertEquals(1, count($addresses)); $this->assertEquals($addressId, $addresses[0]->id); } @@ -431,10 +465,10 @@ public function testFindByAssociationKey() public function testFindAssociationByMagicCall() { list($userId, $addressId) = $this->loadAssociatedFixture(); - $repos = $this->_em->getRepository('Doctrine\Tests\Models\CMS\CmsAddress'); + $repos = $this->_em->getRepository(CmsAddress::class); $addresses = $repos->findByUser($userId); - $this->assertContainsOnly('Doctrine\Tests\Models\CMS\CmsAddress', $addresses); + $this->assertContainsOnly(CmsAddress::class, $addresses); $this->assertEquals(1, count($addresses)); $this->assertEquals($addressId, $addresses[0]->id); } @@ -445,26 +479,26 @@ public function testFindAssociationByMagicCall() public function testFindOneAssociationByMagicCall() { list($userId, $addressId) = $this->loadAssociatedFixture(); - $repos = $this->_em->getRepository('Doctrine\Tests\Models\CMS\CmsAddress'); + $repos = $this->_em->getRepository(CmsAddress::class); $address = $repos->findOneByUser($userId); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsAddress', $address); + $this->assertInstanceOf(CmsAddress::class, $address); $this->assertEquals($addressId, $address->id); } public function testValidNamedQueryRetrieval() { - $repos = $this->_em->getRepository('Doctrine\Tests\Models\CMS\CmsUser'); + $repos = $this->_em->getRepository(CmsUser::class); $query = $repos->createNamedQuery('all'); - $this->assertInstanceOf('Doctrine\ORM\Query', $query); + $this->assertInstanceOf(Query::class, $query); $this->assertEquals('SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u', $query->getDQL()); } public function testInvalidNamedQueryRetrieval() { - $repos = $this->_em->getRepository('Doctrine\Tests\Models\CMS\CmsUser'); + $repos = $this->_em->getRepository(CmsUser::class); $this->expectException(\Doctrine\ORM\Mapping\MappingException::class); @@ -476,21 +510,21 @@ public function testInvalidNamedQueryRetrieval() */ public function testIsNullCriteriaDoesNotGenerateAParameter() { - $repos = $this->_em->getRepository('Doctrine\Tests\Models\CMS\CmsUser'); - $users = $repos->findBy(array('status' => null, 'username' => 'romanb')); + $repos = $this->_em->getRepository(CmsUser::class); + $users = $repos->findBy(['status' => null, 'username' => 'romanb']); $params = $this->_sqlLoggerStack->queries[$this->_sqlLoggerStack->currentQuery]['params']; $this->assertEquals(1, count($params), "Should only execute with one parameter."); - $this->assertEquals(array('romanb'), $params); + $this->assertEquals(['romanb'], $params); } public function testIsNullCriteria() { $this->loadFixture(); - $repos = $this->_em->getRepository('Doctrine\Tests\Models\CMS\CmsUser'); + $repos = $this->_em->getRepository(CmsUser::class); - $users = $repos->findBy(array('status' => null)); + $users = $repos->findBy(['status' => null]); $this->assertEquals(1, count($users)); } @@ -501,12 +535,12 @@ public function testFindByLimitOffset() { $this->loadFixture(); - $repos = $this->_em->getRepository('Doctrine\Tests\Models\CMS\CmsUser'); + $repos = $this->_em->getRepository(CmsUser::class); - $users1 = $repos->findBy(array(), null, 1, 0); - $users2 = $repos->findBy(array(), null, 1, 1); + $users1 = $repos->findBy([], null, 1, 0); + $users2 = $repos->findBy([], null, 1, 1); - $this->assertEquals(4, count($repos->findBy(array()))); + $this->assertEquals(4, count($repos->findBy([]))); $this->assertEquals(1, count($users1)); $this->assertEquals(1, count($users2)); $this->assertNotSame($users1[0], $users2[0]); @@ -519,9 +553,9 @@ public function testFindByOrderBy() { $this->loadFixture(); - $repos = $this->_em->getRepository('Doctrine\Tests\Models\CMS\CmsUser'); - $usersAsc = $repos->findBy(array(), array("username" => "ASC")); - $usersDesc = $repos->findBy(array(), array("username" => "DESC")); + $repos = $this->_em->getRepository(CmsUser::class); + $usersAsc = $repos->findBy([], ["username" => "ASC"]); + $usersDesc = $repos->findBy([], ["username" => "DESC"]); $this->assertEquals(4, count($usersAsc), "Pre-condition: only four users in fixture"); $this->assertEquals(4, count($usersDesc), "Pre-condition: only four users in fixture"); @@ -536,9 +570,9 @@ public function testFindByOrderByAssociation() { $this->loadFixtureUserEmail(); - $repository = $this->_em->getRepository('Doctrine\Tests\Models\CMS\CmsUser'); - $resultAsc = $repository->findBy(array(), array('email' => 'ASC')); - $resultDesc = $repository->findBy(array(), array('email' => 'DESC')); + $repository = $this->_em->getRepository(CmsUser::class); + $resultAsc = $repository->findBy([], ['email' => 'ASC']); + $resultDesc = $repository->findBy([], ['email' => 'DESC']); $this->assertCount(3, $resultAsc); $this->assertCount(3, $resultDesc); @@ -553,15 +587,15 @@ public function testFindByOrderByAssociation() public function testFindFieldByMagicCallOrderBy() { $this->loadFixture(); - $repos = $this->_em->getRepository('Doctrine\Tests\Models\CMS\CmsUser'); + $repos = $this->_em->getRepository(CmsUser::class); - $usersAsc = $repos->findByStatus('dev', array('username' => "ASC")); - $usersDesc = $repos->findByStatus('dev', array('username' => "DESC")); + $usersAsc = $repos->findByStatus('dev', ['username' => "ASC"]); + $usersDesc = $repos->findByStatus('dev', ['username' => "DESC"]); $this->assertEquals(2, count($usersAsc)); $this->assertEquals(2, count($usersDesc)); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsUser',$usersAsc[0]); + $this->assertInstanceOf(CmsUser::class,$usersAsc[0]); $this->assertEquals('Alexander', $usersAsc[0]->name); $this->assertEquals('dev', $usersAsc[0]->status); @@ -575,10 +609,10 @@ public function testFindFieldByMagicCallOrderBy() public function testFindFieldByMagicCallLimitOffset() { $this->loadFixture(); - $repos = $this->_em->getRepository('Doctrine\Tests\Models\CMS\CmsUser'); + $repos = $this->_em->getRepository(CmsUser::class); - $users1 = $repos->findByStatus('dev', array(), 1, 0); - $users2 = $repos->findByStatus('dev', array(), 1, 1); + $users1 = $repos->findByStatus('dev', [], 1, 0); + $users2 = $repos->findByStatus('dev', [], 1, 1); $this->assertEquals(1, count($users1)); $this->assertEquals(1, count($users2)); @@ -590,22 +624,22 @@ public function testFindFieldByMagicCallLimitOffset() */ public function testDefaultRepositoryClassName() { - $this->assertEquals($this->_em->getConfiguration()->getDefaultRepositoryClassName(), "Doctrine\ORM\EntityRepository"); - $this->_em->getConfiguration()->setDefaultRepositoryClassName("Doctrine\Tests\Models\DDC753\DDC753DefaultRepository"); - $this->assertEquals($this->_em->getConfiguration()->getDefaultRepositoryClassName(), "Doctrine\Tests\Models\DDC753\DDC753DefaultRepository"); + $this->assertEquals($this->_em->getConfiguration()->getDefaultRepositoryClassName(), EntityRepository::class); + $this->_em->getConfiguration()->setDefaultRepositoryClassName(DDC753DefaultRepository::class); + $this->assertEquals($this->_em->getConfiguration()->getDefaultRepositoryClassName(), DDC753DefaultRepository::class); - $repos = $this->_em->getRepository('Doctrine\Tests\Models\DDC753\DDC753EntityWithDefaultCustomRepository'); - $this->assertInstanceOf("Doctrine\Tests\Models\DDC753\DDC753DefaultRepository", $repos); + $repos = $this->_em->getRepository(DDC753EntityWithDefaultCustomRepository::class); + $this->assertInstanceOf(DDC753DefaultRepository::class, $repos); $this->assertTrue($repos->isDefaultRepository()); - $repos = $this->_em->getRepository('Doctrine\Tests\Models\DDC753\DDC753EntityWithCustomRepository'); - $this->assertInstanceOf("Doctrine\Tests\Models\DDC753\DDC753CustomRepository", $repos); + $repos = $this->_em->getRepository(DDC753EntityWithCustomRepository::class); + $this->assertInstanceOf(DDC753CustomRepository::class, $repos); $this->assertTrue($repos->isCustomRepository()); - $this->assertEquals($this->_em->getConfiguration()->getDefaultRepositoryClassName(), "Doctrine\Tests\Models\DDC753\DDC753DefaultRepository"); - $this->_em->getConfiguration()->setDefaultRepositoryClassName("Doctrine\ORM\EntityRepository"); - $this->assertEquals($this->_em->getConfiguration()->getDefaultRepositoryClassName(), "Doctrine\ORM\EntityRepository"); + $this->assertEquals($this->_em->getConfiguration()->getDefaultRepositoryClassName(), DDC753DefaultRepository::class); + $this->_em->getConfiguration()->setDefaultRepositoryClassName(EntityRepository::class); + $this->assertEquals($this->_em->getConfiguration()->getDefaultRepositoryClassName(), EntityRepository::class); } @@ -616,8 +650,8 @@ public function testDefaultRepositoryClassName() */ public function testSetDefaultRepositoryInvalidClassError() { - $this->assertEquals($this->_em->getConfiguration()->getDefaultRepositoryClassName(), "Doctrine\ORM\EntityRepository"); - $this->_em->getConfiguration()->setDefaultRepositoryClassName("Doctrine\Tests\Models\DDC753\DDC753InvalidRepository"); + $this->assertEquals($this->_em->getConfiguration()->getDefaultRepositoryClassName(), EntityRepository::class); + $this->_em->getConfiguration()->setDefaultRepositoryClassName(DDC753InvalidRepository::class); } /** @@ -630,7 +664,7 @@ public function testSingleRepositoryInstanceForDifferentEntityAliases() $config->addEntityNamespace('Aliased', 'Doctrine\Tests\Models\CMS'); $config->addEntityNamespace('AliasedAgain', 'Doctrine\Tests\Models\CMS'); - $repository = $this->_em->getRepository('Doctrine\Tests\Models\CMS\CmsUser'); + $repository = $this->_em->getRepository(CmsUser::class); $this->assertSame($repository, $this->_em->getRepository('Aliased:CmsUser')); $this->assertSame($repository, $this->_em->getRepository('AliasedAgain:CmsUser')); @@ -642,8 +676,8 @@ public function testSingleRepositoryInstanceForDifferentEntityAliases() public function testCanRetrieveRepositoryFromClassNameWithLeadingBackslash() { $this->assertSame( - $this->_em->getRepository('\\Doctrine\\Tests\\Models\\CMS\\CmsUser'), - $this->_em->getRepository('Doctrine\\Tests\\Models\\CMS\\CmsUser') + $this->_em->getRepository('\\' . CmsUser::class), + $this->_em->getRepository(CmsUser::class) ); } @@ -655,8 +689,8 @@ public function testCanRetrieveRepositoryFromClassNameWithLeadingBackslash() */ public function testInvalidOrderByAssociation() { - $this->_em->getRepository('Doctrine\Tests\Models\CMS\CmsUser') - ->findBy(array('status' => 'test'), array('address' => 'ASC')); + $this->_em->getRepository(CmsUser::class) + ->findBy(['status' => 'test'], ['address' => 'ASC']); } /** @@ -667,8 +701,8 @@ public function testInvalidOrientation() $this->expectException(ORMException::class); $this->expectExceptionMessage('Invalid order by orientation specified for Doctrine\Tests\Models\CMS\CmsUser#username'); - $repo = $this->_em->getRepository('Doctrine\Tests\Models\CMS\CmsUser'); - $repo->findBy(array('status' => 'test'), array('username' => 'INVALID')); + $repo = $this->_em->getRepository(CmsUser::class); + $repo->findBy(['status' => 'test'], ['username' => 'INVALID']); } /** @@ -676,11 +710,11 @@ public function testInvalidOrientation() */ public function testFindByAssociationArray() { - $repo = $this->_em->getRepository('Doctrine\Tests\Models\CMS\CmsArticle'); - $data = $repo->findBy(array('user' => array(1, 2, 3))); + $repo = $this->_em->getRepository(CmsAddress::class); + $data = $repo->findBy(['user' => [1, 2, 3]]); $query = array_pop($this->_sqlLoggerStack->queries); - $this->assertEquals(array(1,2,3), $query['params'][0]); + $this->assertEquals([1,2,3], $query['params'][0]); $this->assertEquals(Connection::PARAM_INT_ARRAY, $query['types'][0]); } @@ -691,7 +725,7 @@ public function testMatchingEmptyCriteria() { $this->loadFixture(); - $repository = $this->_em->getRepository('Doctrine\Tests\Models\CMS\CmsUser'); + $repository = $this->_em->getRepository(CmsUser::class); $users = $repository->matching(new Criteria()); $this->assertEquals(4, count($users)); @@ -704,7 +738,7 @@ public function testMatchingCriteriaEqComparison() { $this->loadFixture(); - $repository = $this->_em->getRepository('Doctrine\Tests\Models\CMS\CmsUser'); + $repository = $this->_em->getRepository(CmsUser::class); $users = $repository->matching(new Criteria( Criteria::expr()->eq('username', 'beberlei') )); @@ -719,7 +753,7 @@ public function testMatchingCriteriaNeqComparison() { $this->loadFixture(); - $repository = $this->_em->getRepository('Doctrine\Tests\Models\CMS\CmsUser'); + $repository = $this->_em->getRepository(CmsUser::class); $users = $repository->matching(new Criteria( Criteria::expr()->neq('username', 'beberlei') )); @@ -734,9 +768,9 @@ public function testMatchingCriteriaInComparison() { $this->loadFixture(); - $repository = $this->_em->getRepository('Doctrine\Tests\Models\CMS\CmsUser'); + $repository = $this->_em->getRepository(CmsUser::class); $users = $repository->matching(new Criteria( - Criteria::expr()->in('username', array('beberlei', 'gblanco')) + Criteria::expr()->in('username', ['beberlei', 'gblanco']) )); $this->assertEquals(2, count($users)); @@ -749,9 +783,9 @@ public function testMatchingCriteriaNotInComparison() { $this->loadFixture(); - $repository = $this->_em->getRepository('Doctrine\Tests\Models\CMS\CmsUser'); + $repository = $this->_em->getRepository(CmsUser::class); $users = $repository->matching(new Criteria( - Criteria::expr()->notIn('username', array('beberlei', 'gblanco', 'asm89')) + Criteria::expr()->notIn('username', ['beberlei', 'gblanco', 'asm89']) )); $this->assertEquals(1, count($users)); @@ -764,7 +798,7 @@ public function testMatchingCriteriaLtComparison() { $firstUserId = $this->loadFixture(); - $repository = $this->_em->getRepository('Doctrine\Tests\Models\CMS\CmsUser'); + $repository = $this->_em->getRepository(CmsUser::class); $users = $repository->matching(new Criteria( Criteria::expr()->lt('id', $firstUserId + 1) )); @@ -779,7 +813,7 @@ public function testMatchingCriteriaLeComparison() { $firstUserId = $this->loadFixture(); - $repository = $this->_em->getRepository('Doctrine\Tests\Models\CMS\CmsUser'); + $repository = $this->_em->getRepository(CmsUser::class); $users = $repository->matching(new Criteria( Criteria::expr()->lte('id', $firstUserId + 1) )); @@ -794,7 +828,7 @@ public function testMatchingCriteriaGtComparison() { $firstUserId = $this->loadFixture(); - $repository = $this->_em->getRepository('Doctrine\Tests\Models\CMS\CmsUser'); + $repository = $this->_em->getRepository(CmsUser::class); $users = $repository->matching(new Criteria( Criteria::expr()->gt('id', $firstUserId) )); @@ -809,7 +843,7 @@ public function testMatchingCriteriaGteComparison() { $firstUserId = $this->loadFixture(); - $repository = $this->_em->getRepository('Doctrine\Tests\Models\CMS\CmsUser'); + $repository = $this->_em->getRepository(CmsUser::class); $users = $repository->matching(new Criteria( Criteria::expr()->gte('id', $firstUserId) )); @@ -824,13 +858,13 @@ public function testMatchingCriteriaAssocationByObjectInMemory() { list($userId, $addressId) = $this->loadAssociatedFixture(); - $user = $this->_em->find('Doctrine\Tests\Models\CMS\CmsUser', $userId); + $user = $this->_em->find(CmsUser::class, $userId); $criteria = new Criteria( Criteria::expr()->eq('user', $user) ); - $repository = $this->_em->getRepository('Doctrine\Tests\Models\CMS\CmsAddress'); + $repository = $this->_em->getRepository(CmsAddress::class); $addresses = $repository->matching($criteria); $this->assertEquals(1, count($addresses)); @@ -847,13 +881,13 @@ public function testMatchingCriteriaAssocationInWithArray() { list($userId, $addressId) = $this->loadAssociatedFixture(); - $user = $this->_em->find('Doctrine\Tests\Models\CMS\CmsUser', $userId); + $user = $this->_em->find(CmsUser::class, $userId); $criteria = new Criteria( - Criteria::expr()->in('user', array($user)) + Criteria::expr()->in('user', [$user]) ); - $repository = $this->_em->getRepository('Doctrine\Tests\Models\CMS\CmsAddress'); + $repository = $this->_em->getRepository(CmsAddress::class); $addresses = $repository->matching($criteria); $this->assertEquals(1, count($addresses)); @@ -867,7 +901,7 @@ public function testMatchingCriteriaContainsComparison() { $this->loadFixture(); - $repository = $this->_em->getRepository('Doctrine\Tests\Models\CMS\CmsUser'); + $repository = $this->_em->getRepository(CmsUser::class); $users = $repository->matching(new Criteria(Criteria::expr()->contains('name', 'Foobar'))); $this->assertEquals(0, count($users)); @@ -879,6 +913,38 @@ public function testMatchingCriteriaContainsComparison() $this->assertEquals(2, count($users)); } + public function testMatchingCriteriaStartsWithComparison() + { + $this->loadFixture(); + + $repository = $this->_em->getRepository(CmsUser::class); + + $users = $repository->matching(new Criteria(Criteria::expr()->startsWith('name', 'Foo'))); + $this->assertCount(0, $users); + + $users = $repository->matching(new Criteria(Criteria::expr()->startsWith('name', 'R'))); + $this->assertCount(1, $users); + + $users = $repository->matching(new Criteria(Criteria::expr()->startsWith('status', 'de'))); + $this->assertCount(2, $users); + } + + public function testMatchingCriteriaEndsWithComparison() + { + $this->loadFixture(); + + $repository = $this->_em->getRepository(CmsUser::class); + + $users = $repository->matching(new Criteria(Criteria::expr()->endsWith('name', 'foo'))); + $this->assertCount(0, $users); + + $users = $repository->matching(new Criteria(Criteria::expr()->endsWith('name', 'oman'))); + $this->assertCount(1, $users); + + $users = $repository->matching(new Criteria(Criteria::expr()->endsWith('status', 'ev'))); + $this->assertCount(2, $users); + } + /** * @group DDC-2478 */ @@ -886,7 +952,7 @@ public function testMatchingCriteriaNullAssocComparison() { $fixtures = $this->loadFixtureUserEmail(); $user = $this->_em->merge($fixtures[0]); - $repository = $this->_em->getRepository('Doctrine\Tests\Models\CMS\CmsUser'); + $repository = $this->_em->getRepository(CmsUser::class); $criteriaIsNull = Criteria::create()->where(Criteria::expr()->isNull('email')); $criteriaEqNull = Criteria::create()->where(Criteria::expr()->eq('email', null)); @@ -901,11 +967,12 @@ public function testMatchingCriteriaNullAssocComparison() $this->assertCount(1, $usersIsNull); $this->assertCount(1, $usersEqNull); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsUser', $usersIsNull[0]); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsUser', $usersEqNull[0]); + $this->assertInstanceOf(CmsUser::class, $usersIsNull[0]); + $this->assertInstanceOf(CmsUser::class, $usersEqNull[0]); $this->assertNull($usersIsNull[0]->getEmail()); $this->assertNull($usersEqNull[0]->getEmail()); + $this->assertHasDeprecationMessages(); } /** @@ -913,11 +980,11 @@ public function testMatchingCriteriaNullAssocComparison() */ public function testCreateResultSetMappingBuilder() { - $repository = $this->_em->getRepository('Doctrine\Tests\Models\CMS\CmsUser'); + $repository = $this->_em->getRepository(CmsUser::class); $rsm = $repository->createResultSetMappingBuilder('u'); - $this->assertInstanceOf('Doctrine\ORM\Query\ResultSetMappingBuilder', $rsm); - $this->assertEquals(array('u' => 'Doctrine\Tests\Models\CMS\CmsUser'), $rsm->aliasMap); + $this->assertInstanceOf(Query\ResultSetMappingBuilder::class, $rsm); + $this->assertEquals(['u' => CmsUser::class], $rsm->aliasMap); } /** @@ -928,8 +995,8 @@ public function testFindByFieldInjectionPrevented() $this->expectException(ORMException::class); $this->expectExceptionMessage('Unrecognized field: '); - $repository = $this->_em->getRepository('Doctrine\Tests\Models\CMS\CmsUser'); - $repository->findBy(array('username = ?; DELETE FROM cms_users; SELECT 1 WHERE 1' => 'test')); + $repository = $this->_em->getRepository(CmsUser::class); + $repository->findBy(['username = ?; DELETE FROM cms_users; SELECT 1 WHERE 1' => 'test']); } /** @@ -940,8 +1007,8 @@ public function testFindOneByFieldInjectionPrevented() $this->expectException(ORMException::class); $this->expectExceptionMessage('Unrecognized field: '); - $repository = $this->_em->getRepository('Doctrine\Tests\Models\CMS\CmsUser'); - $repository->findOneBy(array('username = ?; DELETE FROM cms_users; SELECT 1 WHERE 1' => 'test')); + $repository = $this->_em->getRepository(CmsUser::class); + $repository->findOneBy(['username = ?; DELETE FROM cms_users; SELECT 1 WHERE 1' => 'test']); } /** @@ -952,7 +1019,7 @@ public function testMatchingInjectionPrevented() $this->expectException(ORMException::class); $this->expectExceptionMessage('Unrecognized field: '); - $repository = $this->_em->getRepository('Doctrine\Tests\Models\CMS\CmsUser'); + $repository = $this->_em->getRepository(CmsUser::class); $result = $repository->matching(new Criteria( Criteria::expr()->eq('username = ?; DELETE FROM cms_users; SELECT 1 WHERE 1', 'beberlei') )); @@ -969,8 +1036,8 @@ public function testFindInjectionPrevented() $this->expectException(ORMException::class); $this->expectExceptionMessage('Unrecognized identifier fields: '); - $repository = $this->_em->getRepository('Doctrine\Tests\Models\CMS\CmsUser'); - $repository->find(array('username = ?; DELETE FROM cms_users; SELECT 1 WHERE 1' => 'test', 'id' => 1)); + $repository = $this->_em->getRepository(CmsUser::class); + $repository->find(['username = ?; DELETE FROM cms_users; SELECT 1 WHERE 1' => 'test', 'id' => 1]); } /** @@ -992,7 +1059,7 @@ public function testFindByNullValueInInCondition() $this->_em->persist($user2); $this->_em->flush(); - $users = $this->_em->getRepository('Doctrine\Tests\Models\CMS\CmsUser')->findBy(array('status' => array(null))); + $users = $this->_em->getRepository(CmsUser::class)->findBy(['status' => [null]]); $this->assertCount(1, $users); $this->assertSame($user1, reset($users)); @@ -1019,8 +1086,8 @@ public function testFindByNullValueInMultipleInCriteriaValues() $users = $this ->_em - ->getRepository('Doctrine\Tests\Models\CMS\CmsUser') - ->findBy(array('status' => array('foo', null))); + ->getRepository(CmsUser::class) + ->findBy(['status' => ['foo', null]]); $this->assertCount(1, $users); $this->assertSame($user1, reset($users)); @@ -1047,13 +1114,13 @@ public function testFindMultipleByNullValueInMultipleInCriteriaValues() $users = $this ->_em - ->getRepository('Doctrine\Tests\Models\CMS\CmsUser') - ->findBy(array('status' => array('dbal maintainer', null))); + ->getRepository(CmsUser::class) + ->findBy(['status' => ['dbal maintainer', null]]); $this->assertCount(2, $users); foreach ($users as $user) { - $this->assertTrue(in_array($user, array($user1, $user2))); + $this->assertTrue(in_array($user, [$user1, $user2])); } } } diff --git a/tests/Doctrine/Tests/ORM/Functional/ExtraLazyCollectionTest.php b/tests/Doctrine/Tests/ORM/Functional/ExtraLazyCollectionTest.php index c8af5bd8546..e7f4fd29803 100644 --- a/tests/Doctrine/Tests/ORM/Functional/ExtraLazyCollectionTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/ExtraLazyCollectionTest.php @@ -40,7 +40,7 @@ public function setUp() $this->useModelSet('ddc2504'); parent::setUp(); - $class = $this->_em->getClassMetadata('Doctrine\Tests\Models\CMS\CmsUser'); + $class = $this->_em->getClassMetadata(CmsUser::class); $class->associationMappings['groups']['fetch'] = ClassMetadataInfo::FETCH_EXTRA_LAZY; $class->associationMappings['groups']['indexBy'] = 'name'; $class->associationMappings['articles']['fetch'] = ClassMetadataInfo::FETCH_EXTRA_LAZY; @@ -52,7 +52,7 @@ public function setUp() unset($class->associationMappings['articles']['cache']); unset($class->associationMappings['users']['cache']); - $class = $this->_em->getClassMetadata('Doctrine\Tests\Models\CMS\CmsGroup'); + $class = $this->_em->getClassMetadata(CmsGroup::class); $class->associationMappings['users']['fetch'] = ClassMetadataInfo::FETCH_EXTRA_LAZY; $class->associationMappings['users']['indexBy'] = 'username'; @@ -63,7 +63,7 @@ public function tearDown() { parent::tearDown(); - $class = $this->_em->getClassMetadata('Doctrine\Tests\Models\CMS\CmsUser'); + $class = $this->_em->getClassMetadata(CmsUser::class); $class->associationMappings['groups']['fetch'] = ClassMetadataInfo::FETCH_LAZY; $class->associationMappings['articles']['fetch'] = ClassMetadataInfo::FETCH_LAZY; $class->associationMappings['phonenumbers']['fetch'] = ClassMetadataInfo::FETCH_LAZY; @@ -72,7 +72,7 @@ public function tearDown() unset($class->associationMappings['articles']['indexBy']); unset($class->associationMappings['phonenumbers']['indexBy']); - $class = $this->_em->getClassMetadata('Doctrine\Tests\Models\CMS\CmsGroup'); + $class = $this->_em->getClassMetadata(CmsGroup::class); $class->associationMappings['users']['fetch'] = ClassMetadataInfo::FETCH_LAZY; unset($class->associationMappings['users']['indexBy']); @@ -84,7 +84,7 @@ public function tearDown() */ public function testCountNotInitializesCollection() { - $user = $this->_em->find('Doctrine\Tests\Models\CMS\CmsUser', $this->userId); + $user = $this->_em->find(CmsUser::class, $this->userId); $queryCount = $this->getCurrentQueryCount(); $this->assertFalse($user->groups->isInitialized()); @@ -101,7 +101,7 @@ public function testCountNotInitializesCollection() */ public function testCountWhenNewEntityPresent() { - $user = $this->_em->find('Doctrine\Tests\Models\CMS\CmsUser', $this->userId); + $user = $this->_em->find(CmsUser::class, $this->userId); $newGroup = new CmsGroup(); $newGroup->name = "Test4"; @@ -120,7 +120,7 @@ public function testCountWhenNewEntityPresent() */ public function testCountWhenInitialized() { - $user = $this->_em->find('Doctrine\Tests\Models\CMS\CmsUser', $this->userId); + $user = $this->_em->find(CmsUser::class, $this->userId); $queryCount = $this->getCurrentQueryCount(); foreach ($user->groups AS $group) { } @@ -135,7 +135,7 @@ public function testCountWhenInitialized() */ public function testCountInverseCollection() { - $group = $this->_em->find('Doctrine\Tests\Models\CMS\CmsGroup', $this->groupId); + $group = $this->_em->find(CmsGroup::class, $this->groupId); $this->assertFalse($group->users->isInitialized(), "Pre-Condition"); $this->assertEquals(4, count($group->users)); @@ -147,7 +147,7 @@ public function testCountInverseCollection() */ public function testCountOneToMany() { - $user = $this->_em->find('Doctrine\Tests\Models\CMS\CmsUser', $this->userId); + $user = $this->_em->find(CmsUser::class, $this->userId); $this->assertFalse($user->groups->isInitialized(), "Pre-Condition"); $this->assertEquals(2, count($user->articles)); @@ -158,7 +158,7 @@ public function testCountOneToMany() */ public function testCountOneToManyJoinedInheritance() { - $otherClass = $this->_em->find(DDC2504OtherClass::CLASSNAME, $this->ddc2504OtherClassId); + $otherClass = $this->_em->find(DDC2504OtherClass::class, $this->ddc2504OtherClassId); $this->assertFalse($otherClass->childClasses->isInitialized(), "Pre-Condition"); $this->assertEquals(2, count($otherClass->childClasses)); @@ -169,7 +169,7 @@ public function testCountOneToManyJoinedInheritance() */ public function testFullSlice() { - $user = $this->_em->find('Doctrine\Tests\Models\CMS\CmsUser', $this->userId); + $user = $this->_em->find(CmsUser::class, $this->userId); $this->assertFalse($user->groups->isInitialized(), "Pre-Condition: Collection is not initialized."); $someGroups = $user->groups->slice(null); @@ -182,20 +182,20 @@ public function testFullSlice() */ public function testSlice() { - $user = $this->_em->find('Doctrine\Tests\Models\CMS\CmsUser', $this->userId); + $user = $this->_em->find(CmsUser::class, $this->userId); $this->assertFalse($user->groups->isInitialized(), "Pre-Condition: Collection is not initialized."); $queryCount = $this->getCurrentQueryCount(); $someGroups = $user->groups->slice(0, 2); - $this->assertContainsOnly('Doctrine\Tests\Models\CMS\CmsGroup', $someGroups); + $this->assertContainsOnly(CmsGroup::class, $someGroups); $this->assertEquals(2, count($someGroups)); $this->assertFalse($user->groups->isInitialized(), "Slice should not initialize the collection if it wasn't before!"); $otherGroup = $user->groups->slice(2, 1); - $this->assertContainsOnly('Doctrine\Tests\Models\CMS\CmsGroup', $otherGroup); + $this->assertContainsOnly(CmsGroup::class, $otherGroup); $this->assertEquals(1, count($otherGroup)); $this->assertFalse($user->groups->isInitialized()); @@ -213,7 +213,7 @@ public function testSlice() */ public function testSliceInitializedCollection() { - $user = $this->_em->find('Doctrine\Tests\Models\CMS\CmsUser', $this->userId); + $user = $this->_em->find(CmsUser::class, $this->userId); $queryCount = $this->getCurrentQueryCount(); foreach ($user->groups AS $group) { } @@ -232,15 +232,15 @@ public function testSliceInitializedCollection() */ public function testSliceInverseCollection() { - $group = $this->_em->find('Doctrine\Tests\Models\CMS\CmsGroup', $this->groupId); + $group = $this->_em->find(CmsGroup::class, $this->groupId); $this->assertFalse($group->users->isInitialized(), "Pre-Condition"); $queryCount = $this->getCurrentQueryCount(); $someUsers = $group->users->slice(0, 2); $otherUsers = $group->users->slice(2, 2); - $this->assertContainsOnly('Doctrine\Tests\Models\CMS\CmsUser', $someUsers); - $this->assertContainsOnly('Doctrine\Tests\Models\CMS\CmsUser', $otherUsers); + $this->assertContainsOnly(CmsUser::class, $someUsers); + $this->assertContainsOnly(CmsUser::class, $otherUsers); $this->assertEquals(2, count($someUsers)); $this->assertEquals(2, count($otherUsers)); @@ -253,7 +253,7 @@ public function testSliceInverseCollection() */ public function testSliceOneToMany() { - $user = $this->_em->find('Doctrine\Tests\Models\CMS\CmsUser', $this->userId); + $user = $this->_em->find(CmsUser::class, $this->userId); $this->assertFalse($user->articles->isInitialized(), "Pre-Condition: Collection is not initialized."); $queryCount = $this->getCurrentQueryCount(); @@ -269,11 +269,11 @@ public function testSliceOneToMany() */ public function testContainsOneToMany() { - $user = $this->_em->find('Doctrine\Tests\Models\CMS\CmsUser', $this->userId); + $user = $this->_em->find(CmsUser::class, $this->userId); $this->assertFalse($user->articles->isInitialized(), "Pre-Condition: Collection is not initialized."); // Test One to Many existence retrieved from DB - $article = $this->_em->find('Doctrine\Tests\Models\CMS\CmsArticle', $this->articleId); + $article = $this->_em->find(CmsArticle::class, $this->articleId); $queryCount = $this->getCurrentQueryCount(); $this->assertTrue($user->articles->contains($article)); @@ -317,7 +317,7 @@ public function testContainsOneToMany() */ public function testLazyOneToManyJoinedInheritanceIsLazilyInitialized() { - $otherClass = $this->_em->find(DDC2504OtherClass::CLASSNAME, $this->ddc2504OtherClassId); + $otherClass = $this->_em->find(DDC2504OtherClass::class, $this->ddc2504OtherClassId); $this->assertFalse($otherClass->childClasses->isInitialized(), 'Collection is not initialized.'); } @@ -327,10 +327,10 @@ public function testLazyOneToManyJoinedInheritanceIsLazilyInitialized() */ public function testContainsOnOneToManyJoinedInheritanceWillNotInitializeCollectionWhenMatchingItemIsFound() { - $otherClass = $this->_em->find(DDC2504OtherClass::CLASSNAME, $this->ddc2504OtherClassId); + $otherClass = $this->_em->find(DDC2504OtherClass::class, $this->ddc2504OtherClassId); // Test One to Many existence retrieved from DB - $childClass = $this->_em->find(DDC2504ChildClass::CLASSNAME, $this->ddc2504ChildClassId); + $childClass = $this->_em->find(DDC2504ChildClass::class, $this->ddc2504ChildClassId); $queryCount = $this->getCurrentQueryCount(); $this->assertTrue($otherClass->childClasses->contains($childClass)); @@ -343,7 +343,7 @@ public function testContainsOnOneToManyJoinedInheritanceWillNotInitializeCollect */ public function testContainsOnOneToManyJoinedInheritanceWillNotCauseQueriesWhenNonPersistentItemIsMatched() { - $otherClass = $this->_em->find(DDC2504OtherClass::CLASSNAME, $this->ddc2504OtherClassId); + $otherClass = $this->_em->find(DDC2504OtherClass::class, $this->ddc2504OtherClassId); $queryCount = $this->getCurrentQueryCount(); $this->assertFalse($otherClass->childClasses->contains(new DDC2504ChildClass())); @@ -359,7 +359,7 @@ public function testContainsOnOneToManyJoinedInheritanceWillNotCauseQueriesWhenN */ public function testContainsOnOneToManyJoinedInheritanceWillNotInitializeCollectionWithClearStateMatchingItem() { - $otherClass = $this->_em->find(DDC2504OtherClass::CLASSNAME, $this->ddc2504OtherClassId); + $otherClass = $this->_em->find(DDC2504OtherClass::class, $this->ddc2504OtherClassId); $childClass = new DDC2504ChildClass(); // Test One to Many existence with state clear @@ -377,7 +377,7 @@ public function testContainsOnOneToManyJoinedInheritanceWillNotInitializeCollect */ public function testContainsOnOneToManyJoinedInheritanceWillNotInitializeCollectionWithNewStateNotMatchingItem() { - $otherClass = $this->_em->find(DDC2504OtherClass::CLASSNAME, $this->ddc2504OtherClassId); + $otherClass = $this->_em->find(DDC2504OtherClass::class, $this->ddc2504OtherClassId); $childClass = new DDC2504ChildClass(); $this->_em->persist($childClass); @@ -394,7 +394,7 @@ public function testContainsOnOneToManyJoinedInheritanceWillNotInitializeCollect */ public function testCountingOnOneToManyJoinedInheritanceWillNotInitializeCollection() { - $otherClass = $this->_em->find(DDC2504OtherClass::CLASSNAME, $this->ddc2504OtherClassId); + $otherClass = $this->_em->find(DDC2504OtherClass::class, $this->ddc2504OtherClassId); $this->assertEquals(2, count($otherClass->childClasses)); @@ -406,11 +406,11 @@ public function testCountingOnOneToManyJoinedInheritanceWillNotInitializeCollect */ public function testContainsManyToMany() { - $user = $this->_em->find('Doctrine\Tests\Models\CMS\CmsUser', $this->userId); + $user = $this->_em->find(CmsUser::class, $this->userId); $this->assertFalse($user->groups->isInitialized(), "Pre-Condition: Collection is not initialized."); // Test Many to Many existence retrieved from DB - $group = $this->_em->find('Doctrine\Tests\Models\CMS\CmsGroup', $this->groupId); + $group = $this->_em->find(CmsGroup::class, $this->groupId); $queryCount = $this->getCurrentQueryCount(); $this->assertTrue($user->groups->contains($group)); @@ -455,10 +455,10 @@ public function testContainsManyToMany() */ public function testContainsManyToManyInverse() { - $group = $this->_em->find('Doctrine\Tests\Models\CMS\CmsGroup', $this->groupId); + $group = $this->_em->find(CmsGroup::class, $this->groupId); $this->assertFalse($group->users->isInitialized(), "Pre-Condition: Collection is not initialized."); - $user = $this->_em->find('Doctrine\Tests\Models\CMS\CmsUser', $this->userId); + $user = $this->_em->find(CmsUser::class, $this->userId); $queryCount = $this->getCurrentQueryCount(); $this->assertTrue($group->users->contains($user)); @@ -479,11 +479,11 @@ public function testContainsManyToManyInverse() */ public function testRemoveElementOneToMany() { - $user = $this->_em->find('Doctrine\Tests\Models\CMS\CmsUser', $this->userId); + $user = $this->_em->find(CmsUser::class, $this->userId); $this->assertFalse($user->articles->isInitialized(), "Pre-Condition: Collection is not initialized."); // Test One to Many removal with Entity retrieved from DB - $article = $this->_em->find('Doctrine\Tests\Models\CMS\CmsArticle', $this->articleId); + $article = $this->_em->find(CmsArticle::class, $this->articleId); $queryCount = $this->getCurrentQueryCount(); $user->articles->removeElement($article); @@ -533,9 +533,9 @@ public function testRemoveElementOneToMany() public function testRemovalOfManagedElementFromOneToManyJoinedInheritanceCollectionDoesNotInitializeIt() { /* @var $otherClass DDC2504OtherClass */ - $otherClass = $this->_em->find(DDC2504OtherClass::CLASSNAME, $this->ddc2504OtherClassId); + $otherClass = $this->_em->find(DDC2504OtherClass::class, $this->ddc2504OtherClassId); /* @var $childClass DDC2504ChildClass */ - $childClass = $this->_em->find(DDC2504ChildClass::CLASSNAME, $this->ddc2504ChildClassId); + $childClass = $this->_em->find(DDC2504ChildClass::class, $this->ddc2504ChildClassId); $queryCount = $this->getCurrentQueryCount(); @@ -571,7 +571,7 @@ public function testRemovalOfManagedElementFromOneToManyJoinedInheritanceCollect public function testRemovalOfNonManagedElementFromOneToManyJoinedInheritanceCollectionDoesNotInitializeIt() { /* @var $otherClass DDC2504OtherClass */ - $otherClass = $this->_em->find(DDC2504OtherClass::CLASSNAME, $this->ddc2504OtherClassId); + $otherClass = $this->_em->find(DDC2504OtherClass::class, $this->ddc2504OtherClassId); $queryCount = $this->getCurrentQueryCount(); $otherClass->childClasses->removeElement(new DDC2504ChildClass()); @@ -589,7 +589,7 @@ public function testRemovalOfNonManagedElementFromOneToManyJoinedInheritanceColl public function testRemovalOfNewElementFromOneToManyJoinedInheritanceCollectionDoesNotInitializeIt() { /* @var $otherClass DDC2504OtherClass */ - $otherClass = $this->_em->find(DDC2504OtherClass::CLASSNAME, $this->ddc2504OtherClassId); + $otherClass = $this->_em->find(DDC2504OtherClass::class, $this->ddc2504OtherClassId); $childClass = new DDC2504ChildClass(); $this->_em->persist($childClass); @@ -610,7 +610,7 @@ public function testRemovalOfNewElementFromOneToManyJoinedInheritanceCollectionD */ public function testRemovalOfNewManagedElementFromOneToManyJoinedInheritanceCollectionDoesNotInitializeIt() { - $otherClass = $this->_em->find(DDC2504OtherClass::CLASSNAME, $this->ddc2504OtherClassId); + $otherClass = $this->_em->find(DDC2504OtherClass::class, $this->ddc2504OtherClassId); $childClass = new DDC2504ChildClass(); $this->_em->persist($childClass); @@ -633,18 +633,20 @@ public function testRemovalOfNewManagedElementFromOneToManyJoinedInheritanceColl */ public function testRemoveElementManyToMany() { - $user = $this->_em->find('Doctrine\Tests\Models\CMS\CmsUser', $this->userId); + $user = $this->_em->find(CmsUser::class, $this->userId); $this->assertFalse($user->groups->isInitialized(), "Pre-Condition: Collection is not initialized."); // Test Many to Many removal with Entity retrieved from DB - $group = $this->_em->find('Doctrine\Tests\Models\CMS\CmsGroup', $this->groupId); + $group = $this->_em->find(CmsGroup::class, $this->groupId); $queryCount = $this->getCurrentQueryCount(); - $user->groups->removeElement($group); + $this->assertTrue($user->groups->removeElement($group)); $this->assertEquals($queryCount + 1, $this->getCurrentQueryCount(), "Removing a persisted entity should cause one query to be executed."); $this->assertFalse($user->groups->isInitialized(), "Post-Condition: Collection is not initialized."); + $this->assertFalse($user->groups->removeElement($group), "Removing an already removed element returns false"); + // Test Many to Many removal with Entity state as new $group = new CmsGroup(); $group->name = "A New group!"; @@ -686,10 +688,10 @@ public function testRemoveElementManyToMany() */ public function testRemoveElementManyToManyInverse() { - $group = $this->_em->find('Doctrine\Tests\Models\CMS\CmsGroup', $this->groupId); + $group = $this->_em->find(CmsGroup::class, $this->groupId); $this->assertFalse($group->users->isInitialized(), "Pre-Condition: Collection is not initialized."); - $user = $this->_em->find('Doctrine\Tests\Models\CMS\CmsUser', $this->userId); + $user = $this->_em->find(CmsUser::class, $this->userId); $queryCount = $this->getCurrentQueryCount(); $group->users->removeElement($user); @@ -713,7 +715,7 @@ public function testRemoveElementManyToManyInverse() */ public function testCountAfterAddThenFlush() { - $user = $this->_em->find('Doctrine\Tests\Models\CMS\CmsUser', $this->userId); + $user = $this->_em->find(CmsUser::class, $this->userId); $newGroup = new CmsGroup(); $newGroup->name = "Test4"; @@ -736,7 +738,7 @@ public function testCountAfterAddThenFlush() */ public function testSliceOnDirtyCollection() { - $user = $this->_em->find('Doctrine\Tests\Models\CMS\CmsUser', $this->userId); + $user = $this->_em->find(CmsUser::class, $this->userId); /* @var $user CmsUser */ $newGroup = new CmsGroup(); @@ -758,7 +760,7 @@ public function testSliceOnDirtyCollection() */ public function testGetIndexByIdentifier() { - $user = $this->_em->find('Doctrine\Tests\Models\CMS\CmsUser', $this->userId); + $user = $this->_em->find(CmsUser::class, $this->userId); /* @var $user CmsUser */ $queryCount = $this->getCurrentQueryCount(); @@ -766,7 +768,7 @@ public function testGetIndexByIdentifier() $this->assertFalse($user->phonenumbers->isInitialized()); $this->assertEquals($queryCount + 1, $this->getCurrentQueryCount()); - $this->assertSame($phonenumber, $this->_em->find('Doctrine\Tests\Models\CMS\CmsPhonenumber', $this->phonenumber)); + $this->assertSame($phonenumber, $this->_em->find(CmsPhonenumber::class, $this->phonenumber)); $article = $user->phonenumbers->get($this->phonenumber); $this->assertEquals($queryCount + 1, $this->getCurrentQueryCount(), "Getting the same entity should not cause an extra query to be executed"); @@ -777,7 +779,7 @@ public function testGetIndexByIdentifier() */ public function testGetIndexByOneToMany() { - $user = $this->_em->find('Doctrine\Tests\Models\CMS\CmsUser', $this->userId); + $user = $this->_em->find(CmsUser::class, $this->userId); /* @var $user CmsUser */ $queryCount = $this->getCurrentQueryCount(); @@ -786,7 +788,7 @@ public function testGetIndexByOneToMany() $this->assertFalse($user->articles->isInitialized()); $this->assertEquals($queryCount + 1, $this->getCurrentQueryCount()); - $this->assertSame($article, $this->_em->find('Doctrine\Tests\Models\CMS\CmsArticle', $this->articleId)); + $this->assertSame($article, $this->_em->find(CmsArticle::class, $this->articleId)); } /** @@ -794,7 +796,7 @@ public function testGetIndexByOneToMany() */ public function testGetIndexByManyToManyInverseSide() { - $group = $this->_em->find('Doctrine\Tests\Models\CMS\CmsGroup', $this->groupId); + $group = $this->_em->find(CmsGroup::class, $this->groupId); /* @var $group CmsGroup */ $queryCount = $this->getCurrentQueryCount(); @@ -803,7 +805,7 @@ public function testGetIndexByManyToManyInverseSide() $this->assertFalse($group->users->isInitialized()); $this->assertEquals($queryCount + 1, $this->getCurrentQueryCount()); - $this->assertSame($user, $this->_em->find('Doctrine\Tests\Models\CMS\CmsUser', $this->userId)); + $this->assertSame($user, $this->_em->find(CmsUser::class, $this->userId)); } /** @@ -811,7 +813,7 @@ public function testGetIndexByManyToManyInverseSide() */ public function testGetIndexByManyToManyOwningSide() { - $user = $this->_em->find('Doctrine\Tests\Models\CMS\CmsUser', $this->userId); + $user = $this->_em->find(CmsUser::class, $this->userId); /* @var $user CmsUser */ $queryCount = $this->getCurrentQueryCount(); @@ -820,7 +822,7 @@ public function testGetIndexByManyToManyOwningSide() $this->assertFalse($user->groups->isInitialized()); $this->assertEquals($queryCount + 1, $this->getCurrentQueryCount()); - $this->assertSame($group, $this->_em->find('Doctrine\Tests\Models\CMS\CmsGroup', $this->groupId)); + $this->assertSame($group, $this->_em->find(CmsGroup::class, $this->groupId)); } /** @@ -828,14 +830,14 @@ public function testGetIndexByManyToManyOwningSide() */ public function testGetNonExistentIndexBy() { - $user = $this->_em->find('Doctrine\Tests\Models\CMS\CmsUser', $this->userId); + $user = $this->_em->find(CmsUser::class, $this->userId); $this->assertNull($user->articles->get(-1)); $this->assertNull($user->groups->get(-1)); } public function testContainsKeyIndexByOneToMany() { - $user = $this->_em->find('Doctrine\Tests\Models\CMS\CmsUser', $this->userId); + $user = $this->_em->find(CmsUser::class, $this->userId); /* @var $user CmsUser */ $queryCount = $this->getCurrentQueryCount(); @@ -849,10 +851,10 @@ public function testContainsKeyIndexByOneToMany() public function testContainsKeyIndexByOneToManyJoinedInheritance() { - $class = $this->_em->getClassMetadata(DDC2504OtherClass::CLASSNAME); + $class = $this->_em->getClassMetadata(DDC2504OtherClass::class); $class->associationMappings['childClasses']['indexBy'] = 'id'; - $otherClass = $this->_em->find(DDC2504OtherClass::CLASSNAME, $this->ddc2504OtherClassId); + $otherClass = $this->_em->find(DDC2504OtherClass::class, $this->ddc2504OtherClassId); $queryCount = $this->getCurrentQueryCount(); @@ -865,9 +867,9 @@ public function testContainsKeyIndexByOneToManyJoinedInheritance() public function testContainsKeyIndexByManyToMany() { - $user = $this->_em->find('Doctrine\Tests\Models\CMS\CmsUser', $this->userId2); + $user = $this->_em->find(CmsUser::class, $this->userId2); - $group = $this->_em->find('Doctrine\Tests\Models\CMS\CmsGroup', $this->groupId); + $group = $this->_em->find(CmsGroup::class, $this->groupId); $queryCount = $this->getCurrentQueryCount(); @@ -879,8 +881,8 @@ public function testContainsKeyIndexByManyToMany() } public function testContainsKeyIndexByManyToManyNonOwning() { - $user = $this->_em->find('Doctrine\Tests\Models\CMS\CmsUser', $this->userId2); - $group = $this->_em->find('Doctrine\Tests\Models\CMS\CmsGroup', $this->groupId); + $user = $this->_em->find(CmsUser::class, $this->userId2); + $group = $this->_em->find(CmsGroup::class, $this->groupId); $queryCount = $this->getCurrentQueryCount(); @@ -893,10 +895,10 @@ public function testContainsKeyIndexByManyToManyNonOwning() public function testContainsKeyIndexByWithPkManyToMany() { - $class = $this->_em->getClassMetadata('Doctrine\Tests\Models\CMS\CmsUser'); + $class = $this->_em->getClassMetadata(CmsUser::class); $class->associationMappings['groups']['indexBy'] = 'id'; - $user = $this->_em->find('Doctrine\Tests\Models\CMS\CmsUser', $this->userId2); + $user = $this->_em->find(CmsUser::class, $this->userId2); $queryCount = $this->getCurrentQueryCount(); @@ -908,10 +910,10 @@ public function testContainsKeyIndexByWithPkManyToMany() } public function testContainsKeyIndexByWithPkManyToManyNonOwning() { - $class = $this->_em->getClassMetadata('Doctrine\Tests\Models\CMS\CmsGroup'); + $class = $this->_em->getClassMetadata(CmsGroup::class); $class->associationMappings['users']['indexBy'] = 'id'; - $group = $this->_em->find('Doctrine\Tests\Models\CMS\CmsGroup', $this->groupId); + $group = $this->_em->find(CmsGroup::class, $this->groupId); $queryCount = $this->getCurrentQueryCount(); @@ -924,7 +926,7 @@ public function testContainsKeyIndexByWithPkManyToManyNonOwning() public function testContainsKeyNonExistentIndexByOneToMany() { - $user = $this->_em->find('Doctrine\Tests\Models\CMS\CmsUser', $this->userId2); + $user = $this->_em->find(CmsUser::class, $this->userId2); $queryCount = $this->getCurrentQueryCount(); @@ -937,7 +939,7 @@ public function testContainsKeyNonExistentIndexByOneToMany() public function testContainsKeyNonExistentIndexByManyToMany() { - $user = $this->_em->find('Doctrine\Tests\Models\CMS\CmsUser', $this->userId2); + $user = $this->_em->find(CmsUser::class, $this->userId2); $queryCount = $this->getCurrentQueryCount(); @@ -1061,14 +1063,14 @@ public function testRemoveManagedElementFromOneToManyExtraLazyCollectionIsNoOp() list($userId, $tweetId) = $this->loadTweetFixture(); /* @var $user User */ - $user = $this->_em->find(User::CLASSNAME, $userId); + $user = $this->_em->find(User::class, $userId); - $user->tweets->removeElement($this->_em->find(Tweet::CLASSNAME, $tweetId)); + $user->tweets->removeElement($this->_em->find(Tweet::class, $tweetId)); $this->_em->clear(); /* @var $user User */ - $user = $this->_em->find(User::CLASSNAME, $userId); + $user = $this->_em->find(User::class, $userId); $this->assertCount(1, $user->tweets, 'Element was not removed - need to update the owning side first'); } @@ -1081,23 +1083,23 @@ public function testRemoveManagedElementFromOneToManyExtraLazyCollectionWithoutD list($userId, $tweetId) = $this->loadTweetFixture(); /* @var $user User */ - $user = $this->_em->find(User::CLASSNAME, $userId); - $tweet = $this->_em->find(Tweet::CLASSNAME, $tweetId); + $user = $this->_em->find(User::class, $userId); + $tweet = $this->_em->find(Tweet::class, $tweetId); $user->tweets->removeElement($tweet); $this->_em->clear(); /* @var $tweet Tweet */ - $tweet = $this->_em->find(Tweet::CLASSNAME, $tweetId); + $tweet = $this->_em->find(Tweet::class, $tweetId); $this->assertInstanceOf( - Tweet::CLASSNAME, + Tweet::class, $tweet, 'Even though the collection is extra lazy, the tweet should not have been deleted' ); $this->assertInstanceOf( - User::CLASSNAME, + User::class, $tweet->author, 'Tweet author link has not been removed - need to update the owning side first' ); @@ -1111,25 +1113,25 @@ public function testRemovingManagedLazyProxyFromExtraLazyOneToManyDoesRemoveTheA list($userId, $tweetId) = $this->loadTweetFixture(); /* @var $user User */ - $user = $this->_em->find(User::CLASSNAME, $userId); - $tweet = $this->_em->getReference(Tweet::CLASSNAME, $tweetId); + $user = $this->_em->find(User::class, $userId); + $tweet = $this->_em->getReference(Tweet::class, $tweetId); - $user->tweets->removeElement($this->_em->getReference(Tweet::CLASSNAME, $tweetId)); + $user->tweets->removeElement($this->_em->getReference(Tweet::class, $tweetId)); $this->_em->clear(); /* @var $tweet Tweet */ - $tweet = $this->_em->find(Tweet::CLASSNAME, $tweet->id); + $tweet = $this->_em->find(Tweet::class, $tweet->id); $this->assertInstanceOf( - Tweet::CLASSNAME, + Tweet::class, $tweet, 'Even though the collection is extra lazy, the tweet should not have been deleted' ); - $this->assertInstanceOf(User::CLASSNAME, $tweet->author); + $this->assertInstanceOf(User::class, $tweet->author); /* @var $user User */ - $user = $this->_em->find(User::CLASSNAME, $userId); + $user = $this->_em->find(User::class, $userId); $this->assertCount(1, $user->tweets, 'Element was not removed - need to update the owning side first'); } @@ -1142,18 +1144,18 @@ public function testRemoveOrphanedManagedElementFromOneToManyExtraLazyCollection list($userId, $userListId) = $this->loadUserListFixture(); /* @var $user User */ - $user = $this->_em->find(User::CLASSNAME, $userId); + $user = $this->_em->find(User::class, $userId); - $user->userLists->removeElement($this->_em->find(UserList::CLASSNAME, $userListId)); + $user->userLists->removeElement($this->_em->find(UserList::class, $userListId)); $this->_em->clear(); /* @var $user User */ - $user = $this->_em->find(User::CLASSNAME, $userId); + $user = $this->_em->find(User::class, $userId); $this->assertCount(0, $user->userLists, 'Element was removed from association due to orphan removal'); $this->assertNull( - $this->_em->find(UserList::CLASSNAME, $userListId), + $this->_em->find(UserList::class, $userListId), 'Element was deleted due to orphan removal' ); } @@ -1166,22 +1168,22 @@ public function testRemoveOrphanedUnManagedElementFromOneToManyExtraLazyCollecti list($userId, $userListId) = $this->loadUserListFixture(); /* @var $user User */ - $user = $this->_em->find(User::CLASSNAME, $userId); + $user = $this->_em->find(User::class, $userId); $user->userLists->removeElement(new UserList()); $this->_em->clear(); /* @var $userList UserList */ - $userList = $this->_em->find(UserList::CLASSNAME, $userListId); + $userList = $this->_em->find(UserList::class, $userListId); $this->assertInstanceOf( - UserList::CLASSNAME, + UserList::class, $userList, 'Even though the collection is extra lazy + orphan removal, the user list should not have been deleted' ); $this->assertInstanceOf( - User::CLASSNAME, + User::class, $userList->owner, 'User list to owner link has not been removed' ); @@ -1195,18 +1197,18 @@ public function testRemoveOrphanedManagedLazyProxyFromExtraLazyOneToMany() list($userId, $userListId) = $this->loadUserListFixture(); /* @var $user User */ - $user = $this->_em->find(User::CLASSNAME, $userId); + $user = $this->_em->find(User::class, $userId); - $user->userLists->removeElement($this->_em->getReference(UserList::CLASSNAME, $userListId)); + $user->userLists->removeElement($this->_em->getReference(UserList::class, $userListId)); $this->_em->clear(); /* @var $user User */ - $user = $this->_em->find(User::CLASSNAME, $userId); + $user = $this->_em->find(User::class, $userId); $this->assertCount(0, $user->userLists, 'Element was removed from association due to orphan removal'); $this->assertNull( - $this->_em->find(UserList::CLASSNAME, $userListId), + $this->_em->find(UserList::class, $userListId), 'Element was deleted due to orphan removal' ); } @@ -1229,7 +1231,7 @@ private function loadTweetFixture() $this->_em->flush(); $this->_em->clear(); - return array($user->id, $tweet->id); + return [$user->id, $tweet->id]; } /** @@ -1250,6 +1252,6 @@ private function loadUserListFixture() $this->_em->flush(); $this->_em->clear(); - return array($user->id, $userList->id); + return [$user->id, $userList->id]; } } diff --git a/tests/Doctrine/Tests/ORM/Functional/GH5988Test.php b/tests/Doctrine/Tests/ORM/Functional/GH5988Test.php new file mode 100644 index 00000000000..928f432320d --- /dev/null +++ b/tests/Doctrine/Tests/ORM/Functional/GH5988Test.php @@ -0,0 +1,114 @@ +setUpEntitySchema([GH5988CustomIdObjectTypeParent::class, GH5988CustomIdObjectTypeChild::class]); + } + + public function testDelete() + { + $object = new GH5988CustomIdObjectTypeChild(new CustomIdObject('foo'), 'Test'); + + $this->_em->persist($object); + $this->_em->flush(); + + $id = $object->id; + + $object2 = $this->_em->find(GH5988CustomIdObjectTypeChild::class, $id); + + $this->_em->remove($object2); + $this->_em->flush(); + + self::assertNull($this->_em->find(GH5988CustomIdObjectTypeChild::class, $id)); + } +} + + +class GH5988CustomIdObjectHashType extends DBALType +{ + /** + * {@inheritdoc} + */ + public function convertToDatabaseValue($value, AbstractPlatform $platform) + { + return $value->id . '_test'; + } + /** + * {@inheritdoc} + */ + public function convertToPHPValue($value, AbstractPlatform $platform) + { + return new CustomIdObject(str_replace('_test', '', $value)); + } + /** + * {@inheritdoc} + */ + public function getSQLDeclaration(array $fieldDeclaration, AbstractPlatform $platform) + { + return $platform->getVarcharTypeDeclarationSQL($fieldDeclaration); + } + /** + * {@inheritdoc} + */ + public function getName() + { + return self::class; + } +} + +/** + * @Entity + * @Table + * @InheritanceType("JOINED") + * @DiscriminatorColumn(name="type", type="string") + * @DiscriminatorMap({"child" = GH5988CustomIdObjectTypeChild::class}) + */ +abstract class GH5988CustomIdObjectTypeParent +{ + /** + * @Id + * @Column(type="Doctrine\Tests\ORM\Functional\GH5988CustomIdObjectHashType") + * @var CustomIdObject + */ + public $id; +} + + +/** + * @Entity + * @Table + */ +class GH5988CustomIdObjectTypeChild extends GH5988CustomIdObjectTypeParent +{ + /** @var string */ + public $name; + + public function __construct(CustomIdObject $id, string $name) + { + $this->id = $id; + $this->name = $name; + } +} diff --git a/tests/Doctrine/Tests/ORM/Functional/IdentityMapTest.php b/tests/Doctrine/Tests/ORM/Functional/IdentityMapTest.php index 94a11dab490..15929ae270d 100644 --- a/tests/Doctrine/Tests/ORM/Functional/IdentityMapTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/IdentityMapTest.php @@ -82,7 +82,7 @@ public function testSingleValuedAssociationIdentityMapBehaviorWithRefresh() $this->assertSame($user1, $address->user); //external update to CmsAddress - $this->_em->getConnection()->executeUpdate('update cms_addresses set user_id = ?', array($user2->getId())); + $this->_em->getConnection()->executeUpdate('update cms_addresses set user_id = ?', [$user2->getId()]); // But we want to have this external change! // Solution 1: refresh(), broken atm! @@ -125,7 +125,7 @@ public function testSingleValuedAssociationIdentityMapBehaviorWithRefreshQuery() $this->assertSame($user1, $address->user); //external update to CmsAddress - $this->_em->getConnection()->executeUpdate('update cms_addresses set user_id = ?', array($user2->getId())); + $this->_em->getConnection()->executeUpdate('update cms_addresses set user_id = ?', [$user2->getId()]); //select $q = $this->_em->createQuery('select a, u from Doctrine\Tests\Models\CMS\CmsAddress a join a.user u'); @@ -181,7 +181,8 @@ public function testCollectionValuedAssociationIdentityMapBehaviorWithRefreshQue $this->assertFalse($user->getPhonenumbers()->isDirty()); //external update to CmsAddress - $this->_em->getConnection()->executeUpdate('insert into cms_phonenumbers (phonenumber, user_id) VALUES (?,?)', array(999, $user->getId())); + $this->_em->getConnection()->executeUpdate('insert into cms_phonenumbers (phonenumber, user_id) VALUES (?,?)', [999, $user->getId()] + ); //select $q = $this->_em->createQuery('select u, p from Doctrine\Tests\Models\CMS\CmsUser u join u.phonenumbers p'); @@ -232,7 +233,8 @@ public function testCollectionValuedAssociationIdentityMapBehaviorWithRefresh() $this->assertEquals(3, count($user->getPhonenumbers())); //external update to CmsAddress - $this->_em->getConnection()->executeUpdate('insert into cms_phonenumbers (phonenumber, user_id) VALUES (?,?)', array(999, $user->getId())); + $this->_em->getConnection()->executeUpdate('insert into cms_phonenumbers (phonenumber, user_id) VALUES (?,?)', [999, $user->getId()] + ); //select $q = $this->_em->createQuery('select u, p from Doctrine\Tests\Models\CMS\CmsUser u join u.phonenumbers p'); diff --git a/tests/Doctrine/Tests/ORM/Functional/IndexByAssociationTest.php b/tests/Doctrine/Tests/ORM/Functional/IndexByAssociationTest.php index 9dac4155ded..289e55807f8 100644 --- a/tests/Doctrine/Tests/ORM/Functional/IndexByAssociationTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/IndexByAssociationTest.php @@ -46,8 +46,8 @@ public function loadFixture() public function testManyToOneFinder() { - /* @var $market Doctrine\Tests\Models\StockExchange\Market */ - $market = $this->_em->find('Doctrine\Tests\Models\StockExchange\Market', $this->market->getId()); + /* @var $market Market */ + $market = $this->_em->find(Market::class, $this->market->getId()); $this->assertEquals(2, count($market->stocks)); $this->assertTrue(isset($market->stocks['AAPL']), "AAPL symbol has to be key in indexed association."); @@ -70,7 +70,7 @@ public function testManyToOneDQL() public function testManyToMany() { - $bond = $this->_em->find('Doctrine\Tests\Models\StockExchange\Bond', $this->bond->getId()); + $bond = $this->_em->find(Bond::class, $this->bond->getId()); $this->assertEquals(2, count($bond->stocks)); $this->assertTrue(isset($bond->stocks['AAPL']), "AAPL symbol has to be key in indexed association."); diff --git a/tests/Doctrine/Tests/ORM/Functional/JoinedTableCompositeKeyTest.php b/tests/Doctrine/Tests/ORM/Functional/JoinedTableCompositeKeyTest.php index 8f6e0cc59fd..ab5c394e020 100644 --- a/tests/Doctrine/Tests/ORM/Functional/JoinedTableCompositeKeyTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/JoinedTableCompositeKeyTest.php @@ -1,6 +1,7 @@ _em->find( - 'Doctrine\Tests\Models\CompositeKeyInheritance\JoinedRootClass', - array('keyPart1' => 'part-1', 'keyPart2' => 'part-2') + JoinedRootClass::class, + ['keyPart1' => 'part-1', 'keyPart2' => 'part-2'] ); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/LifecycleCallbackTest.php b/tests/Doctrine/Tests/ORM/Functional/LifecycleCallbackTest.php index 50864592751..e23095fe848 100644 --- a/tests/Doctrine/Tests/ORM/Functional/LifecycleCallbackTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/LifecycleCallbackTest.php @@ -15,12 +15,14 @@ protected function setUp() { parent::setUp(); try { - $this->_schemaTool->createSchema(array( - $this->_em->getClassMetadata('Doctrine\Tests\ORM\Functional\LifecycleCallbackEventArgEntity'), - $this->_em->getClassMetadata('Doctrine\Tests\ORM\Functional\LifecycleCallbackTestEntity'), - $this->_em->getClassMetadata('Doctrine\Tests\ORM\Functional\LifecycleCallbackTestUser'), - $this->_em->getClassMetadata('Doctrine\Tests\ORM\Functional\LifecycleCallbackCascader'), - )); + $this->_schemaTool->createSchema( + [ + $this->_em->getClassMetadata(LifecycleCallbackEventArgEntity::class), + $this->_em->getClassMetadata(LifecycleCallbackTestEntity::class), + $this->_em->getClassMetadata(LifecycleCallbackTestUser::class), + $this->_em->getClassMetadata(LifecycleCallbackCascader::class), + ] + ); } catch (\Exception $e) { // Swallow all exceptions. We do not test the schema tool here. } @@ -104,7 +106,7 @@ public function testGetReferenceWithPostLoadEventIsDelayedUntilProxyTrigger() $this->_em->clear(); - $reference = $this->_em->getReference('Doctrine\Tests\ORM\Functional\LifecycleCallbackTestEntity', $id); + $reference = $this->_em->getReference(LifecycleCallbackTestEntity::class, $id); $this->assertFalse($reference->postLoadCallbackInvoked); $reference->getValue(); // trigger proxy load @@ -124,7 +126,7 @@ public function testPostLoadTriggeredOnRefresh() $this->_em->clear(); - $reference = $this->_em->find('Doctrine\Tests\ORM\Functional\LifecycleCallbackTestEntity', $id); + $reference = $this->_em->find(LifecycleCallbackTestEntity::class, $id); $this->assertTrue($reference->postLoadCallbackInvoked); $reference->postLoadCallbackInvoked = false; @@ -266,17 +268,58 @@ public function testCascadedEntitiesNotLoadedInPostLoadDuringIterationWithSimple break; } } + + /** + * https://github.com/doctrine/orm/issues/6568 + */ + public function testPostLoadIsInvokedOnFetchJoinedEntities() + { + $entA = new LifecycleCallbackCascader(); + $this->_em->persist($entA); + + $entB_1 = new LifecycleCallbackTestEntity(); + $entB_2 = new LifecycleCallbackTestEntity(); + + $entA->entities[] = $entB_1; + $entA->entities[] = $entB_2; + $entB_1->cascader = $entA; + $entB_2->cascader = $entA; + + $this->_em->flush(); + $this->_em->clear(); + + $dql = <<<'DQL' +SELECT + entA, entB +FROM + Doctrine\Tests\ORM\Functional\LifecycleCallbackCascader AS entA +LEFT JOIN + entA.entities AS entB +WHERE + entA.id = :entA_id +DQL; + + $fetchedA = $this + ->_em + ->createQuery($dql)->setParameter('entA_id', $entA->getId()) + ->getOneOrNullResult(); + + $this->assertTrue($fetchedA->postLoadCallbackInvoked); + foreach ($fetchedA->entities as $fetchJoinedEntB) { + $this->assertTrue($fetchJoinedEntB->postLoadCallbackInvoked); + } + } public function testLifecycleCallbacksGetInherited() { - $childMeta = $this->_em->getClassMetadata(__NAMESPACE__ . '\LifecycleCallbackChildEntity'); - $this->assertEquals(array('prePersist' => array(0 => 'doStuff')), $childMeta->lifecycleCallbacks); + $childMeta = $this->_em->getClassMetadata(LifecycleCallbackChildEntity::class); + $this->assertEquals(['prePersist' => [0 => 'doStuff']], $childMeta->lifecycleCallbacks); } public function testLifecycleListener_ChangeUpdateChangeSet() { $listener = new LifecycleListenerPreUpdate; - $this->_em->getEventManager()->addEventListener(array('preUpdate'), $listener); + $this->_em->getEventManager()->addEventListener(['preUpdate'], $listener); $user = new LifecycleCallbackTestUser; $user->setName('Bob'); @@ -292,7 +335,7 @@ public function testLifecycleListener_ChangeUpdateChangeSet() $this->_em->flush(); // preUpdate reverts Alice to Bob $this->_em->clear(); - $this->_em->getEventManager()->removeEventListener(array('preUpdate'), $listener); + $this->_em->getEventManager()->removeEventListener(['preUpdate'], $listener); $bob = $this->_em->createQuery($dql)->getSingleResult(); @@ -315,7 +358,7 @@ public function testLifecycleCallbackEventArgs() $this->_em->flush(); $this->_em->refresh($e); - + $this->_em->remove($e); $this->_em->flush(); @@ -329,45 +372,14 @@ public function testLifecycleCallbackEventArgs() $this->assertArrayHasKey('preRemoveHandler', $e->calls); $this->assertArrayHasKey('postRemoveHandler', $e->calls); - $this->assertInstanceOf( - 'Doctrine\ORM\Event\PreFlushEventArgs', - $e->calls['preFlushHandler'] - ); - - $this->assertInstanceOf( - 'Doctrine\ORM\Event\LifecycleEventArgs', - $e->calls['postLoadHandler'] - ); - - $this->assertInstanceOf( - 'Doctrine\ORM\Event\LifecycleEventArgs', - $e->calls['prePersistHandler'] - ); - - $this->assertInstanceOf( - 'Doctrine\ORM\Event\LifecycleEventArgs', - $e->calls['postPersistHandler'] - ); - - $this->assertInstanceOf( - 'Doctrine\ORM\Event\PreUpdateEventArgs', - $e->calls['preUpdateHandler'] - ); - - $this->assertInstanceOf( - 'Doctrine\ORM\Event\LifecycleEventArgs', - $e->calls['postUpdateHandler'] - ); - - $this->assertInstanceOf( - 'Doctrine\ORM\Event\LifecycleEventArgs', - $e->calls['preRemoveHandler'] - ); - - $this->assertInstanceOf( - 'Doctrine\ORM\Event\LifecycleEventArgs', - $e->calls['postRemoveHandler'] - ); + $this->assertInstanceOf(PreFlushEventArgs::class, $e->calls['preFlushHandler']); + $this->assertInstanceOf(LifecycleEventArgs::class, $e->calls['postLoadHandler']); + $this->assertInstanceOf(LifecycleEventArgs::class, $e->calls['prePersistHandler']); + $this->assertInstanceOf(LifecycleEventArgs::class, $e->calls['postPersistHandler']); + $this->assertInstanceOf(PreUpdateEventArgs::class, $e->calls['preUpdateHandler']); + $this->assertInstanceOf(LifecycleEventArgs::class, $e->calls['postUpdateHandler']); + $this->assertInstanceOf(LifecycleEventArgs::class, $e->calls['preRemoveHandler']); + $this->assertInstanceOf(LifecycleEventArgs::class, $e->calls['postRemoveHandler']); } } @@ -484,6 +496,10 @@ public function doStuffOnPostLoad() { $this->postLoadCallbackInvoked = true; $this->postLoadEntitiesCount = count($this->entities); } + + public function getId() { + return $this->id; + } } /** @MappedSuperclass @HasLifecycleCallbacks */ @@ -517,7 +533,7 @@ class LifecycleCallbackEventArgEntity /** @Column() */ public $value; - public $calls = array(); + public $calls = []; /** * @PostPersist diff --git a/tests/Doctrine/Tests/ORM/Functional/Locking/GearmanLockTest.php b/tests/Doctrine/Tests/ORM/Functional/Locking/GearmanLockTest.php index e69d3ee6aa3..e804a5c339e 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Locking/GearmanLockTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/Locking/GearmanLockTest.php @@ -23,11 +23,14 @@ protected function setUp() $this->useModelSet('cms'); parent::setUp(); - $this->tasks = array(); + $this->tasks = []; $this->gearman = new \GearmanClient(); - $this->gearman->addServer(); - $this->gearman->setCompleteCallback(array($this, "gearmanTaskCompleted")); + $this->gearman->addServer( + $_SERVER['GEARMAN_HOST'] ?? null, + $_SERVER['GEARMAN_PORT'] ?? 4730 + ); + $this->gearman->setCompleteCallback([$this, "gearmanTaskCompleted"]); $article = new CmsArticle(); $article->text = "my article"; @@ -46,72 +49,72 @@ public function gearmanTaskCompleted($task) public function testFindWithLock() { - $this->asyncFindWithLock('Doctrine\Tests\Models\CMS\CmsArticle', $this->articleId, LockMode::PESSIMISTIC_WRITE); - $this->asyncFindWithLock('Doctrine\Tests\Models\CMS\CmsArticle', $this->articleId, LockMode::PESSIMISTIC_WRITE); + $this->asyncFindWithLock(CmsArticle::class, $this->articleId, LockMode::PESSIMISTIC_WRITE); + $this->asyncFindWithLock(CmsArticle::class, $this->articleId, LockMode::PESSIMISTIC_WRITE); $this->assertLockWorked(); } public function testFindWithWriteThenReadLock() { - $this->asyncFindWithLock('Doctrine\Tests\Models\CMS\CmsArticle', $this->articleId, LockMode::PESSIMISTIC_WRITE); - $this->asyncFindWithLock('Doctrine\Tests\Models\CMS\CmsArticle', $this->articleId, LockMode::PESSIMISTIC_READ); + $this->asyncFindWithLock(CmsArticle::class, $this->articleId, LockMode::PESSIMISTIC_WRITE); + $this->asyncFindWithLock(CmsArticle::class, $this->articleId, LockMode::PESSIMISTIC_READ); $this->assertLockWorked(); } public function testFindWithReadThenWriteLock() { - $this->asyncFindWithLock('Doctrine\Tests\Models\CMS\CmsArticle', $this->articleId, LockMode::PESSIMISTIC_READ); - $this->asyncFindWithLock('Doctrine\Tests\Models\CMS\CmsArticle', $this->articleId, LockMode::PESSIMISTIC_WRITE); + $this->asyncFindWithLock(CmsArticle::class, $this->articleId, LockMode::PESSIMISTIC_READ); + $this->asyncFindWithLock(CmsArticle::class, $this->articleId, LockMode::PESSIMISTIC_WRITE); $this->assertLockWorked(); } public function testFindWithOneLock() { - $this->asyncFindWithLock('Doctrine\Tests\Models\CMS\CmsArticle', $this->articleId, LockMode::PESSIMISTIC_WRITE); - $this->asyncFindWithLock('Doctrine\Tests\Models\CMS\CmsArticle', $this->articleId, LockMode::NONE); + $this->asyncFindWithLock(CmsArticle::class, $this->articleId, LockMode::PESSIMISTIC_WRITE); + $this->asyncFindWithLock(CmsArticle::class, $this->articleId, LockMode::NONE); $this->assertLockDoesNotBlock(); } public function testDqlWithLock() { - $this->asyncDqlWithLock('SELECT a FROM Doctrine\Tests\Models\CMS\CmsArticle a', array(), LockMode::PESSIMISTIC_WRITE); - $this->asyncFindWithLock('Doctrine\Tests\Models\CMS\CmsArticle', $this->articleId, LockMode::PESSIMISTIC_WRITE); + $this->asyncDqlWithLock('SELECT a FROM Doctrine\Tests\Models\CMS\CmsArticle a', [], LockMode::PESSIMISTIC_WRITE); + $this->asyncFindWithLock(CmsArticle::class, $this->articleId, LockMode::PESSIMISTIC_WRITE); $this->assertLockWorked(); } public function testLock() { - $this->asyncFindWithLock('Doctrine\Tests\Models\CMS\CmsArticle', $this->articleId, LockMode::PESSIMISTIC_WRITE); - $this->asyncLock('Doctrine\Tests\Models\CMS\CmsArticle', $this->articleId, LockMode::PESSIMISTIC_WRITE); + $this->asyncFindWithLock(CmsArticle::class, $this->articleId, LockMode::PESSIMISTIC_WRITE); + $this->asyncLock(CmsArticle::class, $this->articleId, LockMode::PESSIMISTIC_WRITE); $this->assertLockWorked(); } public function testLock2() { - $this->asyncFindWithLock('Doctrine\Tests\Models\CMS\CmsArticle', $this->articleId, LockMode::PESSIMISTIC_WRITE); - $this->asyncLock('Doctrine\Tests\Models\CMS\CmsArticle', $this->articleId, LockMode::PESSIMISTIC_READ); + $this->asyncFindWithLock(CmsArticle::class, $this->articleId, LockMode::PESSIMISTIC_WRITE); + $this->asyncLock(CmsArticle::class, $this->articleId, LockMode::PESSIMISTIC_READ); $this->assertLockWorked(); } public function testLock3() { - $this->asyncFindWithLock('Doctrine\Tests\Models\CMS\CmsArticle', $this->articleId, LockMode::PESSIMISTIC_READ); - $this->asyncLock('Doctrine\Tests\Models\CMS\CmsArticle', $this->articleId, LockMode::PESSIMISTIC_WRITE); + $this->asyncFindWithLock(CmsArticle::class, $this->articleId, LockMode::PESSIMISTIC_READ); + $this->asyncLock(CmsArticle::class, $this->articleId, LockMode::PESSIMISTIC_WRITE); $this->assertLockWorked(); } public function testLock4() { - $this->asyncFindWithLock('Doctrine\Tests\Models\CMS\CmsArticle', $this->articleId, LockMode::NONE); - $this->asyncLock('Doctrine\Tests\Models\CMS\CmsArticle', $this->articleId, LockMode::PESSIMISTIC_WRITE); + $this->asyncFindWithLock(CmsArticle::class, $this->articleId, LockMode::NONE); + $this->asyncLock(CmsArticle::class, $this->articleId, LockMode::PESSIMISTIC_WRITE); $this->assertLockDoesNotBlock(); } @@ -140,37 +143,42 @@ protected function assertLockWorked($forTime = 2, $notLongerThan = null) protected function asyncFindWithLock($entityName, $entityId, $lockMode) { - $this->startJob('findWithLock', array( + $this->startJob('findWithLock', [ 'entityName' => $entityName, 'entityId' => $entityId, 'lockMode' => $lockMode, - )); + ] + ); } protected function asyncDqlWithLock($dql, $params, $lockMode) { - $this->startJob('dqlWithLock', array( + $this->startJob('dqlWithLock', [ 'dql' => $dql, 'dqlParams' => $params, 'lockMode' => $lockMode, - )); + ] + ); } protected function asyncLock($entityName, $entityId, $lockMode) { - $this->startJob('lock', array( + $this->startJob('lock', [ 'entityName' => $entityName, 'entityId' => $entityId, 'lockMode' => $lockMode, - )); + ] + ); } protected function startJob($fn, $fixture) { - $this->gearman->addTask($fn, serialize(array( + $this->gearman->addTask($fn, serialize( + [ 'conn' => $this->_em->getConnection()->getParams(), 'fixture' => $fixture - ))); + ] + )); $this->assertEquals(GEARMAN_SUCCESS, $this->gearman->returnCode()); } diff --git a/tests/Doctrine/Tests/ORM/Functional/Locking/LockAgentWorker.php b/tests/Doctrine/Tests/ORM/Functional/Locking/LockAgentWorker.php index 0ca10460f80..4271b12b476 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Locking/LockAgentWorker.php +++ b/tests/Doctrine/Tests/ORM/Functional/Locking/LockAgentWorker.php @@ -16,10 +16,13 @@ static public function run() $lockAgent = new LockAgentWorker(); $worker = new \GearmanWorker(); - $worker->addServer(); - $worker->addFunction("findWithLock", array($lockAgent, "findWithLock")); - $worker->addFunction("dqlWithLock", array($lockAgent, "dqlWithLock")); - $worker->addFunction('lock', array($lockAgent, 'lock')); + $worker->addServer( + $_SERVER['GEARMAN_HOST'] ?? null, + $_SERVER['GEARMAN_PORT'] ?? 4730 + ); + $worker->addFunction("findWithLock", [$lockAgent, "findWithLock"]); + $worker->addFunction("dqlWithLock", [$lockAgent, "dqlWithLock"]); + $worker->addFunction('lock', [$lockAgent, 'lock']); while($worker->work()) { if ($worker->returnCode() != GEARMAN_SUCCESS) { @@ -98,7 +101,7 @@ protected function createEntityManager($conn) $config->setProxyNamespace('MyProject\Proxies'); $config->setAutoGenerateProxyClasses(true); - $annotDriver = $config->newDefaultAnnotationDriver(array(__DIR__ . '/../../../Models/'), true); + $annotDriver = $config->newDefaultAnnotationDriver([__DIR__ . '/../../../Models/'], true); $config->setMetadataDriverImpl($annotDriver); $cache = new ArrayCache(); diff --git a/tests/Doctrine/Tests/ORM/Functional/Locking/LockTest.php b/tests/Doctrine/Tests/ORM/Functional/Locking/LockTest.php index 421b075d940..d515e95bff7 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Locking/LockTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/Locking/LockTest.php @@ -19,14 +19,16 @@ protected function setUp() { $this->useModelSet('cms'); parent::setUp(); - $this->handles = array(); + + $this->handles = []; } /** * @group DDC-178 * @group locking */ - public function testLockVersionedEntity() { + public function testLockVersionedEntity() + { $article = new CmsArticle(); $article->text = "my article"; $article->topic = "Hello"; @@ -35,13 +37,16 @@ public function testLockVersionedEntity() { $this->_em->flush(); $this->_em->lock($article, LockMode::OPTIMISTIC, $article->version); + + $this->addToAssertionCount(1); } /** * @group DDC-178 * @group locking */ - public function testLockVersionedEntity_MismatchThrowsException() { + public function testLockVersionedEntity_MismatchThrowsException() + { $article = new CmsArticle(); $article->text = "my article"; $article->topic = "Hello"; @@ -58,7 +63,8 @@ public function testLockVersionedEntity_MismatchThrowsException() { * @group DDC-178 * @group locking */ - public function testLockUnversionedEntity_ThrowsException() { + public function testLockUnversionedEntity_ThrowsException() + { $user = new CmsUser(); $user->name = "foo"; $user->status = "active"; @@ -76,11 +82,12 @@ public function testLockUnversionedEntity_ThrowsException() { * @group DDC-178 * @group locking */ - public function testLockUnmanagedEntity_ThrowsException() { + public function testLockUnmanagedEntity_ThrowsException() + { $article = new CmsArticle(); $this->expectException(\InvalidArgumentException::class); - $this->expectExceptionMessage('Entity Doctrine\Tests\Models\CMS\CmsArticle'); + $this->expectExceptionMessage('Entity ' . CmsArticle::class); $this->_em->lock($article, LockMode::OPTIMISTIC, $article->version + 1); } @@ -89,7 +96,8 @@ public function testLockUnmanagedEntity_ThrowsException() { * @group DDC-178 * @group locking */ - public function testLockPessimisticRead_NoTransaction_ThrowsException() { + public function testLockPessimisticRead_NoTransaction_ThrowsException() + { $article = new CmsArticle(); $article->text = "my article"; $article->topic = "Hello"; @@ -106,7 +114,8 @@ public function testLockPessimisticRead_NoTransaction_ThrowsException() { * @group DDC-178 * @group locking */ - public function testLockPessimisticWrite_NoTransaction_ThrowsException() { + public function testLockPessimisticWrite_NoTransaction_ThrowsException() + { $article = new CmsArticle(); $article->text = "my article"; $article->topic = "Hello"; @@ -126,7 +135,8 @@ public function testLockPessimisticWrite_NoTransaction_ThrowsException() { public function testLockPessimisticWrite() { $writeLockSql = $this->_em->getConnection()->getDatabasePlatform()->getWriteLockSQL(); - if (strlen($writeLockSql) == 0) { + + if (! $writeLockSql) { $this->markTestSkipped('Database Driver has no Write Lock support.'); } @@ -157,7 +167,8 @@ public function testLockPessimisticWrite() public function testLockPessimisticRead() { $readLockSql = $this->_em->getConnection()->getDatabasePlatform()->getReadLockSQL(); - if (strlen($readLockSql) == 0) { + + if (! $readLockSql) { $this->markTestSkipped('Database Driver has no Write Lock support.'); } @@ -169,6 +180,7 @@ public function testLockPessimisticRead() $this->_em->flush(); $this->_em->beginTransaction(); + try { $this->_em->lock($article, LockMode::PESSIMISTIC_READ); $this->_em->commit(); @@ -177,8 +189,9 @@ public function testLockPessimisticRead() throw $e; } - $query = array_pop( $this->_sqlLoggerStack->queries ); - $query = array_pop( $this->_sqlLoggerStack->queries ); + array_pop($this->_sqlLoggerStack->queries); + $query = array_pop($this->_sqlLoggerStack->queries); + $this->assertContains($readLockSql, $query['sql']); } @@ -187,13 +200,13 @@ public function testLockPessimisticRead() */ public function testLockOptimisticNonVersionedThrowsExceptionInDQL() { - $dql = "SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.username = 'gblanco'"; + $dql = "SELECT u FROM " . CmsUser::class . " u WHERE u.username = 'gblanco'"; $this->expectException(OptimisticLockException::class); $this->expectExceptionMessage('The optimistic lock on an entity failed.'); - $sql = $this->_em->createQuery($dql)->setHint( - Query::HINT_LOCK_MODE, LockMode::OPTIMISTIC - )->getSQL(); + $this->_em->createQuery($dql) + ->setHint(Query::HINT_LOCK_MODE, LockMode::OPTIMISTIC) + ->getSQL(); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/Locking/OptimisticTest.php b/tests/Doctrine/Tests/ORM/Functional/Locking/OptimisticTest.php index e4cad517168..8b8113b6a66 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Locking/OptimisticTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/Locking/OptimisticTest.php @@ -2,9 +2,9 @@ namespace Doctrine\Tests\ORM\Functional\Locking; -use Doctrine\ORM\OptimisticLockException; -use Doctrine\DBAL\LockMode; use DateTime; +use Doctrine\DBAL\LockMode; +use Doctrine\ORM\OptimisticLockException; use Doctrine\Tests\OrmFunctionalTestCase; class OptimisticTest extends OrmFunctionalTestCase @@ -14,15 +14,18 @@ protected function setUp() parent::setUp(); try { - $this->_schemaTool->createSchema(array( - $this->_em->getClassMetadata('Doctrine\Tests\ORM\Functional\Locking\OptimisticJoinedParent'), - $this->_em->getClassMetadata('Doctrine\Tests\ORM\Functional\Locking\OptimisticJoinedChild'), - $this->_em->getClassMetadata('Doctrine\Tests\ORM\Functional\Locking\OptimisticStandard'), - $this->_em->getClassMetadata('Doctrine\Tests\ORM\Functional\Locking\OptimisticTimestamp') - )); + $this->_schemaTool->createSchema( + [ + $this->_em->getClassMetadata(OptimisticJoinedParent::class), + $this->_em->getClassMetadata(OptimisticJoinedChild::class), + $this->_em->getClassMetadata(OptimisticStandard::class), + $this->_em->getClassMetadata(OptimisticTimestamp::class) + ] + ); } catch (\Exception $e) { // Swallow all exceptions. We do not test the schema tool here. } + $this->_conn = $this->_em->getConnection(); } @@ -55,7 +58,7 @@ public function testJoinedChildFailureThrowsException(OptimisticJoinedChild $chi // Manually update/increment the version so we can try and save the same // $test and make sure the exception is thrown saying the record was // changed or updated since you read it - $this->_conn->executeQuery('UPDATE optimistic_joined_parent SET version = ? WHERE id = ?', array(2, $test->id)); + $this->_conn->executeQuery('UPDATE optimistic_joined_parent SET version = ? WHERE id = ?', [2, $test->id]); // Now lets change a property and try and save it again $test->whatever = 'ok'; @@ -95,7 +98,7 @@ public function testJoinedParentFailureThrowsException(OptimisticJoinedParent $p // Manually update/increment the version so we can try and save the same // $test and make sure the exception is thrown saying the record was // changed or updated since you read it - $this->_conn->executeQuery('UPDATE optimistic_joined_parent SET version = ? WHERE id = ?', array(2, $test->id)); + $this->_conn->executeQuery('UPDATE optimistic_joined_parent SET version = ? WHERE id = ?', [2, $test->id]); // Now lets change a property and try and save it again $test->name = 'WHATT???'; @@ -151,7 +154,7 @@ public function testStandardFailureThrowsException(OptimisticStandard $entity) // Manually update/increment the version so we can try and save the same // $test and make sure the exception is thrown saying the record was // changed or updated since you read it - $this->_conn->executeQuery('UPDATE optimistic_standard SET version = ? WHERE id = ?', array(2, $test->id)); + $this->_conn->executeQuery('UPDATE optimistic_standard SET version = ? WHERE id = ?', [2, $test->id]); // Now lets change a property and try and save it again $test->name = 'WHATT???'; @@ -166,16 +169,17 @@ public function testStandardFailureThrowsException(OptimisticStandard $entity) public function testLockWorksWithProxy() { $test = new OptimisticStandard(); - $test->name = 'test'; $this->_em->persist($test); $this->_em->flush(); $this->_em->clear(); - $proxy = $this->_em->getReference('Doctrine\Tests\ORM\Functional\Locking\OptimisticStandard', $test->id); + $proxy = $this->_em->getReference(OptimisticStandard::class, $test->id); $this->_em->lock($proxy, LockMode::OPTIMISTIC, 1); + + $this->addToAssertionCount(1); } public function testOptimisticTimestampSetsDefaultValue() @@ -210,7 +214,8 @@ public function testOptimisticTimestampFailureThrowsException(OptimisticTimestam // Manually increment the version datetime column $format = $this->_em->getConnection()->getDatabasePlatform()->getDateTimeFormatString(); - $this->_conn->executeQuery('UPDATE optimistic_timestamp SET version = ? WHERE id = ?', array(date($format, strtotime($test->version->format($format)) + 3600), $test->id)); + $this->_conn->executeQuery('UPDATE optimistic_timestamp SET version = ? WHERE id = ?', [date($format, strtotime($test->version->format($format)) + 3600), $test->id] + ); // Try and update the record and it should throw an exception $caughtException = null; diff --git a/tests/Doctrine/Tests/ORM/Functional/ManyToManyBasicAssociationTest.php b/tests/Doctrine/Tests/ORM/Functional/ManyToManyBasicAssociationTest.php index 2d051b68831..0436b2af762 100644 --- a/tests/Doctrine/Tests/ORM/Functional/ManyToManyBasicAssociationTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/ManyToManyBasicAssociationTest.php @@ -2,12 +2,13 @@ namespace Doctrine\Tests\ORM\Functional; +use Doctrine\Common\Collections\ArrayCollection; use Doctrine\Common\Collections\Criteria; +use Doctrine\ORM\PersistentCollection; use Doctrine\ORM\UnitOfWork; +use Doctrine\Tests\Models\CMS\CmsGroup; use Doctrine\Tests\Models\CMS\CmsTag; -use Doctrine\Tests\Models\CMS\CmsUser, - Doctrine\Tests\Models\CMS\CmsGroup, - Doctrine\Common\Collections\ArrayCollection; +use Doctrine\Tests\Models\CMS\CmsUser; use Doctrine\Tests\OrmFunctionalTestCase; /** @@ -49,7 +50,7 @@ public function testBasicManyToManyJoin() $result = $query->getResult(); $this->assertEquals(2, $this->_em->getUnitOfWork()->size()); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsUser', $result[0]); + $this->assertInstanceOf(CmsUser::class, $result[0]); $this->assertEquals('Guilherme', $result[0]->name); $this->assertEquals(1, $result[0]->getGroups()->count()); $groups = $result[0]->getGroups(); @@ -58,8 +59,8 @@ public function testBasicManyToManyJoin() $this->assertEquals(UnitOfWork::STATE_MANAGED, $this->_em->getUnitOfWork()->getEntityState($result[0])); $this->assertEquals(UnitOfWork::STATE_MANAGED, $this->_em->getUnitOfWork()->getEntityState($groups[0])); - $this->assertInstanceOf('Doctrine\ORM\PersistentCollection', $groups); - $this->assertInstanceOf('Doctrine\ORM\PersistentCollection', $groups[0]->getUsers()); + $this->assertInstanceOf(PersistentCollection::class, $groups); + $this->assertInstanceOf(PersistentCollection::class, $groups[0]->getUsers()); $groups[0]->getUsers()->clear(); $groups->clear(); @@ -152,7 +153,7 @@ public function testManyToManyCollectionClearAndAdd() $user->groups[] = $group; } - $this->assertInstanceOf('Doctrine\ORM\PersistentCollection', $user->groups); + $this->assertInstanceOf(PersistentCollection::class, $user->groups); $this->assertTrue($user->groups->isDirty()); $this->assertEquals($groupCount, count($user->groups), "There should be 10 groups in the collection."); @@ -187,7 +188,7 @@ public function testRetrieveManyToManyAndAddMore() $this->_em->clear(); /* @var $freshUser CmsUser */ - $freshUser = $this->_em->find('Doctrine\Tests\Models\CMS\CmsUser', $user->getId()); + $freshUser = $this->_em->find(CmsUser::class, $user->getId()); $newGroup = new CmsGroup(); $newGroup->setName('12Monkeys'); $freshUser->addGroup($newGroup); @@ -202,7 +203,7 @@ public function testRetrieveManyToManyAndAddMore() $this->_em->clear(); - $freshUser = $this->_em->find('Doctrine\Tests\Models\CMS\CmsUser', $user->getId()); + $freshUser = $this->_em->find(CmsUser::class, $user->getId()); $this->assertEquals(3, count($freshUser->getGroups())); } @@ -303,15 +304,6 @@ public function addCmsUserGblancoWithGroups($groupCount = 1) return $user; } - /** - * @group DDC-980 - */ - public function testUpdateDeleteSizeSubselectQueries() - { - $this->_em->createQuery("DELETE Doctrine\Tests\Models\CMS\CmsUser u WHERE SIZE(u.groups) = 10")->execute(); - $this->_em->createQuery("UPDATE Doctrine\Tests\Models\CMS\CmsUser u SET u.status = 'inactive' WHERE SIZE(u.groups) = 10")->execute(); - } - /** * @group DDC-978 */ @@ -330,10 +322,10 @@ public function testClearAndResetCollection() $user = $this->_em->find(get_class($user), $user->id); - $coll = new ArrayCollection(array($group1, $group2)); + $coll = new ArrayCollection([$group1, $group2]); $user->groups = $coll; $this->_em->flush(); - $this->assertInstanceOf('Doctrine\ORM\PersistentCollection', $user->groups, + $this->assertInstanceOf(PersistentCollection::class, $user->groups, "UnitOfWork should have replaced ArrayCollection with PersistentCollection."); $this->_em->flush(); diff --git a/tests/Doctrine/Tests/ORM/Functional/ManyToManyBidirectionalAssociationTest.php b/tests/Doctrine/Tests/ORM/Functional/ManyToManyBidirectionalAssociationTest.php index 51121b09abc..9c70ab7f6aa 100644 --- a/tests/Doctrine/Tests/ORM/Functional/ManyToManyBidirectionalAssociationTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/ManyToManyBidirectionalAssociationTest.php @@ -115,8 +115,8 @@ protected function _findCategories() //$query->setHint(Query::HINT_FORCE_PARTIAL_LOAD, true); $result = $query->getResult(); $this->assertEquals(2, count($result)); - $this->assertInstanceOf('Doctrine\Tests\Models\ECommerce\ECommerceCategory', $result[0]); - $this->assertInstanceOf('Doctrine\Tests\Models\ECommerce\ECommerceCategory', $result[1]); + $this->assertInstanceOf(ECommerceCategory::class, $result[0]); + $this->assertInstanceOf(ECommerceCategory::class, $result[1]); $prods1 = $result[0]->getProducts(); $prods2 = $result[1]->getProducts(); $this->assertTrue($prods1->isInitialized()); @@ -155,10 +155,10 @@ public function assertLazyLoadFromInverseSide($products) $this->assertEquals(2, count($secondCategoryProducts)); // lazy-load $this->assertTrue($secondCategoryProducts->isInitialized()); - $this->assertInstanceOf('Doctrine\Tests\Models\ECommerce\ECommerceProduct', $firstCategoryProducts[0]); - $this->assertInstanceOf('Doctrine\Tests\Models\ECommerce\ECommerceProduct', $firstCategoryProducts[1]); - $this->assertInstanceOf('Doctrine\Tests\Models\ECommerce\ECommerceProduct', $secondCategoryProducts[0]); - $this->assertInstanceOf('Doctrine\Tests\Models\ECommerce\ECommerceProduct', $secondCategoryProducts[1]); + $this->assertInstanceOf(ECommerceProduct::class, $firstCategoryProducts[0]); + $this->assertInstanceOf(ECommerceProduct::class, $firstCategoryProducts[1]); + $this->assertInstanceOf(ECommerceProduct::class, $secondCategoryProducts[0]); + $this->assertInstanceOf(ECommerceProduct::class, $secondCategoryProducts[1]); $this->assertCollectionEquals($firstCategoryProducts, $secondCategoryProducts); } @@ -190,10 +190,10 @@ public function assertLazyLoadFromOwningSide($categories) $this->assertEquals(2, count($secondProductCategories)); // lazy-load $this->assertTrue($secondProductCategories->isInitialized()); - $this->assertInstanceOf('Doctrine\Tests\Models\ECommerce\ECommerceCategory', $firstProductCategories[0]); - $this->assertInstanceOf('Doctrine\Tests\Models\ECommerce\ECommerceCategory', $firstProductCategories[1]); - $this->assertInstanceOf('Doctrine\Tests\Models\ECommerce\ECommerceCategory', $secondProductCategories[0]); - $this->assertInstanceOf('Doctrine\Tests\Models\ECommerce\ECommerceCategory', $secondProductCategories[1]); + $this->assertInstanceOf(ECommerceCategory::class, $firstProductCategories[0]); + $this->assertInstanceOf(ECommerceCategory::class, $firstProductCategories[1]); + $this->assertInstanceOf(ECommerceCategory::class, $secondProductCategories[0]); + $this->assertInstanceOf(ECommerceCategory::class, $secondProductCategories[1]); $this->assertCollectionEquals($firstProductCategories, $secondProductCategories); } diff --git a/tests/Doctrine/Tests/ORM/Functional/ManyToManySelfReferentialAssociationTest.php b/tests/Doctrine/Tests/ORM/Functional/ManyToManySelfReferentialAssociationTest.php index 3ad4068803a..559cd4ba662 100644 --- a/tests/Doctrine/Tests/ORM/Functional/ManyToManySelfReferentialAssociationTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/ManyToManySelfReferentialAssociationTest.php @@ -72,7 +72,7 @@ public function testLazyLoadsOwningSide() { $this->_createLoadingFixture(); - $metadata = $this->_em->getClassMetadata('Doctrine\Tests\Models\ECommerce\ECommerceProduct'); + $metadata = $this->_em->getClassMetadata(ECommerceProduct::class); $metadata->associationMappings['related']['fetch'] = ClassMetadata::FETCH_LAZY; $query = $this->_em->createQuery('SELECT p FROM Doctrine\Tests\Models\ECommerce\ECommerceProduct p'); @@ -93,10 +93,10 @@ public function assertLoadingOfOwningSide($products) $this->assertEquals(2, count($firstRelatedBy)); $this->assertEquals(2, count($secondRelatedBy)); - $this->assertInstanceOf('Doctrine\Tests\Models\ECommerce\ECommerceProduct', $firstRelatedBy[0]); - $this->assertInstanceOf('Doctrine\Tests\Models\ECommerce\ECommerceProduct', $firstRelatedBy[1]); - $this->assertInstanceOf('Doctrine\Tests\Models\ECommerce\ECommerceProduct', $secondRelatedBy[0]); - $this->assertInstanceOf('Doctrine\Tests\Models\ECommerce\ECommerceProduct', $secondRelatedBy[1]); + $this->assertInstanceOf(ECommerceProduct::class, $firstRelatedBy[0]); + $this->assertInstanceOf(ECommerceProduct::class, $firstRelatedBy[1]); + $this->assertInstanceOf(ECommerceProduct::class, $secondRelatedBy[0]); + $this->assertInstanceOf(ECommerceProduct::class, $secondRelatedBy[1]); $this->assertCollectionEquals($firstRelatedBy, $secondRelatedBy); } diff --git a/tests/Doctrine/Tests/ORM/Functional/ManyToManyUnidirectionalAssociationTest.php b/tests/Doctrine/Tests/ORM/Functional/ManyToManyUnidirectionalAssociationTest.php index 241b3c2fb06..20e31db00df 100644 --- a/tests/Doctrine/Tests/ORM/Functional/ManyToManyUnidirectionalAssociationTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/ManyToManyUnidirectionalAssociationTest.php @@ -67,8 +67,8 @@ public function testEagerLoad() $products = $firstCart->getProducts(); $secondCart = $result[1]; - $this->assertInstanceOf('Doctrine\Tests\Models\ECommerce\ECommerceProduct', $products[0]); - $this->assertInstanceOf('Doctrine\Tests\Models\ECommerce\ECommerceProduct', $products[1]); + $this->assertInstanceOf(ECommerceProduct::class, $products[0]); + $this->assertInstanceOf(ECommerceProduct::class, $products[1]); $this->assertCollectionEquals($products, $secondCart->getProducts()); //$this->assertEquals("Doctrine 1.x Manual", $products[0]->getName()); //$this->assertEquals("Doctrine 2.x Manual", $products[1]->getName()); @@ -77,7 +77,7 @@ public function testEagerLoad() public function testLazyLoadsCollection() { $this->_createFixture(); - $metadata = $this->_em->getClassMetadata('Doctrine\Tests\Models\ECommerce\ECommerceCart'); + $metadata = $this->_em->getClassMetadata(ECommerceCart::class); $metadata->associationMappings['products']['fetch'] = ClassMetadata::FETCH_LAZY; $query = $this->_em->createQuery('SELECT c FROM Doctrine\Tests\Models\ECommerce\ECommerceCart c'); @@ -86,8 +86,8 @@ public function testLazyLoadsCollection() $products = $firstCart->getProducts(); $secondCart = $result[1]; - $this->assertInstanceOf('Doctrine\Tests\Models\ECommerce\ECommerceProduct', $products[0]); - $this->assertInstanceOf('Doctrine\Tests\Models\ECommerce\ECommerceProduct', $products[1]); + $this->assertInstanceOf(ECommerceProduct::class, $products[0]); + $this->assertInstanceOf(ECommerceProduct::class, $products[1]); $this->assertCollectionEquals($products, $secondCart->getProducts()); } diff --git a/tests/Doctrine/Tests/ORM/Functional/ManyToOneOrphanRemovalTest.php b/tests/Doctrine/Tests/ORM/Functional/ManyToOneOrphanRemovalTest.php new file mode 100644 index 00000000000..36039b2b2a3 --- /dev/null +++ b/tests/Doctrine/Tests/ORM/Functional/ManyToOneOrphanRemovalTest.php @@ -0,0 +1,86 @@ + [ + Person::class, + PhoneNumber::class, + ] + ]; + + protected function setUp() + { + $this->useModelSet('ornemental_orphan_removal'); + + parent::setUp(); + + $person = new Person; + $person->id = 'ca41a293-799f-4d68-bf79-626c3ad223ec'; + + $phone1 = new PhoneNumber; + $phone1->id = 'f4132478-c492-4dfe-aab5-a5b79ae129e7'; + $phone1->phonenumber = '123456'; + + $phone2 = new PhoneNumber; + $phone2->id = '7faa4cd3-a155-4fbf-bc42-aa4269a4454d'; + $phone2->phonenumber = '234567'; + + $phone1->person = $person; + $phone2->person = $person; + + $this->_em->persist($phone1); + $this->_em->persist($phone2); + $this->_em->persist($person); + $this->_em->flush(); + + $this->personId = $person->id; + $this->_em->clear(); + } + + public function testOrphanRemovalIsPurelyOrnemental() + { + $person = $this->_em->getReference(Person::class, $this->personId); + + $this->_em->remove($person); + $this->_em->flush(); + $this->_em->clear(); + + $query = $this->_em->createQuery( + 'SELECT u FROM Doctrine\Tests\Models\OrnementalOrphanRemoval\Person u' + ); + $result = $query->getResult(); + + $this->assertEquals(0, count($result), 'Person should be removed by EntityManager'); + + $query = $this->_em->createQuery( + 'SELECT p FROM Doctrine\Tests\Models\OrnementalOrphanRemoval\PhoneNumber p' + ); + $result = $query->getResult(); + + $this->assertEquals(2, count($result), 'Orphan removal should not kick in'); + } + + protected function _getEntityManager( + Connection $connection = null, + MappingDriver $mappingDriver = null + ) { + return parent::_getEntityManager($connection, new XmlDriver( + __DIR__.DIRECTORY_SEPARATOR.'xml' + )); + } +} diff --git a/tests/Doctrine/Tests/ORM/Functional/MappedSuperclassTest.php b/tests/Doctrine/Tests/ORM/Functional/MappedSuperclassTest.php index fb7f0a7249d..97c34bba335 100644 --- a/tests/Doctrine/Tests/ORM/Functional/MappedSuperclassTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/MappedSuperclassTest.php @@ -1,6 +1,8 @@ _em->find(get_class($file), $file->getId()); - $this->assertInstanceOf('Doctrine\Tests\Models\DirectoryTree\Directory', $cleanFile->getParent()); - $this->assertInstanceOf('Doctrine\ORM\Proxy\Proxy', $cleanFile->getParent()); + $this->assertInstanceOf(Directory::class, $cleanFile->getParent()); + $this->assertInstanceOf(Proxy::class, $cleanFile->getParent()); $this->assertEquals($directory->getId(), $cleanFile->getParent()->getId()); - $this->assertInstanceOf('Doctrine\Tests\Models\DirectoryTree\Directory', $cleanFile->getParent()->getParent()); + $this->assertInstanceOf(Directory::class, $cleanFile->getParent()->getParent()); $this->assertEquals($root->getId(), $cleanFile->getParent()->getParent()->getId()); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/MergeCompositeToOneKeyTest.php b/tests/Doctrine/Tests/ORM/Functional/MergeCompositeToOneKeyTest.php index 9b3b338a083..54a9bc833da 100644 --- a/tests/Doctrine/Tests/ORM/Functional/MergeCompositeToOneKeyTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/MergeCompositeToOneKeyTest.php @@ -5,9 +5,12 @@ use Doctrine\Tests\Models\MixedToOneIdentity\CompositeToOneKeyState; use Doctrine\Tests\Models\MixedToOneIdentity\Country; use Doctrine\Tests\OrmFunctionalTestCase; +use Doctrine\Tests\VerifyDeprecations; class MergeCompositeToOneKeyTest extends OrmFunctionalTestCase { + use VerifyDeprecations; + /** * {@inheritDoc} */ @@ -15,10 +18,12 @@ protected function setUp() { parent::setUp(); - $this->_schemaTool->createSchema(array( - $this->_em->getClassMetadata(Country::CLASSNAME), - $this->_em->getClassMetadata(CompositeToOneKeyState::CLASSNAME), - )); + $this->_schemaTool->createSchema( + [ + $this->_em->getClassMetadata(Country::class), + $this->_em->getClassMetadata(CompositeToOneKeyState::class), + ] + ); } /** @@ -37,9 +42,10 @@ public function testMergingOfEntityWithCompositeIdentifierContainingToOneAssocia /* @var $merged CompositeToOneKeyState */ $merged = $this->_em->merge($state); - $this->assertInstanceOf(CompositeToOneKeyState::CLASSNAME, $state); + $this->assertInstanceOf(CompositeToOneKeyState::class, $state); $this->assertNotSame($state, $merged); - $this->assertInstanceOf(Country::CLASSNAME, $merged->country); + $this->assertInstanceOf(Country::class, $merged->country); $this->assertNotSame($country, $merged->country); + $this->assertHasDeprecationMessages(); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/MergeProxiesTest.php b/tests/Doctrine/Tests/ORM/Functional/MergeProxiesTest.php index 42bf4187e52..e323a190711 100644 --- a/tests/Doctrine/Tests/ORM/Functional/MergeProxiesTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/MergeProxiesTest.php @@ -7,12 +7,16 @@ use Doctrine\DBAL\Logging\SQLLogger; use Doctrine\ORM\Configuration; use Doctrine\ORM\EntityManager; +use Doctrine\ORM\Proxy\Proxy; use Doctrine\ORM\Tools\SchemaTool; use Doctrine\Tests\Models\Generic\DateTimeModel; use Doctrine\Tests\OrmFunctionalTestCase; +use Doctrine\Tests\VerifyDeprecations; class MergeProxiesTest extends OrmFunctionalTestCase { + use VerifyDeprecations; + /** * {@inheritDoc} */ @@ -23,6 +27,12 @@ protected function setUp() parent::setUp(); } + /** @after */ + public function ensureTestGeneratedDeprecationMessages() : void + { + $this->assertHasDeprecationMessages(); + } + /** * @group DDC-1392 * @group DDC-1734 @@ -31,11 +41,11 @@ protected function setUp() */ public function testMergeDetachedUnInitializedProxy() { - $detachedUninitialized = $this->_em->getReference(DateTimeModel::CLASSNAME, 123); + $detachedUninitialized = $this->_em->getReference(DateTimeModel::class, 123); $this->_em->clear(); - $managed = $this->_em->getReference(DateTimeModel::CLASSNAME, 123); + $managed = $this->_em->getReference(DateTimeModel::class, 123); $this->assertSame($managed, $this->_em->merge($detachedUninitialized)); @@ -51,11 +61,11 @@ public function testMergeDetachedUnInitializedProxy() */ public function testMergeUnserializedUnInitializedProxy() { - $detachedUninitialized = $this->_em->getReference(DateTimeModel::CLASSNAME, 123); + $detachedUninitialized = $this->_em->getReference(DateTimeModel::class, 123); $this->_em->clear(); - $managed = $this->_em->getReference(DateTimeModel::CLASSNAME, 123); + $managed = $this->_em->getReference(DateTimeModel::class, 123); $this->assertSame( $managed, @@ -74,7 +84,7 @@ public function testMergeUnserializedUnInitializedProxy() */ public function testMergeManagedProxy() { - $managed = $this->_em->getReference(DateTimeModel::CLASSNAME, 123); + $managed = $this->_em->getReference(DateTimeModel::class, 123); $this->assertSame($managed, $this->_em->merge($managed)); @@ -98,9 +108,9 @@ public function testMergeWithExistingUninitializedManagedProxy() $this->_em->flush($date); $this->_em->clear(); - $managed = $this->_em->getReference(DateTimeModel::CLASSNAME, $date->id); + $managed = $this->_em->getReference(DateTimeModel::class, $date->id); - $this->assertInstanceOf('Doctrine\Common\Proxy\Proxy', $managed); + $this->assertInstanceOf(Proxy::class, $managed); $this->assertFalse($managed->__isInitialized()); $date->date = $dateTime = new \DateTime(); @@ -134,8 +144,8 @@ public function testMergingProxyFromDifferentEntityManagerWithExistingManagedIns $queryCount1 = count($logger1->queries); $queryCount2 = count($logger2->queries); - $proxy1 = $em1->getReference(DateTimeModel::CLASSNAME, $file1->id); - $proxy2 = $em2->getReference(DateTimeModel::CLASSNAME, $file1->id); + $proxy1 = $em1->getReference(DateTimeModel::class, $file1->id); + $proxy2 = $em2->getReference(DateTimeModel::class, $file1->id); $merged2 = $em2->merge($proxy1); $this->assertNotSame($proxy1, $merged2); @@ -195,10 +205,10 @@ public function testMergingUnInitializedProxyDoesNotInitializeIt() $queryCount1 = count($logger1->queries); $queryCount2 = count($logger1->queries); - $unManagedProxy = $em1->getReference(DateTimeModel::CLASSNAME, $file1->id); + $unManagedProxy = $em1->getReference(DateTimeModel::class, $file1->id); $mergedInstance = $em2->merge($unManagedProxy); - $this->assertNotInstanceOf('Doctrine\Common\Proxy\Proxy', $mergedInstance); + $this->assertNotInstanceOf(Proxy::class, $mergedInstance); $this->assertNotSame($unManagedProxy, $mergedInstance); $this->assertFalse($unManagedProxy->__isInitialized()); @@ -239,7 +249,7 @@ private function createEntityManager(SQLLogger $logger) $config->setProxyDir(realpath(__DIR__ . '/../../Proxies')); $config->setProxyNamespace('Doctrine\Tests\Proxies'); $config->setMetadataDriverImpl($config->newDefaultAnnotationDriver( - array(realpath(__DIR__ . '/../../Models/Cache')), + [realpath(__DIR__ . '/../../Models/Cache')], true )); $config->setSQLLogger($logger); @@ -248,17 +258,17 @@ private function createEntityManager(SQLLogger $logger) // multi-connection is not relevant for the purpose of checking locking here, but merely // to stub out DB-level access and intercept it $connection = DriverManager::getConnection( - array( + [ 'driver' => 'pdo_sqlite', 'memory' => true - ), + ], $config ); $entityManager = EntityManager::create($connection, $config); - (new SchemaTool($entityManager))->createSchema([$entityManager->getClassMetadata(DateTimeModel::CLASSNAME)]); + (new SchemaTool($entityManager))->createSchema([$entityManager->getClassMetadata(DateTimeModel::class)]); return $entityManager; } diff --git a/tests/Doctrine/Tests/ORM/Functional/MergeSharedEntitiesTest.php b/tests/Doctrine/Tests/ORM/Functional/MergeSharedEntitiesTest.php index 28e89c36094..3e2937eda99 100644 --- a/tests/Doctrine/Tests/ORM/Functional/MergeSharedEntitiesTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/MergeSharedEntitiesTest.php @@ -1,29 +1,15 @@ . - */ namespace Doctrine\Tests\ORM\Functional; use Doctrine\ORM\Tools\ToolsException; use Doctrine\Tests\OrmFunctionalTestCase; +use Doctrine\Tests\VerifyDeprecations; class MergeSharedEntitiesTest extends OrmFunctionalTestCase { + use VerifyDeprecations; + /** * {@inheritDoc} */ @@ -32,14 +18,22 @@ protected function setUp() parent::setUp(); try { - $this->_schemaTool->createSchema(array( - $this->_em->getClassMetadata(__NAMESPACE__ . '\MSEFile'), - $this->_em->getClassMetadata(__NAMESPACE__ . '\MSEPicture'), - )); + $this->_schemaTool->createSchema( + [ + $this->_em->getClassMetadata(MSEFile::class), + $this->_em->getClassMetadata(MSEPicture::class), + ] + ); } catch (ToolsException $ignored) { } } + /** @after */ + public function ensureTestGeneratedDeprecationMessages() : void + { + $this->assertHasDeprecationMessages(); + } + public function testMergeSharedNewEntities() { $file = new MSEFile; diff --git a/tests/Doctrine/Tests/ORM/Functional/MergeVersionedManyToOneTest.php b/tests/Doctrine/Tests/ORM/Functional/MergeVersionedManyToOneTest.php index 43af6720c83..18e061a45e2 100644 --- a/tests/Doctrine/Tests/ORM/Functional/MergeVersionedManyToOneTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/MergeVersionedManyToOneTest.php @@ -5,12 +5,15 @@ use Doctrine\Tests\Models\VersionedManyToOne\Article; use Doctrine\Tests\Models\VersionedManyToOne\Category; use Doctrine\Tests\OrmFunctionalTestCase; +use Doctrine\Tests\VerifyDeprecations; /** * @group MergeVersionedOneToMany */ class MergeVersionedManyToOneTest extends OrmFunctionalTestCase { + use VerifyDeprecations; + protected function setUp() { $this->useModelSet('versioned_many_to_one'); @@ -40,5 +43,6 @@ public function testSetVersionOnCreate() $this->_em->flush(); $this->assertEquals(2, $articleMerged->version); + $this->assertHasDeprecationMessages(); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/NativeQueryTest.php b/tests/Doctrine/Tests/ORM/Functional/NativeQueryTest.php index 320aa357ac0..31c19a1cd4c 100644 --- a/tests/Doctrine/Tests/ORM/Functional/NativeQueryTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/NativeQueryTest.php @@ -3,17 +3,22 @@ namespace Doctrine\Tests\ORM\Functional; use Doctrine\Common\Collections\ArrayCollection; - use Doctrine\ORM\Internal\Hydration\HydrationException; +use Doctrine\ORM\PersistentCollection; +use Doctrine\ORM\Query\Parameter; use Doctrine\ORM\Query\ResultSetMapping; use Doctrine\ORM\Query\ResultSetMappingBuilder; -use Doctrine\ORM\Query\Parameter; -use Doctrine\Tests\Models\CMS\CmsUser; -use Doctrine\Tests\Models\CMS\CmsPhonenumber; use Doctrine\Tests\Models\CMS\CmsAddress; use Doctrine\Tests\Models\CMS\CmsEmail; +use Doctrine\Tests\Models\CMS\CmsPhonenumber; +use Doctrine\Tests\Models\CMS\CmsUser; +use Doctrine\Tests\Models\Company\CompanyContract; use Doctrine\Tests\Models\Company\CompanyEmployee; +use Doctrine\Tests\Models\Company\CompanyFixContract; +use Doctrine\Tests\Models\Company\CompanyFlexContract; use Doctrine\Tests\Models\Company\CompanyPerson; +use Doctrine\Tests\Models\DDC3899\DDC3899FixContract; +use Doctrine\Tests\Models\DDC3899\DDC3899User; use Doctrine\Tests\OrmFunctionalTestCase; /** @@ -30,6 +35,7 @@ protected function setUp() $this->useModelSet('cms'); $this->useModelSet('company'); parent::setUp(); + $this->platform = $this->_em->getConnection()->getDatabasePlatform(); } @@ -45,7 +51,7 @@ public function testBasicNativeQuery() $this->_em->clear(); $rsm = new ResultSetMapping; - $rsm->addEntityResult('Doctrine\Tests\Models\CMS\CmsUser', 'u'); + $rsm->addEntityResult(CmsUser::class, 'u'); $rsm->addFieldResult('u', $this->platform->getSQLResultCasing('id'), 'id'); $rsm->addFieldResult('u', $this->platform->getSQLResultCasing('name'), 'name'); @@ -55,7 +61,7 @@ public function testBasicNativeQuery() $users = $query->getResult(); $this->assertEquals(1, count($users)); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsUser', $users[0]); + $this->assertInstanceOf(CmsUser::class, $users[0]); $this->assertEquals('Roman', $users[0]->name); } @@ -80,7 +86,7 @@ public function testBasicNativeQueryWithMetaResult() $this->_em->clear(); $rsm = new ResultSetMapping; - $rsm->addEntityResult('Doctrine\Tests\Models\CMS\CmsAddress', 'a'); + $rsm->addEntityResult(CmsAddress::class, 'a'); $rsm->addFieldResult('a', $this->platform->getSQLResultCasing('id'), 'id'); $rsm->addFieldResult('a', $this->platform->getSQLResultCasing('country'), 'country'); $rsm->addFieldResult('a', $this->platform->getSQLResultCasing('zip'), 'zip'); @@ -119,11 +125,11 @@ public function testJoinedOneToManyNativeQuery() $this->_em->clear(); $rsm = new ResultSetMapping; - $rsm->addEntityResult('Doctrine\Tests\Models\CMS\CmsUser', 'u'); + $rsm->addEntityResult(CmsUser::class, 'u'); $rsm->addFieldResult('u', $this->platform->getSQLResultCasing('id'), 'id'); $rsm->addFieldResult('u', $this->platform->getSQLResultCasing('name'), 'name'); $rsm->addFieldResult('u', $this->platform->getSQLResultCasing('status'), 'status'); - $rsm->addJoinedEntityResult('Doctrine\Tests\Models\CMS\CmsPhonenumber', 'p', 'u', 'phonenumbers'); + $rsm->addJoinedEntityResult(CmsPhonenumber::class, 'p', 'u', 'phonenumbers'); $rsm->addFieldResult('p', $this->platform->getSQLResultCasing('phonenumber'), 'phonenumber'); $query = $this->_em->createNativeQuery('SELECT id, name, status, phonenumber FROM cms_users INNER JOIN cms_phonenumbers ON id = user_id WHERE username = ?', $rsm); @@ -131,9 +137,9 @@ public function testJoinedOneToManyNativeQuery() $users = $query->getResult(); $this->assertEquals(1, count($users)); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsUser', $users[0]); + $this->assertInstanceOf(CmsUser::class, $users[0]); $this->assertEquals('Roman', $users[0]->name); - $this->assertInstanceOf('Doctrine\ORM\PersistentCollection', $users[0]->getPhonenumbers()); + $this->assertInstanceOf(PersistentCollection::class, $users[0]->getPhonenumbers()); $this->assertTrue($users[0]->getPhonenumbers()->isInitialized()); $this->assertEquals(1, count($users[0]->getPhonenumbers())); $phones = $users[0]->getPhonenumbers(); @@ -164,11 +170,11 @@ public function testJoinedOneToOneNativeQuery() $rsm = new ResultSetMapping; - $rsm->addEntityResult('Doctrine\Tests\Models\CMS\CmsUser', 'u'); + $rsm->addEntityResult(CmsUser::class, 'u'); $rsm->addFieldResult('u', $this->platform->getSQLResultCasing('id'), 'id'); $rsm->addFieldResult('u', $this->platform->getSQLResultCasing('name'), 'name'); $rsm->addFieldResult('u', $this->platform->getSQLResultCasing('status'), 'status'); - $rsm->addJoinedEntityResult('Doctrine\Tests\Models\CMS\CmsAddress', 'a', 'u', 'address'); + $rsm->addJoinedEntityResult(CmsAddress::class, 'a', 'u', 'address'); $rsm->addFieldResult('a', $this->platform->getSQLResultCasing('a_id'), 'id'); $rsm->addFieldResult('a', $this->platform->getSQLResultCasing('country'), 'country'); $rsm->addFieldResult('a', $this->platform->getSQLResultCasing('zip'), 'zip'); @@ -180,11 +186,11 @@ public function testJoinedOneToOneNativeQuery() $users = $query->getResult(); $this->assertEquals(1, count($users)); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsUser', $users[0]); + $this->assertInstanceOf(CmsUser::class, $users[0]); $this->assertEquals('Roman', $users[0]->name); - $this->assertInstanceOf('Doctrine\ORM\PersistentCollection', $users[0]->getPhonenumbers()); + $this->assertInstanceOf(PersistentCollection::class, $users[0]->getPhonenumbers()); $this->assertFalse($users[0]->getPhonenumbers()->isInitialized()); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsAddress', $users[0]->getAddress()); + $this->assertInstanceOf(CmsAddress::class, $users[0]->getAddress()); $this->assertTrue($users[0]->getAddress()->getUser() == $users[0]); $this->assertEquals('germany', $users[0]->getAddress()->getCountry()); $this->assertEquals(10827, $users[0]->getAddress()->getZipCode()); @@ -230,16 +236,16 @@ public function testJoinedOneToManyNativeQueryWithRSMBuilder() $this->_em->clear(); $rsm = new ResultSetMappingBuilder($this->_em); - $rsm->addRootEntityFromClassMetadata('Doctrine\Tests\Models\CMS\CmsUser', 'u'); - $rsm->addJoinedEntityFromClassMetadata('Doctrine\Tests\Models\CMS\CmsPhonenumber', 'p', 'u', 'phonenumbers'); + $rsm->addRootEntityFromClassMetadata(CmsUser::class, 'u'); + $rsm->addJoinedEntityFromClassMetadata(CmsPhonenumber::class, 'p', 'u', 'phonenumbers'); $query = $this->_em->createNativeQuery('SELECT u.*, p.* FROM cms_users u LEFT JOIN cms_phonenumbers p ON u.id = p.user_id WHERE username = ?', $rsm); $query->setParameter(1, 'romanb'); $users = $query->getResult(); $this->assertEquals(1, count($users)); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsUser', $users[0]); + $this->assertInstanceOf(CmsUser::class, $users[0]); $this->assertEquals('Roman', $users[0]->name); - $this->assertInstanceOf('Doctrine\ORM\PersistentCollection', $users[0]->getPhonenumbers()); + $this->assertInstanceOf(PersistentCollection::class, $users[0]->getPhonenumbers()); $this->assertTrue($users[0]->getPhonenumbers()->isInitialized()); $this->assertEquals(1, count($users[0]->getPhonenumbers())); $phones = $users[0]->getPhonenumbers(); @@ -249,7 +255,7 @@ public function testJoinedOneToManyNativeQueryWithRSMBuilder() $this->_em->clear(); $rsm = new ResultSetMappingBuilder($this->_em); - $rsm->addRootEntityFromClassMetadata('Doctrine\Tests\Models\CMS\CmsPhonenumber', 'p'); + $rsm->addRootEntityFromClassMetadata(CmsPhonenumber::class, 'p'); $query = $this->_em->createNativeQuery('SELECT p.* FROM cms_phonenumbers p WHERE p.phonenumber = ?', $rsm); $query->setParameter(1, $phone->phonenumber); $phone = $query->getSingleResult(); @@ -280,8 +286,9 @@ public function testJoinedOneToOneNativeQueryWithRSMBuilder() $rsm = new ResultSetMappingBuilder($this->_em); - $rsm->addRootEntityFromClassMetadata('Doctrine\Tests\Models\CMS\CmsUser', 'u'); - $rsm->addJoinedEntityFromClassMetadata('Doctrine\Tests\Models\CMS\CmsAddress', 'a', 'u', 'address', array('id' => 'a_id')); + $rsm->addRootEntityFromClassMetadata(CmsUser::class, 'u'); + $rsm->addJoinedEntityFromClassMetadata(CmsAddress::class, 'a', 'u', 'address', ['id' => 'a_id'] + ); $query = $this->_em->createNativeQuery('SELECT u.*, a.*, a.id AS a_id FROM cms_users u INNER JOIN cms_addresses a ON u.id = a.user_id WHERE u.username = ?', $rsm); $query->setParameter(1, 'romanb'); @@ -289,11 +296,11 @@ public function testJoinedOneToOneNativeQueryWithRSMBuilder() $users = $query->getResult(); $this->assertEquals(1, count($users)); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsUser', $users[0]); + $this->assertInstanceOf(CmsUser::class, $users[0]); $this->assertEquals('Roman', $users[0]->name); - $this->assertInstanceOf('Doctrine\ORM\PersistentCollection', $users[0]->getPhonenumbers()); + $this->assertInstanceOf(PersistentCollection::class, $users[0]->getPhonenumbers()); $this->assertFalse($users[0]->getPhonenumbers()->isInitialized()); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsAddress', $users[0]->getAddress()); + $this->assertInstanceOf(CmsAddress::class, $users[0]->getAddress()); $this->assertTrue($users[0]->getAddress()->getUser() == $users[0]); $this->assertEquals('germany', $users[0]->getAddress()->getCountry()); $this->assertEquals(10827, $users[0]->getAddress()->getZipCode()); @@ -302,7 +309,7 @@ public function testJoinedOneToOneNativeQueryWithRSMBuilder() $this->_em->clear(); $rsm = new ResultSetMappingBuilder($this->_em); - $rsm->addRootEntityFromClassMetadata('Doctrine\Tests\Models\CMS\CmsAddress', 'a'); + $rsm->addRootEntityFromClassMetadata(CmsAddress::class, 'a'); $query = $this->_em->createNativeQuery('SELECT a.* FROM cms_addresses a WHERE a.id = ?', $rsm); $query->setParameter(1, $addr->getId()); $address = $query->getSingleResult(); @@ -317,7 +324,9 @@ public function testJoinedOneToOneNativeQueryWithRSMBuilder() public function testConcreteClassInSingleTableInheritanceSchemaWithRSMBuilderIsFine() { $rsm = new ResultSetMappingBuilder($this->_em); - $rsm->addRootEntityFromClassMetadata('Doctrine\Tests\Models\Company\CompanyFixContract', 'c'); + $rsm->addRootEntityFromClassMetadata(CompanyFixContract::class, 'c'); + + self::assertSame(CompanyFixContract::class, $rsm->getClassName('c')); } /** @@ -329,7 +338,7 @@ public function testAbstractClassInSingleTableInheritanceSchemaWithRSMBuilderThr $this->expectExceptionMessage('ResultSetMapping builder does not currently support your inheritance scheme.'); $rsm = new ResultSetMappingBuilder($this->_em); - $rsm->addRootEntityFromClassMetadata('Doctrine\Tests\Models\Company\CompanyContract', 'c'); + $rsm->addRootEntityFromClassMetadata(CompanyContract::class, 'c'); } /** @@ -338,8 +347,8 @@ public function testAbstractClassInSingleTableInheritanceSchemaWithRSMBuilderThr public function testRSMBuilderThrowsExceptionOnColumnConflict() { $rsm = new ResultSetMappingBuilder($this->_em); - $rsm->addRootEntityFromClassMetadata('Doctrine\Tests\Models\CMS\CmsUser', 'u'); - $rsm->addJoinedEntityFromClassMetadata('Doctrine\Tests\Models\CMS\CmsAddress', 'a', 'u', 'address'); + $rsm->addRootEntityFromClassMetadata(CmsUser::class, 'u'); + $rsm->addJoinedEntityFromClassMetadata(CmsAddress::class, 'a', 'u', 'address'); } /** @@ -348,8 +357,9 @@ public function testRSMBuilderThrowsExceptionOnColumnConflict() public function testUnknownParentAliasThrowsException() { $rsm = new ResultSetMappingBuilder($this->_em); - $rsm->addRootEntityFromClassMetadata('Doctrine\Tests\Models\CMS\CmsUser', 'u'); - $rsm->addJoinedEntityFromClassMetadata('Doctrine\Tests\Models\CMS\CmsAddress', 'a', 'un', 'address', array('id' => 'a_id')); + $rsm->addRootEntityFromClassMetadata(CmsUser::class, 'u'); + $rsm->addJoinedEntityFromClassMetadata(CmsAddress::class, 'a', 'un', 'address', ['id' => 'a_id'] + ); $query = $this->_em->createNativeQuery('SELECT u.*, a.*, a.id AS a_id FROM cms_users u INNER JOIN cms_addresses a ON u.id = a.user_id WHERE u.username = ?', $rsm); $query->setParameter(1, 'romanb'); @@ -385,12 +395,12 @@ public function testBasicNativeNamedQueryWithSqlResultSetMapping() $this->_em->clear(); - $repository = $this->_em->getRepository('Doctrine\Tests\Models\CMS\CmsAddress'); + $repository = $this->_em->getRepository(CmsAddress::class); $query = $repository->createNativeNamedQuery('find-all'); $result = $query->getResult(); $this->assertCount(1, $result); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsAddress', $result[0]); + $this->assertInstanceOf(CmsAddress::class, $result[0]); $this->assertEquals($addr->id, $result[0]->id); $this->assertEquals($addr->city, $result[0]->city); $this->assertEquals($addr->country, $result[0]->country); @@ -417,14 +427,14 @@ public function testBasicNativeNamedQueryWithResultClass() $this->_em->clear(); - $repository = $this->_em->getRepository('Doctrine\Tests\Models\CMS\CmsUser'); - + $repository = $this->_em->getRepository(CmsUser::class); $result = $repository->createNativeNamedQuery('fetchIdAndUsernameWithResultClass') - ->setParameter(1, 'FabioBatSilva')->getResult(); + ->setParameter(1, 'FabioBatSilva') + ->getResult(); $this->assertEquals(1, count($result)); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsUser', $result[0]); + $this->assertInstanceOf(CmsUser::class, $result[0]); $this->assertNull($result[0]->name); $this->assertNull($result[0]->email); $this->assertEquals($user->id, $result[0]->id); @@ -432,17 +442,17 @@ public function testBasicNativeNamedQueryWithResultClass() $this->_em->clear(); - $result = $repository->createNativeNamedQuery('fetchAllColumns') - ->setParameter(1, 'FabioBatSilva')->getResult(); + ->setParameter(1, 'FabioBatSilva') + ->getResult(); $this->assertEquals(1, count($result)); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsUser', $result[0]); + $this->assertInstanceOf(CmsUser::class, $result[0]); $this->assertEquals($user->id, $result[0]->id); $this->assertEquals('Fabio B. Silva', $result[0]->name); $this->assertEquals('FabioBatSilva', $result[0]->username); $this->assertEquals('dev', $result[0]->status); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsEmail', $result[0]->email); + $this->assertInstanceOf(CmsEmail::class, $result[0]->email); } @@ -461,26 +471,23 @@ public function testJoinedOneToOneNativeNamedQueryWithResultSetMapping() $addr->zip = 10827; $addr->city = 'São Paulo'; - $user->setAddress($addr); $this->_em->persist($user); $this->_em->flush(); - $this->_em->clear(); - $repository = $this->_em->getRepository('Doctrine\Tests\Models\CMS\CmsUser'); - - - $result = $repository->createNativeNamedQuery('fetchJoinedAddress') - ->setParameter(1, 'FabioBatSilva')->getResult(); + $result = $this->_em->getRepository(CmsUser::class) + ->createNativeNamedQuery('fetchJoinedAddress') + ->setParameter(1, 'FabioBatSilva') + ->getResult(); $this->assertEquals(1, count($result)); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsUser', $result[0]); + $this->assertInstanceOf(CmsUser::class, $result[0]); $this->assertEquals('Fabio B. Silva', $result[0]->name); - $this->assertInstanceOf('Doctrine\ORM\PersistentCollection', $result[0]->getPhonenumbers()); + $this->assertInstanceOf(PersistentCollection::class, $result[0]->getPhonenumbers()); $this->assertFalse($result[0]->getPhonenumbers()->isInitialized()); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsAddress', $result[0]->getAddress()); + $this->assertInstanceOf(CmsAddress::class, $result[0]->getAddress()); $this->assertTrue($result[0]->getAddress()->getUser() == $result[0]); $this->assertEquals('Brazil', $result[0]->getAddress()->getCountry()); $this->assertEquals(10827, $result[0]->getAddress()->getZipCode()); @@ -507,15 +514,15 @@ public function testJoinedOneToManyNativeNamedQueryWithResultSetMapping() $this->_em->clear(); - $repository = $this->_em->getRepository('Doctrine\Tests\Models\CMS\CmsUser'); + $repository = $this->_em->getRepository(CmsUser::class); $result = $repository->createNativeNamedQuery('fetchJoinedPhonenumber') ->setParameter(1, 'FabioBatSilva')->getResult(); $this->assertEquals(1, count($result)); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsUser', $result[0]); + $this->assertInstanceOf(CmsUser::class, $result[0]); $this->assertEquals('Fabio B. Silva', $result[0]->name); - $this->assertInstanceOf('Doctrine\ORM\PersistentCollection', $result[0]->getPhonenumbers()); + $this->assertInstanceOf(PersistentCollection::class, $result[0]->getPhonenumbers()); $this->assertTrue($result[0]->getPhonenumbers()->isInitialized()); $this->assertEquals(1, count($result[0]->getPhonenumbers())); $phones = $result[0]->getPhonenumbers(); @@ -555,22 +562,22 @@ public function testMixedNativeNamedQueryNormalJoin() $this->_em->clear(); - $repository = $this->_em->getRepository('Doctrine\Tests\Models\CMS\CmsUser'); + $repository = $this->_em->getRepository(CmsUser::class); $result = $repository->createNativeNamedQuery('fetchUserPhonenumberCount') - ->setParameter(1, array('test','FabioBatSilva'))->getResult(); + ->setParameter(1, ['test','FabioBatSilva'])->getResult(); $this->assertEquals(2, count($result)); $this->assertTrue(is_array($result[0])); $this->assertTrue(is_array($result[1])); // first user => 2 phonenumbers - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsUser', $result[0][0]); + $this->assertInstanceOf(CmsUser::class, $result[0][0]); $this->assertEquals('Fabio B. Silva', $result[0][0]->name); $this->assertEquals(2, $result[0]['numphones']); // second user => 1 phonenumbers - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsUser', $result[1][0]); + $this->assertInstanceOf(CmsUser::class, $result[1][0]); $this->assertEquals('test tester', $result[1][0]->name); $this->assertEquals(1, $result[1]['numphones']); } @@ -594,14 +601,14 @@ public function testNativeNamedQueryInheritance() $this->_em->flush(); $this->_em->clear(); - $repository = $this->_em->getRepository('Doctrine\Tests\Models\Company\CompanyPerson'); + $repository = $this->_em->getRepository(CompanyPerson::class); $result = $repository->createNativeNamedQuery('fetchAllWithSqlResultSetMapping') ->getResult(); $this->assertEquals(2, count($result)); - $this->assertInstanceOf('Doctrine\Tests\Models\Company\CompanyPerson', $result[0]); - $this->assertInstanceOf('Doctrine\Tests\Models\Company\CompanyEmployee', $result[1]); + $this->assertInstanceOf(CompanyPerson::class, $result[0]); + $this->assertInstanceOf(CompanyEmployee::class, $result[1]); $this->assertTrue(is_numeric($result[0]->getId())); $this->assertTrue(is_numeric($result[1]->getId())); $this->assertEquals('Fabio B. Silva', $result[0]->getName()); @@ -615,8 +622,8 @@ public function testNativeNamedQueryInheritance() ->getResult(); $this->assertEquals(2, count($result)); - $this->assertInstanceOf('Doctrine\Tests\Models\Company\CompanyPerson', $result[0]); - $this->assertInstanceOf('Doctrine\Tests\Models\Company\CompanyEmployee', $result[1]); + $this->assertInstanceOf(CompanyPerson::class, $result[0]); + $this->assertInstanceOf(CompanyEmployee::class, $result[1]); $this->assertTrue(is_numeric($result[0]->getId())); $this->assertTrue(is_numeric($result[1]->getId())); $this->assertEquals('Fabio B. Silva', $result[0]->getName()); @@ -655,7 +662,7 @@ public function testMultipleEntityResults() $this->_em->clear(); - $repository = $this->_em->getRepository('Doctrine\Tests\Models\CMS\CmsUser'); + $repository = $this->_em->getRepository(CmsUser::class); $query = $repository->createNativeNamedQuery('fetchMultipleJoinsEntityResults'); $result = $query->getResult(); @@ -663,9 +670,9 @@ public function testMultipleEntityResults() $this->assertEquals(1, count($result)); $this->assertTrue(is_array($result[0])); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsUser', $result[0][0]); + $this->assertInstanceOf(CmsUser::class, $result[0][0]); $this->assertEquals('Fabio B. Silva', $result[0][0]->name); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsAddress', $result[0][0]->getAddress()); + $this->assertInstanceOf(CmsAddress::class, $result[0][0]->getAddress()); $this->assertTrue($result[0][0]->getAddress()->getUser() == $result[0][0]); $this->assertEquals('Brazil', $result[0][0]->getAddress()->getCountry()); $this->assertEquals(10827, $result[0][0]->getAddress()->getZipCode()); @@ -679,8 +686,8 @@ public function testMultipleEntityResults() */ public function testNamedNativeQueryInheritance() { - $contractMetadata = $this->_em->getClassMetadata('Doctrine\Tests\Models\Company\CompanyContract'); - $flexMetadata = $this->_em->getClassMetadata('Doctrine\Tests\Models\Company\CompanyFlexContract'); + $contractMetadata = $this->_em->getClassMetadata(CompanyContract::class); + $flexMetadata = $this->_em->getClassMetadata(CompanyFlexContract::class); $contractQueries = $contractMetadata->getNamedNativeQueries(); $flexQueries = $flexMetadata->getNamedNativeQueries(); @@ -691,39 +698,39 @@ public function testNamedNativeQueryInheritance() // contract queries $this->assertEquals('all-contracts', $contractQueries['all-contracts']['name']); - $this->assertEquals('Doctrine\Tests\Models\Company\CompanyContract', $contractQueries['all-contracts']['resultClass']); + $this->assertEquals(CompanyContract::class, $contractQueries['all-contracts']['resultClass']); $this->assertEquals('all', $contractQueries['all']['name']); - $this->assertEquals('Doctrine\Tests\Models\Company\CompanyContract', $contractQueries['all']['resultClass']); + $this->assertEquals(CompanyContract::class, $contractQueries['all']['resultClass']); // flex contract queries $this->assertEquals('all-contracts', $flexQueries['all-contracts']['name']); - $this->assertEquals('Doctrine\Tests\Models\Company\CompanyFlexContract', $flexQueries['all-contracts']['resultClass']); + $this->assertEquals(CompanyFlexContract::class, $flexQueries['all-contracts']['resultClass']); $this->assertEquals('all-flex', $flexQueries['all-flex']['name']); - $this->assertEquals('Doctrine\Tests\Models\Company\CompanyFlexContract', $flexQueries['all-flex']['resultClass']); + $this->assertEquals(CompanyFlexContract::class, $flexQueries['all-flex']['resultClass']); $this->assertEquals('all', $flexQueries['all']['name']); - $this->assertEquals('Doctrine\Tests\Models\Company\CompanyFlexContract', $flexQueries['all']['resultClass']); + $this->assertEquals(CompanyFlexContract::class, $flexQueries['all']['resultClass']); // contract result mapping $this->assertEquals('mapping-all-contracts', $contractMappings['mapping-all-contracts']['name']); - $this->assertEquals('Doctrine\Tests\Models\Company\CompanyContract', $contractMappings['mapping-all-contracts']['entities'][0]['entityClass']); + $this->assertEquals(CompanyContract::class, $contractMappings['mapping-all-contracts']['entities'][0]['entityClass']); $this->assertEquals('mapping-all', $contractMappings['mapping-all']['name']); - $this->assertEquals('Doctrine\Tests\Models\Company\CompanyContract', $contractMappings['mapping-all-contracts']['entities'][0]['entityClass']); + $this->assertEquals(CompanyContract::class, $contractMappings['mapping-all-contracts']['entities'][0]['entityClass']); // flex contract result mapping $this->assertEquals('mapping-all-contracts', $flexMappings['mapping-all-contracts']['name']); - $this->assertEquals('Doctrine\Tests\Models\Company\CompanyFlexContract', $flexMappings['mapping-all-contracts']['entities'][0]['entityClass']); + $this->assertEquals(CompanyFlexContract::class, $flexMappings['mapping-all-contracts']['entities'][0]['entityClass']); $this->assertEquals('mapping-all', $flexMappings['mapping-all']['name']); - $this->assertEquals('Doctrine\Tests\Models\Company\CompanyFlexContract', $flexMappings['mapping-all']['entities'][0]['entityClass']); + $this->assertEquals(CompanyFlexContract::class, $flexMappings['mapping-all']['entities'][0]['entityClass']); $this->assertEquals('mapping-all-flex', $flexMappings['mapping-all-flex']['name']); - $this->assertEquals('Doctrine\Tests\Models\Company\CompanyFlexContract', $flexMappings['mapping-all-flex']['entities'][0]['entityClass']); + $this->assertEquals(CompanyFlexContract::class, $flexMappings['mapping-all-flex']['entities'][0]['entityClass']); } @@ -733,7 +740,7 @@ public function testNamedNativeQueryInheritance() public function testGenerateSelectClauseNoRenameSingleEntity() { $rsm = new ResultSetMappingBuilder($this->_em); - $rsm->addRootEntityFromClassMetadata('Doctrine\Tests\Models\CMS\CmsUser', 'u'); + $rsm->addRootEntityFromClassMetadata(CmsUser::class, 'u'); $selectClause = $rsm->generateSelectClause(); @@ -746,10 +753,11 @@ public function testGenerateSelectClauseNoRenameSingleEntity() public function testGenerateSelectClauseCustomRenames() { $rsm = new ResultSetMappingBuilder($this->_em); - $rsm->addRootEntityFromClassMetadata('Doctrine\Tests\Models\CMS\CmsUser', 'u', array( + $rsm->addRootEntityFromClassMetadata(CmsUser::class, 'u', [ 'id' => 'id1', 'username' => 'username2' - )); + ] + ); $selectClause = $rsm->generateSelectClause(); @@ -762,9 +770,9 @@ public function testGenerateSelectClauseCustomRenames() public function testGenerateSelectClauseRenameTableAlias() { $rsm = new ResultSetMappingBuilder($this->_em); - $rsm->addRootEntityFromClassMetadata('Doctrine\Tests\Models\CMS\CmsUser', 'u'); + $rsm->addRootEntityFromClassMetadata(CmsUser::class, 'u'); - $selectClause = $rsm->generateSelectClause(array('u' => 'u1')); + $selectClause = $rsm->generateSelectClause(['u' => 'u1']); $this->assertSQLEquals('u1.id AS id, u1.status AS status, u1.username AS username, u1.name AS name, u1.email_id AS email_id', $selectClause); } @@ -775,7 +783,7 @@ public function testGenerateSelectClauseRenameTableAlias() public function testGenerateSelectClauseIncrement() { $rsm = new ResultSetMappingBuilder($this->_em, ResultSetMappingBuilder::COLUMN_RENAMING_INCREMENT); - $rsm->addRootEntityFromClassMetadata('Doctrine\Tests\Models\CMS\CmsUser', 'u'); + $rsm->addRootEntityFromClassMetadata(CmsUser::class, 'u'); $selectClause = $rsm->generateSelectClause(); @@ -788,7 +796,7 @@ public function testGenerateSelectClauseIncrement() public function testGenerateSelectClauseToString() { $rsm = new ResultSetMappingBuilder($this->_em, ResultSetMappingBuilder::COLUMN_RENAMING_INCREMENT); - $rsm->addRootEntityFromClassMetadata('Doctrine\Tests\Models\CMS\CmsUser', 'u'); + $rsm->addRootEntityFromClassMetadata(CmsUser::class, 'u'); $this->assertSQLEquals('u.id AS id0, u.status AS status1, u.username AS username2, u.name AS name3, u.email_id AS email_id4', (string)$rsm); } @@ -799,12 +807,12 @@ public function testGenerateSelectClauseToString() public function testGenerateSelectClauseWithDiscriminatorColumn() { $rsm = new ResultSetMappingBuilder($this->_em, ResultSetMappingBuilder::COLUMN_RENAMING_INCREMENT); - $rsm->addEntityResult('Doctrine\Tests\Models\DDC3899\DDC3899User', 'u'); - $rsm->addJoinedEntityResult('Doctrine\Tests\Models\DDC3899\DDC3899FixContract', 'c', 'u', 'contracts'); + $rsm->addEntityResult(DDC3899User::class, 'u'); + $rsm->addJoinedEntityResult(DDC3899FixContract::class, 'c', 'u', 'contracts'); $rsm->addFieldResult('u', $this->platform->getSQLResultCasing('id'), 'id'); $rsm->setDiscriminatorColumn('c', $this->platform->getSQLResultCasing('discr')); - $selectClause = $rsm->generateSelectClause(array('u' => 'u1', 'c' => 'c1')); + $selectClause = $rsm->generateSelectClause(['u' => 'u1', 'c' => 'c1']); $this->assertSQLEquals('u1.id as id, c1.discr as discr', $selectClause); } diff --git a/tests/Doctrine/Tests/ORM/Functional/NewOperatorTest.php b/tests/Doctrine/Tests/ORM/Functional/NewOperatorTest.php index 37067aec075..1422dcd9a2c 100644 --- a/tests/Doctrine/Tests/ORM/Functional/NewOperatorTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/NewOperatorTest.php @@ -3,10 +3,12 @@ namespace Doctrine\Tests\ORM\Functional; use Doctrine\ORM\Query; +use Doctrine\Tests\Models\CMS\CmsAddressDTO; use Doctrine\Tests\Models\CMS\CmsUser; use Doctrine\Tests\Models\CMS\CmsEmail; use Doctrine\Tests\Models\CMS\CmsAddress; use Doctrine\Tests\Models\CMS\CmsPhonenumber; +use Doctrine\Tests\Models\CMS\CmsUserDTO; use Doctrine\Tests\OrmFunctionalTestCase; /** @@ -18,7 +20,7 @@ class NewOperatorTest extends OrmFunctionalTestCase * @var array */ private $fixtures; - + protected function setUp() { $this->useModelSet('cms'); @@ -26,13 +28,13 @@ protected function setUp() $this->loadFixtures(); } - + public function provideDataForHydrationMode() { - return array( - array(Query::HYDRATE_ARRAY), - array(Query::HYDRATE_OBJECT), - ); + return [ + [Query::HYDRATE_ARRAY], + [Query::HYDRATE_OBJECT], + ]; } private function loadFixtures() @@ -93,7 +95,7 @@ private function loadFixtures() $this->_em->flush(); $this->_em->clear(); - $this->fixtures = array($u1, $u2, $u3); + $this->fixtures = [$u1, $u2, $u3]; } /** @@ -122,9 +124,9 @@ public function testShouldSupportsBasicUsage($hydrationMode) $this->assertCount(3, $result); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsUserDTO', $result[0]); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsUserDTO', $result[1]); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsUserDTO', $result[2]); + $this->assertInstanceOf(CmsUserDTO::class, $result[0]); + $this->assertInstanceOf(CmsUserDTO::class, $result[1]); + $this->assertInstanceOf(CmsUserDTO::class, $result[2]); $this->assertEquals($this->fixtures[0]->name, $result[0]->name); $this->assertEquals($this->fixtures[1]->name, $result[1]->name); @@ -165,9 +167,9 @@ public function testShouldIgnoreAliasesForSingleObject($hydrationMode) $this->assertCount(3, $result); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsUserDTO', $result[0]); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsUserDTO', $result[1]); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsUserDTO', $result[2]); + $this->assertInstanceOf(CmsUserDTO::class, $result[0]); + $this->assertInstanceOf(CmsUserDTO::class, $result[1]); + $this->assertInstanceOf(CmsUserDTO::class, $result[2]); $this->assertEquals($this->fixtures[0]->name, $result[0]->name); $this->assertEquals($this->fixtures[1]->name, $result[1]->name); @@ -201,9 +203,9 @@ public function testShouldAssumeFromEntityNamespaceWhenNotGiven() $this->assertCount(3, $result); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsUserDTO', $result[0]); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsUserDTO', $result[1]); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsUserDTO', $result[2]); + $this->assertInstanceOf(CmsUserDTO::class, $result[0]); + $this->assertInstanceOf(CmsUserDTO::class, $result[1]); + $this->assertInstanceOf(CmsUserDTO::class, $result[2]); } public function testShouldSupportFromEntityNamespaceAlias() @@ -223,15 +225,15 @@ public function testShouldSupportFromEntityNamespaceAlias() $this->_em->getConfiguration() ->addEntityNamespace('cms', 'Doctrine\Tests\Models\CMS'); - + $query = $this->_em->createQuery($dql); $result = $query->getResult(); $this->assertCount(3, $result); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsUserDTO', $result[0]); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsUserDTO', $result[1]); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsUserDTO', $result[2]); + $this->assertInstanceOf(CmsUserDTO::class, $result[0]); + $this->assertInstanceOf(CmsUserDTO::class, $result[1]); + $this->assertInstanceOf(CmsUserDTO::class, $result[2]); } public function testShouldSupportValueObjectNamespaceAlias() @@ -257,9 +259,9 @@ public function testShouldSupportValueObjectNamespaceAlias() $this->assertCount(3, $result); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsUserDTO', $result[0]); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsUserDTO', $result[1]); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsUserDTO', $result[2]); + $this->assertInstanceOf(CmsUserDTO::class, $result[0]); + $this->assertInstanceOf(CmsUserDTO::class, $result[1]); + $this->assertInstanceOf(CmsUserDTO::class, $result[2]); } public function testShouldSupportLiteralExpression() @@ -290,9 +292,9 @@ public function testShouldSupportLiteralExpression() $this->assertCount(3, $result); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsUserDTO', $result[0]); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsUserDTO', $result[1]); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsUserDTO', $result[2]); + $this->assertInstanceOf(CmsUserDTO::class, $result[0]); + $this->assertInstanceOf(CmsUserDTO::class, $result[1]); + $this->assertInstanceOf(CmsUserDTO::class, $result[2]); $this->assertEquals($this->fixtures[0]->name, $result[0]->name); @@ -338,9 +340,9 @@ public function testShouldSupportCaseExpression() $this->assertCount(3, $result); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsUserDTO', $result[0]); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsUserDTO', $result[1]); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsUserDTO', $result[2]); + $this->assertInstanceOf(CmsUserDTO::class, $result[0]); + $this->assertInstanceOf(CmsUserDTO::class, $result[1]); + $this->assertInstanceOf(CmsUserDTO::class, $result[2]); $this->assertEquals($this->fixtures[0]->name, $result[0]->name); @@ -380,9 +382,9 @@ public function testShouldSupportSimpleArithmeticExpression() $this->assertCount(3, $result); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsUserDTO', $result[0]); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsUserDTO', $result[1]); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsUserDTO', $result[2]); + $this->assertInstanceOf(CmsUserDTO::class, $result[0]); + $this->assertInstanceOf(CmsUserDTO::class, $result[1]); + $this->assertInstanceOf(CmsUserDTO::class, $result[2]); $this->assertEquals($this->fixtures[0]->name, $result[0]->name); $this->assertEquals($this->fixtures[1]->name, $result[1]->name); @@ -440,9 +442,9 @@ public function testShouldSupportAggregateFunctions() $this->assertCount(3, $result); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsUserDTO', $result[0]); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsUserDTO', $result[1]); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsUserDTO', $result[2]); + $this->assertInstanceOf(CmsUserDTO::class, $result[0]); + $this->assertInstanceOf(CmsUserDTO::class, $result[1]); + $this->assertInstanceOf(CmsUserDTO::class, $result[2]); $this->assertEquals($this->fixtures[0]->name, $result[0]->name); $this->assertEquals($this->fixtures[1]->name, $result[1]->name); @@ -500,9 +502,9 @@ public function testShouldSupportArithmeticExpression() $this->assertCount(3, $result); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsUserDTO', $result[0]); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsUserDTO', $result[1]); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsUserDTO', $result[2]); + $this->assertInstanceOf(CmsUserDTO::class, $result[0]); + $this->assertInstanceOf(CmsUserDTO::class, $result[1]); + $this->assertInstanceOf(CmsUserDTO::class, $result[2]); $this->assertEquals($this->fixtures[0]->name, $result[0]->name); $this->assertEquals($this->fixtures[1]->name, $result[1]->name); @@ -558,13 +560,13 @@ public function testShouldSupportMultipleNewOperators() $this->assertCount(3, $result); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsUserDTO', $result[0][0]); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsUserDTO', $result[1][0]); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsUserDTO', $result[2][0]); + $this->assertInstanceOf(CmsUserDTO::class, $result[0][0]); + $this->assertInstanceOf(CmsUserDTO::class, $result[1][0]); + $this->assertInstanceOf(CmsUserDTO::class, $result[2][0]); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsAddressDTO', $result[0][1]); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsAddressDTO', $result[1][1]); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsAddressDTO', $result[2][1]); + $this->assertInstanceOf(CmsAddressDTO::class, $result[0][1]); + $this->assertInstanceOf(CmsAddressDTO::class, $result[1][1]); + $this->assertInstanceOf(CmsAddressDTO::class, $result[2][1]); $this->assertEquals($this->fixtures[0]->name, $result[0][0]->name); $this->assertEquals($this->fixtures[1]->name, $result[1][0]->name); @@ -610,13 +612,13 @@ public function testShouldSupportMultipleNewOperatorsWithAliases() $this->assertCount(3, $result); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsUserDTO', $result[0]['cmsUser']); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsUserDTO', $result[1]['cmsUser']); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsUserDTO', $result[2]['cmsUser']); + $this->assertInstanceOf(CmsUserDTO::class, $result[0]['cmsUser']); + $this->assertInstanceOf(CmsUserDTO::class, $result[1]['cmsUser']); + $this->assertInstanceOf(CmsUserDTO::class, $result[2]['cmsUser']); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsAddressDTO', $result[0]['cmsAddress']); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsAddressDTO', $result[1]['cmsAddress']); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsAddressDTO', $result[2]['cmsAddress']); + $this->assertInstanceOf(CmsAddressDTO::class, $result[0]['cmsAddress']); + $this->assertInstanceOf(CmsAddressDTO::class, $result[1]['cmsAddress']); + $this->assertInstanceOf(CmsAddressDTO::class, $result[2]['cmsAddress']); $this->assertEquals($this->fixtures[0]->name, $result[0]['cmsUser']->name); $this->assertEquals($this->fixtures[1]->name, $result[1]['cmsUser']->name); @@ -662,13 +664,13 @@ public function testShouldSupportMultipleNewOperatorsWithAndWithoutAliases() $this->assertCount(3, $result); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsUserDTO', $result[0]['cmsUser']); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsUserDTO', $result[1]['cmsUser']); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsUserDTO', $result[2]['cmsUser']); + $this->assertInstanceOf(CmsUserDTO::class, $result[0]['cmsUser']); + $this->assertInstanceOf(CmsUserDTO::class, $result[1]['cmsUser']); + $this->assertInstanceOf(CmsUserDTO::class, $result[2]['cmsUser']); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsAddressDTO', $result[0][0]); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsAddressDTO', $result[1][0]); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsAddressDTO', $result[2][0]); + $this->assertInstanceOf(CmsAddressDTO::class, $result[0][0]); + $this->assertInstanceOf(CmsAddressDTO::class, $result[1][0]); + $this->assertInstanceOf(CmsAddressDTO::class, $result[2][0]); $this->assertEquals($this->fixtures[0]->name, $result[0]['cmsUser']->name); $this->assertEquals($this->fixtures[1]->name, $result[1]['cmsUser']->name); @@ -715,13 +717,13 @@ public function testShouldSupportMultipleNewOperatorsAndSingleScalar() $this->assertCount(3, $result); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsUserDTO', $result[0][0]); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsUserDTO', $result[1][0]); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsUserDTO', $result[2][0]); + $this->assertInstanceOf(CmsUserDTO::class, $result[0][0]); + $this->assertInstanceOf(CmsUserDTO::class, $result[1][0]); + $this->assertInstanceOf(CmsUserDTO::class, $result[2][0]); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsAddressDTO', $result[0][1]); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsAddressDTO', $result[1][1]); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsAddressDTO', $result[2][1]); + $this->assertInstanceOf(CmsAddressDTO::class, $result[0][1]); + $this->assertInstanceOf(CmsAddressDTO::class, $result[1][1]); + $this->assertInstanceOf(CmsAddressDTO::class, $result[2][1]); $this->assertEquals($this->fixtures[0]->name, $result[0][0]->name); $this->assertEquals($this->fixtures[1]->name, $result[1][0]->name); @@ -772,13 +774,13 @@ public function testShouldSupportMultipleNewOperatorsAndSingleScalarWithAliases( $this->assertCount(3, $result); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsUserDTO', $result[0]['cmsUser']); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsUserDTO', $result[1]['cmsUser']); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsUserDTO', $result[2]['cmsUser']); + $this->assertInstanceOf(CmsUserDTO::class, $result[0]['cmsUser']); + $this->assertInstanceOf(CmsUserDTO::class, $result[1]['cmsUser']); + $this->assertInstanceOf(CmsUserDTO::class, $result[2]['cmsUser']); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsAddressDTO', $result[0]['cmsAddress']); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsAddressDTO', $result[1]['cmsAddress']); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsAddressDTO', $result[2]['cmsAddress']); + $this->assertInstanceOf(CmsAddressDTO::class, $result[0]['cmsAddress']); + $this->assertInstanceOf(CmsAddressDTO::class, $result[1]['cmsAddress']); + $this->assertInstanceOf(CmsAddressDTO::class, $result[2]['cmsAddress']); $this->assertEquals($this->fixtures[0]->name, $result[0]['cmsUser']->name); $this->assertEquals($this->fixtures[1]->name, $result[1]['cmsUser']->name); @@ -829,13 +831,13 @@ public function testShouldSupportMultipleNewOperatorsAndSingleScalarWithAndWitho $this->assertCount(3, $result); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsUserDTO', $result[0]['cmsUser']); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsUserDTO', $result[1]['cmsUser']); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsUserDTO', $result[2]['cmsUser']); + $this->assertInstanceOf(CmsUserDTO::class, $result[0]['cmsUser']); + $this->assertInstanceOf(CmsUserDTO::class, $result[1]['cmsUser']); + $this->assertInstanceOf(CmsUserDTO::class, $result[2]['cmsUser']); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsAddressDTO', $result[0][0]); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsAddressDTO', $result[1][0]); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsAddressDTO', $result[2][0]); + $this->assertInstanceOf(CmsAddressDTO::class, $result[0][0]); + $this->assertInstanceOf(CmsAddressDTO::class, $result[1][0]); + $this->assertInstanceOf(CmsAddressDTO::class, $result[2][0]); $this->assertEquals($this->fixtures[0]->name, $result[0]['cmsUser']->name); $this->assertEquals($this->fixtures[1]->name, $result[1]['cmsUser']->name); @@ -887,13 +889,13 @@ public function testShouldSupportMultipleNewOperatorsAndMultipleScalars() $this->assertCount(3, $result); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsUserDTO', $result[0][0]); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsUserDTO', $result[1][0]); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsUserDTO', $result[2][0]); + $this->assertInstanceOf(CmsUserDTO::class, $result[0][0]); + $this->assertInstanceOf(CmsUserDTO::class, $result[1][0]); + $this->assertInstanceOf(CmsUserDTO::class, $result[2][0]); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsAddressDTO', $result[0][1]); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsAddressDTO', $result[1][1]); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsAddressDTO', $result[2][1]); + $this->assertInstanceOf(CmsAddressDTO::class, $result[0][1]); + $this->assertInstanceOf(CmsAddressDTO::class, $result[1][1]); + $this->assertInstanceOf(CmsAddressDTO::class, $result[2][1]); $this->assertEquals($this->fixtures[0]->name, $result[0][0]->name); $this->assertEquals($this->fixtures[1]->name, $result[1][0]->name); @@ -949,13 +951,13 @@ public function testShouldSupportMultipleNewOperatorsAndMultipleScalarsWithAlias $this->assertCount(3, $result); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsUserDTO', $result[0]['cmsUser']); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsUserDTO', $result[1]['cmsUser']); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsUserDTO', $result[2]['cmsUser']); + $this->assertInstanceOf(CmsUserDTO::class, $result[0]['cmsUser']); + $this->assertInstanceOf(CmsUserDTO::class, $result[1]['cmsUser']); + $this->assertInstanceOf(CmsUserDTO::class, $result[2]['cmsUser']); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsAddressDTO', $result[0]['cmsAddress']); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsAddressDTO', $result[1]['cmsAddress']); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsAddressDTO', $result[2]['cmsAddress']); + $this->assertInstanceOf(CmsAddressDTO::class, $result[0]['cmsAddress']); + $this->assertInstanceOf(CmsAddressDTO::class, $result[1]['cmsAddress']); + $this->assertInstanceOf(CmsAddressDTO::class, $result[2]['cmsAddress']); $this->assertEquals($this->fixtures[0]->name, $result[0]['cmsUser']->name); $this->assertEquals($this->fixtures[1]->name, $result[1]['cmsUser']->name); @@ -1011,13 +1013,13 @@ public function testShouldSupportMultipleNewOperatorsAndMultipleScalarsWithAndWi $this->assertCount(3, $result); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsUserDTO', $result[0]['cmsUser']); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsUserDTO', $result[1]['cmsUser']); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsUserDTO', $result[2]['cmsUser']); + $this->assertInstanceOf(CmsUserDTO::class, $result[0]['cmsUser']); + $this->assertInstanceOf(CmsUserDTO::class, $result[1]['cmsUser']); + $this->assertInstanceOf(CmsUserDTO::class, $result[2]['cmsUser']); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsAddressDTO', $result[0][0]); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsAddressDTO', $result[1][0]); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsAddressDTO', $result[2][0]); + $this->assertInstanceOf(CmsAddressDTO::class, $result[0][0]); + $this->assertInstanceOf(CmsAddressDTO::class, $result[1][0]); + $this->assertInstanceOf(CmsAddressDTO::class, $result[2][0]); $this->assertEquals($this->fixtures[0]->name, $result[0]['cmsUser']->name); $this->assertEquals($this->fixtures[1]->name, $result[1]['cmsUser']->name); diff --git a/tests/Doctrine/Tests/ORM/Functional/NotifyPolicyTest.php b/tests/Doctrine/Tests/ORM/Functional/NotifyPolicyTest.php index ecebc28d9e3..5444af6710e 100644 --- a/tests/Doctrine/Tests/ORM/Functional/NotifyPolicyTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/NotifyPolicyTest.php @@ -18,10 +18,12 @@ protected function setUp() { parent::setUp(); try { - $this->_schemaTool->createSchema(array( - $this->_em->getClassMetadata('Doctrine\Tests\ORM\Functional\NotifyUser'), - $this->_em->getClassMetadata('Doctrine\Tests\ORM\Functional\NotifyGroup') - )); + $this->_schemaTool->createSchema( + [ + $this->_em->getClassMetadata(NotifyUser::class), + $this->_em->getClassMetadata(NotifyGroup::class) + ] + ); } catch (\Exception $e) { // Swallow all exceptions. We do not test the schema tool here. } @@ -29,8 +31,6 @@ protected function setUp() public function testChangeTracking() { - //$this->_em->getConnection()->getConfiguration()->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger); - $user = new NotifyUser(); $group = new NotifyGroup(); $user->setName('roman'); @@ -55,9 +55,9 @@ public function testChangeTracking() $groupId = $group->getId(); unset($user, $group); - $user = $this->_em->find(__NAMESPACE__.'\NotifyUser', $userId); + $user = $this->_em->find(NotifyUser::class, $userId); $this->assertEquals(1, $user->getGroups()->count()); - $group = $this->_em->find(__NAMESPACE__.'\NotifyGroup', $groupId); + $group = $this->_em->find(NotifyGroup::class, $groupId); $this->assertEquals(1, $group->getUsers()->count()); $this->assertEquals(1, count($user->listeners)); @@ -80,18 +80,18 @@ public function testChangeTracking() $group2Id = $group2->getId(); unset($group2, $user); - $user = $this->_em->find(__NAMESPACE__.'\NotifyUser', $userId); + $user = $this->_em->find(NotifyUser::class, $userId); $this->assertEquals(2, $user->getGroups()->count()); - $group2 = $this->_em->find(__NAMESPACE__.'\NotifyGroup', $group2Id); + $group2 = $this->_em->find(NotifyGroup::class, $group2Id); $this->assertEquals(1, $group2->getUsers()->count()); - $group = $this->_em->find(__NAMESPACE__.'\NotifyGroup', $groupId); + $group = $this->_em->find(NotifyGroup::class, $groupId); $this->assertEquals(1, $group->getUsers()->count()); $this->assertEquals('geeks', $group->getName()); } } class NotifyBaseEntity implements NotifyPropertyChanged { - public $listeners = array(); + public $listeners = []; public function addPropertyChangedListener(PropertyChangedListener $listener) { $this->listeners[] = $listener; diff --git a/tests/Doctrine/Tests/ORM/Functional/OneToManyBidirectionalAssociationTest.php b/tests/Doctrine/Tests/ORM/Functional/OneToManyBidirectionalAssociationTest.php index 8327142fda6..95309c60579 100644 --- a/tests/Doctrine/Tests/ORM/Functional/OneToManyBidirectionalAssociationTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/OneToManyBidirectionalAssociationTest.php @@ -2,9 +2,11 @@ namespace Doctrine\Tests\ORM\Functional; -use Doctrine\Tests\Models\ECommerce\ECommerceProduct; -use Doctrine\Tests\Models\ECommerce\ECommerceFeature; +use Doctrine\Common\Collections\Collection; use Doctrine\Common\Collections\Criteria; +use Doctrine\ORM\Proxy\Proxy; +use Doctrine\Tests\Models\ECommerce\ECommerceFeature; +use Doctrine\Tests\Models\ECommerce\ECommerceProduct; use Doctrine\Tests\OrmFunctionalTestCase; /** @@ -76,13 +78,13 @@ public function testEagerLoadsOneToManyAssociation() $features = $product->getFeatures(); - $this->assertInstanceOf('Doctrine\Tests\Models\ECommerce\ECommerceFeature', $features[0]); - $this->assertNotInstanceOf('Doctrine\ORM\Proxy\Proxy', $features[0]->getProduct()); + $this->assertInstanceOf(ECommerceFeature::class, $features[0]); + $this->assertNotInstanceOf(Proxy::class, $features[0]->getProduct()); $this->assertSame($product, $features[0]->getProduct()); $this->assertEquals('Model writing tutorial', $features[0]->getDescription()); - $this->assertInstanceOf('Doctrine\Tests\Models\ECommerce\ECommerceFeature', $features[1]); + $this->assertInstanceOf(ECommerceFeature::class, $features[1]); $this->assertSame($product, $features[1]->getProduct()); - $this->assertNotInstanceOf('Doctrine\ORM\Proxy\Proxy', $features[1]->getProduct()); + $this->assertNotInstanceOf(Proxy::class, $features[1]->getProduct()); $this->assertEquals('Annotations examples', $features[1]->getDescription()); } @@ -96,11 +98,11 @@ public function testLazyLoadsObjectsOnTheOwningSide() $features = $product->getFeatures(); $this->assertFalse($features->isInitialized()); - $this->assertInstanceOf('Doctrine\Tests\Models\ECommerce\ECommerceFeature', $features[0]); + $this->assertInstanceOf(ECommerceFeature::class, $features[0]); $this->assertTrue($features->isInitialized()); $this->assertSame($product, $features[0]->getProduct()); $this->assertEquals('Model writing tutorial', $features[0]->getDescription()); - $this->assertInstanceOf('Doctrine\Tests\Models\ECommerce\ECommerceFeature', $features[1]); + $this->assertInstanceOf(ECommerceFeature::class, $features[1]); $this->assertSame($product, $features[1]->getProduct()); $this->assertEquals('Annotations examples', $features[1]->getDescription()); } @@ -113,8 +115,8 @@ public function testLazyLoadsObjectsOnTheInverseSide() $features = $query->getResult(); $product = $features[0]->getProduct(); - $this->assertInstanceOf('Doctrine\ORM\Proxy\Proxy', $product); - $this->assertInstanceOf('Doctrine\Tests\Models\ECommerce\ECommerceProduct', $product); + $this->assertInstanceOf(Proxy::class, $product); + $this->assertInstanceOf(ECommerceProduct::class, $product); $this->assertFalse($product->__isInitialized__); $this->assertSame('Doctrine Cookbook', $product->getName()); $this->assertTrue($product->__isInitialized__); @@ -129,8 +131,8 @@ public function testLazyLoadsObjectsOnTheInverseSide2() $features = $query->getResult(); $product = $features[0]->getProduct(); - $this->assertNotInstanceOf('Doctrine\ORM\Proxy\Proxy', $product); - $this->assertInstanceOf('Doctrine\Tests\Models\ECommerce\ECommerceProduct', $product); + $this->assertNotInstanceOf(Proxy::class, $product); + $this->assertInstanceOf(ECommerceProduct::class, $product); $this->assertSame('Doctrine Cookbook', $product->getName()); $this->assertFalse($product->getFeatures()->isInitialized()); @@ -157,19 +159,19 @@ public function testMatching() { $this->_createFixture(); - $product = $this->_em->find('Doctrine\Tests\Models\ECommerce\ECommerceProduct', $this->product->getId()); + $product = $this->_em->find(ECommerceProduct::class, $this->product->getId()); $features = $product->getFeatures(); $results = $features->matching(new Criteria( Criteria::expr()->eq('description', 'Model writing tutorial') )); - $this->assertInstanceOf('Doctrine\Common\Collections\Collection', $results); + $this->assertInstanceOf(Collection::class, $results); $this->assertEquals(1, count($results)); $results = $features->matching(new Criteria()); - $this->assertInstanceOf('Doctrine\Common\Collections\Collection', $results); + $this->assertInstanceOf(Collection::class, $results); $this->assertEquals(2, count($results)); } @@ -180,7 +182,7 @@ public function testMatchingOnDirtyCollection() { $this->_createFixture(); - $product = $this->_em->find('Doctrine\Tests\Models\ECommerce\ECommerceProduct', $this->product->getId()); + $product = $this->_em->find(ECommerceProduct::class, $this->product->getId()); $thirdFeature = new ECommerceFeature(); $thirdFeature->setDescription('Model writing tutorial'); @@ -199,7 +201,7 @@ public function testMatchingBis() { $this->_createFixture(); - $product = $this->_em->find('Doctrine\Tests\Models\ECommerce\ECommerceProduct', $this->product->getId()); + $product = $this->_em->find(ECommerceProduct::class, $this->product->getId()); $features = $product->getFeatures(); $thirdFeature = new ECommerceFeature(); @@ -210,12 +212,12 @@ public function testMatchingBis() Criteria::expr()->eq('description', 'Third feature') )); - $this->assertInstanceOf('Doctrine\Common\Collections\Collection', $results); + $this->assertInstanceOf(Collection::class, $results); $this->assertCount(1, $results); $results = $features->matching(new Criteria()); - $this->assertInstanceOf('Doctrine\Common\Collections\Collection', $results); + $this->assertInstanceOf(Collection::class, $results); $this->assertCount(3, $results); } @@ -232,7 +234,7 @@ private function _createFixture() public function assertFeatureForeignKeyIs($value, ECommerceFeature $feature) { $foreignKey = $this->_em->getConnection()->executeQuery( 'SELECT product_id FROM ecommerce_features WHERE id=?', - array($feature->getId()) + [$feature->getId()] )->fetchColumn(); $this->assertEquals($value, $foreignKey); } diff --git a/tests/Doctrine/Tests/ORM/Functional/OneToManyOrphanRemovalTest.php b/tests/Doctrine/Tests/ORM/Functional/OneToManyOrphanRemovalTest.php index d22dbd4e2c3..da70672b6d2 100644 --- a/tests/Doctrine/Tests/ORM/Functional/OneToManyOrphanRemovalTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/OneToManyOrphanRemovalTest.php @@ -2,8 +2,8 @@ namespace Doctrine\Tests\ORM\Functional; -use Doctrine\Tests\Models\CMS\CmsUser, - Doctrine\Tests\Models\CMS\CmsPhonenumber; +use Doctrine\Tests\Models\CMS\CmsPhonenumber; +use Doctrine\Tests\Models\CMS\CmsUser; use Doctrine\Tests\OrmFunctionalTestCase; /** @@ -42,7 +42,7 @@ protected function setUp() public function testOrphanRemoval() { - $userProxy = $this->_em->getReference('Doctrine\Tests\Models\CMS\CmsUser', $this->userId); + $userProxy = $this->_em->getReference(CmsUser::class, $this->userId); $this->_em->remove($userProxy); $this->_em->flush(); @@ -64,7 +64,7 @@ public function testOrphanRemoval() */ public function testOrphanRemovalRemoveFromCollection() { - $user = $this->_em->find('Doctrine\Tests\Models\CMS\CmsUser', $this->userId); + $user = $this->_em->find(CmsUser::class, $this->userId); $phonenumber = $user->getPhonenumbers()->remove(0); @@ -82,7 +82,7 @@ public function testOrphanRemovalRemoveFromCollection() */ public function testOrphanRemovalClearCollectionAndReAdd() { - $user = $this->_em->find('Doctrine\Tests\Models\CMS\CmsUser', $this->userId); + $user = $this->_em->find(CmsUser::class, $this->userId); $phone1 = $user->getPhonenumbers()->first(); @@ -102,7 +102,7 @@ public function testOrphanRemovalClearCollectionAndReAdd() */ public function testOrphanRemovalClearCollectionAndAddNew() { - $user = $this->_em->find('Doctrine\Tests\Models\CMS\CmsUser', $this->userId); + $user = $this->_em->find(CmsUser::class, $this->userId); $newPhone = new CmsPhonenumber(); $newPhone->phonenumber = '654321'; @@ -123,7 +123,7 @@ public function testOrphanRemovalClearCollectionAndAddNew() */ public function testOrphanRemovalUnitializedCollection() { - $user = $this->_em->find('Doctrine\Tests\Models\CMS\CmsUser', $this->userId); + $user = $this->_em->find(CmsUser::class, $this->userId); $user->phonenumbers->clear(); $this->_em->flush(); diff --git a/tests/Doctrine/Tests/ORM/Functional/OneToManySelfReferentialAssociationTest.php b/tests/Doctrine/Tests/ORM/Functional/OneToManySelfReferentialAssociationTest.php index 3d6c688bd2e..c9f42237d19 100644 --- a/tests/Doctrine/Tests/ORM/Functional/OneToManySelfReferentialAssociationTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/OneToManySelfReferentialAssociationTest.php @@ -2,9 +2,9 @@ namespace Doctrine\Tests\ORM\Functional; -use Doctrine\Tests\Models\ECommerce\ECommerceCategory; use Doctrine\ORM\Mapping\AssociationMapping; use Doctrine\ORM\Mapping\ClassMetadata; +use Doctrine\Tests\Models\ECommerce\ECommerceCategory; use Doctrine\Tests\OrmFunctionalTestCase; /** @@ -78,10 +78,10 @@ public function testEagerLoadsOneToManyAssociation() $parent = $result[0]; $children = $parent->getChildren(); - $this->assertInstanceOf('Doctrine\Tests\Models\ECommerce\ECommerceCategory', $children[0]); + $this->assertInstanceOf(ECommerceCategory::class, $children[0]); $this->assertSame($parent, $children[0]->getParent()); $this->assertEquals(' books', strstr($children[0]->getName(), ' books')); - $this->assertInstanceOf('Doctrine\Tests\Models\ECommerce\ECommerceCategory', $children[1]); + $this->assertInstanceOf(ECommerceCategory::class, $children[1]); $this->assertSame($parent, $children[1]->getParent()); $this->assertEquals(' books', strstr($children[1]->getName(), ' books')); } @@ -89,7 +89,7 @@ public function testEagerLoadsOneToManyAssociation() public function testLazyLoadsOneToManyAssociation() { $this->_createFixture(); - $metadata = $this->_em->getClassMetadata('Doctrine\Tests\Models\ECommerce\ECommerceCategory'); + $metadata = $this->_em->getClassMetadata(ECommerceCategory::class); $metadata->associationMappings['children']['fetch'] = ClassMetadata::FETCH_LAZY; $query = $this->_em->createQuery('select c from Doctrine\Tests\Models\ECommerce\ECommerceCategory c order by c.id asc'); @@ -97,10 +97,10 @@ public function testLazyLoadsOneToManyAssociation() $parent = $result[0]; $children = $parent->getChildren(); - $this->assertInstanceOf('Doctrine\Tests\Models\ECommerce\ECommerceCategory', $children[0]); + $this->assertInstanceOf(ECommerceCategory::class, $children[0]); $this->assertSame($parent, $children[0]->getParent()); $this->assertEquals(' books', strstr($children[0]->getName(), ' books')); - $this->assertInstanceOf('Doctrine\Tests\Models\ECommerce\ECommerceCategory', $children[1]); + $this->assertInstanceOf(ECommerceCategory::class, $children[1]); $this->assertSame($parent, $children[1]->getParent()); $this->assertEquals(' books', strstr($children[1]->getName(), ' books')); } @@ -116,7 +116,8 @@ private function _createFixture() } public function assertForeignKeyIs($value, ECommerceCategory $child) { - $foreignKey = $this->_em->getConnection()->executeQuery('SELECT parent_id FROM ecommerce_categories WHERE id=?', array($child->getId()))->fetchColumn(); + $foreignKey = $this->_em->getConnection()->executeQuery('SELECT parent_id FROM ecommerce_categories WHERE id=?', [$child->getId()] + )->fetchColumn(); $this->assertEquals($value, $foreignKey); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/OneToManyUnidirectionalAssociationTest.php b/tests/Doctrine/Tests/ORM/Functional/OneToManyUnidirectionalAssociationTest.php index e2c66311817..c13a6fe9971 100644 --- a/tests/Doctrine/Tests/ORM/Functional/OneToManyUnidirectionalAssociationTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/OneToManyUnidirectionalAssociationTest.php @@ -12,14 +12,14 @@ */ class OneToManyUnidirectionalAssociationTest extends OrmFunctionalTestCase { - protected $locations = array(); + protected $locations = []; public function setUp() { $this->useModelSet('routing'); parent::setUp(); - $locations = array("Berlin", "Bonn", "Brasilia", "Atlanta"); + $locations = ["Berlin", "Bonn", "Brasilia", "Atlanta"]; foreach ($locations AS $locationName) { $location = new RoutingLocation(); diff --git a/tests/Doctrine/Tests/ORM/Functional/OneToOneBidirectionalAssociationTest.php b/tests/Doctrine/Tests/ORM/Functional/OneToOneBidirectionalAssociationTest.php index 6d42e76348d..c989e126c44 100644 --- a/tests/Doctrine/Tests/ORM/Functional/OneToOneBidirectionalAssociationTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/OneToOneBidirectionalAssociationTest.php @@ -2,10 +2,11 @@ namespace Doctrine\Tests\ORM\Functional; -use Doctrine\Tests\Models\ECommerce\ECommerceCart; -use Doctrine\Tests\Models\ECommerce\ECommerceCustomer; use Doctrine\ORM\Mapping\AssociationMapping; use Doctrine\ORM\Mapping\ClassMetadata; +use Doctrine\ORM\Proxy\Proxy; +use Doctrine\Tests\Models\ECommerce\ECommerceCart; +use Doctrine\Tests\Models\ECommerce\ECommerceCustomer; use Doctrine\Tests\OrmFunctionalTestCase; /** @@ -61,27 +62,27 @@ public function testEagerLoad() $result = $query->getResult(); $customer = $result[0]; - $this->assertInstanceOf('Doctrine\Tests\Models\ECommerce\ECommerceCart', $customer->getCart()); + $this->assertInstanceOf(ECommerceCart::class, $customer->getCart()); $this->assertEquals('paypal', $customer->getCart()->getPayment()); } public function testLazyLoadsObjectsOnTheOwningSide() { $this->_createFixture(); - $metadata = $this->_em->getClassMetadata('Doctrine\Tests\Models\ECommerce\ECommerceCart'); + $metadata = $this->_em->getClassMetadata(ECommerceCart::class); $metadata->associationMappings['customer']['fetchMode'] = ClassMetadata::FETCH_LAZY; $query = $this->_em->createQuery('select c from Doctrine\Tests\Models\ECommerce\ECommerceCart c'); $result = $query->getResult(); $cart = $result[0]; - $this->assertInstanceOf('Doctrine\Tests\Models\ECommerce\ECommerceCustomer', $cart->getCustomer()); + $this->assertInstanceOf(ECommerceCustomer::class, $cart->getCustomer()); $this->assertEquals('Giorgio', $cart->getCustomer()->getName()); } public function testInverseSideIsNeverLazy() { $this->_createFixture(); - $metadata = $this->_em->getClassMetadata('Doctrine\Tests\Models\ECommerce\ECommerceCustomer'); + $metadata = $this->_em->getClassMetadata(ECommerceCustomer::class); $metadata->associationMappings['mentor']['fetch'] = ClassMetadata::FETCH_EAGER; $query = $this->_em->createQuery('select c from Doctrine\Tests\Models\ECommerce\ECommerceCustomer c'); @@ -89,8 +90,8 @@ public function testInverseSideIsNeverLazy() $customer = $result[0]; $this->assertNull($customer->getMentor()); - $this->assertInstanceOf('Doctrine\Tests\Models\ECommerce\ECommerceCart', $customer->getCart()); - $this->assertNotInstanceOf('Doctrine\ORM\Proxy\Proxy', $customer->getCart()); + $this->assertInstanceOf(ECommerceCart::class, $customer->getCart()); + $this->assertNotInstanceOf(Proxy::class, $customer->getCart()); $this->assertEquals('paypal', $customer->getCart()->getPayment()); } @@ -106,7 +107,7 @@ public function testUpdateWithProxyObject() $this->_em->flush(); $this->_em->clear(); - $this->assertInstanceOf('Doctrine\Tests\Models\ECommerce\ECommerceCart', $cust->getCart()); + $this->assertInstanceOf(ECommerceCart::class, $cust->getCart()); $this->assertEquals('Roman', $cust->getName()); $this->assertSame($cust, $cart->getCustomer()); @@ -125,7 +126,7 @@ public function testUpdateWithProxyObject() $cart3 = $query2->getSingleResult(); - $this->assertInstanceOf('Doctrine\Tests\Models\ECommerce\ECommerceCustomer', $cart3->getCustomer()); + $this->assertInstanceOf(ECommerceCustomer::class, $cart3->getCustomer()); $this->assertEquals('Roman', $cart3->getCustomer()->getName()); } @@ -144,7 +145,8 @@ protected function _createFixture() } public function assertCartForeignKeyIs($value) { - $foreignKey = $this->_em->getConnection()->executeQuery('SELECT customer_id FROM ecommerce_carts WHERE id=?', array($this->cart->getId()))->fetchColumn(); + $foreignKey = $this->_em->getConnection()->executeQuery('SELECT customer_id FROM ecommerce_carts WHERE id=?', [$this->cart->getId()] + )->fetchColumn(); $this->assertEquals($value, $foreignKey); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/OneToOneEagerLoadingTest.php b/tests/Doctrine/Tests/ORM/Functional/OneToOneEagerLoadingTest.php index 522a009eba8..5b4cdffdfe5 100644 --- a/tests/Doctrine/Tests/ORM/Functional/OneToOneEagerLoadingTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/OneToOneEagerLoadingTest.php @@ -2,6 +2,7 @@ namespace Doctrine\Tests\ORM\Functional; use Doctrine\Common\Collections\ArrayCollection; +use Doctrine\ORM\Proxy\Proxy; use Doctrine\ORM\Tools\SchemaTool; use Doctrine\Tests\OrmFunctionalTestCase; @@ -15,13 +16,15 @@ protected function setUp() parent::setUp(); $schemaTool = new SchemaTool($this->_em); try { - $schemaTool->createSchema(array( - $this->_em->getClassMetadata('Doctrine\Tests\ORM\Functional\Train'), - $this->_em->getClassMetadata('Doctrine\Tests\ORM\Functional\TrainDriver'), - $this->_em->getClassMetadata('Doctrine\Tests\ORM\Functional\TrainOwner'), - $this->_em->getClassMetadata('Doctrine\Tests\ORM\Functional\Waggon'), - $this->_em->getClassMetadata('Doctrine\Tests\ORM\Functional\TrainOrder'), - )); + $schemaTool->createSchema( + [ + $this->_em->getClassMetadata(Train::class), + $this->_em->getClassMetadata(TrainDriver::class), + $this->_em->getClassMetadata(TrainOwner::class), + $this->_em->getClassMetadata(Waggon::class), + $this->_em->getClassMetadata(TrainOrder::class), + ] + ); } catch(\Exception $e) {} } @@ -44,7 +47,7 @@ public function testEagerLoadOneToOneOwningSide() $sqlCount = count($this->_sqlLoggerStack->queries); $train = $this->_em->find(get_class($train), $train->id); - $this->assertNotInstanceOf('Doctrine\ORM\Proxy\Proxy', $train->driver); + $this->assertNotInstanceOf(Proxy::class, $train->driver); $this->assertEquals("Benjamin", $train->driver->name); $this->assertEquals($sqlCount + 1, count($this->_sqlLoggerStack->queries)); @@ -64,7 +67,7 @@ public function testEagerLoadOneToOneNullOwningSide() $sqlCount = count($this->_sqlLoggerStack->queries); $train = $this->_em->find(get_class($train), $train->id); - $this->assertNotInstanceOf('Doctrine\ORM\Proxy\Proxy', $train->driver); + $this->assertNotInstanceOf(Proxy::class, $train->driver); $this->assertNull($train->driver); $this->assertEquals($sqlCount + 1, count($this->_sqlLoggerStack->queries)); @@ -85,7 +88,7 @@ public function testEagerLoadOneToOneInverseSide() $sqlCount = count($this->_sqlLoggerStack->queries); $driver = $this->_em->find(get_class($owner), $owner->id); - $this->assertNotInstanceOf('Doctrine\ORM\Proxy\Proxy', $owner->train); + $this->assertNotInstanceOf(Proxy::class, $owner->train); $this->assertNotNull($owner->train); $this->assertEquals($sqlCount + 1, count($this->_sqlLoggerStack->queries)); @@ -107,7 +110,7 @@ public function testEagerLoadOneToOneNullInverseSide() $sqlCount = count($this->_sqlLoggerStack->queries); $driver = $this->_em->find(get_class($driver), $driver->id); - $this->assertNotInstanceOf('Doctrine\ORM\Proxy\Proxy', $driver->train); + $this->assertNotInstanceOf(Proxy::class, $driver->train); $this->assertNull($driver->train); $this->assertEquals($sqlCount + 1, count($this->_sqlLoggerStack->queries)); @@ -124,7 +127,7 @@ public function testEagerLoadManyToOne() $this->_em->clear(); $waggon = $this->_em->find(get_class($waggon), $waggon->id); - $this->assertNotInstanceOf('Doctrine\ORM\Proxy\Proxy', $waggon->train); + $this->assertNotInstanceOf(Proxy::class, $waggon->train); $this->assertNotNull($waggon->train); } diff --git a/tests/Doctrine/Tests/ORM/Functional/OneToOneInverseSideLoadAfterDqlQueryTest.php b/tests/Doctrine/Tests/ORM/Functional/OneToOneInverseSideLoadAfterDqlQueryTest.php new file mode 100644 index 00000000000..85e518efa78 --- /dev/null +++ b/tests/Doctrine/Tests/ORM/Functional/OneToOneInverseSideLoadAfterDqlQueryTest.php @@ -0,0 +1,70 @@ +_schemaTool->createSchema([ + $this->_em->getClassMetadata(OwningSide::class), + $this->_em->getClassMetadata(InverseSide::class), + ]); + } catch(ToolsException $e) { + // ignored + } + } + + /** + * @group 6759 + */ + public function testInverseSideOneToOneLoadedAfterDqlQuery(): void + { + $owner = new OwningSide(); + $inverse = new InverseSide(); + + $owner->id = 'owner'; + $inverse->id = 'inverse'; + $owner->inverse = $inverse; + $inverse->owning = $owner; + + $this->_em->persist($owner); + $this->_em->persist($inverse); + $this->_em->flush(); + $this->_em->clear(); + + /* @var $fetchedInverse InverseSide */ + $fetchedInverse = $this + ->_em + ->createQueryBuilder() + ->select('inverse') + ->from(InverseSide::class, 'inverse') + ->andWhere('inverse.id = :id') + ->setParameter('id', 'inverse') + ->getQuery() + ->getSingleResult(); + + self::assertInstanceOf(InverseSide::class, $fetchedInverse); + self::assertInstanceOf(OwningSide::class, $fetchedInverse->owning); + + $this->assertSQLEquals( + 'select o0_.id as id_0 from one_to_one_inverse_side_load_inverse o0_ where o0_.id = ?', + $this->_sqlLoggerStack->queries[$this->_sqlLoggerStack->currentQuery - 1]['sql'] + ); + + $this->assertSQLEquals( + 'select t0.id as id_1, t0.inverse as inverse_2 from one_to_one_inverse_side_load_owning t0 WHERE t0.inverse = ?', + $this->_sqlLoggerStack->queries[$this->_sqlLoggerStack->currentQuery]['sql'] + ); + } +} diff --git a/tests/Doctrine/Tests/ORM/Functional/OneToOneOrphanRemovalTest.php b/tests/Doctrine/Tests/ORM/Functional/OneToOneOrphanRemovalTest.php index 34bbc8c55b9..09ef64e021f 100644 --- a/tests/Doctrine/Tests/ORM/Functional/OneToOneOrphanRemovalTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/OneToOneOrphanRemovalTest.php @@ -2,9 +2,9 @@ namespace Doctrine\Tests\ORM\Functional; -use Doctrine\Tests\Models\CMS\CmsUser, - Doctrine\Tests\Models\CMS\CmsEmail, - Doctrine\Tests\Models\CMS\CmsAddress; +use Doctrine\Tests\Models\CMS\CmsAddress; +use Doctrine\Tests\Models\CMS\CmsEmail; +use Doctrine\Tests\Models\CMS\CmsUser; use Doctrine\Tests\OrmFunctionalTestCase; /** @@ -40,7 +40,7 @@ public function testOrphanRemoval() $this->_em->clear(); - $userProxy = $this->_em->getReference('Doctrine\Tests\Models\CMS\CmsUser', $userId); + $userProxy = $this->_em->getReference(CmsUser::class, $userId); $this->_em->remove($userProxy); $this->_em->flush(); @@ -76,7 +76,7 @@ public function testOrphanRemovalWhenUnlink() $this->_em->clear(); - $user = $this->_em->find('Doctrine\Tests\Models\CMS\CmsUser', $userId); + $user = $this->_em->find(CmsUser::class, $userId); $user->setEmail(null); diff --git a/tests/Doctrine/Tests/ORM/Functional/OneToOneSelfReferentialAssociationTest.php b/tests/Doctrine/Tests/ORM/Functional/OneToOneSelfReferentialAssociationTest.php index cad28d4c3c1..0011e8c8c40 100644 --- a/tests/Doctrine/Tests/ORM/Functional/OneToOneSelfReferentialAssociationTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/OneToOneSelfReferentialAssociationTest.php @@ -2,9 +2,10 @@ namespace Doctrine\Tests\ORM\Functional; -use Doctrine\Tests\Models\ECommerce\ECommerceCustomer; use Doctrine\ORM\Mapping\AssociationMapping; use Doctrine\ORM\Mapping\ClassMetadata; +use Doctrine\ORM\Proxy\Proxy; +use Doctrine\Tests\Models\ECommerce\ECommerceCustomer; use Doctrine\Tests\OrmFunctionalTestCase; /** @@ -52,8 +53,8 @@ public function testFind() { $id = $this->_createFixture(); - $customer = $this->_em->find('Doctrine\Tests\Models\ECommerce\ECommerceCustomer', $id); - $this->assertNotInstanceOf('Doctrine\ORM\Proxy\Proxy', $customer->getMentor()); + $customer = $this->_em->find(ECommerceCustomer::class, $id); + $this->assertNotInstanceOf(Proxy::class, $customer->getMentor()); } public function testEagerLoadsAssociation() @@ -74,7 +75,7 @@ public function testLazyLoadsAssociation() { $this->_createFixture(); - $metadata = $this->_em->getClassMetadata('Doctrine\Tests\Models\ECommerce\ECommerceCustomer'); + $metadata = $this->_em->getClassMetadata(ECommerceCustomer::class); $metadata->associationMappings['mentor']['fetch'] = ClassMetadata::FETCH_LAZY; $query = $this->_em->createQuery("select c from Doctrine\Tests\Models\ECommerce\ECommerceCustomer c where c.name='Luke Skywalker'"); @@ -86,9 +87,11 @@ public function testLazyLoadsAssociation() public function testMultiSelfReference() { try { - $this->_schemaTool->createSchema(array( - $this->_em->getClassMetadata('Doctrine\Tests\ORM\Functional\MultiSelfReference') - )); + $this->_schemaTool->createSchema( + [ + $this->_em->getClassMetadata(MultiSelfReference::class) + ] + ); } catch (\Exception $e) { // Swallow all exceptions. We do not test the schema tool here. } @@ -103,8 +106,8 @@ public function testMultiSelfReference() $entity2 = $this->_em->find(get_class($entity1), $entity1->getId()); - $this->assertInstanceOf('Doctrine\Tests\ORM\Functional\MultiSelfReference', $entity2->getOther1()); - $this->assertInstanceOf('Doctrine\Tests\ORM\Functional\MultiSelfReference', $entity2->getOther2()); + $this->assertInstanceOf(MultiSelfReference::class, $entity2->getOther1()); + $this->assertInstanceOf(MultiSelfReference::class, $entity2->getOther2()); $this->assertNull($entity2->getOther1()->getOther1()); $this->assertNull($entity2->getOther1()->getOther2()); $this->assertNull($entity2->getOther2()->getOther1()); @@ -113,12 +116,13 @@ public function testMultiSelfReference() public function assertLoadingOfAssociation($customer) { - $this->assertInstanceOf('Doctrine\Tests\Models\ECommerce\ECommerceCustomer', $customer->getMentor()); + $this->assertInstanceOf(ECommerceCustomer::class, $customer->getMentor()); $this->assertEquals('Obi-wan Kenobi', $customer->getMentor()->getName()); } public function assertForeignKeyIs($value) { - $foreignKey = $this->_em->getConnection()->executeQuery('SELECT mentor_id FROM ecommerce_customers WHERE id=?', array($this->customer->getId()))->fetchColumn(); + $foreignKey = $this->_em->getConnection()->executeQuery('SELECT mentor_id FROM ecommerce_customers WHERE id=?', [$this->customer->getId()] + )->fetchColumn(); $this->assertEquals($value, $foreignKey); } diff --git a/tests/Doctrine/Tests/ORM/Functional/OneToOneSingleTableInheritanceTest.php b/tests/Doctrine/Tests/ORM/Functional/OneToOneSingleTableInheritanceTest.php index b677df624d1..3e9a291f00b 100644 --- a/tests/Doctrine/Tests/ORM/Functional/OneToOneSingleTableInheritanceTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/OneToOneSingleTableInheritanceTest.php @@ -15,9 +15,9 @@ protected function setUp() parent::setUp(); $this->_schemaTool->createSchema([ - $this->_em->getClassMetadata(Pet::CLASSNAME), - $this->_em->getClassMetadata(Cat::CLASSNAME), - $this->_em->getClassMetadata(LitterBox::CLASSNAME), + $this->_em->getClassMetadata(Pet::class), + $this->_em->getClassMetadata(Cat::class), + $this->_em->getClassMetadata(LitterBox::class), ]); } @@ -38,11 +38,11 @@ public function testFindFromOneToOneOwningSideJoinedTableInheritance() $this->_em->clear(); /* @var $foundCat Cat */ - $foundCat = $this->_em->find(Pet::CLASSNAME, $cat->id); + $foundCat = $this->_em->find(Pet::class, $cat->id); - $this->assertInstanceOf(Cat::CLASSNAME, $foundCat); + $this->assertInstanceOf(Cat::class, $foundCat); $this->assertSame($cat->id, $foundCat->id); - $this->assertInstanceOf(LitterBox::CLASSNAME, $foundCat->litterBox); + $this->assertInstanceOf(LitterBox::class, $foundCat->litterBox); $this->assertSame($cat->litterBox->id, $foundCat->litterBox->id); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/OneToOneUnidirectionalAssociationTest.php b/tests/Doctrine/Tests/ORM/Functional/OneToOneUnidirectionalAssociationTest.php index 60b5b36567b..797a38517d0 100644 --- a/tests/Doctrine/Tests/ORM/Functional/OneToOneUnidirectionalAssociationTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/OneToOneUnidirectionalAssociationTest.php @@ -2,11 +2,11 @@ namespace Doctrine\Tests\ORM\Functional; -use Doctrine\Tests\Models\ECommerce\ECommerceProduct; -use Doctrine\Tests\Models\ECommerce\ECommerceShipping; use Doctrine\ORM\Mapping\AssociationMapping; use Doctrine\ORM\Mapping\ClassMetadata; use Doctrine\ORM\Query; +use Doctrine\Tests\Models\ECommerce\ECommerceProduct; +use Doctrine\Tests\Models\ECommerce\ECommerceShipping; use Doctrine\Tests\OrmFunctionalTestCase; /** @@ -55,20 +55,20 @@ public function _testEagerLoad() $result = $query->getResult(); $product = $result[0]; - $this->assertInstanceOf('Doctrine\Tests\Models\ECommerce\ECommerceShipping', $product->getShipping()); + $this->assertInstanceOf(ECommerceShipping::class, $product->getShipping()); $this->assertEquals(1, $product->getShipping()->getDays()); } public function testLazyLoadsObjects() { $this->_createFixture(); - $metadata = $this->_em->getClassMetadata('Doctrine\Tests\Models\ECommerce\ECommerceProduct'); + $metadata = $this->_em->getClassMetadata(ECommerceProduct::class); $metadata->associationMappings['shipping']['fetch'] = ClassMetadata::FETCH_LAZY; $query = $this->_em->createQuery('select p from Doctrine\Tests\Models\ECommerce\ECommerceProduct p'); $result = $query->getResult(); $product = $result[0]; - $this->assertInstanceOf('Doctrine\Tests\Models\ECommerce\ECommerceShipping', $product->getShipping()); + $this->assertInstanceOf(ECommerceShipping::class, $product->getShipping()); $this->assertEquals(1, $product->getShipping()->getDays()); } @@ -101,7 +101,7 @@ protected function _createFixture() public function assertForeignKeyIs($value) { $foreignKey = $this->_em->getConnection()->executeQuery( 'SELECT shipping_id FROM ecommerce_products WHERE id=?', - array($this->product->getId()) + [$this->product->getId()] )->fetchColumn(); $this->assertEquals($value, $foreignKey); } diff --git a/tests/Doctrine/Tests/ORM/Functional/OrderedCollectionTest.php b/tests/Doctrine/Tests/ORM/Functional/OrderedCollectionTest.php index c4e5dca7018..aa4fb1da0f6 100644 --- a/tests/Doctrine/Tests/ORM/Functional/OrderedCollectionTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/OrderedCollectionTest.php @@ -2,22 +2,22 @@ namespace Doctrine\Tests\ORM\Functional; -use Doctrine\Tests\Models\Routing\RoutingRoute; -use Doctrine\Tests\Models\Routing\RoutingLocation; use Doctrine\Tests\Models\Routing\RoutingLeg; +use Doctrine\Tests\Models\Routing\RoutingLocation; +use Doctrine\Tests\Models\Routing\RoutingRoute; use Doctrine\Tests\Models\Routing\RoutingRouteBooking; use Doctrine\Tests\OrmFunctionalTestCase; class OrderedCollectionTest extends OrmFunctionalTestCase { - protected $locations = array(); + protected $locations = []; public function setUp() { $this->useModelSet('routing'); parent::setUp(); - $locations = array("Berlin", "Bonn", "Brasilia", "Atlanta"); + $locations = ["Berlin", "Bonn", "Brasilia", "Atlanta"]; foreach ($locations AS $locationName) { $location = new RoutingLocation(); @@ -59,7 +59,7 @@ public function testLazyManyToManyCollection_IsRetrievedWithOrderByClause() { $routeId = $this->createPersistedRouteWithLegs(); - $route = $this->_em->find('Doctrine\Tests\Models\Routing\RoutingRoute', $routeId); + $route = $this->_em->find(RoutingRoute::class, $routeId); $this->assertEquals(2, count($route->legs)); $this->assertEquals("Berlin", $route->legs[0]->fromLocation->getName()); @@ -90,7 +90,7 @@ public function testLazyOneToManyCollection_IsRetrievedWithOrderByClause() $this->_em->flush(); $this->_em->clear(); - $route = $this->_em->find('Doctrine\Tests\Models\Routing\RoutingRoute', $routeId); + $route = $this->_em->find(RoutingRoute::class, $routeId); $this->assertEquals(2, count($route->bookings)); $this->assertEquals('Benjamin', $route->bookings[0]->getPassengerName()); diff --git a/tests/Doctrine/Tests/ORM/Functional/OrderedJoinedTableInheritanceCollectionTest.php b/tests/Doctrine/Tests/ORM/Functional/OrderedJoinedTableInheritanceCollectionTest.php index b3d85340e97..30531bae98d 100644 --- a/tests/Doctrine/Tests/ORM/Functional/OrderedJoinedTableInheritanceCollectionTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/OrderedJoinedTableInheritanceCollectionTest.php @@ -16,11 +16,13 @@ protected function setUp() { parent::setUp(); try { - $this->_schemaTool->createSchema(array( - $this->_em->getClassMetadata('Doctrine\Tests\ORM\Functional\OJTIC_Pet'), - $this->_em->getClassMetadata('Doctrine\Tests\ORM\Functional\OJTIC_Cat'), - $this->_em->getClassMetadata('Doctrine\Tests\ORM\Functional\OJTIC_Dog'), - )); + $this->_schemaTool->createSchema( + [ + $this->_em->getClassMetadata(OJTIC_Pet::class), + $this->_em->getClassMetadata(OJTIC_Cat::class), + $this->_em->getClassMetadata(OJTIC_Dog::class), + ] + ); } catch (\Exception $e) { // Swallow all exceptions. We do not test the schema tool here. } diff --git a/tests/Doctrine/Tests/ORM/Functional/PaginationTest.php b/tests/Doctrine/Tests/ORM/Functional/PaginationTest.php index 8afe9d3323d..9f200cb8e9d 100644 --- a/tests/Doctrine/Tests/ORM/Functional/PaginationTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/PaginationTest.php @@ -2,19 +2,24 @@ namespace Doctrine\Tests\ORM\Functional; +use Doctrine\DBAL\Types\Type as DBALType; use Doctrine\ORM\Query; +use Doctrine\ORM\Tools\Pagination\Paginator; +use Doctrine\Tests\DbalTypes\CustomIdObject; +use Doctrine\Tests\DbalTypes\CustomIdObjectType; use Doctrine\Tests\Models\CMS\CmsArticle; use Doctrine\Tests\Models\CMS\CmsEmail; -use Doctrine\Tests\Models\CMS\CmsUser; use Doctrine\Tests\Models\CMS\CmsGroup; -use Doctrine\ORM\Tools\Pagination\Paginator; +use Doctrine\Tests\Models\CMS\CmsUser; use Doctrine\Tests\Models\Company\CompanyManager; +use Doctrine\Tests\Models\CustomType\CustomIdObjectTypeParent; use Doctrine\Tests\Models\Pagination\Company; use Doctrine\Tests\Models\Pagination\Department; use Doctrine\Tests\Models\Pagination\Logo; use Doctrine\Tests\Models\Pagination\User1; use Doctrine\Tests\OrmFunctionalTestCase; use ReflectionMethod; +use function iterator_to_array; /** * @group DDC-1613 @@ -26,6 +31,14 @@ protected function setUp() $this->useModelSet('cms'); $this->useModelSet('pagination'); $this->useModelSet('company'); + $this->useModelSet('custom_id_object_type'); + + if (DBALType::hasType(CustomIdObjectType::NAME)) { + DBALType::overrideType(CustomIdObjectType::NAME, CustomIdObjectType::class); + } else { + DBALType::addType(CustomIdObjectType::NAME, CustomIdObjectType::class); + } + parent::setUp(); $this->populate(); } @@ -595,7 +608,7 @@ public function testDetectOutputWalker() // If the Paginator detects the custom output walker it should fall back to using the // Tree walkers for pagination, which leads to an exception. If the query works, the output walkers were used - $query->setHint(Query::HINT_CUSTOM_OUTPUT_WALKER, 'Doctrine\ORM\Query\SqlWalker'); + $query->setHint(Query::HINT_CUSTOM_OUTPUT_WALKER, Query\SqlWalker::class); $paginator = new Paginator($query); $this->expectException(\RuntimeException::class); @@ -633,14 +646,35 @@ public function testQueryWalkerIsKept() { $dql = 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u'; $query = $this->_em->createQuery($dql); - $query->setHint(Query::HINT_CUSTOM_TREE_WALKERS, array('Doctrine\Tests\ORM\Functional\CustomPaginationTestTreeWalker')); + $query->setHint(Query::HINT_CUSTOM_TREE_WALKERS, [CustomPaginationTestTreeWalker::class]); $paginator = new Paginator($query, true); $paginator->setUseOutputWalkers(false); $this->assertCount(1, $paginator->getIterator()); $this->assertEquals(1, $paginator->count()); } - + + /** + * @group GH-7890 + */ + public function testCustomIdTypeWithoutOutputWalker() + { + $this->_em->persist(new CustomIdObjectTypeParent(new CustomIdObject('foo'))); + $this->_em->flush(); + + $dql = 'SELECT p FROM Doctrine\Tests\Models\CustomType\CustomIdObjectTypeParent p'; + $query = $this->_em->createQuery($dql); + + $paginator = new Paginator($query, true); + $paginator->setUseOutputWalkers(false); + + $matchedItems = iterator_to_array($paginator->getIterator()); + + self::assertCount(1, $matchedItems); + self::assertInstanceOf(CustomIdObjectTypeParent::class, $matchedItems[0]); + self::assertSame('foo', (string) $matchedItems[0]->id); + } + public function testCountQueryStripsParametersInSelect() { $query = $this->_em->createQuery( @@ -661,7 +695,7 @@ public function testCountQueryStripsParametersInSelect() $this->assertCount(2, $getCountQuery->invoke($paginator)->getParameters()); $this->assertCount(9, $paginator); - $query->setHint(Query::HINT_CUSTOM_OUTPUT_WALKER, 'Doctrine\ORM\Query\SqlWalker'); + $query->setHint(Query::HINT_CUSTOM_OUTPUT_WALKER, Query\SqlWalker::class); $paginator = new Paginator($query); @@ -695,7 +729,7 @@ public function testPaginationWithSubSelectOrderByExpression($useOutputWalker, $ public function populate() { - $groups = array(); + $groups = []; for ($j = 0; $j < 3; $j++) {; $group = new CmsGroup(); $group->name = "group$j"; @@ -762,28 +796,28 @@ public function populate() public function useOutputWalkers() { - return array( - array(true), - array(false), - ); + return [ + [true], + [false], + ]; } public function fetchJoinCollection() { - return array( - array(true), - array(false), - ); + return [ + [true], + [false], + ]; } public function useOutputWalkersAndFetchJoinCollection() { - return array( - array(true, false), - array(true, true), - array(false, false), - array(false, true), - ); + return [ + [true, false], + [true, true], + [false, false], + [false, true], + ]; } } diff --git a/tests/Doctrine/Tests/ORM/Functional/PersistentCollectionCriteriaTest.php b/tests/Doctrine/Tests/ORM/Functional/PersistentCollectionCriteriaTest.php index e38574b7c80..4e0f442d84a 100644 --- a/tests/Doctrine/Tests/ORM/Functional/PersistentCollectionCriteriaTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/PersistentCollectionCriteriaTest.php @@ -1,27 +1,13 @@ _em) { - $this->_em->getConfiguration()->setEntityNamespaces(array()); + $this->_em->getConfiguration()->setEntityNamespaces([]); } parent::tearDown(); } @@ -89,12 +75,12 @@ public function testCanCountWithoutLoadingPersistentCollection() { $this->loadTweetFixture(); - $repository = $this->_em->getRepository('Doctrine\Tests\Models\Tweet\User'); + $repository = $this->_em->getRepository(User::class); - $user = $repository->findOneBy(array('name' => 'ngal')); + $user = $repository->findOneBy(['name' => 'ngal']); $tweets = $user->tweets->matching(new Criteria()); - $this->assertInstanceOf('Doctrine\ORM\LazyCriteriaCollection', $tweets); + $this->assertInstanceOf(LazyCriteriaCollection::class, $tweets); $this->assertFalse($tweets->isInitialized()); $this->assertCount(2, $tweets); $this->assertFalse($tweets->isInitialized()); @@ -104,33 +90,9 @@ public function testCanCountWithoutLoadingPersistentCollection() Criteria::expr()->eq('content', 'Foo') )); - $this->assertInstanceOf('Doctrine\ORM\LazyCriteriaCollection', $tweets); + $this->assertInstanceOf(LazyCriteriaCollection::class, $tweets); $this->assertFalse($tweets->isInitialized()); $this->assertCount(1, $tweets); $this->assertFalse($tweets->isInitialized()); } - - /*public function testCanCountWithoutLoadingManyToManyPersistentCollection() - { - $this->loadQuoteFixture(); - - $repository = $this->_em->getRepository('Doctrine\Tests\Models\Quote\User'); - - $user = $repository->findOneBy(array('name' => 'mgal')); - $groups = $user->groups->matching(new Criteria()); - - $this->assertInstanceOf('Doctrine\ORM\LazyManyToManyCriteriaCollection', $groups); - $this->assertFalse($groups->isInitialized()); - $this->assertCount(2, $groups); - $this->assertFalse($groups->isInitialized()); - - // Make sure it works with constraints - $criteria = new Criteria(Criteria::expr()->eq('name', 'quote1')); - $groups = $user->groups->matching($criteria); - - $this->assertInstanceOf('Doctrine\ORM\LazyManyToManyCriteriaCollection', $groups); - $this->assertFalse($groups->isInitialized()); - $this->assertCount(1, $groups); - $this->assertFalse($groups->isInitialized()); - }*/ } diff --git a/tests/Doctrine/Tests/ORM/Functional/PersistentCollectionTest.php b/tests/Doctrine/Tests/ORM/Functional/PersistentCollectionTest.php index c6cb20e236d..b1751455f34 100644 --- a/tests/Doctrine/Tests/ORM/Functional/PersistentCollectionTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/PersistentCollectionTest.php @@ -7,18 +7,18 @@ use Doctrine\Common\Persistence\PersistentObject; use Doctrine\Tests\OrmFunctionalTestCase; -/** - */ class PersistentCollectionTest extends OrmFunctionalTestCase { protected function setUp() { parent::setUp(); try { - $this->_schemaTool->createSchema(array( - $this->_em->getClassMetadata(__NAMESPACE__ . '\PersistentCollectionHolder'), - $this->_em->getClassMetadata(__NAMESPACE__ . '\PersistentCollectionContent'), - )); + $this->_schemaTool->createSchema( + [ + $this->_em->getClassMetadata(PersistentCollectionHolder::class), + $this->_em->getClassMetadata(PersistentCollectionContent::class), + ] + ); } catch (\Exception $e) { } @@ -35,7 +35,7 @@ public function testPersist() $this->_em->flush(); $this->_em->clear(); - $collectionHolder = $this->_em->find(__NAMESPACE__ . '\PersistentCollectionHolder', $collectionHolder->getId()); + $collectionHolder = $this->_em->find(PersistentCollectionHolder::class, $collectionHolder->getId()); $collectionHolder->getCollection(); $content = new PersistentCollectionContent('second element'); @@ -55,7 +55,7 @@ public function testExtraLazyIsEmptyDoesNotInitializeCollection() $this->_em->flush(); $this->_em->clear(); - $collectionHolder = $this->_em->find(__NAMESPACE__ . '\PersistentCollectionHolder', $collectionHolder->getId()); + $collectionHolder = $this->_em->find(PersistentCollectionHolder::class, $collectionHolder->getId()); $collection = $collectionHolder->getRawCollection(); $this->assertTrue($collection->isEmpty()); @@ -66,7 +66,7 @@ public function testExtraLazyIsEmptyDoesNotInitializeCollection() $this->_em->flush(); $this->_em->clear(); - $collectionHolder = $this->_em->find(__NAMESPACE__ . '\PersistentCollectionHolder', $collectionHolder->getId()); + $collectionHolder = $this->_em->find(PersistentCollectionHolder::class, $collectionHolder->getId()); $collection = $collectionHolder->getRawCollection(); $this->assertFalse($collection->isEmpty()); @@ -87,7 +87,7 @@ public function testMatchingDoesNotModifyTheGivenCriteria() $criteria = new Criteria(); - $collectionHolder = $this->_em->find(__NAMESPACE__ . '\PersistentCollectionHolder', $collectionHolder->getId()); + $collectionHolder = $this->_em->find(PersistentCollectionHolder::class, $collectionHolder->getId()); $collectionHolder->getCollection()->matching($criteria); $this->assertEmpty($criteria->getWhereExpression()); diff --git a/tests/Doctrine/Tests/ORM/Functional/PersistentObjectTest.php b/tests/Doctrine/Tests/ORM/Functional/PersistentObjectTest.php index 861b2922510..0fd2b47455c 100644 --- a/tests/Doctrine/Tests/ORM/Functional/PersistentObjectTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/PersistentObjectTest.php @@ -16,13 +16,16 @@ class PersistentObjectTest extends OrmFunctionalTestCase protected function setUp() { parent::setUp(); + try { - $this->_schemaTool->createSchema(array( - $this->_em->getClassMetadata('Doctrine\Tests\ORM\Functional\PersistentEntity'), - )); + $this->_schemaTool->createSchema( + [ + $this->_em->getClassMetadata(PersistentEntity::class), + ] + ); } catch (\Exception $e) { - } + PersistentObject::setObjectManager($this->_em); } @@ -33,6 +36,8 @@ public function testPersist() $this->_em->persist($entity); $this->_em->flush(); + + $this->addToAssertionCount(1); } public function testFind() @@ -44,7 +49,7 @@ public function testFind() $this->_em->flush(); $this->_em->clear(); - $entity = $this->_em->find(__NAMESPACE__ . '\PersistentEntity', $entity->getId()); + $entity = $this->_em->find(PersistentEntity::class, $entity->getId()); $this->assertEquals('test', $entity->getName()); $entity->setName('foobar'); @@ -61,7 +66,7 @@ public function testGetReference() $this->_em->flush(); $this->_em->clear(); - $entity = $this->_em->getReference(__NAMESPACE__ . '\PersistentEntity', $entity->getId()); + $entity = $this->_em->getReference(PersistentEntity::class, $entity->getId()); $this->assertEquals('test', $entity->getName()); } @@ -76,7 +81,7 @@ public function testSetAssociation() $this->_em->flush(); $this->_em->clear(); - $entity = $this->_em->getReference(__NAMESPACE__ . '\PersistentEntity', $entity->getId()); + $entity = $this->_em->getReference(PersistentEntity::class, $entity->getId()); $this->assertSame($entity, $entity->getParent()); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/PostLoadEventTest.php b/tests/Doctrine/Tests/ORM/Functional/PostLoadEventTest.php index b6fb57964c3..02a08666673 100644 --- a/tests/Doctrine/Tests/ORM/Functional/PostLoadEventTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/PostLoadEventTest.php @@ -2,12 +2,12 @@ namespace Doctrine\Tests\ORM\Functional; use Doctrine\Common\Util\ClassUtils; -use Doctrine\Tests\Models\CMS\CmsUser; -use Doctrine\Tests\Models\CMS\CmsPhonenumber; -use Doctrine\Tests\Models\CMS\CmsAddress; -use Doctrine\Tests\Models\CMS\CmsEmail; use Doctrine\ORM\Event\LifecycleEventArgs; use Doctrine\ORM\Events; +use Doctrine\Tests\Models\CMS\CmsAddress; +use Doctrine\Tests\Models\CMS\CmsEmail; +use Doctrine\Tests\Models\CMS\CmsPhonenumber; +use Doctrine\Tests\Models\CMS\CmsUser; use Doctrine\Tests\OrmFunctionalTestCase; /** @@ -46,9 +46,9 @@ public function testLoadedEntityUsingFindShouldTriggerEvent() $eventManager = $this->_em->getEventManager(); - $eventManager->addEventListener(array(Events::postLoad), $mockListener); + $eventManager->addEventListener([Events::postLoad], $mockListener); - $this->_em->find('Doctrine\Tests\Models\CMS\CmsUser', $this->userId); + $this->_em->find(CmsUser::class, $this->userId); } public function testLoadedEntityUsingQueryShouldTriggerEvent() @@ -63,7 +63,7 @@ public function testLoadedEntityUsingQueryShouldTriggerEvent() $eventManager = $this->_em->getEventManager(); - $eventManager->addEventListener(array(Events::postLoad), $mockListener); + $eventManager->addEventListener([Events::postLoad], $mockListener); $query = $this->_em->createQuery('SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.id = :id'); @@ -83,7 +83,7 @@ public function testLoadedAssociationToOneShouldTriggerEvent() $eventManager = $this->_em->getEventManager(); - $eventManager->addEventListener(array(Events::postLoad), $mockListener); + $eventManager->addEventListener([Events::postLoad], $mockListener); $query = $this->_em->createQuery('SELECT u, e FROM Doctrine\Tests\Models\CMS\CmsUser u JOIN u.email e WHERE u.id = :id'); @@ -103,7 +103,7 @@ public function testLoadedAssociationToManyShouldTriggerEvent() $eventManager = $this->_em->getEventManager(); - $eventManager->addEventListener(array(Events::postLoad), $mockListener); + $eventManager->addEventListener([Events::postLoad], $mockListener); $query = $this->_em->createQuery('SELECT u, p FROM Doctrine\Tests\Models\CMS\CmsUser u JOIN u.phonenumbers p WHERE u.id = :id'); @@ -123,12 +123,12 @@ public function testLoadedProxyEntityShouldTriggerEvent() ->method('postLoad') ->will($this->returnValue(true)); - $eventManager->addEventListener(array(Events::postLoad), $mockListener); + $eventManager->addEventListener([Events::postLoad], $mockListener); - $userProxy = $this->_em->getReference('Doctrine\Tests\Models\CMS\CmsUser', $this->userId); + $userProxy = $this->_em->getReference(CmsUser::class, $this->userId); // Now deactivate original listener and attach new one - $eventManager->removeEventListener(array(Events::postLoad), $mockListener); + $eventManager->removeEventListener([Events::postLoad], $mockListener); $mockListener2 = $this->createMock(PostLoadListener::class); @@ -137,7 +137,7 @@ public function testLoadedProxyEntityShouldTriggerEvent() ->method('postLoad') ->will($this->returnValue(true)); - $eventManager->addEventListener(array(Events::postLoad), $mockListener2); + $eventManager->addEventListener([Events::postLoad], $mockListener2); $userProxy->getName(); } @@ -155,7 +155,7 @@ public function testLoadedProxyPartialShouldTriggerEvent() ->method('postLoad') ->will($this->returnValue(true)); - $eventManager->addEventListener(array(Events::postLoad), $mockListener); + $eventManager->addEventListener([Events::postLoad], $mockListener); $query = $this->_em->createQuery('SELECT PARTIAL u.{id, name}, p FROM Doctrine\Tests\Models\CMS\CmsUser u JOIN u.phonenumbers p WHERE u.id = :id'); @@ -165,7 +165,7 @@ public function testLoadedProxyPartialShouldTriggerEvent() public function testLoadedProxyAssociationToOneShouldTriggerEvent() { - $user = $this->_em->find('Doctrine\Tests\Models\CMS\CmsUser', $this->userId); + $user = $this->_em->find(CmsUser::class, $this->userId); $mockListener = $this->createMock(PostLoadListener::class); @@ -177,7 +177,7 @@ public function testLoadedProxyAssociationToOneShouldTriggerEvent() $eventManager = $this->_em->getEventManager(); - $eventManager->addEventListener(array(Events::postLoad), $mockListener); + $eventManager->addEventListener([Events::postLoad], $mockListener); $emailProxy = $user->getEmail(); @@ -186,7 +186,7 @@ public function testLoadedProxyAssociationToOneShouldTriggerEvent() public function testLoadedProxyAssociationToManyShouldTriggerEvent() { - $user = $this->_em->find('Doctrine\Tests\Models\CMS\CmsUser', $this->userId); + $user = $this->_em->find(CmsUser::class, $this->userId); $mockListener = $this->createMock(PostLoadListener::class); @@ -198,7 +198,7 @@ public function testLoadedProxyAssociationToManyShouldTriggerEvent() $eventManager = $this->_em->getEventManager(); - $eventManager->addEventListener(array(Events::postLoad), $mockListener); + $eventManager->addEventListener([Events::postLoad], $mockListener); $phonenumbersCol = $user->getPhonenumbers(); @@ -211,9 +211,9 @@ public function testLoadedProxyAssociationToManyShouldTriggerEvent() public function testAssociationsArePopulatedWhenEventIsFired() { $checkerListener = new PostLoadListenerCheckAssociationsArePopulated(); - $this->_em->getEventManager()->addEventListener(array(Events::postLoad), $checkerListener); + $this->_em->getEventManager()->addEventListener([Events::postLoad], $checkerListener); - $qb = $this->_em->getRepository('Doctrine\Tests\Models\CMS\CmsUser')->createQueryBuilder('u'); + $qb = $this->_em->getRepository(CmsUser::class)->createQueryBuilder('u'); $qb->leftJoin('u.email', 'email'); $qb->addSelect('email'); $qb->getQuery()->getSingleResult(); @@ -229,11 +229,11 @@ public function testEventRaisedCorrectTimesWhenOtherEntityLoadedInEventHandler() { $eventManager = $this->_em->getEventManager(); $listener = new PostLoadListenerLoadEntityInEventHandler(); - $eventManager->addEventListener(array(Events::postLoad), $listener); + $eventManager->addEventListener([Events::postLoad], $listener); - $this->_em->find('Doctrine\Tests\Models\CMS\CmsUser', $this->userId); - $this->assertSame(1, $listener->countHandledEvents('Doctrine\Tests\Models\CMS\CmsUser'), 'Doctrine\Tests\Models\CMS\CmsUser should be handled once!'); - $this->assertSame(1, $listener->countHandledEvents('Doctrine\Tests\Models\CMS\CmsEmail'), '\Doctrine\Tests\Models\CMS\CmsEmail should be handled once!'); + $this->_em->find(CmsUser::class, $this->userId); + $this->assertSame(1, $listener->countHandledEvents(CmsUser::class), CmsUser::class . ' should be handled once!'); + $this->assertSame(1, $listener->countHandledEvents(CmsEmail::class), CmsEmail::class . ' should be handled once!'); } private function loadFixture() @@ -303,7 +303,7 @@ public function postLoad(LifecycleEventArgs $event) class PostLoadListenerLoadEntityInEventHandler { - private $firedByClasses = array(); + private $firedByClasses = []; public function postLoad(LifecycleEventArgs $event) { diff --git a/tests/Doctrine/Tests/ORM/Functional/ProxiesLikeEntitiesTest.php b/tests/Doctrine/Tests/ORM/Functional/ProxiesLikeEntitiesTest.php index 1528404dfdd..e88733d7db5 100644 --- a/tests/Doctrine/Tests/ORM/Functional/ProxiesLikeEntitiesTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/ProxiesLikeEntitiesTest.php @@ -2,8 +2,15 @@ namespace Doctrine\Tests\ORM\Functional; +use Doctrine\Tests\Models\CMS\CmsAddress; +use Doctrine\Tests\Models\CMS\CmsArticle; +use Doctrine\Tests\Models\CMS\CmsEmail; +use Doctrine\Tests\Models\CMS\CmsGroup; +use Doctrine\Tests\Models\CMS\CmsPhonenumber; +use Doctrine\Tests\Models\CMS\CmsTag; use Doctrine\Tests\Models\CMS\CmsUser; use Doctrine\Tests\OrmFunctionalTestCase; +use Doctrine\Tests\Proxies\__CG__\Doctrine\Tests\Models\CMS\CmsUser as CmsUserProxy; /** * Test that Doctrine ORM correctly works with proxy instances exactly like with ordinary Entities @@ -24,14 +31,17 @@ protected function setUp() { parent::setUp(); try { - $this->_schemaTool->createSchema(array( - $this->_em->getClassMetadata('Doctrine\Tests\Models\CMS\CmsUser'), - $this->_em->getClassMetadata('Doctrine\Tests\Models\CMS\CmsPhonenumber'), - $this->_em->getClassMetadata('Doctrine\Tests\Models\CMS\CmsArticle'), - $this->_em->getClassMetadata('Doctrine\Tests\Models\CMS\CmsAddress'), - $this->_em->getClassMetadata('Doctrine\Tests\Models\CMS\CmsEmail'), - $this->_em->getClassMetadata('Doctrine\Tests\Models\CMS\CmsGroup'), - )); + $this->_schemaTool->createSchema( + [ + $this->_em->getClassMetadata(CmsUser::class), + $this->_em->getClassMetadata(CmsTag::class), + $this->_em->getClassMetadata(CmsPhonenumber::class), + $this->_em->getClassMetadata(CmsArticle::class), + $this->_em->getClassMetadata(CmsAddress::class), + $this->_em->getClassMetadata(CmsEmail::class), + $this->_em->getClassMetadata(CmsGroup::class), + ] + ); } catch (\Exception $e) { } $this->user = new CmsUser(); @@ -48,7 +58,7 @@ protected function setUp() public function testPersistUpdate() { // Considering case (a) - $proxy = $this->_em->getProxyFactory()->getProxy('Doctrine\Tests\Models\CMS\CmsUser', array('id' => 123)); + $proxy = $this->_em->getProxyFactory()->getProxy(CmsUser::class, ['id' => 123]); $proxy->__isInitialized__ = true; $proxy->id = null; $proxy->username = 'ocra'; @@ -57,12 +67,10 @@ public function testPersistUpdate() $this->_em->flush(); $this->assertNotNull($proxy->getId()); $proxy->name = 'Marco Pivetta'; - $this - ->_em - ->getUnitOfWork() - ->computeChangeSet($this->_em->getClassMetadata('Doctrine\Tests\Models\CMS\CmsUser'), $proxy); + $this->_em->getUnitOfWork() + ->computeChangeSet($this->_em->getClassMetadata(CmsUser::class), $proxy); $this->assertNotEmpty($this->_em->getUnitOfWork()->getEntityChangeSet($proxy)); - $this->assertEquals('Marco Pivetta', $this->_em->find('Doctrine\Tests\Models\CMS\CmsUser', $proxy->getId())->name); + $this->assertEquals('Marco Pivetta', $this->_em->find(CmsUser::class, $proxy->getId())->name); $this->_em->remove($proxy); $this->_em->flush(); } @@ -70,12 +78,12 @@ public function testPersistUpdate() public function testEntityWithIdentifier() { $userId = $this->user->getId(); - /* @var $uninitializedProxy \Doctrine\Tests\Proxies\__CG__\Doctrine\Tests\Models\CMS\CmsUser */ - $uninitializedProxy = $this->_em->getReference('Doctrine\Tests\Models\CMS\CmsUser', $userId); - $this->assertInstanceOf('Doctrine\Tests\Proxies\__CG__\Doctrine\Tests\Models\CMS\CmsUser', $uninitializedProxy); + /* @var $uninitializedProxy CmsUserProxy */ + $uninitializedProxy = $this->_em->getReference(CmsUser::class, $userId); + $this->assertInstanceOf(CmsUserProxy::class, $uninitializedProxy); $this->_em->persist($uninitializedProxy); - $this->_em->flush($uninitializedProxy); + $this->_em->flush(); $this->assertFalse($uninitializedProxy->__isInitialized(), 'Proxy didn\'t get initialized during flush operations'); $this->assertEquals($userId, $uninitializedProxy->getId()); $this->_em->remove($uninitializedProxy); @@ -87,7 +95,8 @@ public function testEntityWithIdentifier() */ public function testProxyAsDqlParameterPersist() { - $proxy = $this->_em->getProxyFactory()->getProxy('Doctrine\Tests\Models\CMS\CmsUser', array('id' => $this->user->getId())); + $proxy = $this->_em->getProxyFactory()->getProxy(CmsUser::class, ['id' => $this->user->getId()] + ); $proxy->id = $this->user->getId(); $result = $this ->_em @@ -104,27 +113,23 @@ public function testProxyAsDqlParameterPersist() */ public function testFindWithProxyName() { - $result = $this - ->_em - ->find('Doctrine\Tests\Proxies\__CG__\Doctrine\Tests\Models\CMS\CmsUser', $this->user->getId()); + $result = $this->_em->find(CmsUserProxy::class, $this->user->getId()); $this->assertSame($this->user->getId(), $result->getId()); $this->_em->clear(); - $result = $this - ->_em - ->getReference('Doctrine\Tests\Proxies\__CG__\Doctrine\Tests\Models\CMS\CmsUser', $this->user->getId()); + + $result = $this->_em->getReference(CmsUserProxy::class, $this->user->getId()); $this->assertSame($this->user->getId(), $result->getId()); $this->_em->clear(); - $result = $this - ->_em - ->getRepository('Doctrine\Tests\Proxies\__CG__\Doctrine\Tests\Models\CMS\CmsUser') - ->findOneBy(array('username' => $this->user->username)); + + $result = $this->_em->getRepository(CmsUserProxy::class)->findOneBy(['username' => $this->user->username]); $this->assertSame($this->user->getId(), $result->getId()); $this->_em->clear(); - $result = $this - ->_em + + $result = $this->_em ->createQuery('SELECT u FROM Doctrine\Tests\Proxies\__CG__\Doctrine\Tests\Models\CMS\CmsUser u WHERE u.id = ?1') ->setParameter(1, $this->user->getId()) ->getSingleResult(); + $this->assertSame($this->user->getId(), $result->getId()); $this->_em->clear(); } @@ -133,4 +138,4 @@ protected function tearDown() { $this->_em->createQuery('DELETE FROM Doctrine\Tests\Models\CMS\CmsUser u')->execute(); } -} \ No newline at end of file +} diff --git a/tests/Doctrine/Tests/ORM/Functional/QueryCacheTest.php b/tests/Doctrine/Tests/ORM/Functional/QueryCacheTest.php index a2444527102..a307ad13786 100644 --- a/tests/Doctrine/Tests/ORM/Functional/QueryCacheTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/QueryCacheTest.php @@ -23,7 +23,7 @@ class QueryCacheTest extends OrmFunctionalTestCase protected function setUp() { - $this->cacheDataReflection = new \ReflectionProperty("Doctrine\Common\Cache\ArrayCache", "data"); + $this->cacheDataReflection = new \ReflectionProperty(ArrayCache::class, "data"); $this->cacheDataReflection->setAccessible(true); $this->useModelSet('cms'); @@ -116,7 +116,7 @@ public function testQueryCache_NoHitSaveParserResult() $cache ->expects(self::once()) ->method('save') - ->with(self::isType('string'), self::isInstanceOf('Doctrine\ORM\Query\ParserResult')); + ->with(self::isType('string'), self::isInstanceOf(ParserResult::class)); $query->getResult(); } @@ -128,20 +128,22 @@ public function testQueryCache_HitDoesNotSaveParserResult() $query = $this->_em->createQuery('select ux from Doctrine\Tests\Models\CMS\CmsUser ux'); $sqlExecMock = $this->getMockBuilder(AbstractSqlExecutor::class) - ->setMethods(array('execute')) + ->setMethods(['execute']) ->getMock(); $sqlExecMock->expects($this->once()) ->method('execute') ->will($this->returnValue( 10 )); - $parserResultMock = $this->createMock(ParserResult::class); + $parserResultMock = $this->getMockBuilder(ParserResult::class) + ->setMethods(['getSqlExecutor']) + ->getMock(); $parserResultMock->expects($this->once()) ->method('getSqlExecutor') ->will($this->returnValue($sqlExecMock)); $cache = $this->getMockBuilder(CacheProvider::class) - ->setMethods(array('doFetch', 'doContains', 'doSave', 'doDelete', 'doFlush', 'doGetStats')) + ->setMethods(['doFetch', 'doContains', 'doSave', 'doDelete', 'doFlush', 'doGetStats']) ->getMock(); $cache->expects($this->at(0))->method('doFetch')->will($this->returnValue(1)); @@ -149,6 +151,7 @@ public function testQueryCache_HitDoesNotSaveParserResult() ->method('doFetch') ->with($this->isType('string')) ->will($this->returnValue($parserResultMock)); + $cache->expects($this->never()) ->method('doSave'); diff --git a/tests/Doctrine/Tests/ORM/Functional/QueryDqlFunctionTest.php b/tests/Doctrine/Tests/ORM/Functional/QueryDqlFunctionTest.php index 764b213dde2..50008eb6932 100644 --- a/tests/Doctrine/Tests/ORM/Functional/QueryDqlFunctionTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/QueryDqlFunctionTest.php @@ -2,8 +2,10 @@ namespace Doctrine\Tests\ORM\Functional; +use Doctrine\ORM\AbstractQuery; use Doctrine\Tests\Models\Company\CompanyManager; use Doctrine\Tests\OrmFunctionalTestCase; +use function sprintf; /** * Functional Query tests. @@ -176,7 +178,7 @@ public function testFunctionSubstring() $this->assertEquals('Gui', $result[1]['str1']); $this->assertEquals('Jon', $result[2]['str1']); $this->assertEquals('Rom', $result[3]['str1']); - + $this->assertEquals('amin E.', $result[0]['str2']); $this->assertEquals('herme B.', $result[1]['str2']); $this->assertEquals('than W.', $result[2]['str2']); @@ -287,51 +289,77 @@ public function testDateDiff() /** * @group DDC-1014 + * @group DDC-2938 + * + * @dataProvider dateAddSubProvider */ - public function testDateAdd() - { - $arg = $this->_em->createQuery("SELECT DATE_ADD(CURRENT_TIMESTAMP(), 10, 'day') AS add FROM Doctrine\Tests\Models\Company\CompanyManager m") - ->getArrayResult(); - - $this->assertTrue(strtotime($arg[0]['add']) > 0); - - $arg = $this->_em->createQuery("SELECT DATE_ADD(CURRENT_TIMESTAMP(), 10, 'month') AS add FROM Doctrine\Tests\Models\Company\CompanyManager m") - ->getArrayResult(); - - $this->assertTrue(strtotime($arg[0]['add']) > 0); - } - - public function testDateAddSecond() + public function testDateAdd(string $unit, int $amount, int $delta = 0) : void { - $dql = "SELECT CURRENT_TIMESTAMP() now, DATE_ADD(CURRENT_TIMESTAMP(), 10, 'second') AS add FROM Doctrine\Tests\Models\Company\CompanyManager m"; - $query = $this->_em->createQuery($dql)->setMaxResults(1); - $result = $query->getArrayResult(); - - $this->assertCount(1, $result); - $this->assertArrayHasKey('now', $result[0]); - $this->assertArrayHasKey('add', $result[0]); - - $now = strtotime($result[0]['now']); - $add = strtotime($result[0]['add']); - $diff = $add - $now; - - $this->assertSQLEquals(10, $diff); + $query = sprintf( + 'SELECT CURRENT_TIMESTAMP() as now, DATE_ADD(CURRENT_TIMESTAMP(), %d, \'%s\') AS add FROM %s m', + $amount, + $unit, + CompanyManager::class + ); + + $result = $this->_em->createQuery($query) + ->setMaxResults(1) + ->getSingleResult(AbstractQuery::HYDRATE_ARRAY); + + self::assertArrayHasKey('now', $result); + self::assertArrayHasKey('add', $result); + + self::assertEquals( + (new \DateTimeImmutable($result['now']))->modify(sprintf('+%d %s', $amount, $unit)), + new \DateTimeImmutable($result['add']), + '', + $delta + ); } /** * @group DDC-1014 + * @group DDC-2938 + * + * @dataProvider dateAddSubProvider */ - public function testDateSub() + public function testDateSub(string $unit, int $amount, int $delta = 0) : void { - $arg = $this->_em->createQuery("SELECT DATE_SUB(CURRENT_TIMESTAMP(), 10, 'day') AS add FROM Doctrine\Tests\Models\Company\CompanyManager m") - ->getArrayResult(); - - $this->assertTrue(strtotime($arg[0]['add']) > 0); - - $arg = $this->_em->createQuery("SELECT DATE_SUB(CURRENT_TIMESTAMP(), 10, 'month') AS add FROM Doctrine\Tests\Models\Company\CompanyManager m") - ->getArrayResult(); + $query = sprintf( + 'SELECT CURRENT_TIMESTAMP() as now, DATE_SUB(CURRENT_TIMESTAMP(), %d, \'%s\') AS sub FROM %s m', + $amount, + $unit, + CompanyManager::class + ); + + $result = $this->_em->createQuery($query) + ->setMaxResults(1) + ->getSingleResult(AbstractQuery::HYDRATE_ARRAY); + + self::assertArrayHasKey('now', $result); + self::assertArrayHasKey('sub', $result); + + self::assertEquals( + (new \DateTimeImmutable($result['now']))->modify(sprintf('-%d %s', $amount, $unit)), + new \DateTimeImmutable($result['sub']), + '', + $delta + ); + } - $this->assertTrue(strtotime($arg[0]['add']) > 0); + public function dateAddSubProvider() : array + { + $secondsInDay = 86400; + + return [ + 'year' => ['year', 1, $secondsInDay], + 'month' => ['month', 1, $secondsInDay], + 'week' => ['week', 1, $secondsInDay], + 'day' => ['day', 2, $secondsInDay], + 'hour' => ['hour', 1, 3600], + 'minute' => ['minute', 1, 60], + 'second' => ['second', 10, 10], + ]; } /** diff --git a/tests/Doctrine/Tests/ORM/Functional/QueryTest.php b/tests/Doctrine/Tests/ORM/Functional/QueryTest.php index f234095060d..f25cd33faaa 100644 --- a/tests/Doctrine/Tests/ORM/Functional/QueryTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/QueryTest.php @@ -5,6 +5,7 @@ use Doctrine\Common\Collections\ArrayCollection; use Doctrine\ORM\NonUniqueResultException; +use Doctrine\ORM\Proxy\Proxy; use Doctrine\ORM\Query\QueryException; use Doctrine\ORM\UnexpectedResultException; use Doctrine\Tests\Models\CMS\CmsUser, @@ -25,6 +26,7 @@ class QueryTest extends OrmFunctionalTestCase protected function setUp() { $this->useModelSet('cms'); + parent::setUp(); } @@ -43,7 +45,7 @@ public function testSimpleQueries() $result = $query->getResult(); $this->assertEquals(1, count($result)); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsUser', $result[0][0]); + $this->assertInstanceOf(CmsUser::class, $result[0][0]); $this->assertEquals('Guilherme', $result[0][0]->name); $this->assertEquals('gblanco', $result[0][0]->username); $this->assertEquals('developer', $result[0][0]->status); @@ -92,10 +94,10 @@ public function testJoinQueries() $this->_em->flush(); $this->_em->clear(); - $query = $this->_em->createQuery("select u, a from Doctrine\Tests\Models\CMS\CmsUser u join u.articles a ORDER BY a.topic"); + $query = $this->_em->createQuery('select u, a from ' . CmsUser::class . ' u join u.articles a ORDER BY a.topic'); $users = $query->getResult(); $this->assertEquals(1, count($users)); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsUser', $users[0]); + $this->assertInstanceOf(CmsUser::class, $users[0]); $this->assertEquals(2, count($users[0]->articles)); $this->assertEquals('Doctrine 2', $users[0]->articles[0]->topic); $this->assertEquals('Symfony 2', $users[0]->articles[1]->topic); @@ -111,7 +113,7 @@ public function testUsingZeroBasedQueryParameterShouldWork() $this->_em->flush(); $this->_em->clear(); - $q = $this->_em->createQuery('SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.username = ?0'); + $q = $this->_em->createQuery('SELECT u FROM ' . CmsUser::class . ' u WHERE u.username = ?0'); $q->setParameter(0, 'jwage'); $user = $q->getSingleResult(); @@ -123,7 +125,7 @@ public function testUsingUnknownQueryParameterShouldThrowException() $this->expectException(QueryException::class); $this->expectExceptionMessage('Invalid parameter: token 2 is not defined in the query.'); - $q = $this->_em->createQuery('SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.name = ?1'); + $q = $this->_em->createQuery('SELECT u FROM ' . CmsUser::class . ' u WHERE u.name = ?1'); $q->setParameter(2, 'jwage'); $user = $q->getSingleResult(); } @@ -133,7 +135,7 @@ public function testTooManyParametersShouldThrowException() $this->expectException(QueryException::class); $this->expectExceptionMessage('Too many parameters: the query defines 1 parameters and you bound 2'); - $q = $this->_em->createQuery('SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.name = ?1'); + $q = $this->_em->createQuery('SELECT u FROM ' . CmsUser::class . ' u WHERE u.name = ?1'); $q->setParameter(1, 'jwage'); $q->setParameter(2, 'jwage'); @@ -145,38 +147,51 @@ public function testTooFewParametersShouldThrowException() $this->expectException(QueryException::class); $this->expectExceptionMessage('Too few parameters: the query defines 1 parameters but you only bound 0'); - $q = $this->_em->createQuery('SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.name = ?1'); - - $user = $q->getSingleResult(); + $this->_em->createQuery('SELECT u FROM ' . CmsUser::class . ' u WHERE u.name = ?1') + ->getSingleResult(); } public function testInvalidInputParameterThrowsException() { $this->expectException(QueryException::class); - $q = $this->_em->createQuery('SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.name = ?'); - $q->setParameter(1, 'jwage'); - $user = $q->getSingleResult(); + $this->_em->createQuery('SELECT u FROM ' . CmsUser::class . ' u WHERE u.name = ?') + ->setParameter(1, 'jwage') + ->getSingleResult(); } public function testSetParameters() { - $q = $this->_em->createQuery('SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.name = ?1 AND u.status = ?2'); - $parameters = new ArrayCollection(); $parameters->add(new Parameter(1, 'jwage')); $parameters->add(new Parameter(2, 'active')); - $q->setParameters($parameters); - $users = $q->getResult(); + $this->_em->createQuery('SELECT u FROM ' . CmsUser::class . ' u WHERE u.name = ?1 AND u.status = ?2') + ->setParameters($parameters) + ->getResult(); + + $extractValue = function (Parameter $parameter) { + return $parameter->getValue(); + }; + + self::assertSame( + $parameters->map($extractValue)->toArray(), + $this->_sqlLoggerStack->queries[$this->_sqlLoggerStack->currentQuery]['params'] + ); } public function testSetParametersBackwardsCompatible() { - $q = $this->_em->createQuery('SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.name = ?1 AND u.status = ?2'); - $q->setParameters(array(1 => 'jwage', 2 => 'active')); - - $users = $q->getResult(); + $parameters = [1 => 'jwage', 2 => 'active']; + + $this->_em->createQuery('SELECT u FROM ' . CmsUser::class . ' u WHERE u.name = ?1 AND u.status = ?2') + ->setParameters($parameters) + ->getResult(); + + self::assertSame( + array_values($parameters), + $this->_sqlLoggerStack->queries[$this->_sqlLoggerStack->currentQuery]['params'] + ); } /** @@ -199,17 +214,29 @@ public function testIterateResultAsArrayAndParams() $this->_em->clear(); $articleId = $article1->id; - $query = $this->_em->createQuery("select a from Doctrine\Tests\Models\CMS\CmsArticle a WHERE a.topic = ?1"); - $articles = $query->iterate(new ArrayCollection(array(new Parameter(1, 'Doctrine 2'))), Query::HYDRATE_ARRAY); + $query = $this->_em->createQuery('select a from ' . CmsArticle::class . ' a WHERE a.topic = ?1'); + $articles = $query->iterate(new ArrayCollection([new Parameter(1, 'Doctrine 2')]), Query::HYDRATE_ARRAY); + + $found = []; - $found = array(); foreach ($articles AS $article) { $found[] = $article; } + $this->assertEquals(1, count($found)); - $this->assertEquals(array( - array(array('id' => $articleId, 'topic' => 'Doctrine 2', 'text' => 'This is an introduction to Doctrine 2.', 'version' => 1)) - ), $found); + $this->assertSame( + [ + [ + [ + 'id' => $articleId, + 'topic' => 'Doctrine 2', + 'text' => 'This is an introduction to Doctrine 2.', + 'version' => 1, + ], + ], + ], + $found + ); } public function testIterateResult_IterativelyBuildUpUnitOfWork() @@ -228,24 +255,25 @@ public function testIterateResult_IterativelyBuildUpUnitOfWork() $this->_em->flush(); $this->_em->clear(); - $query = $this->_em->createQuery("select a from Doctrine\Tests\Models\CMS\CmsArticle a"); + $query = $this->_em->createQuery('select a from ' . CmsArticle::class . ' a'); $articles = $query->iterate(); $iteratedCount = 0; - $topics = array(); + $topics = []; + foreach($articles AS $row) { $article = $row[0]; $topics[] = $article->topic; $identityMap = $this->_em->getUnitOfWork()->getIdentityMap(); - $identityMapCount = count($identityMap['Doctrine\Tests\Models\CMS\CmsArticle']); + $identityMapCount = count($identityMap[CmsArticle::class]); $this->assertTrue($identityMapCount>$iteratedCount); $iteratedCount++; } - $this->assertEquals(array("Doctrine 2", "Symfony 2"), $topics); - $this->assertEquals(2, $iteratedCount); + $this->assertSame(["Doctrine 2", "Symfony 2"], $topics); + $this->assertSame(2, $iteratedCount); $this->_em->flush(); $this->_em->clear(); @@ -271,7 +299,7 @@ public function testIterateResultClearEveryCycle() $articles = $query->iterate(); $iteratedCount = 0; - $topics = array(); + $topics = []; foreach($articles AS $row) { $article = $row[0]; $topics[] = $article->topic; @@ -281,8 +309,8 @@ public function testIterateResultClearEveryCycle() $iteratedCount++; } - $this->assertEquals(array("Doctrine 2", "Symfony 2"), $topics); - $this->assertEquals(2, $iteratedCount); + $this->assertSame(["Doctrine 2", "Symfony 2"], $topics); + $this->assertSame(2, $iteratedCount); $this->_em->flush(); } @@ -292,7 +320,7 @@ public function testIterateResultClearEveryCycle() */ public function testIterateResult_FetchJoinedCollection_ThrowsException() { - $query = $this->_em->createQuery("SELECT u, a FROM Doctrine\Tests\Models\CMS\CmsUser u JOIN u.articles a"); + $query = $this->_em->createQuery("SELECT u, a FROM ' . CmsUser::class . ' u JOIN u.articles a"); $articles = $query->iterate(); } @@ -358,7 +386,7 @@ public function testModifiedLimitQuery() $this->_em->flush(); $this->_em->clear(); - $data = $this->_em->createQuery('SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u') + $data = $this->_em->createQuery('SELECT u FROM ' . CmsUser::class . ' u') ->setFirstResult(1) ->setMaxResults(2) ->getResult(); @@ -367,7 +395,7 @@ public function testModifiedLimitQuery() $this->assertEquals('gblanco1', $data[0]->username); $this->assertEquals('gblanco2', $data[1]->username); - $data = $this->_em->createQuery('SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u') + $data = $this->_em->createQuery('SELECT u FROM ' . CmsUser::class . ' u') ->setFirstResult(3) ->setMaxResults(2) ->getResult(); @@ -376,7 +404,7 @@ public function testModifiedLimitQuery() $this->assertEquals('gblanco3', $data[0]->username); $this->assertEquals('gblanco4', $data[1]->username); - $data = $this->_em->createQuery('SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u') + $data = $this->_em->createQuery('SELECT u FROM ' . CmsUser::class . ' u') ->setFirstResult(3) ->setMaxResults(2) ->getScalarResult(); @@ -394,7 +422,7 @@ public function testSupportsQueriesWithEntityNamespaces() $this->fail($e->getMessage()); } - $this->_em->getConfiguration()->setEntityNamespaces(array()); + $this->_em->getConfiguration()->setEntityNamespaces([]); } /** @@ -416,14 +444,14 @@ public function testEntityParameters() $this->_em->clear(); //$this->_em->getConnection()->getConfiguration()->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger); $q = $this->_em->createQuery("select a from Doctrine\Tests\Models\CMS\CmsArticle a where a.topic = :topic and a.user = :user") - ->setParameter("user", $this->_em->getReference('Doctrine\Tests\Models\CMS\CmsUser', $author->id)) + ->setParameter("user", $this->_em->getReference(CmsUser::class, $author->id)) ->setParameter("topic", "dr. dolittle"); $result = $q->getResult(); $this->assertEquals(1, count($result)); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsArticle', $result[0]); + $this->assertInstanceOf(CmsArticle::class, $result[0]); $this->assertEquals("dr. dolittle", $result[0]->topic); - $this->assertInstanceOf('Doctrine\ORM\Proxy\Proxy', $result[0]->user); + $this->assertInstanceOf(Proxy::class, $result[0]->user); $this->assertFalse($result[0]->user->__isInitialized__); } @@ -448,12 +476,12 @@ public function testEnableFetchEagerMode() $this->_em->clear(); $articles = $this->_em->createQuery('select a from Doctrine\Tests\Models\CMS\CmsArticle a') - ->setFetchMode('Doctrine\Tests\Models\CMS\CmsArticle', 'user', ClassMetadata::FETCH_EAGER) + ->setFetchMode(CmsArticle::class, 'user', ClassMetadata::FETCH_EAGER) ->getResult(); $this->assertEquals(10, count($articles)); foreach ($articles AS $article) { - $this->assertNotInstanceOf('Doctrine\ORM\Proxy\Proxy', $article); + $this->assertNotInstanceOf(Proxy::class, $article); } } @@ -470,13 +498,13 @@ public function testgetOneOrNullResult() $this->_em->flush(); $this->_em->clear(); - $query = $this->_em->createQuery("select u from Doctrine\Tests\Models\CMS\CmsUser u where u.username = 'gblanco'"); + $query = $this->_em->createQuery("select u from " . CmsUser::class . " u where u.username = 'gblanco'"); $fetchedUser = $query->getOneOrNullResult(); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsUser', $fetchedUser); + $this->assertInstanceOf(CmsUser::class, $fetchedUser); $this->assertEquals('gblanco', $fetchedUser->username); - $query = $this->_em->createQuery("select u.username from Doctrine\Tests\Models\CMS\CmsUser u where u.username = 'gblanco'"); + $query = $this->_em->createQuery("select u.username from " . CmsUser::class . " u where u.username = 'gblanco'"); $fetchedUsername = $query->getOneOrNullResult(Query::HYDRATE_SINGLE_SCALAR); $this->assertEquals('gblanco', $fetchedUsername); } @@ -502,7 +530,7 @@ public function testgetOneOrNullResultSeveralRows() $query = $this->_em->createQuery("select u from Doctrine\Tests\Models\CMS\CmsUser u"); $this->expectException(NonUniqueResultException::class); - + $fetchedUser = $query->getOneOrNullResult(); } @@ -545,10 +573,12 @@ public function testParameterOrder() $this->_em->clear(); $query = $this->_em->createQuery("SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.status = :a AND u.id IN (:b)"); - $query->setParameters(new ArrayCollection(array( - new Parameter('b', array($user1->id, $user2->id, $user3->id)), + $query->setParameters(new ArrayCollection( + [ + new Parameter('b', [$user1->id, $user2->id, $user3->id]), new Parameter('a', 'developer') - ))); + ] + )); $result = $query->getResult(); $this->assertEquals(3, count($result)); @@ -578,7 +608,7 @@ public function testDqlWithAutoInferOfParameters() $this->_em->clear(); $query = $this->_em->createQuery("SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.username IN (?0)"); - $query->setParameter(0, array('beberlei', 'jwage')); + $query->setParameter(0, ['beberlei', 'jwage']); $users = $query->execute(); @@ -589,7 +619,7 @@ public function testQueryBuilderWithStringWhereClauseContainingOrAndConditionalP { $qb = $this->_em->createQueryBuilder(); $qb->select('u') - ->from('Doctrine\Tests\Models\CMS\CmsUser', 'u') + ->from(CmsUser::class, 'u') ->innerJoin('u.articles', 'a') ->where('(u.id = 0) OR (u.id IS NULL)'); @@ -623,7 +653,7 @@ public function testQueryWithArrayOfEntitiesAsParameter() $this->_em->clear(); $query = $this->_em->createQuery("SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u IN (?0) OR u.username = ?1"); - $query->setParameter(0, array($userA, $userC)); + $query->setParameter(0, [$userA, $userC]); $query->setParameter(1, 'beberlei'); $users = $query->execute(); @@ -658,7 +688,7 @@ public function testQueryWithHiddenAsSelectExpression() $users = $query->execute(); $this->assertEquals(3, count($users)); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsUser', $users[0]); + $this->assertInstanceOf(CmsUser::class, $users[0]); } /** @@ -721,9 +751,9 @@ public function testSetCollectionParameterBindingSingleIdentifierObject() $users = $q->execute(); $this->assertEquals(3, count($users)); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsUser', $users[0]); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsUser', $users[1]); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsUser', $users[2]); + $this->assertInstanceOf(CmsUser::class, $users[0]); + $this->assertInstanceOf(CmsUser::class, $users[1]); + $this->assertInstanceOf(CmsUser::class, $users[2]); $resultUser1 = $users[0]; $resultUser2 = $users[1]; @@ -799,8 +829,8 @@ public function testMultipleJoinComponentsUsingInnerJoin() $users = $query->execute(); $this->assertEquals(2, count($users)); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsUser', $users[0]); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsPhonenumber', $users[1]); + $this->assertInstanceOf(CmsUser::class, $users[0]); + $this->assertInstanceOf(CmsPhonenumber::class, $users[1]); } public function testMultipleJoinComponentsUsingLeftJoin() @@ -832,9 +862,9 @@ public function testMultipleJoinComponentsUsingLeftJoin() $users = $query->execute(); $this->assertEquals(4, count($users)); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsUser', $users[0]); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsPhonenumber', $users[1]); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsUser', $users[2]); + $this->assertInstanceOf(CmsUser::class, $users[0]); + $this->assertInstanceOf(CmsPhonenumber::class, $users[1]); + $this->assertInstanceOf(CmsUser::class, $users[2]); $this->assertNull($users[3]); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/ReadOnlyTest.php b/tests/Doctrine/Tests/ORM/Functional/ReadOnlyTest.php index dd8a23ff374..a664a4df252 100644 --- a/tests/Doctrine/Tests/ORM/Functional/ReadOnlyTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/ReadOnlyTest.php @@ -1,6 +1,7 @@ _schemaTool->createSchema(array( - $this->_em->getClassMetadata('Doctrine\Tests\ORM\Functional\ReadOnlyEntity'), - )); + $this->_schemaTool->createSchema( + [ + $this->_em->getClassMetadata(ReadOnlyEntity::class), + ] + ); } catch(\Exception $e) { } } @@ -34,7 +37,7 @@ public function testReadOnlyEntityNeverChangeTracked() $this->_em->flush(); $this->_em->clear(); - $dbReadOnly = $this->_em->find('Doctrine\Tests\ORM\Functional\ReadOnlyEntity', $readOnly->id); + $dbReadOnly = $this->_em->find(ReadOnlyEntity::class, $readOnly->id); $this->assertEquals("Test1", $dbReadOnly->name); $this->assertEquals(1234, $dbReadOnly->numericValue); } diff --git a/tests/Doctrine/Tests/ORM/Functional/ReferenceProxyTest.php b/tests/Doctrine/Tests/ORM/Functional/ReferenceProxyTest.php index 4baeed9f1b9..5e1cb2fb223 100644 --- a/tests/Doctrine/Tests/ORM/Functional/ReferenceProxyTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/ReferenceProxyTest.php @@ -2,12 +2,12 @@ namespace Doctrine\Tests\ORM\Functional; +use Doctrine\Common\Persistence\Proxy; use Doctrine\Common\Util\ClassUtils; use Doctrine\ORM\Proxy\ProxyFactory; -use Doctrine\ORM\Proxy\ProxyClassGenerator; +use Doctrine\Tests\Models\Company\CompanyAuction; use Doctrine\Tests\Models\ECommerce\ECommerceProduct; use Doctrine\Tests\Models\ECommerce\ECommerceShipping; -use Doctrine\Tests\Models\Company\CompanyAuction; use Doctrine\Tests\OrmFunctionalTestCase; /** @@ -57,7 +57,7 @@ public function testLazyLoadsFieldValuesFromDatabase() { $id = $this->createProduct(); - $productProxy = $this->_em->getReference('Doctrine\Tests\Models\ECommerce\ECommerceProduct', array('id' => $id)); + $productProxy = $this->_em->getReference(ECommerceProduct::class, ['id' => $id]); $this->assertEquals('Doctrine Cookbook', $productProxy->getName()); } @@ -68,10 +68,10 @@ public function testAccessMetatadaForProxy() { $id = $this->createProduct(); - $entity = $this->_em->getReference('Doctrine\Tests\Models\ECommerce\ECommerceProduct' , $id); + $entity = $this->_em->getReference(ECommerceProduct::class , $id); $class = $this->_em->getClassMetadata(get_class($entity)); - $this->assertEquals('Doctrine\Tests\Models\ECommerce\ECommerceProduct', $class->name); + $this->assertEquals(ECommerceProduct::class, $class->name); } /** @@ -81,8 +81,8 @@ public function testReferenceFind() { $id = $this->createProduct(); - $entity = $this->_em->getReference('Doctrine\Tests\Models\ECommerce\ECommerceProduct' , $id); - $entity2 = $this->_em->find('Doctrine\Tests\Models\ECommerce\ECommerceProduct' , $id); + $entity = $this->_em->getReference(ECommerceProduct::class , $id); + $entity2 = $this->_em->find(ECommerceProduct::class , $id); $this->assertSame($entity, $entity2); $this->assertEquals('Doctrine Cookbook', $entity2->getName()); @@ -95,10 +95,10 @@ public function testCloneProxy() { $id = $this->createProduct(); - /* @var $entity Doctrine\Tests\Models\ECommerce\ECommerceProduct */ - $entity = $this->_em->getReference('Doctrine\Tests\Models\ECommerce\ECommerceProduct' , $id); + /* @var $entity ECommerceProduct */ + $entity = $this->_em->getReference(ECommerceProduct::class , $id); - /* @var $clone Doctrine\Tests\Models\ECommerce\ECommerceProduct */ + /* @var $clone ECommerceProduct */ $clone = clone $entity; $this->assertEquals($id, $entity->getId()); @@ -120,8 +120,8 @@ public function testInitializeProxy() { $id = $this->createProduct(); - /* @var $entity Doctrine\Tests\Models\ECommerce\ECommerceProduct */ - $entity = $this->_em->getReference('Doctrine\Tests\Models\ECommerce\ECommerceProduct' , $id); + /* @var $entity ECommerceProduct */ + $entity = $this->_em->getReference(ECommerceProduct::class , $id); $this->assertFalse($entity->__isInitialized__, "Pre-Condition: Object is unitialized proxy."); $this->_em->getUnitOfWork()->initializeObject($entity); @@ -135,14 +135,14 @@ public function testInitializeChangeAndFlushProxy() { $id = $this->createProduct(); - /* @var $entity Doctrine\Tests\Models\ECommerce\ECommerceProduct */ - $entity = $this->_em->getReference('Doctrine\Tests\Models\ECommerce\ECommerceProduct' , $id); + /* @var $entity ECommerceProduct */ + $entity = $this->_em->getReference(ECommerceProduct::class , $id); $entity->setName('Doctrine 2 Cookbook'); $this->_em->flush(); $this->_em->clear(); - $entity = $this->_em->getReference('Doctrine\Tests\Models\ECommerce\ECommerceProduct' , $id); + $entity = $this->_em->getReference(ECommerceProduct::class , $id); $this->assertEquals('Doctrine 2 Cookbook', $entity->getName()); } @@ -153,8 +153,8 @@ public function testWakeupCalledOnProxy() { $id = $this->createProduct(); - /* @var $entity Doctrine\Tests\Models\ECommerce\ECommerceProduct */ - $entity = $this->_em->getReference('Doctrine\Tests\Models\ECommerce\ECommerceProduct' , $id); + /* @var $entity ECommerceProduct */ + $entity = $this->_em->getReference(ECommerceProduct::class , $id); $this->assertFalse($entity->wakeUp); @@ -167,8 +167,8 @@ public function testDoNotInitializeProxyOnGettingTheIdentifier() { $id = $this->createProduct(); - /* @var $entity Doctrine\Tests\Models\ECommerce\ECommerceProduct */ - $entity = $this->_em->getReference('Doctrine\Tests\Models\ECommerce\ECommerceProduct' , $id); + /* @var $entity ECommerceProduct */ + $entity = $this->_em->getReference(ECommerceProduct::class , $id); $this->assertFalse($entity->__isInitialized__, "Pre-Condition: Object is unitialized proxy."); $this->assertEquals($id, $entity->getId()); @@ -182,14 +182,14 @@ public function testDoNotInitializeProxyOnGettingTheIdentifier_DDC_1625() { $id = $this->createAuction(); - /* @var $entity Doctrine\Tests\Models\Company\CompanyAuction */ - $entity = $this->_em->getReference('Doctrine\Tests\Models\Company\CompanyAuction' , $id); + /* @var $entity CompanyAuction */ + $entity = $this->_em->getReference(CompanyAuction::class , $id); $this->assertFalse($entity->__isInitialized__, "Pre-Condition: Object is unitialized proxy."); $this->assertEquals($id, $entity->getId()); $this->assertFalse($entity->__isInitialized__, "Getting the identifier doesn't initialize the proxy when extending."); } - + public function testDoNotInitializeProxyOnGettingTheIdentifierAndReturnTheRightType() { $product = new ECommerceProduct(); @@ -204,7 +204,7 @@ public function testDoNotInitializeProxyOnGettingTheIdentifierAndReturnTheRightT $id = $shipping->getId(); - $product = $this->_em->getRepository('Doctrine\Tests\Models\ECommerce\ECommerceProduct')->find($product->getId()); + $product = $this->_em->getRepository(ECommerceProduct::class)->find($product->getId()); $entity = $product->getShipping(); $this->assertFalse($entity->__isInitialized__, "Pre-Condition: Object is unitialized proxy."); @@ -217,8 +217,8 @@ public function testInitializeProxyOnGettingSomethingOtherThanTheIdentifier() { $id = $this->createProduct(); - /* @var $entity Doctrine\Tests\Models\ECommerce\ECommerceProduct */ - $entity = $this->_em->getReference('Doctrine\Tests\Models\ECommerce\ECommerceProduct' , $id); + /* @var $entity ECommerceProduct */ + $entity = $this->_em->getReference(ECommerceProduct::class , $id); $this->assertFalse($entity->__isInitialized__, "Pre-Condition: Object is unitialized proxy."); $this->assertEquals('Doctrine Cookbook', $entity->getName()); @@ -233,12 +233,12 @@ public function testCommonPersistenceProxy() $id = $this->createProduct(); /* @var $entity ECommerceProduct */ - $entity = $this->_em->getReference('Doctrine\Tests\Models\ECommerce\ECommerceProduct' , $id); + $entity = $this->_em->getReference(ECommerceProduct::class , $id); $className = ClassUtils::getClass($entity); - $this->assertInstanceOf('Doctrine\Common\Persistence\Proxy', $entity); + $this->assertInstanceOf(Proxy::class, $entity); $this->assertFalse($entity->__isInitialized()); - $this->assertEquals('Doctrine\Tests\Models\ECommerce\ECommerceProduct', $className); + $this->assertEquals(ECommerceProduct::class, $className); $restName = str_replace($this->_em->getConfiguration()->getProxyNamespace(), "", get_class($entity)); $restName = substr(get_class($entity), strlen($this->_em->getConfiguration()->getProxyNamespace()) +1); diff --git a/tests/Doctrine/Tests/ORM/Functional/ResultCacheTest.php b/tests/Doctrine/Tests/ORM/Functional/ResultCacheTest.php index e1bd93ed792..cffe07fe7d2 100644 --- a/tests/Doctrine/Tests/ORM/Functional/ResultCacheTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/ResultCacheTest.php @@ -8,6 +8,7 @@ use Doctrine\Tests\Models\CMS\CmsArticle; use Doctrine\Common\Cache\ArrayCache; use Doctrine\Tests\OrmFunctionalTestCase; +use function count; /** * ResultCacheTest @@ -22,7 +23,7 @@ class ResultCacheTest extends OrmFunctionalTestCase private $cacheDataReflection; protected function setUp() { - $this->cacheDataReflection = new \ReflectionProperty("Doctrine\Common\Cache\ArrayCache", "data"); + $this->cacheDataReflection = new \ReflectionProperty(ArrayCache::class, "data"); $this->cacheDataReflection->setAccessible(true); $this->useModelSet('cms'); parent::setUp(); @@ -89,7 +90,7 @@ public function testSetResultCacheId() $this->assertTrue($cache->contains('testing_result_cache_id')); } - public function testUseResultCache() + public function testUseResultCacheTrue() { $cache = new ArrayCache(); $query = $this->_em->createQuery('select ux from Doctrine\Tests\Models\CMS\CmsUser ux'); @@ -104,6 +105,22 @@ public function testUseResultCache() $this->_em->getConfiguration()->setResultCacheImpl(new ArrayCache()); } + public function testUseResultCacheFalse() + { + $cache = new ArrayCache(); + $query = $this->_em->createQuery('select ux from Doctrine\Tests\Models\CMS\CmsUser ux'); + + $query->setResultCacheDriver($cache); + $query->setResultCacheId('testing_result_cache_id'); + $query->useResultCache(false); + $query->getResult(); + + $this->assertFalse($cache->contains('testing_result_cache_id')); + + $this->_em->getConfiguration()->setResultCacheImpl(new ArrayCache()); + } + + /** * @group DDC-1026 */ @@ -113,24 +130,99 @@ public function testUseResultCacheParams() $sqlCount = count($this->_sqlLoggerStack->queries); $query = $this->_em->createQuery('select ux from Doctrine\Tests\Models\CMS\CmsUser ux WHERE ux.id = ?1'); - $query->setParameter(1, 1); $query->setResultCacheDriver($cache); $query->useResultCache(true); + + // these queries should result in cache miss: + $query->setParameter(1, 1); + $query->getResult(); + $query->setParameter(1, 2); $query->getResult(); + $this->assertCount( + $sqlCount + 2, + $this->_sqlLoggerStack->queries, + 'Two non-cached queries.' + ); + + // these two queries should actually be cached, as they repeat previous ones: + $query->setParameter(1, 1); + $query->getResult(); $query->setParameter(1, 2); $query->getResult(); - $this->assertEquals($sqlCount + 2, count($this->_sqlLoggerStack->queries), "Two non-cached queries."); + $this->assertCount( + $sqlCount + 2, + $this->_sqlLoggerStack->queries, + 'The next two sql queries should have been cached, but were not.' + ); + } + + public function testEnableResultCache() : void + { + $cache = new ArrayCache(); + $query = $this->_em->createQuery('select ux from Doctrine\Tests\Models\CMS\CmsUser ux'); + + $query->enableResultCache(); + $query->setResultCacheDriver($cache); + $query->setResultCacheId('testing_result_cache_id'); + $query->getResult(); + + $this->assertTrue($cache->contains('testing_result_cache_id')); + $this->_em->getConfiguration()->setResultCacheImpl(new ArrayCache()); + } + + /** + * @group DDC-1026 + */ + public function testEnableResultCacheParams() : void + { + $cache = new ArrayCache(); + $sqlCount = count($this->_sqlLoggerStack->queries); + $query = $this->_em->createQuery('select ux from Doctrine\Tests\Models\CMS\CmsUser ux WHERE ux.id = ?1'); + + $query->setResultCacheDriver($cache); + $query->enableResultCache(); + + // these queries should result in cache miss: $query->setParameter(1, 1); - $query->useResultCache(true); + $query->getResult(); + $query->setParameter(1, 2); $query->getResult(); + $this->assertCount( + $sqlCount + 2, + $this->_sqlLoggerStack->queries, + 'Two non-cached queries.' + ); + + // these two queries should actually be cached, as they repeat previous ones: + $query->setParameter(1, 1); + $query->getResult(); $query->setParameter(1, 2); $query->getResult(); - $this->assertEquals($sqlCount + 2, count($this->_sqlLoggerStack->queries), "The next two sql should have been cached, but were not."); + $this->assertCount( + $sqlCount + 2, + $this->_sqlLoggerStack->queries, + 'The next two sql queries should have been cached, but were not.' + ); + } + + public function testDisableResultCache() : void + { + $cache = new ArrayCache(); + $query = $this->_em->createQuery('select ux from Doctrine\Tests\Models\CMS\CmsUser ux'); + + $query->setResultCacheDriver($cache); + $query->setResultCacheId('testing_result_cache_id'); + $query->disableResultCache(); + $query->getResult(); + + $this->assertFalse($cache->contains('testing_result_cache_id')); + + $this->_em->getConfiguration()->setResultCacheImpl(new ArrayCache()); } public function testNativeQueryResultCaching() @@ -143,7 +235,7 @@ public function testNativeQueryResultCaching() $query = $this->_em->createNativeQuery('select u.id FROM cms_users u WHERE u.id = ?', $rsm); $query->setParameter(1, 10); - $query->setResultCacheDriver($cache)->useResultCache(true); + $query->setResultCacheDriver($cache)->enableResultCache(); $this->assertEquals(0, $this->getCacheSize($cache)); @@ -229,7 +321,7 @@ public function testResultCacheWithObjectParameter() $cache = new ArrayCache(); - $query->setResultCacheDriver($cache)->useResultCache(true); + $query->setResultCacheDriver($cache)->enableResultCache(); $articles = $query->getResult(); @@ -241,7 +333,7 @@ public function testResultCacheWithObjectParameter() $query2 = $this->_em->createQuery('select a from Doctrine\Tests\Models\CMS\CmsArticle a WHERE a.user = ?1'); $query2->setParameter(1, $user1); - $query2->setResultCacheDriver($cache)->useResultCache(true); + $query2->setResultCacheDriver($cache)->enableResultCache(); $articles = $query2->getResult(); @@ -251,7 +343,7 @@ public function testResultCacheWithObjectParameter() $query3 = $this->_em->createQuery('select a from Doctrine\Tests\Models\CMS\CmsArticle a WHERE a.user = ?1'); $query3->setParameter(1, $user2); - $query3->setResultCacheDriver($cache)->useResultCache(true); + $query3->setResultCacheDriver($cache)->enableResultCache(); $articles = $query3->getResult(); diff --git a/tests/Doctrine/Tests/ORM/Functional/SQLFilterTest.php b/tests/Doctrine/Tests/ORM/Functional/SQLFilterTest.php index 5fccc0bdb81..c35036b6e3c 100644 --- a/tests/Doctrine/Tests/ORM/Functional/SQLFilterTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/SQLFilterTest.php @@ -2,26 +2,27 @@ namespace Doctrine\Tests\ORM\Functional; +use Doctrine\Common\Cache\ArrayCache; +use Doctrine\DBAL\Connection; use Doctrine\DBAL\Types\Type as DBALType; use Doctrine\ORM\Configuration; -use Doctrine\ORM\Query\Filter\SQLFilter; +use Doctrine\ORM\EntityManager; use Doctrine\ORM\Mapping\ClassMetadata; -use Doctrine\Common\Cache\ArrayCache; - use Doctrine\ORM\Mapping\ClassMetadataInfo; - -use Doctrine\Tests\Models\CMS\CmsUser; +use Doctrine\ORM\Query\Filter\SQLFilter; +use Doctrine\ORM\Query\FilterCollection; use Doctrine\Tests\Models\CMS\CmsAddress; -use Doctrine\Tests\Models\CMS\CmsGroup; use Doctrine\Tests\Models\CMS\CmsArticle; - -use Doctrine\Tests\Models\Company\CompanyPerson; -use Doctrine\Tests\Models\Company\CompanyManager; -use Doctrine\Tests\Models\Company\CompanyOrganization; +use Doctrine\Tests\Models\CMS\CmsGroup; +use Doctrine\Tests\Models\CMS\CmsUser; use Doctrine\Tests\Models\Company\CompanyAuction; - +use Doctrine\Tests\Models\Company\CompanyContract; +use Doctrine\Tests\Models\Company\CompanyEvent; use Doctrine\Tests\Models\Company\CompanyFlexContract; use Doctrine\Tests\Models\Company\CompanyFlexUltraContract; +use Doctrine\Tests\Models\Company\CompanyManager; +use Doctrine\Tests\Models\Company\CompanyOrganization; +use Doctrine\Tests\Models\Company\CompanyPerson; use Doctrine\Tests\OrmFunctionalTestCase; /** @@ -49,7 +50,7 @@ public function tearDown() { parent::tearDown(); - $class = $this->_em->getClassMetadata('Doctrine\Tests\Models\CMS\CmsUser'); + $class = $this->_em->getClassMetadata(CmsUser::class); $class->associationMappings['groups']['fetch'] = ClassMetadataInfo::FETCH_LAZY; $class->associationMappings['articles']['fetch'] = ClassMetadataInfo::FETCH_LAZY; } @@ -92,7 +93,7 @@ public function testEntityManagerEnabledFilters() $em = $this->_getEntityManager(); // No enabled filters - $this->assertEquals(array(), $em->getFilters()->getEnabledFilters()); + $this->assertEquals([], $em->getFilters()->getEnabledFilters()); $this->configureFilters($em); $filter = $em->getFilters()->enable("locale"); @@ -170,11 +171,11 @@ public function testEntityManagerIsFilterEnabled() // Check for a disabled filter $em->getFilters()->disable("locale"); $this->assertFalse($em->getFilters()->isEnabled("locale")); - + // Check a non-existing filter - $this->assertFalse($em->getFilters()->isEnabled("foo_filter")); + $this->assertFalse($em->getFilters()->isEnabled("foo_filter")); } - + protected function configureFilters($em) { // Add filters to the configuration of the EM @@ -186,7 +187,7 @@ protected function configureFilters($em) protected function getMockConnection() { // Setup connection mock - $conn = $this->getMockBuilder('Doctrine\DBAL\Connection') + $conn = $this->getMockBuilder(Connection::class) ->disableOriginalConstructor() ->getMock(); @@ -196,7 +197,7 @@ protected function getMockConnection() protected function getMockEntityManager() { // Setup connection mock - $em = $this->getMockBuilder('Doctrine\ORM\EntityManager') + $em = $this->getMockBuilder(EntityManager::class) ->disableOriginalConstructor() ->getMock(); @@ -205,7 +206,7 @@ protected function getMockEntityManager() protected function addMockFilterCollection($em) { - $filterCollection = $this->getMockBuilder('Doctrine\ORM\Query\FilterCollection') + $filterCollection = $this->getMockBuilder(FilterCollection::class) ->disableOriginalConstructor() ->getMock(); @@ -258,7 +259,7 @@ public function testSQLFilterGetConnection() $filter = new MyLocaleFilter($em); - $reflMethod = new \ReflectionMethod('Doctrine\ORM\Query\Filter\SQLFilter', 'getConnection'); + $reflMethod = new \ReflectionMethod(SQLFilter::class, 'getConnection'); $reflMethod->setAccessible(true); $this->assertSame($conn, $reflMethod->invoke($filter)); @@ -293,7 +294,7 @@ public function testSQLFilterSetParameterInfersType() public function testSQLFilterAddConstraint() { // Set up metadata mock - $targetEntity = $this->getMockBuilder('Doctrine\ORM\Mapping\ClassMetadata') + $targetEntity = $this->getMockBuilder(ClassMetadata::class) ->disableOriginalConstructor() ->getMock(); @@ -322,10 +323,10 @@ public function testSQLFilterToString() $filter2->setParameter('foo', 'bar', DBALType::STRING); $filter2->setParameter('locale', 'en', DBALType::STRING); - $parameters = array( - 'foo' => array('value' => 'bar', 'type' => DBALType::STRING), - 'locale' => array('value' => 'en', 'type' => DBALType::STRING), - ); + $parameters = [ + 'foo' => ['value' => 'bar', 'type' => DBALType::STRING], + 'locale' => ['value' => 'en', 'type' => DBALType::STRING], + ]; $this->assertEquals(serialize($parameters), ''.$filter); $this->assertEquals(''.$filter, ''.$filter2); @@ -333,7 +334,7 @@ public function testSQLFilterToString() public function testQueryCache_DependsOnFilters() { - $cacheDataReflection = new \ReflectionProperty("Doctrine\Common\Cache\ArrayCache", "data"); + $cacheDataReflection = new \ReflectionProperty(ArrayCache::class, "data"); $cacheDataReflection->setAccessible(true); $query = $this->_em->createQuery('select ux from Doctrine\Tests\Models\CMS\CmsUser ux'); @@ -373,74 +374,82 @@ public function testRepositoryFind() { $this->loadFixtureData(); - $this->assertNotNull($this->_em->getRepository('Doctrine\Tests\Models\CMS\CmsGroup')->find($this->groupId)); - $this->assertNotNull($this->_em->getRepository('Doctrine\Tests\Models\CMS\CmsGroup')->find($this->groupId2)); + $this->assertNotNull($this->_em->getRepository(CmsGroup::class)->find($this->groupId)); + $this->assertNotNull($this->_em->getRepository(CmsGroup::class)->find($this->groupId2)); $this->useCMSGroupPrefixFilter(); $this->_em->clear(); - $this->assertNotNull($this->_em->getRepository('Doctrine\Tests\Models\CMS\CmsGroup')->find($this->groupId)); - $this->assertNull($this->_em->getRepository('Doctrine\Tests\Models\CMS\CmsGroup')->find($this->groupId2)); + $this->assertNotNull($this->_em->getRepository(CmsGroup::class)->find($this->groupId)); + $this->assertNull($this->_em->getRepository(CmsGroup::class)->find($this->groupId2)); } public function testRepositoryFindAll() { $this->loadFixtureData(); - $this->assertCount(2, $this->_em->getRepository('Doctrine\Tests\Models\CMS\CmsGroup')->findAll()); + $this->assertCount(2, $this->_em->getRepository(CmsGroup::class)->findAll()); $this->useCMSGroupPrefixFilter(); $this->_em->clear(); - $this->assertCount(1, $this->_em->getRepository('Doctrine\Tests\Models\CMS\CmsGroup')->findAll()); + $this->assertCount(1, $this->_em->getRepository(CmsGroup::class)->findAll()); } public function testRepositoryFindBy() { $this->loadFixtureData(); - $this->assertCount(1, $this->_em->getRepository('Doctrine\Tests\Models\CMS\CmsGroup')->findBy(array('id' => $this->groupId2))); + $this->assertCount(1, $this->_em->getRepository(CmsGroup::class)->findBy( + ['id' => $this->groupId2] + )); $this->useCMSGroupPrefixFilter(); $this->_em->clear(); - $this->assertCount(0, $this->_em->getRepository('Doctrine\Tests\Models\CMS\CmsGroup')->findBy(array('id' => $this->groupId2))); + $this->assertCount(0, $this->_em->getRepository(CmsGroup::class)->findBy( + ['id' => $this->groupId2] + )); } public function testRepositoryFindByX() { $this->loadFixtureData(); - $this->assertCount(1, $this->_em->getRepository('Doctrine\Tests\Models\CMS\CmsGroup')->findById($this->groupId2)); + $this->assertCount(1, $this->_em->getRepository(CmsGroup::class)->findById($this->groupId2)); $this->useCMSGroupPrefixFilter(); $this->_em->clear(); - $this->assertCount(0, $this->_em->getRepository('Doctrine\Tests\Models\CMS\CmsGroup')->findById($this->groupId2)); + $this->assertCount(0, $this->_em->getRepository(CmsGroup::class)->findById($this->groupId2)); } public function testRepositoryFindOneBy() { $this->loadFixtureData(); - $this->assertNotNull($this->_em->getRepository('Doctrine\Tests\Models\CMS\CmsGroup')->findOneBy(array('id' => $this->groupId2))); + $this->assertNotNull($this->_em->getRepository(CmsGroup::class)->findOneBy( + ['id' => $this->groupId2] + )); $this->useCMSGroupPrefixFilter(); $this->_em->clear(); - $this->assertNull($this->_em->getRepository('Doctrine\Tests\Models\CMS\CmsGroup')->findOneBy(array('id' => $this->groupId2))); + $this->assertNull($this->_em->getRepository(CmsGroup::class)->findOneBy( + ['id' => $this->groupId2] + )); } public function testRepositoryFindOneByX() { $this->loadFixtureData(); - $this->assertNotNull($this->_em->getRepository('Doctrine\Tests\Models\CMS\CmsGroup')->findOneById($this->groupId2)); + $this->assertNotNull($this->_em->getRepository(CmsGroup::class)->findOneById($this->groupId2)); $this->useCMSGroupPrefixFilter(); $this->_em->clear(); - $this->assertNull($this->_em->getRepository('Doctrine\Tests\Models\CMS\CmsGroup')->findOneById($this->groupId2)); + $this->assertNull($this->_em->getRepository(CmsGroup::class)->findOneById($this->groupId2)); } public function testToOneFilter() @@ -513,7 +522,7 @@ public function testWhereOrFilter() private function loadLazyFixtureData() { - $class = $this->_em->getClassMetadata('Doctrine\Tests\Models\CMS\CmsUser'); + $class = $this->_em->getClassMetadata(CmsUser::class); $class->associationMappings['articles']['fetch'] = ClassMetadataInfo::FETCH_EXTRA_LAZY; $class->associationMappings['groups']['fetch'] = ClassMetadataInfo::FETCH_EXTRA_LAZY; $this->loadFixtureData(); @@ -529,7 +538,7 @@ private function useCMSArticleTopicFilter() public function testOneToMany_ExtraLazyCountWithFilter() { $this->loadLazyFixtureData(); - $user = $this->_em->find('Doctrine\Tests\Models\CMS\CmsUser', $this->userId); + $user = $this->_em->find(CmsUser::class, $this->userId); $this->assertFalse($user->articles->isInitialized()); $this->assertEquals(2, count($user->articles)); @@ -542,8 +551,8 @@ public function testOneToMany_ExtraLazyCountWithFilter() public function testOneToMany_ExtraLazyContainsWithFilter() { $this->loadLazyFixtureData(); - $user = $this->_em->find('Doctrine\Tests\Models\CMS\CmsUser', $this->userId); - $filteredArticle = $this->_em->find('Doctrine\Tests\Models\CMS\CmsArticle', $this->articleId2); + $user = $this->_em->find(CmsUser::class, $this->userId); + $filteredArticle = $this->_em->find(CmsArticle::class, $this->articleId2); $this->assertFalse($user->articles->isInitialized()); $this->assertTrue($user->articles->contains($filteredArticle)); @@ -556,7 +565,7 @@ public function testOneToMany_ExtraLazyContainsWithFilter() public function testOneToMany_ExtraLazySliceWithFilter() { $this->loadLazyFixtureData(); - $user = $this->_em->find('Doctrine\Tests\Models\CMS\CmsUser', $this->userId); + $user = $this->_em->find(CmsUser::class, $this->userId); $this->assertFalse($user->articles->isInitialized()); $this->assertEquals(2, count($user->articles->slice(0,10))); @@ -577,7 +586,7 @@ public function testManyToMany_ExtraLazyCountWithFilter() { $this->loadLazyFixtureData(); - $user = $this->_em->find('Doctrine\Tests\Models\CMS\CmsUser', $this->userId2); + $user = $this->_em->find(CmsUser::class, $this->userId2); $this->assertFalse($user->groups->isInitialized()); $this->assertEquals(2, count($user->groups)); @@ -590,8 +599,8 @@ public function testManyToMany_ExtraLazyCountWithFilter() public function testManyToMany_ExtraLazyContainsWithFilter() { $this->loadLazyFixtureData(); - $user = $this->_em->find('Doctrine\Tests\Models\CMS\CmsUser', $this->userId2); - $filteredArticle = $this->_em->find('Doctrine\Tests\Models\CMS\CmsGroup', $this->groupId2); + $user = $this->_em->find(CmsUser::class, $this->userId2); + $filteredArticle = $this->_em->find(CmsGroup::class, $this->groupId2); $this->assertFalse($user->groups->isInitialized()); $this->assertTrue($user->groups->contains($filteredArticle)); @@ -604,7 +613,7 @@ public function testManyToMany_ExtraLazyContainsWithFilter() public function testManyToMany_ExtraLazySliceWithFilter() { $this->loadLazyFixtureData(); - $user = $this->_em->find('Doctrine\Tests\Models\CMS\CmsUser', $this->userId2); + $user = $this->_em->find(CmsUser::class, $this->userId2); $this->assertFalse($user->groups->isInitialized()); $this->assertEquals(2, count($user->groups->slice(0,10))); @@ -682,14 +691,14 @@ public function testJoinSubclassPersister_FilterOnlyOnRootTableWhenFetchingSubEn { $this->loadCompanyJoinedSubclassFixtureData(); // Persister - $this->assertEquals(2, count($this->_em->getRepository('Doctrine\Tests\Models\Company\CompanyManager')->findAll())); + $this->assertEquals(2, count($this->_em->getRepository(CompanyManager::class)->findAll())); // SQLWalker $this->assertEquals(2, count($this->_em->createQuery("SELECT cm FROM Doctrine\Tests\Models\Company\CompanyManager cm")->getResult())); // Enable the filter $this->usePersonNameFilter('Guilh%'); - $managers = $this->_em->getRepository('Doctrine\Tests\Models\Company\CompanyManager')->findAll(); + $managers = $this->_em->getRepository(CompanyManager::class)->findAll(); $this->assertEquals(1, count($managers)); $this->assertEquals("Guilherme", $managers[0]->getName()); @@ -699,13 +708,13 @@ public function testJoinSubclassPersister_FilterOnlyOnRootTableWhenFetchingSubEn public function testJoinSubclassPersister_FilterOnlyOnRootTableWhenFetchingRootEntity() { $this->loadCompanyJoinedSubclassFixtureData(); - $this->assertEquals(3, count($this->_em->getRepository('Doctrine\Tests\Models\Company\CompanyPerson')->findAll())); + $this->assertEquals(3, count($this->_em->getRepository(CompanyPerson::class)->findAll())); $this->assertEquals(3, count($this->_em->createQuery("SELECT cp FROM Doctrine\Tests\Models\Company\CompanyPerson cp")->getResult())); // Enable the filter $this->usePersonNameFilter('Guilh%'); - $persons = $this->_em->getRepository('Doctrine\Tests\Models\Company\CompanyPerson')->findAll(); + $persons = $this->_em->getRepository(CompanyPerson::class)->findAll(); $this->assertEquals(1, count($persons)); $this->assertEquals("Guilherme", $persons[0]->getName()); @@ -740,7 +749,7 @@ public function testSingleTableInheritance_FilterOnlyOnRootTableWhenFetchingSubE { $this->loadCompanySingleTableInheritanceFixtureData(); // Persister - $this->assertEquals(2, count($this->_em->getRepository('Doctrine\Tests\Models\Company\CompanyFlexUltraContract')->findAll())); + $this->assertEquals(2, count($this->_em->getRepository(CompanyFlexUltraContract::class)->findAll())); // SQLWalker $this->assertEquals(2, count($this->_em->createQuery("SELECT cfc FROM Doctrine\Tests\Models\Company\CompanyFlexUltraContract cfc")->getResult())); @@ -751,14 +760,14 @@ public function testSingleTableInheritance_FilterOnlyOnRootTableWhenFetchingSubE ->enable("completed_contract") ->setParameter("completed", true, DBALType::BOOLEAN); - $this->assertEquals(1, count($this->_em->getRepository('Doctrine\Tests\Models\Company\CompanyFlexUltraContract')->findAll())); + $this->assertEquals(1, count($this->_em->getRepository(CompanyFlexUltraContract::class)->findAll())); $this->assertEquals(1, count($this->_em->createQuery("SELECT cfc FROM Doctrine\Tests\Models\Company\CompanyFlexUltraContract cfc")->getResult())); } public function testSingleTableInheritance_FilterOnlyOnRootTableWhenFetchingRootEntity() { $this->loadCompanySingleTableInheritanceFixtureData(); - $this->assertEquals(4, count($this->_em->getRepository('Doctrine\Tests\Models\Company\CompanyFlexContract')->findAll())); + $this->assertEquals(4, count($this->_em->getRepository(CompanyFlexContract::class)->findAll())); $this->assertEquals(4, count($this->_em->createQuery("SELECT cfc FROM Doctrine\Tests\Models\Company\CompanyFlexContract cfc")->getResult())); // Enable the filter @@ -768,7 +777,7 @@ public function testSingleTableInheritance_FilterOnlyOnRootTableWhenFetchingRoot ->enable("completed_contract") ->setParameter("completed", true, DBALType::BOOLEAN); - $this->assertEquals(2, count($this->_em->getRepository('Doctrine\Tests\Models\Company\CompanyFlexContract')->findAll())); + $this->assertEquals(2, count($this->_em->getRepository(CompanyFlexContract::class)->findAll())); $this->assertEquals(2, count($this->_em->createQuery("SELECT cfc FROM Doctrine\Tests\Models\Company\CompanyFlexContract cfc")->getResult())); } @@ -832,7 +841,7 @@ public function testManyToMany_ExtraLazyCountWithFilterOnSTI() { $this->loadCompanySingleTableInheritanceFixtureData(); - $manager = $this->_em->find('Doctrine\Tests\Models\Company\CompanyManager', $this->managerId); + $manager = $this->_em->find(CompanyManager::class, $this->managerId); $this->assertFalse($manager->managedContracts->isInitialized()); $this->assertEquals(4, count($manager->managedContracts)); @@ -848,9 +857,9 @@ public function testManyToMany_ExtraLazyContainsWithFilterOnSTI() { $this->loadCompanySingleTableInheritanceFixtureData(); - $manager = $this->_em->find('Doctrine\Tests\Models\Company\CompanyManager', $this->managerId); - $contract1 = $this->_em->find('Doctrine\Tests\Models\Company\CompanyContract', $this->contractId1); - $contract2 = $this->_em->find('Doctrine\Tests\Models\Company\CompanyContract', $this->contractId2); + $manager = $this->_em->find(CompanyManager::class, $this->managerId); + $contract1 = $this->_em->find(CompanyContract::class, $this->contractId1); + $contract2 = $this->_em->find(CompanyContract::class, $this->contractId2); $this->assertFalse($manager->managedContracts->isInitialized()); $this->assertTrue($manager->managedContracts->contains($contract1)); @@ -868,7 +877,7 @@ public function testManyToMany_ExtraLazySliceWithFilterOnSTI() { $this->loadCompanySingleTableInheritanceFixtureData(); - $manager = $this->_em->find('Doctrine\Tests\Models\Company\CompanyManager', $this->managerId); + $manager = $this->_em->find(CompanyManager::class, $this->managerId); $this->assertFalse($manager->managedContracts->isInitialized()); $this->assertEquals(4, count($manager->managedContracts->slice(0, 10))); @@ -894,7 +903,7 @@ public function testManyToMany_ExtraLazyCountWithFilterOnCTI() { $this->loadCompanySingleTableInheritanceFixtureData(); - $contract = $this->_em->find('Doctrine\Tests\Models\Company\CompanyFlexUltraContract', $this->contractId1); + $contract = $this->_em->find(CompanyFlexUltraContract::class, $this->contractId1); $this->assertFalse($contract->managers->isInitialized()); $this->assertEquals(2, count($contract->managers)); @@ -910,9 +919,9 @@ public function testManyToMany_ExtraLazyContainsWithFilterOnCTI() { $this->loadCompanySingleTableInheritanceFixtureData(); - $contract = $this->_em->find('Doctrine\Tests\Models\Company\CompanyFlexUltraContract', $this->contractId1); - $manager1 = $this->_em->find('Doctrine\Tests\Models\Company\CompanyManager', $this->managerId); - $manager2 = $this->_em->find('Doctrine\Tests\Models\Company\CompanyManager', $this->managerId2); + $contract = $this->_em->find(CompanyFlexUltraContract::class, $this->contractId1); + $manager1 = $this->_em->find(CompanyManager::class, $this->managerId); + $manager2 = $this->_em->find(CompanyManager::class, $this->managerId2); $this->assertFalse($contract->managers->isInitialized()); $this->assertTrue($contract->managers->contains($manager1)); @@ -930,7 +939,7 @@ public function testManyToMany_ExtraLazySliceWithFilterOnCTI() { $this->loadCompanySingleTableInheritanceFixtureData(); - $contract = $this->_em->find('Doctrine\Tests\Models\Company\CompanyFlexUltraContract', $this->contractId1); + $contract = $this->_em->find(CompanyFlexUltraContract::class, $this->contractId1); $this->assertFalse($contract->managers->isInitialized()); $this->assertEquals(2, count($contract->managers->slice(0, 10))); @@ -946,7 +955,7 @@ public function testOneToMany_ExtraLazyCountWithFilterOnSTI() { $this->loadCompanySingleTableInheritanceFixtureData(); - $manager = $this->_em->find('Doctrine\Tests\Models\Company\CompanyManager', $this->managerId); + $manager = $this->_em->find(CompanyManager::class, $this->managerId); $this->assertFalse($manager->soldContracts->isInitialized()); $this->assertEquals(2, count($manager->soldContracts)); @@ -962,9 +971,9 @@ public function testOneToMany_ExtraLazyContainsWithFilterOnSTI() { $this->loadCompanySingleTableInheritanceFixtureData(); - $manager = $this->_em->find('Doctrine\Tests\Models\Company\CompanyManager', $this->managerId); - $contract1 = $this->_em->find('Doctrine\Tests\Models\Company\CompanyContract', $this->contractId1); - $contract2 = $this->_em->find('Doctrine\Tests\Models\Company\CompanyContract', $this->contractId2); + $manager = $this->_em->find(CompanyManager::class, $this->managerId); + $contract1 = $this->_em->find(CompanyContract::class, $this->contractId1); + $contract2 = $this->_em->find(CompanyContract::class, $this->contractId2); $this->assertFalse($manager->soldContracts->isInitialized()); $this->assertTrue($manager->soldContracts->contains($contract1)); @@ -983,7 +992,7 @@ public function testOneToMany_ExtraLazySliceWithFilterOnSTI() $this->loadCompanySingleTableInheritanceFixtureData(); - $manager = $this->_em->find('Doctrine\Tests\Models\Company\CompanyManager', $this->managerId); + $manager = $this->_em->find(CompanyManager::class, $this->managerId); $this->assertFalse($manager->soldContracts->isInitialized()); $this->assertEquals(2, count($manager->soldContracts->slice(0, 10))); @@ -1020,7 +1029,7 @@ private function useCompanyEventIdFilter() { // Enable the filter $conf = $this->_em->getConfiguration(); - $conf->addFilter("event_id", "\Doctrine\Tests\ORM\Functional\CompanyEventFilter"); + $conf->addFilter("event_id", CompanyEventFilter::class); $this->_em->getFilters() ->enable("event_id") ->setParameter("id", $this->eventId2); @@ -1031,7 +1040,7 @@ public function testOneToMany_ExtraLazyCountWithFilterOnCTI() { $this->loadCompanyOrganizationEventJoinedSubclassFixtureData(); - $organization = $this->_em->find('Doctrine\Tests\Models\Company\CompanyOrganization', $this->organizationId); + $organization = $this->_em->find(CompanyOrganization::class, $this->organizationId); $this->assertFalse($organization->events->isInitialized()); $this->assertEquals(2, count($organization->events)); @@ -1047,10 +1056,10 @@ public function testOneToMany_ExtraLazyContainsWithFilterOnCTI() { $this->loadCompanyOrganizationEventJoinedSubclassFixtureData(); - $organization = $this->_em->find('Doctrine\Tests\Models\Company\CompanyOrganization', $this->organizationId); + $organization = $this->_em->find(CompanyOrganization::class, $this->organizationId); - $event1 = $this->_em->find('Doctrine\Tests\Models\Company\CompanyEvent', $this->eventId1); - $event2 = $this->_em->find('Doctrine\Tests\Models\Company\CompanyEvent', $this->eventId2); + $event1 = $this->_em->find(CompanyEvent::class, $this->eventId1); + $event2 = $this->_em->find(CompanyEvent::class, $this->eventId2); $this->assertFalse($organization->events->isInitialized()); $this->assertTrue($organization->events->contains($event1)); @@ -1068,7 +1077,7 @@ public function testOneToMany_ExtraLazySliceWithFilterOnCTI() { $this->loadCompanyOrganizationEventJoinedSubclassFixtureData(); - $organization = $this->_em->find('Doctrine\Tests\Models\Company\CompanyOrganization', $this->organizationId); + $organization = $this->_em->find(CompanyOrganization::class, $this->organizationId); $this->assertFalse($organization->events->isInitialized()); $this->assertEquals(2, count($organization->events->slice(0, 10))); @@ -1109,7 +1118,7 @@ class CMSCountryFilter extends SQLFilter { public function addFilterConstraint(ClassMetadata $targetEntity, $targetTableAlias) { - if ($targetEntity->name != "Doctrine\Tests\Models\CMS\CmsAddress") { + if ($targetEntity->name != CmsAddress::class) { return ""; } @@ -1121,7 +1130,7 @@ class CMSGroupPrefixFilter extends SQLFilter { public function addFilterConstraint(ClassMetadata $targetEntity, $targetTableAlias) { - if ($targetEntity->name != "Doctrine\Tests\Models\CMS\CmsGroup") { + if ($targetEntity->name != CmsGroup::class) { return ""; } @@ -1133,7 +1142,7 @@ class CMSArticleTopicFilter extends SQLFilter { public function addFilterConstraint(ClassMetadata $targetEntity, $targetTableAlias) { - if ($targetEntity->name != "Doctrine\Tests\Models\CMS\CmsArticle") { + if ($targetEntity->name != CmsArticle::class) { return ""; } @@ -1145,7 +1154,7 @@ class CompanyPersonNameFilter extends SQLFilter { public function addFilterConstraint(ClassMetadata $targetEntity, $targetTableAlias, $targetTable = '') { - if ($targetEntity->name != "Doctrine\Tests\Models\Company\CompanyPerson") { + if ($targetEntity->name != CompanyPerson::class) { return ""; } @@ -1157,7 +1166,7 @@ class CompletedContractFilter extends SQLFilter { public function addFilterConstraint(ClassMetadata $targetEntity, $targetTableAlias, $targetTable = '') { - if ($targetEntity->name != "Doctrine\Tests\Models\Company\CompanyContract") { + if ($targetEntity->name != CompanyContract::class) { return ""; } @@ -1169,7 +1178,7 @@ class CompanyEventFilter extends SQLFilter { public function addFilterConstraint(ClassMetadata $targetEntity, $targetTableAlias, $targetTable = '') { - if ($targetEntity->name != "Doctrine\Tests\Models\Company\CompanyEvent") { + if ($targetEntity->name != CompanyEvent::class) { return ""; } diff --git a/tests/Doctrine/Tests/ORM/Functional/SchemaTool/CompanySchemaTest.php b/tests/Doctrine/Tests/ORM/Functional/SchemaTool/CompanySchemaTest.php index 32c75d25de6..1a36591cf53 100644 --- a/tests/Doctrine/Tests/ORM/Functional/SchemaTool/CompanySchemaTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/SchemaTool/CompanySchemaTest.php @@ -3,6 +3,7 @@ namespace Doctrine\Tests\ORM\Functional\SchemaTool; use Doctrine\DBAL\Schema\Schema; +use Doctrine\Tests\Models\Company\CompanyManager; use Doctrine\Tests\OrmFunctionalTestCase; /** @@ -59,9 +60,11 @@ public function testDropPartSchemaWithForeignKeys() $this->markTestSkipped("Foreign Key test"); } - $sql = $this->_schemaTool->getDropSchemaSQL(array( - $this->_em->getClassMetadata('Doctrine\Tests\Models\Company\CompanyManager'), - )); + $sql = $this->_schemaTool->getDropSchemaSQL( + [ + $this->_em->getClassMetadata(CompanyManager::class), + ] + ); $this->assertEquals(4, count($sql)); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/SchemaTool/DBAL483Test.php b/tests/Doctrine/Tests/ORM/Functional/SchemaTool/DBAL483Test.php index 22debe96212..8a874c478a7 100644 --- a/tests/Doctrine/Tests/ORM/Functional/SchemaTool/DBAL483Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/SchemaTool/DBAL483Test.php @@ -21,11 +21,11 @@ public function setUp() */ public function testDefaultValueIsComparedCorrectly() { - $class = $this->_em->getClassMetadata(__NAMESPACE__ . '\\DBAL483Default'); + $class = $this->_em->getClassMetadata(DBAL483Default::class); - $this->schemaTool->createSchema(array($class)); + $this->schemaTool->createSchema([$class]); - $updateSql = $this->schemaTool->getUpdateSchemaSql(array($class)); + $updateSql = $this->schemaTool->getUpdateSchemaSql([$class]); $updateSql = array_filter($updateSql, function ($sql) { return strpos($sql, 'DBAL483') !== false; diff --git a/tests/Doctrine/Tests/ORM/Functional/SchemaTool/DDC214Test.php b/tests/Doctrine/Tests/ORM/Functional/SchemaTool/DDC214Test.php index 4b4d0328d50..8c414b119a3 100644 --- a/tests/Doctrine/Tests/ORM/Functional/SchemaTool/DDC214Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/SchemaTool/DDC214Test.php @@ -4,6 +4,7 @@ use Doctrine\DBAL\Schema\Comparator; use Doctrine\ORM\Tools; +use Doctrine\Tests\Models; use Doctrine\Tests\OrmFunctionalTestCase; /** @@ -11,7 +12,7 @@ */ class DDC214Test extends OrmFunctionalTestCase { - private $classes = array(); + private $classes = []; private $schemaTool = null; public function setUp() @@ -31,14 +32,14 @@ public function setUp() */ public function testCmsAddressModel() { - $this->classes = array( - 'Doctrine\Tests\Models\CMS\CmsUser', - 'Doctrine\Tests\Models\CMS\CmsPhonenumber', - 'Doctrine\Tests\Models\CMS\CmsAddress', - 'Doctrine\Tests\Models\CMS\CmsGroup', - 'Doctrine\Tests\Models\CMS\CmsArticle', - 'Doctrine\Tests\Models\CMS\CmsEmail', - ); + $this->classes = [ + Models\CMS\CmsUser::class, + Models\CMS\CmsPhonenumber::class, + Models\CMS\CmsAddress::class, + Models\CMS\CmsGroup::class, + Models\CMS\CmsArticle::class, + Models\CMS\CmsEmail::class, + ]; $this->assertCreatedSchemaNeedsNoUpdates($this->classes); } @@ -48,23 +49,23 @@ public function testCmsAddressModel() */ public function testCompanyModel() { - $this->classes = array( - 'Doctrine\Tests\Models\Company\CompanyPerson', - 'Doctrine\Tests\Models\Company\CompanyEmployee', - 'Doctrine\Tests\Models\Company\CompanyManager', - 'Doctrine\Tests\Models\Company\CompanyOrganization', - 'Doctrine\Tests\Models\Company\CompanyEvent', - 'Doctrine\Tests\Models\Company\CompanyAuction', - 'Doctrine\Tests\Models\Company\CompanyRaffle', - 'Doctrine\Tests\Models\Company\CompanyCar' - ); + $this->classes = [ + Models\Company\CompanyPerson::class, + Models\Company\CompanyEmployee::class, + Models\Company\CompanyManager::class, + Models\Company\CompanyOrganization::class, + Models\Company\CompanyEvent::class, + Models\Company\CompanyAuction::class, + Models\Company\CompanyRaffle::class, + Models\Company\CompanyCar::class + ]; $this->assertCreatedSchemaNeedsNoUpdates($this->classes); } public function assertCreatedSchemaNeedsNoUpdates($classes) { - $classMetadata = array(); + $classMetadata = []; foreach ($classes AS $class) { $classMetadata[] = $this->_em->getClassMetadata($class); } diff --git a/tests/Doctrine/Tests/ORM/Functional/SchemaTool/MySqlSchemaToolTest.php b/tests/Doctrine/Tests/ORM/Functional/SchemaTool/MySqlSchemaToolTest.php index a923c40fca3..829b3aa2b85 100644 --- a/tests/Doctrine/Tests/ORM/Functional/SchemaTool/MySqlSchemaToolTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/SchemaTool/MySqlSchemaToolTest.php @@ -4,6 +4,9 @@ use Doctrine\ORM\Tools\SchemaTool; use Doctrine\Tests\OrmFunctionalTestCase; +use Doctrine\Tests\Models; +use function method_exists; +use function sprintf; class MySqlSchemaToolTest extends OrmFunctionalTestCase { @@ -16,26 +19,27 @@ protected function setUp() { public function testGetCreateSchemaSql() { - $classes = array( - $this->_em->getClassMetadata('Doctrine\Tests\Models\CMS\CmsGroup'), - $this->_em->getClassMetadata('Doctrine\Tests\Models\CMS\CmsUser'), - $this->_em->getClassMetadata('Doctrine\Tests\Models\CMS\CmsTag'), - $this->_em->getClassMetadata('Doctrine\Tests\Models\CMS\CmsAddress'), - $this->_em->getClassMetadata('Doctrine\Tests\Models\CMS\CmsEmail'), - $this->_em->getClassMetadata('Doctrine\Tests\Models\CMS\CmsPhonenumber'), - ); + $classes = [ + $this->_em->getClassMetadata(Models\CMS\CmsGroup::class), + $this->_em->getClassMetadata(Models\CMS\CmsUser::class), + $this->_em->getClassMetadata(Models\CMS\CmsTag::class), + $this->_em->getClassMetadata(Models\CMS\CmsAddress::class), + $this->_em->getClassMetadata(Models\CMS\CmsEmail::class), + $this->_em->getClassMetadata(Models\CMS\CmsPhonenumber::class), + ]; $tool = new SchemaTool($this->_em); $sql = $tool->getCreateSchemaSql($classes); - - $this->assertEquals("CREATE TABLE cms_groups (id INT AUTO_INCREMENT NOT NULL, name VARCHAR(50) NOT NULL, PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB", $sql[0]); - $this->assertEquals("CREATE TABLE cms_users (id INT AUTO_INCREMENT NOT NULL, email_id INT DEFAULT NULL, status VARCHAR(50) DEFAULT NULL, username VARCHAR(255) NOT NULL, name VARCHAR(255) NOT NULL, UNIQUE INDEX UNIQ_3AF03EC5F85E0677 (username), UNIQUE INDEX UNIQ_3AF03EC5A832C1C9 (email_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB", $sql[1]); - $this->assertEquals("CREATE TABLE cms_users_groups (user_id INT NOT NULL, group_id INT NOT NULL, INDEX IDX_7EA9409AA76ED395 (user_id), INDEX IDX_7EA9409AFE54D947 (group_id), PRIMARY KEY(user_id, group_id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB", $sql[2]); - $this->assertEquals("CREATE TABLE cms_users_tags (user_id INT NOT NULL, tag_id INT NOT NULL, INDEX IDX_93F5A1ADA76ED395 (user_id), INDEX IDX_93F5A1ADBAD26311 (tag_id), PRIMARY KEY(user_id, tag_id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB", $sql[3]); - $this->assertEquals("CREATE TABLE cms_tags (id INT AUTO_INCREMENT NOT NULL, tag_name VARCHAR(50) DEFAULT NULL, PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB", $sql[4]); - $this->assertEquals("CREATE TABLE cms_addresses (id INT AUTO_INCREMENT NOT NULL, user_id INT DEFAULT NULL, country VARCHAR(50) NOT NULL, zip VARCHAR(50) NOT NULL, city VARCHAR(50) NOT NULL, UNIQUE INDEX UNIQ_ACAC157BA76ED395 (user_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB", $sql[5]); - $this->assertEquals("CREATE TABLE cms_emails (id INT AUTO_INCREMENT NOT NULL, email VARCHAR(250) NOT NULL, PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB", $sql[6]); - $this->assertEquals("CREATE TABLE cms_phonenumbers (phonenumber VARCHAR(50) NOT NULL, user_id INT DEFAULT NULL, INDEX IDX_F21F790FA76ED395 (user_id), PRIMARY KEY(phonenumber)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB", $sql[7]); + $collation = $this->getColumnCollationDeclarationSQL('utf8_unicode_ci'); + + $this->assertEquals('CREATE TABLE cms_groups (id INT AUTO_INCREMENT NOT NULL, name VARCHAR(50) NOT NULL, PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 ' . $collation . ' ENGINE = InnoDB', $sql[0]); + $this->assertEquals('CREATE TABLE cms_users (id INT AUTO_INCREMENT NOT NULL, email_id INT DEFAULT NULL, status VARCHAR(50) DEFAULT NULL, username VARCHAR(255) NOT NULL, name VARCHAR(255) NOT NULL, UNIQUE INDEX UNIQ_3AF03EC5F85E0677 (username), UNIQUE INDEX UNIQ_3AF03EC5A832C1C9 (email_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 ' . $collation . ' ENGINE = InnoDB', $sql[1]); + $this->assertEquals('CREATE TABLE cms_users_groups (user_id INT NOT NULL, group_id INT NOT NULL, INDEX IDX_7EA9409AA76ED395 (user_id), INDEX IDX_7EA9409AFE54D947 (group_id), PRIMARY KEY(user_id, group_id)) DEFAULT CHARACTER SET utf8 ' . $collation . ' ENGINE = InnoDB', $sql[2]); + $this->assertEquals('CREATE TABLE cms_users_tags (user_id INT NOT NULL, tag_id INT NOT NULL, INDEX IDX_93F5A1ADA76ED395 (user_id), INDEX IDX_93F5A1ADBAD26311 (tag_id), PRIMARY KEY(user_id, tag_id)) DEFAULT CHARACTER SET utf8 ' . $collation . ' ENGINE = InnoDB', $sql[3]); + $this->assertEquals('CREATE TABLE cms_tags (id INT AUTO_INCREMENT NOT NULL, tag_name VARCHAR(50) DEFAULT NULL, PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 ' . $collation . ' ENGINE = InnoDB', $sql[4]); + $this->assertEquals('CREATE TABLE cms_addresses (id INT AUTO_INCREMENT NOT NULL, user_id INT DEFAULT NULL, country VARCHAR(50) NOT NULL, zip VARCHAR(50) NOT NULL, city VARCHAR(50) NOT NULL, UNIQUE INDEX UNIQ_ACAC157BA76ED395 (user_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 ' . $collation . ' ENGINE = InnoDB', $sql[5]); + $this->assertEquals('CREATE TABLE cms_emails (id INT AUTO_INCREMENT NOT NULL, email VARCHAR(250) NOT NULL, PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 ' . $collation . ' ENGINE = InnoDB', $sql[6]); + $this->assertEquals('CREATE TABLE cms_phonenumbers (phonenumber VARCHAR(50) NOT NULL, user_id INT DEFAULT NULL, INDEX IDX_F21F790FA76ED395 (user_id), PRIMARY KEY(phonenumber)) DEFAULT CHARACTER SET utf8 ' . $collation . ' ENGINE = InnoDB', $sql[7]); $this->assertEquals("ALTER TABLE cms_users ADD CONSTRAINT FK_3AF03EC5A832C1C9 FOREIGN KEY (email_id) REFERENCES cms_emails (id)", $sql[8]); $this->assertEquals("ALTER TABLE cms_users_groups ADD CONSTRAINT FK_7EA9409AA76ED395 FOREIGN KEY (user_id) REFERENCES cms_users (id)", $sql[9]); $this->assertEquals("ALTER TABLE cms_users_groups ADD CONSTRAINT FK_7EA9409AFE54D947 FOREIGN KEY (group_id) REFERENCES cms_groups (id)", $sql[10]); @@ -47,30 +51,41 @@ public function testGetCreateSchemaSql() $this->assertEquals(15, count($sql)); } + private function getColumnCollationDeclarationSQL(string $collation) : string + { + if (method_exists($this->_em->getConnection()->getDatabasePlatform(), 'getColumnCollationDeclarationSQL')) { + return $this->_em->getConnection()->getDatabasePlatform()->getColumnCollationDeclarationSQL($collation); + } + + return sprintf('COLLATE %s', $collation); + } + public function testGetCreateSchemaSql2() { - $classes = array( - $this->_em->getClassMetadata('Doctrine\Tests\Models\Generic\DecimalModel') - ); + $classes = [ + $this->_em->getClassMetadata(Models\Generic\DecimalModel::class) + ]; $tool = new SchemaTool($this->_em); $sql = $tool->getCreateSchemaSql($classes); + $collation = $this->getColumnCollationDeclarationSQL('utf8_unicode_ci'); $this->assertEquals(1, count($sql)); - $this->assertEquals("CREATE TABLE decimal_model (id INT AUTO_INCREMENT NOT NULL, `decimal` NUMERIC(5, 2) NOT NULL, `high_scale` NUMERIC(14, 4) NOT NULL, PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB", $sql[0]); + $this->assertEquals('CREATE TABLE decimal_model (id INT AUTO_INCREMENT NOT NULL, `decimal` NUMERIC(5, 2) NOT NULL, `high_scale` NUMERIC(14, 4) NOT NULL, PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 ' . $collation . ' ENGINE = InnoDB', $sql[0]); } public function testGetCreateSchemaSql3() { - $classes = array( - $this->_em->getClassMetadata('Doctrine\Tests\Models\Generic\BooleanModel') - ); + $classes = [ + $this->_em->getClassMetadata(Models\Generic\BooleanModel::class) + ]; $tool = new SchemaTool($this->_em); $sql = $tool->getCreateSchemaSql($classes); + $collation = $this->getColumnCollationDeclarationSQL('utf8_unicode_ci'); $this->assertEquals(1, count($sql)); - $this->assertEquals("CREATE TABLE boolean_model (id INT AUTO_INCREMENT NOT NULL, booleanField TINYINT(1) NOT NULL, PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB", $sql[0]); + $this->assertEquals('CREATE TABLE boolean_model (id INT AUTO_INCREMENT NOT NULL, booleanField TINYINT(1) NOT NULL, PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 ' . $collation . ' ENGINE = InnoDB', $sql[0]); } /** @@ -78,9 +93,9 @@ public function testGetCreateSchemaSql3() */ public function testGetCreateSchemaSql4() { - $classes = array( - $this->_em->getClassMetadata(__NAMESPACE__ . '\\MysqlSchemaNamespacedEntity') - ); + $classes = [ + $this->_em->getClassMetadata(MysqlSchemaNamespacedEntity::class) + ]; $tool = new SchemaTool($this->_em); $sql = $tool->getCreateSchemaSql($classes); diff --git a/tests/Doctrine/Tests/ORM/Functional/SchemaTool/PostgreSqlSchemaToolTest.php b/tests/Doctrine/Tests/ORM/Functional/SchemaTool/PostgreSqlSchemaToolTest.php index f98fe4bebd5..5ebf84c5644 100644 --- a/tests/Doctrine/Tests/ORM/Functional/SchemaTool/PostgreSqlSchemaToolTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/SchemaTool/PostgreSqlSchemaToolTest.php @@ -3,6 +3,7 @@ namespace Doctrine\Tests\ORM\Functional\SchemaTool; use Doctrine\ORM\Tools\SchemaTool; +use Doctrine\Tests\Models; use Doctrine\Tests\OrmFunctionalTestCase; class PostgreSqlSchemaToolTest extends OrmFunctionalTestCase @@ -18,18 +19,18 @@ protected function setUp() public function testPostgresMetadataSequenceIncrementedBy10() { - $address = $this->_em->getClassMetadata('Doctrine\Tests\Models\CMS\CmsAddress'); + $address = $this->_em->getClassMetadata(Models\CMS\CmsAddress::class); $this->assertEquals(1, $address->sequenceGeneratorDefinition['allocationSize']); } public function testGetCreateSchemaSql() { - $classes = array( - $this->_em->getClassMetadata('Doctrine\Tests\Models\CMS\CmsAddress'), - $this->_em->getClassMetadata('Doctrine\Tests\Models\CMS\CmsUser'), - $this->_em->getClassMetadata('Doctrine\Tests\Models\CMS\CmsPhonenumber'), - ); + $classes = [ + $this->_em->getClassMetadata(Models\CMS\CmsAddress::class), + $this->_em->getClassMetadata(Models\CMS\CmsUser::class), + $this->_em->getClassMetadata(Models\CMS\CmsPhonenumber::class), + ]; $tool = new SchemaTool($this->_em); $sql = $tool->getCreateSchemaSql($classes); @@ -58,15 +59,15 @@ public function testGetCreateSchemaSql() $this->assertEquals("ALTER TABLE cms_users_tags ADD CONSTRAINT FK_93F5A1ADBAD26311 FOREIGN KEY (tag_id) REFERENCES cms_tags (id) NOT DEFERRABLE INITIALLY IMMEDIATE", array_shift($sql)); $this->assertEquals("ALTER TABLE cms_phonenumbers ADD CONSTRAINT FK_F21F790FA76ED395 FOREIGN KEY (user_id) REFERENCES cms_users (id) NOT DEFERRABLE INITIALLY IMMEDIATE", array_shift($sql)); - $this->assertEquals(array(), $sql, "SQL Array should be empty now."); + $this->assertEquals([], $sql, "SQL Array should be empty now."); $this->assertEquals(22, $sqlCount, "Total of 22 queries should be executed"); } public function testGetCreateSchemaSql2() { - $classes = array( - $this->_em->getClassMetadata('Doctrine\Tests\Models\Generic\DecimalModel') - ); + $classes = [ + $this->_em->getClassMetadata(Models\Generic\DecimalModel::class) + ]; $tool = new SchemaTool($this->_em); $sql = $tool->getCreateSchemaSql($classes); @@ -79,9 +80,9 @@ public function testGetCreateSchemaSql2() public function testGetCreateSchemaSql3() { - $classes = array( - $this->_em->getClassMetadata('Doctrine\Tests\Models\Generic\BooleanModel') - ); + $classes = [ + $this->_em->getClassMetadata(Models\Generic\BooleanModel::class) + ]; $tool = new SchemaTool($this->_em); $sql = $tool->getCreateSchemaSql($classes); @@ -93,11 +94,11 @@ public function testGetCreateSchemaSql3() public function testGetDropSchemaSql() { - $classes = array( - $this->_em->getClassMetadata('Doctrine\Tests\Models\CMS\CmsAddress'), - $this->_em->getClassMetadata('Doctrine\Tests\Models\CMS\CmsUser'), - $this->_em->getClassMetadata('Doctrine\Tests\Models\CMS\CmsPhonenumber'), - ); + $classes = [ + $this->_em->getClassMetadata(Models\CMS\CmsAddress::class), + $this->_em->getClassMetadata(Models\CMS\CmsUser::class), + $this->_em->getClassMetadata(Models\CMS\CmsPhonenumber::class), + ]; $tool = new SchemaTool($this->_em); $sql = $tool->getDropSchemaSQL($classes); @@ -119,10 +120,10 @@ public function testGetDropSchemaSql() */ public function testUpdateSchemaWithPostgreSQLSchema() { - $classes = array( - $this->_em->getClassMetadata(__NAMESPACE__ . '\\DDC1657Screen'), - $this->_em->getClassMetadata(__NAMESPACE__ . '\\DDC1657Avatar'), - ); + $classes = [ + $this->_em->getClassMetadata(DDC1657Screen::class), + $this->_em->getClassMetadata(DDC1657Avatar::class), + ]; $tool = new SchemaTool($this->_em); $tool->createSchema($classes); diff --git a/tests/Doctrine/Tests/ORM/Functional/SchemaValidatorTest.php b/tests/Doctrine/Tests/ORM/Functional/SchemaValidatorTest.php index 06eb67a2eb1..5ab0f07c07e 100644 --- a/tests/Doctrine/Tests/ORM/Functional/SchemaValidatorTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/SchemaValidatorTest.php @@ -3,7 +3,11 @@ namespace Doctrine\Tests\ORM\Functional; use Doctrine\ORM\Tools\SchemaValidator; +use Doctrine\Tests\DbalTypes\CustomIdObjectType; +use Doctrine\Tests\DbalTypes\NegativeToPositiveType; +use Doctrine\Tests\DbalTypes\UpperCaseStringType; use Doctrine\Tests\OrmFunctionalTestCase; +use Doctrine\DBAL\Types\Type as DBALType; /** * Test the validity of all modelsets @@ -12,26 +16,53 @@ */ class SchemaValidatorTest extends OrmFunctionalTestCase { - static public function dataValidateModelSets() + protected function setUp() { - $modelSets = array(); - foreach (self::$_modelSets as $modelSet => $classes) { - if ($modelSet == "customtype") { - continue; - } - $modelSets[] = array($modelSet); + $this->registerType(CustomIdObjectType::class); + $this->registerType(UpperCaseStringType::class); + $this->registerType(NegativeToPositiveType::class); + + parent::setUp(); + } + + /** + * @param string $className + * + * @throws \Doctrine\DBAL\DBALException + * + * @return void + */ + private function registerType(string $className) + { + $type = constant($className . '::NAME'); + + if (DBALType::hasType($type)) { + DBALType::overrideType($type, $className); + return; } + + DBALType::addType($type, $className); + } + + public static function dataValidateModelSets(): array + { + $modelSets = []; + + foreach (array_keys(self::$_modelSets) as $modelSet) { + $modelSets[$modelSet] = [$modelSet]; + } + return $modelSets; } /** * @dataProvider dataValidateModelSets */ - public function testValidateModelSets($modelSet) + public function testValidateModelSets(string $modelSet) { $validator = new SchemaValidator($this->_em); + $classes = []; - $classes = array(); foreach (self::$_modelSets[$modelSet] as $className) { $classes[] = $this->_em->getClassMetadata($className); } @@ -39,7 +70,7 @@ public function testValidateModelSets($modelSet) foreach ($classes as $class) { $ce = $validator->validateClass($class); - $this->assertEquals(0, count($ce), "Invalid Modelset: " . $modelSet . " class " . $class->name . ": ". implode("\n", $ce)); + $this->assertEmpty($ce, "Invalid Modelset: " . $modelSet . " class " . $class->name . ": ". implode("\n", $ce)); } } } diff --git a/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheAbstractTest.php b/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheAbstractTest.php index 320bbbb2f6a..becf7edbb4d 100644 --- a/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheAbstractTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheAbstractTest.php @@ -27,16 +27,16 @@ */ abstract class SecondLevelCacheAbstractTest extends OrmFunctionalTestCase { - protected $people = array(); - protected $addresses = array(); - protected $countries = array(); - protected $states = array(); - protected $cities = array(); - protected $travels = array(); - protected $travelers = array(); - protected $attractions = array(); - protected $attractionsInfo = array(); - protected $travelersWithProfile = array(); + protected $people = []; + protected $addresses = []; + protected $countries = []; + protected $states = []; + protected $cities = []; + protected $travels = []; + protected $travelers = []; + protected $attractions = []; + protected $attractionsInfo = []; + protected $travelersWithProfile = []; /** * @var \Doctrine\ORM\Cache @@ -280,4 +280,4 @@ protected function evictRegions() $this->cache->evictEntityRegions(); $this->cache->evictCollectionRegions(); } -} \ No newline at end of file +} diff --git a/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheCompositePrimaryKeyTest.php b/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheCompositePrimaryKeyTest.php index f5c10522532..9dff7df1d1c 100644 --- a/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheCompositePrimaryKeyTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheCompositePrimaryKeyTest.php @@ -21,35 +21,35 @@ public function testPutAndLoadCompositPrimaryKeyEntities() $leavingFromId = $this->cities[0]->getId(); $goingToId = $this->cities[1]->getId(); - $leavingFrom = $this->_em->find(City::CLASSNAME, $leavingFromId); - $goingTo = $this->_em->find(City::CLASSNAME, $goingToId); + $leavingFrom = $this->_em->find(City::class, $leavingFromId); + $goingTo = $this->_em->find(City::class, $goingToId); $flight = new Flight($leavingFrom, $goingTo); - $id = array( + $id = [ 'leavingFrom' => $leavingFromId, 'goingTo' => $goingToId, - ); + ]; $flight->setDeparture(new \DateTime('tomorrow')); - $this->assertTrue($this->cache->containsEntity(City::CLASSNAME, $this->cities[0]->getId())); - $this->assertTrue($this->cache->containsEntity(City::CLASSNAME, $this->cities[1]->getId())); + $this->assertTrue($this->cache->containsEntity(City::class, $this->cities[0]->getId())); + $this->assertTrue($this->cache->containsEntity(City::class, $this->cities[1]->getId())); $this->_em->persist($flight); $this->_em->flush(); $this->_em->clear(); - $this->assertTrue($this->cache->containsEntity(Flight::CLASSNAME, $id)); - $this->assertTrue($this->cache->containsEntity(City::CLASSNAME, $this->cities[0]->getId())); - $this->assertTrue($this->cache->containsEntity(City::CLASSNAME, $this->cities[1]->getId())); + $this->assertTrue($this->cache->containsEntity(Flight::class, $id)); + $this->assertTrue($this->cache->containsEntity(City::class, $this->cities[0]->getId())); + $this->assertTrue($this->cache->containsEntity(City::class, $this->cities[1]->getId())); $queryCount = $this->getCurrentQueryCount(); - $flight = $this->_em->find(Flight::CLASSNAME, $id); + $flight = $this->_em->find(Flight::class, $id); $leavingFrom = $flight->getLeavingFrom(); $goingTo = $flight->getGoingTo(); - $this->assertInstanceOf(Flight::CLASSNAME, $flight); - $this->assertInstanceOf(City::CLASSNAME, $goingTo); - $this->assertInstanceOf(City::CLASSNAME, $leavingFrom); + $this->assertInstanceOf(Flight::class, $flight); + $this->assertInstanceOf(City::class, $goingTo); + $this->assertInstanceOf(City::class, $leavingFrom); $this->assertEquals($goingTo->getId(), $goingToId); $this->assertEquals($leavingFrom->getId(), $leavingFromId); @@ -67,35 +67,35 @@ public function testRemoveCompositPrimaryKeyEntities() $leavingFromId = $this->cities[0]->getId(); $goingToId = $this->cities[1]->getId(); - $leavingFrom = $this->_em->find(City::CLASSNAME, $leavingFromId); - $goingTo = $this->_em->find(City::CLASSNAME, $goingToId); + $leavingFrom = $this->_em->find(City::class, $leavingFromId); + $goingTo = $this->_em->find(City::class, $goingToId); $flight = new Flight($leavingFrom, $goingTo); - $id = array( + $id = [ 'leavingFrom' => $leavingFromId, 'goingTo' => $goingToId, - ); + ]; $flight->setDeparture(new \DateTime('tomorrow')); - $this->assertTrue($this->cache->containsEntity(City::CLASSNAME, $this->cities[0]->getId())); - $this->assertTrue($this->cache->containsEntity(City::CLASSNAME, $this->cities[1]->getId())); + $this->assertTrue($this->cache->containsEntity(City::class, $this->cities[0]->getId())); + $this->assertTrue($this->cache->containsEntity(City::class, $this->cities[1]->getId())); $this->_em->persist($flight); $this->_em->flush(); - $this->assertTrue($this->cache->containsEntity(Flight::CLASSNAME, $id)); - $this->assertTrue($this->cache->containsEntity(City::CLASSNAME, $this->cities[0]->getId())); - $this->assertTrue($this->cache->containsEntity(City::CLASSNAME, $this->cities[1]->getId())); + $this->assertTrue($this->cache->containsEntity(Flight::class, $id)); + $this->assertTrue($this->cache->containsEntity(City::class, $this->cities[0]->getId())); + $this->assertTrue($this->cache->containsEntity(City::class, $this->cities[1]->getId())); $this->_em->remove($flight); $this->_em->flush(); $this->_em->clear(); - $this->assertFalse($this->cache->containsEntity(Flight::CLASSNAME, $id)); - $this->assertTrue($this->cache->containsEntity(City::CLASSNAME, $this->cities[0]->getId())); - $this->assertTrue($this->cache->containsEntity(City::CLASSNAME, $this->cities[1]->getId())); + $this->assertFalse($this->cache->containsEntity(Flight::class, $id)); + $this->assertTrue($this->cache->containsEntity(City::class, $this->cities[0]->getId())); + $this->assertTrue($this->cache->containsEntity(City::class, $this->cities[1]->getId())); - $this->assertNull($this->_em->find(Flight::CLASSNAME, $id)); + $this->assertNull($this->_em->find(Flight::class, $id)); } public function testUpdateCompositPrimaryKeyEntities() @@ -111,35 +111,35 @@ public function testUpdateCompositPrimaryKeyEntities() $tomorrow = new \DateTime('tomorrow'); $leavingFromId = $this->cities[0]->getId(); $goingToId = $this->cities[1]->getId(); - $leavingFrom = $this->_em->find(City::CLASSNAME, $leavingFromId); - $goingTo = $this->_em->find(City::CLASSNAME, $goingToId); + $leavingFrom = $this->_em->find(City::class, $leavingFromId); + $goingTo = $this->_em->find(City::class, $goingToId); $flight = new Flight($leavingFrom, $goingTo); - $id = array( + $id = [ 'leavingFrom' => $leavingFromId, 'goingTo' => $goingToId, - ); + ]; $flight->setDeparture($now); - $this->assertTrue($this->cache->containsEntity(City::CLASSNAME, $this->cities[0]->getId())); - $this->assertTrue($this->cache->containsEntity(City::CLASSNAME, $this->cities[1]->getId())); + $this->assertTrue($this->cache->containsEntity(City::class, $this->cities[0]->getId())); + $this->assertTrue($this->cache->containsEntity(City::class, $this->cities[1]->getId())); $this->_em->persist($flight); $this->_em->flush(); $this->_em->clear(); - $this->assertTrue($this->cache->containsEntity(Flight::CLASSNAME, $id)); - $this->assertTrue($this->cache->containsEntity(City::CLASSNAME, $this->cities[0]->getId())); - $this->assertTrue($this->cache->containsEntity(City::CLASSNAME, $this->cities[1]->getId())); + $this->assertTrue($this->cache->containsEntity(Flight::class, $id)); + $this->assertTrue($this->cache->containsEntity(City::class, $this->cities[0]->getId())); + $this->assertTrue($this->cache->containsEntity(City::class, $this->cities[1]->getId())); $queryCount = $this->getCurrentQueryCount(); - $flight = $this->_em->find(Flight::CLASSNAME, $id); + $flight = $this->_em->find(Flight::class, $id); $leavingFrom = $flight->getLeavingFrom(); $goingTo = $flight->getGoingTo(); - $this->assertInstanceOf(Flight::CLASSNAME, $flight); - $this->assertInstanceOf(City::CLASSNAME, $goingTo); - $this->assertInstanceOf(City::CLASSNAME, $leavingFrom); + $this->assertInstanceOf(Flight::class, $flight); + $this->assertInstanceOf(City::class, $goingTo); + $this->assertInstanceOf(City::class, $leavingFrom); $this->assertEquals($goingTo->getId(), $goingToId); $this->assertEquals($flight->getDeparture(), $now); @@ -153,18 +153,18 @@ public function testUpdateCompositPrimaryKeyEntities() $this->_em->flush(); $this->_em->clear(); - $this->assertTrue($this->cache->containsEntity(Flight::CLASSNAME, $id)); - $this->assertTrue($this->cache->containsEntity(City::CLASSNAME, $this->cities[0]->getId())); - $this->assertTrue($this->cache->containsEntity(City::CLASSNAME, $this->cities[1]->getId())); + $this->assertTrue($this->cache->containsEntity(Flight::class, $id)); + $this->assertTrue($this->cache->containsEntity(City::class, $this->cities[0]->getId())); + $this->assertTrue($this->cache->containsEntity(City::class, $this->cities[1]->getId())); $queryCount = $this->getCurrentQueryCount(); - $flight = $this->_em->find(Flight::CLASSNAME, $id); + $flight = $this->_em->find(Flight::class, $id); $leavingFrom = $flight->getLeavingFrom(); $goingTo = $flight->getGoingTo(); - $this->assertInstanceOf(Flight::CLASSNAME, $flight); - $this->assertInstanceOf(City::CLASSNAME, $goingTo); - $this->assertInstanceOf(City::CLASSNAME, $leavingFrom); + $this->assertInstanceOf(Flight::class, $flight); + $this->assertInstanceOf(City::class, $goingTo); + $this->assertInstanceOf(City::class, $leavingFrom); $this->assertEquals($goingTo->getId(), $goingToId); $this->assertEquals($flight->getDeparture(), $tomorrow); @@ -172,4 +172,4 @@ public function testUpdateCompositPrimaryKeyEntities() $this->assertEquals($leavingFrom->getId(), $leavingFromId); $this->assertEquals($queryCount, $this->getCurrentQueryCount()); } -} \ No newline at end of file +} diff --git a/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheCompositePrimaryKeyWithAssociationsTest.php b/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheCompositePrimaryKeyWithAssociationsTest.php index dc4f40db07d..8af09c9bf0d 100644 --- a/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheCompositePrimaryKeyWithAssociationsTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheCompositePrimaryKeyWithAssociationsTest.php @@ -2,10 +2,10 @@ namespace Doctrine\Tests\ORM\Functional; -use Doctrine\Tests\OrmFunctionalTestCase; -use Doctrine\Tests\Models\GeoNames\Country; use Doctrine\Tests\Models\GeoNames\Admin1; use Doctrine\Tests\Models\GeoNames\Admin1AlternateName; +use Doctrine\Tests\Models\GeoNames\Country; +use Doctrine\Tests\OrmFunctionalTestCase; class SecondLevelCacheCompositePrimaryKeyWithAssociationsTest extends OrmFunctionalTestCase { @@ -51,11 +51,11 @@ public function setUp() public function testFindByReturnsCachedEntity() { - $admin1Repo = $this->_em->getRepository('Doctrine\Tests\Models\GeoNames\Admin1'); + $admin1Repo = $this->_em->getRepository(Admin1::class); $queries = $this->getCurrentQueryCount(); - $admin1Rome = $admin1Repo->findOneBy(array('country' => 'IT', 'id' => 1)); + $admin1Rome = $admin1Repo->findOneBy(['country' => 'IT', 'id' => 1]); $this->assertEquals("Italy", $admin1Rome->country->name); $this->assertEquals(2, count($admin1Rome->names)); @@ -65,7 +65,7 @@ public function testFindByReturnsCachedEntity() $queries = $this->getCurrentQueryCount(); - $admin1Rome = $admin1Repo->findOneBy(array('country' => 'IT', 'id' => 1)); + $admin1Rome = $admin1Repo->findOneBy(['country' => 'IT', 'id' => 1]); $this->assertEquals("Italy", $admin1Rome->country->name); $this->assertEquals(2, count($admin1Rome->names)); diff --git a/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheConcurrentTest.php b/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheConcurrentTest.php index f4d8e6b768d..0f4ca383284 100644 --- a/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheConcurrentTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheConcurrentTest.php @@ -37,19 +37,19 @@ protected function setUp() ->getSecondLevelCacheConfiguration() ->setCacheFactory($this->cacheFactory); - $this->countryMetadata = $this->_em->getClassMetadata(Country::CLASSNAME); + $this->countryMetadata = $this->_em->getClassMetadata(Country::class); $countryMetadata = clone $this->countryMetadata; $countryMetadata->cache['usage'] = ClassMetadata::CACHE_USAGE_NONSTRICT_READ_WRITE; - $this->_em->getMetadataFactory()->setMetadataFor(Country::CLASSNAME, $countryMetadata); + $this->_em->getMetadataFactory()->setMetadataFor(Country::class, $countryMetadata); } protected function tearDown() { parent::tearDown(); - $this->_em->getMetadataFactory()->setMetadataFor(Country::CLASSNAME, $this->countryMetadata); + $this->_em->getMetadataFactory()->setMetadataFor(Country::class, $this->countryMetadata); } public function testBasicConcurrentEntityReadLock() @@ -58,22 +58,22 @@ public function testBasicConcurrentEntityReadLock() $this->_em->clear(); $countryId = $this->countries[0]->getId(); - $cacheId = new EntityCacheKey(Country::CLASSNAME, array('id'=>$countryId)); - $region = $this->_em->getCache()->getEntityCacheRegion(Country::CLASSNAME); + $cacheId = new EntityCacheKey(Country::class, ['id'=>$countryId]); + $region = $this->_em->getCache()->getEntityCacheRegion(Country::class); - $this->assertTrue($this->cache->containsEntity(Country::CLASSNAME, $countryId)); + $this->assertTrue($this->cache->containsEntity(Country::class, $countryId)); /** @var \Doctrine\Tests\Mocks\ConcurrentRegionMock */ $region->setLock($cacheId, Lock::createLockRead()); // another proc lock the entity cache - $this->assertFalse($this->cache->containsEntity(Country::CLASSNAME, $countryId)); + $this->assertFalse($this->cache->containsEntity(Country::class, $countryId)); $queryCount = $this->getCurrentQueryCount(); - $country = $this->_em->find(Country::CLASSNAME, $countryId); + $country = $this->_em->find(Country::class, $countryId); - $this->assertInstanceOf(Country::CLASSNAME, $country); + $this->assertInstanceOf(Country::class, $country); $this->assertEquals($queryCount + 1, $this->getCurrentQueryCount()); - $this->assertFalse($this->cache->containsEntity(Country::CLASSNAME, $countryId)); + $this->assertFalse($this->cache->containsEntity(Country::class, $countryId)); } public function testBasicConcurrentCollectionReadLock() @@ -86,10 +86,10 @@ public function testBasicConcurrentCollectionReadLock() $this->evictRegions(); $stateId = $this->states[0]->getId(); - $state = $this->_em->find(State::CLASSNAME, $stateId); + $state = $this->_em->find(State::class, $stateId); - $this->assertInstanceOf(State::CLASSNAME, $state); - $this->assertInstanceOf(Country::CLASSNAME, $state->getCountry()); + $this->assertInstanceOf(State::class, $state); + $this->assertInstanceOf(Country::class, $state->getCountry()); $this->assertNotNull($state->getCountry()->getName()); $this->assertCount(2, $state->getCities()); @@ -97,34 +97,34 @@ public function testBasicConcurrentCollectionReadLock() $this->secondLevelCacheLogger->clearStats(); $stateId = $this->states[0]->getId(); - $cacheId = new CollectionCacheKey(State::CLASSNAME, 'cities', array('id'=>$stateId)); - $region = $this->_em->getCache()->getCollectionCacheRegion(State::CLASSNAME, 'cities'); + $cacheId = new CollectionCacheKey(State::class, 'cities', ['id'=>$stateId]); + $region = $this->_em->getCache()->getCollectionCacheRegion(State::class, 'cities'); - $this->assertTrue($this->cache->containsCollection(State::CLASSNAME, 'cities', $stateId)); + $this->assertTrue($this->cache->containsCollection(State::class, 'cities', $stateId)); /* @var $region \Doctrine\Tests\Mocks\ConcurrentRegionMock */ $region->setLock($cacheId, Lock::createLockRead()); // another proc lock the entity cache - $this->assertFalse($this->cache->containsCollection(State::CLASSNAME, 'cities', $stateId)); + $this->assertFalse($this->cache->containsCollection(State::class, 'cities', $stateId)); $queryCount = $this->getCurrentQueryCount(); - $state = $this->_em->find(State::CLASSNAME, $stateId); + $state = $this->_em->find(State::class, $stateId); $this->assertEquals(0, $this->secondLevelCacheLogger->getMissCount()); $this->assertEquals(1, $this->secondLevelCacheLogger->getHitCount()); - $this->assertEquals(0, $this->secondLevelCacheLogger->getRegionMissCount($this->getEntityRegion(State::CLASSNAME))); - $this->assertEquals(1, $this->secondLevelCacheLogger->getRegionHitCount($this->getEntityRegion(State::CLASSNAME))); + $this->assertEquals(0, $this->secondLevelCacheLogger->getRegionMissCount($this->getEntityRegion(State::class))); + $this->assertEquals(1, $this->secondLevelCacheLogger->getRegionHitCount($this->getEntityRegion(State::class))); - $this->assertInstanceOf(State::CLASSNAME, $state); + $this->assertInstanceOf(State::class, $state); $this->assertCount(2, $state->getCities()); $this->assertEquals(1, $this->secondLevelCacheLogger->getMissCount()); $this->assertEquals(1, $this->secondLevelCacheLogger->getHitCount()); - $this->assertEquals(1, $this->secondLevelCacheLogger->getRegionMissCount($this->getCollectionRegion(State::CLASSNAME, 'cities'))); + $this->assertEquals(1, $this->secondLevelCacheLogger->getRegionMissCount($this->getCollectionRegion(State::class, 'cities'))); $this->assertEquals($queryCount + 1, $this->getCurrentQueryCount()); - $this->assertFalse($this->cache->containsCollection(State::CLASSNAME, 'cities', $stateId)); + $this->assertFalse($this->cache->containsCollection(State::class, 'cities', $stateId)); } } @@ -147,4 +147,4 @@ public function getTimestampRegion() { return new TimestampRegionMock(); } -} \ No newline at end of file +} diff --git a/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheCriteriaTest.php b/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheCriteriaTest.php index 2096c520ce8..17d0ac7fc7e 100644 --- a/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheCriteriaTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheCriteriaTest.php @@ -2,9 +2,10 @@ namespace Doctrine\Tests\ORM\Functional; -use Doctrine\Tests\Models\Cache\State; -use Doctrine\Tests\Models\Cache\Country; +use Doctrine\Common\Collections\Collection; use Doctrine\Common\Collections\Criteria; +use Doctrine\Tests\Models\Cache\Country; +use Doctrine\Tests\Models\Cache\State; /** * @group DDC-2183 @@ -19,9 +20,9 @@ public function testMatchingPut() $this->evictRegions(); $this->_em->clear(); - $this->assertFalse($this->cache->containsEntity(Country::CLASSNAME, $this->countries[0]->getId())); + $this->assertFalse($this->cache->containsEntity(Country::class, $this->countries[0]->getId())); - $repository = $this->_em->getRepository(Country::CLASSNAME); + $repository = $this->_em->getRepository(Country::class); $queryCount = $this->getCurrentQueryCount(); $name = $this->countries[0]->getName(); $result1 = $repository->matching(new Criteria( @@ -35,7 +36,7 @@ public function testMatchingPut() $this->assertEquals($this->countries[0]->getId(), $result1[0]->getId()); $this->assertEquals($this->countries[0]->getName(), $result1[0]->getName()); - $this->assertTrue($this->cache->containsEntity(Country::CLASSNAME, $this->countries[0]->getId())); + $this->assertTrue($this->cache->containsEntity(Country::class, $this->countries[0]->getId())); $this->_em->clear(); @@ -46,7 +47,7 @@ public function testMatchingPut() $this->assertEquals($queryCount + 1, $this->getCurrentQueryCount()); $this->assertCount(1, $result2); - $this->assertInstanceOf('Doctrine\Tests\Models\Cache\Country', $result2[0]); + $this->assertInstanceOf(Country::class, $result2[0]); $this->assertEquals($result1[0]->getId(), $result2[0]->getId()); $this->assertEquals($result1[0]->getName(), $result2[0]->getName()); @@ -59,9 +60,9 @@ public function testRepositoryMatching() $this->loadFixturesCountries(); $this->_em->clear(); - $this->assertTrue($this->cache->containsEntity(Country::CLASSNAME, $this->countries[0]->getId())); + $this->assertTrue($this->cache->containsEntity(Country::class, $this->countries[0]->getId())); - $repository = $this->_em->getRepository(Country::CLASSNAME); + $repository = $this->_em->getRepository(Country::class); $queryCount = $this->getCurrentQueryCount(); $result1 = $repository->matching(new Criteria( Criteria::expr()->eq('name', $this->countries[0]->getName()) @@ -87,7 +88,7 @@ public function testRepositoryMatching() $this->assertEquals($queryCount + 1, $this->getCurrentQueryCount()); $this->assertCount(1, $result2); - $this->assertInstanceOf('Doctrine\Tests\Models\Cache\Country', $result2[0]); + $this->assertInstanceOf(Country::class, $result2[0]); $this->assertEquals($this->countries[0]->getId(), $result2[0]->getId()); $this->assertEquals($this->countries[0]->getName(), $result2[0]->getName()); @@ -102,7 +103,7 @@ public function testRepositoryMatching() $this->assertEquals($queryCount + 2, $this->getCurrentQueryCount()); $this->assertCount(1, $result3); - $this->assertInstanceOf('Doctrine\Tests\Models\Cache\Country', $result3[0]); + $this->assertInstanceOf(Country::class, $result3[0]); $this->assertEquals($this->countries[1]->getId(), $result3[0]->getId()); $this->assertEquals($this->countries[1]->getName(), $result3[0]->getName()); @@ -114,7 +115,7 @@ public function testRepositoryMatching() $this->assertEquals($queryCount + 2, $this->getCurrentQueryCount()); $this->assertCount(1, $result4); - $this->assertInstanceOf('Doctrine\Tests\Models\Cache\Country', $result4[0]); + $this->assertInstanceOf(Country::class, $result4[0]); $this->assertEquals($this->countries[1]->getId(), $result4[0]->getId()); $this->assertEquals($this->countries[1]->getName(), $result4[0]->getName()); @@ -128,7 +129,7 @@ public function testCollectionMatching() $this->_em->clear(); $this->secondLevelCacheLogger->clearStats(); - $entity = $this->_em->find(State::CLASSNAME, $this->states[0]->getId()); + $entity = $this->_em->find(State::class, $this->states[0]->getId()); $itemName = $this->states[0]->getCities()->get(0)->getName(); $queryCount = $this->getCurrentQueryCount(); $collection = $entity->getCities(); @@ -137,12 +138,12 @@ public function testCollectionMatching() )); $this->assertEquals($queryCount + 1, $this->getCurrentQueryCount()); - $this->assertInstanceOf('Doctrine\Common\Collections\Collection', $matching); + $this->assertInstanceOf(Collection::class, $matching); $this->assertCount(1, $matching); $this->_em->clear(); - $entity = $this->_em->find(State::CLASSNAME, $this->states[0]->getId()); + $entity = $this->_em->find(State::class, $this->states[0]->getId()); $queryCount = $this->getCurrentQueryCount(); $collection = $entity->getCities(); $matching = $collection->matching(new Criteria( @@ -150,7 +151,7 @@ public function testCollectionMatching() )); $this->assertEquals($queryCount, $this->getCurrentQueryCount()); - $this->assertInstanceOf('Doctrine\Common\Collections\Collection', $matching); + $this->assertInstanceOf(Collection::class, $matching); $this->assertCount(1, $matching); } diff --git a/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheExtraLazyCollectionTest.php b/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheExtraLazyCollectionTest.php index 366f846f81f..75499ac302c 100644 --- a/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheExtraLazyCollectionTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheExtraLazyCollectionTest.php @@ -16,8 +16,8 @@ public function setUp() { parent::setUp(); - $sourceEntity = $this->_em->getClassMetadata(Travel::CLASSNAME); - $targetEntity = $this->_em->getClassMetadata(City::CLASSNAME); + $sourceEntity = $this->_em->getClassMetadata(Travel::class); + $targetEntity = $this->_em->getClassMetadata(City::class); $sourceEntity->associationMappings['visitedCities']['fetch'] = ClassMetadata::FETCH_EXTRA_LAZY; $targetEntity->associationMappings['travels']['fetch'] = ClassMetadata::FETCH_EXTRA_LAZY; @@ -27,13 +27,13 @@ public function tearDown() { parent::tearDown(); - $sourceEntity = $this->_em->getClassMetadata(Travel::CLASSNAME); - $targetEntity = $this->_em->getClassMetadata(City::CLASSNAME); + $sourceEntity = $this->_em->getClassMetadata(Travel::class); + $targetEntity = $this->_em->getClassMetadata(City::class); $sourceEntity->associationMappings['visitedCities']['fetch'] = ClassMetadata::FETCH_LAZY; $targetEntity->associationMappings['travels']['fetch'] = ClassMetadata::FETCH_LAZY; } - + public function testCacheCountAfterAddThenFlush() { $this->loadFixturesCountries(); @@ -45,11 +45,11 @@ public function testCacheCountAfterAddThenFlush() $this->_em->clear(); $ownerId = $this->travels[0]->getId(); - $owner = $this->_em->find(Travel::CLASSNAME, $ownerId); - $ref = $this->_em->find(State::CLASSNAME, $this->states[1]->getId()); - - $this->assertTrue($this->cache->containsEntity(Travel::CLASSNAME, $ownerId)); - $this->assertTrue($this->cache->containsCollection(Travel::CLASSNAME, 'visitedCities', $ownerId)); + $owner = $this->_em->find(Travel::class, $ownerId); + $ref = $this->_em->find(State::class, $this->states[1]->getId()); + + $this->assertTrue($this->cache->containsEntity(Travel::class, $ownerId)); + $this->assertTrue($this->cache->containsCollection(Travel::class, 'visitedCities', $ownerId)); $newItem = new City("New City", $ref); $owner->getVisitedCities()->add($newItem); @@ -67,15 +67,15 @@ public function testCacheCountAfterAddThenFlush() $this->_em->flush(); $this->assertFalse($owner->getVisitedCities()->isInitialized()); - $this->assertFalse($this->cache->containsCollection(Travel::CLASSNAME, 'visitedCities', $ownerId)); + $this->assertFalse($this->cache->containsCollection(Travel::class, 'visitedCities', $ownerId)); $this->_em->clear(); $queryCount = $this->getCurrentQueryCount(); - $owner = $this->_em->find(Travel::CLASSNAME, $ownerId); + $owner = $this->_em->find(Travel::class, $ownerId); $this->assertEquals(4, $owner->getVisitedCities()->count()); $this->assertFalse($owner->getVisitedCities()->isInitialized()); $this->assertEquals($queryCount + 1, $this->getCurrentQueryCount()); } -} \ No newline at end of file +} diff --git a/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheJoinTableInheritanceTest.php b/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheJoinTableInheritanceTest.php index e81b08b96f9..f9b9542444e 100644 --- a/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheJoinTableInheritanceTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheJoinTableInheritanceTest.php @@ -2,9 +2,10 @@ namespace Doctrine\Tests\ORM\Functional; +use Doctrine\ORM\PersistentCollection; use Doctrine\Tests\Models\Cache\Attraction; -use Doctrine\Tests\Models\Cache\AttractionInfo; use Doctrine\Tests\Models\Cache\AttractionContactInfo; +use Doctrine\Tests\Models\Cache\AttractionInfo; use Doctrine\Tests\Models\Cache\AttractionLocationInfo; /** @@ -14,9 +15,9 @@ class SecondLevelCacheJoinTableInheritanceTest extends SecondLevelCacheAbstractT { public function testUseSameRegion() { - $infoRegion = $this->cache->getEntityCacheRegion(AttractionInfo::CLASSNAME); - $contactRegion = $this->cache->getEntityCacheRegion(AttractionContactInfo::CLASSNAME); - $locationRegion = $this->cache->getEntityCacheRegion(AttractionLocationInfo::CLASSNAME); + $infoRegion = $this->cache->getEntityCacheRegion(AttractionInfo::class); + $contactRegion = $this->cache->getEntityCacheRegion(AttractionContactInfo::class); + $locationRegion = $this->cache->getEntityCacheRegion(AttractionLocationInfo::class); $this->assertEquals($infoRegion->getName(), $contactRegion->getName()); $this->assertEquals($infoRegion->getName(), $locationRegion->getName()); @@ -32,10 +33,10 @@ public function testPutOnPersistJoinTableInheritance() $this->_em->clear(); - $this->assertTrue($this->cache->containsEntity(AttractionInfo::CLASSNAME, $this->attractionsInfo[0]->getId())); - $this->assertTrue($this->cache->containsEntity(AttractionInfo::CLASSNAME, $this->attractionsInfo[1]->getId())); - $this->assertTrue($this->cache->containsEntity(AttractionInfo::CLASSNAME, $this->attractionsInfo[2]->getId())); - $this->assertTrue($this->cache->containsEntity(AttractionInfo::CLASSNAME, $this->attractionsInfo[3]->getId())); + $this->assertTrue($this->cache->containsEntity(AttractionInfo::class, $this->attractionsInfo[0]->getId())); + $this->assertTrue($this->cache->containsEntity(AttractionInfo::class, $this->attractionsInfo[1]->getId())); + $this->assertTrue($this->cache->containsEntity(AttractionInfo::class, $this->attractionsInfo[2]->getId())); + $this->assertTrue($this->cache->containsEntity(AttractionInfo::class, $this->attractionsInfo[3]->getId())); } public function testJoinTableCountaisRootClass() @@ -49,7 +50,7 @@ public function testJoinTableCountaisRootClass() $this->_em->clear(); foreach ($this->attractionsInfo as $info) { - $this->assertTrue($this->cache->containsEntity(AttractionInfo::CLASSNAME, $info->getId())); + $this->assertTrue($this->cache->containsEntity(AttractionInfo::class, $info->getId())); $this->assertTrue($this->cache->containsEntity(get_class($info), $info->getId())); } } @@ -64,32 +65,32 @@ public function testPutAndLoadJoinTableEntities() $this->_em->clear(); - $this->cache->evictEntityRegion(AttractionInfo::CLASSNAME); + $this->cache->evictEntityRegion(AttractionInfo::class); $entityId1 = $this->attractionsInfo[0]->getId(); $entityId2 = $this->attractionsInfo[1]->getId(); - $this->assertFalse($this->cache->containsEntity(AttractionInfo::CLASSNAME, $entityId1)); - $this->assertFalse($this->cache->containsEntity(AttractionInfo::CLASSNAME, $entityId2)); - $this->assertFalse($this->cache->containsEntity(AttractionContactInfo::CLASSNAME, $entityId1)); - $this->assertFalse($this->cache->containsEntity(AttractionContactInfo::CLASSNAME, $entityId2)); + $this->assertFalse($this->cache->containsEntity(AttractionInfo::class, $entityId1)); + $this->assertFalse($this->cache->containsEntity(AttractionInfo::class, $entityId2)); + $this->assertFalse($this->cache->containsEntity(AttractionContactInfo::class, $entityId1)); + $this->assertFalse($this->cache->containsEntity(AttractionContactInfo::class, $entityId2)); $queryCount = $this->getCurrentQueryCount(); - $entity1 = $this->_em->find(AttractionInfo::CLASSNAME, $entityId1); - $entity2 = $this->_em->find(AttractionInfo::CLASSNAME, $entityId2); + $entity1 = $this->_em->find(AttractionInfo::class, $entityId1); + $entity2 = $this->_em->find(AttractionInfo::class, $entityId2); //load entity and relation whit sub classes $this->assertEquals($queryCount + 4, $this->getCurrentQueryCount()); - $this->assertTrue($this->cache->containsEntity(AttractionInfo::CLASSNAME, $entityId1)); - $this->assertTrue($this->cache->containsEntity(AttractionInfo::CLASSNAME, $entityId2)); - $this->assertTrue($this->cache->containsEntity(AttractionContactInfo::CLASSNAME, $entityId1)); - $this->assertTrue($this->cache->containsEntity(AttractionContactInfo::CLASSNAME, $entityId2)); + $this->assertTrue($this->cache->containsEntity(AttractionInfo::class, $entityId1)); + $this->assertTrue($this->cache->containsEntity(AttractionInfo::class, $entityId2)); + $this->assertTrue($this->cache->containsEntity(AttractionContactInfo::class, $entityId1)); + $this->assertTrue($this->cache->containsEntity(AttractionContactInfo::class, $entityId2)); - $this->assertInstanceOf(AttractionInfo::CLASSNAME, $entity1); - $this->assertInstanceOf(AttractionInfo::CLASSNAME, $entity2); - $this->assertInstanceOf(AttractionContactInfo::CLASSNAME, $entity1); - $this->assertInstanceOf(AttractionContactInfo::CLASSNAME, $entity2); + $this->assertInstanceOf(AttractionInfo::class, $entity1); + $this->assertInstanceOf(AttractionInfo::class, $entity2); + $this->assertInstanceOf(AttractionContactInfo::class, $entity1); + $this->assertInstanceOf(AttractionContactInfo::class, $entity2); $this->assertEquals($this->attractionsInfo[0]->getId(), $entity1->getId()); $this->assertEquals($this->attractionsInfo[0]->getFone(), $entity1->getFone()); @@ -100,15 +101,15 @@ public function testPutAndLoadJoinTableEntities() $this->_em->clear(); $queryCount = $this->getCurrentQueryCount(); - $entity3 = $this->_em->find(AttractionInfo::CLASSNAME, $entityId1); - $entity4 = $this->_em->find(AttractionInfo::CLASSNAME, $entityId2); + $entity3 = $this->_em->find(AttractionInfo::class, $entityId1); + $entity4 = $this->_em->find(AttractionInfo::class, $entityId2); $this->assertEquals($queryCount, $this->getCurrentQueryCount()); - $this->assertInstanceOf(AttractionInfo::CLASSNAME, $entity3); - $this->assertInstanceOf(AttractionInfo::CLASSNAME, $entity4); - $this->assertInstanceOf(AttractionContactInfo::CLASSNAME, $entity3); - $this->assertInstanceOf(AttractionContactInfo::CLASSNAME, $entity4); + $this->assertInstanceOf(AttractionInfo::class, $entity3); + $this->assertInstanceOf(AttractionInfo::class, $entity4); + $this->assertInstanceOf(AttractionContactInfo::class, $entity3); + $this->assertInstanceOf(AttractionContactInfo::class, $entity4); $this->assertNotSame($entity1, $entity3); $this->assertEquals($entity1->getId(), $entity3->getId()); @@ -148,7 +149,7 @@ public function testQueryCacheFindAllJoinTableEntities() $this->assertEquals($queryCount + 1, $this->getCurrentQueryCount()); foreach ($result2 as $entity) { - $this->assertInstanceOf(AttractionInfo::CLASSNAME, $entity); + $this->assertInstanceOf(AttractionInfo::class, $entity); } } @@ -162,30 +163,73 @@ public function testOneToManyRelationJoinTable() $this->evictRegions(); $this->_em->clear(); - $entity = $this->_em->find(Attraction::CLASSNAME, $this->attractions[0]->getId()); + $entity = $this->_em->find(Attraction::class, $this->attractions[0]->getId()); - $this->assertInstanceOf(Attraction::CLASSNAME, $entity); - $this->assertInstanceOf('Doctrine\ORM\PersistentCollection', $entity->getInfos()); + $this->assertInstanceOf(Attraction::class, $entity); + $this->assertInstanceOf(PersistentCollection::class, $entity->getInfos()); $this->assertCount(1, $entity->getInfos()); $ownerId = $this->attractions[0]->getId(); $queryCount = $this->getCurrentQueryCount(); - $this->assertTrue($this->cache->containsEntity(Attraction::CLASSNAME, $ownerId)); - $this->assertTrue($this->cache->containsCollection(Attraction::CLASSNAME, 'infos', $ownerId)); + $this->assertTrue($this->cache->containsEntity(Attraction::class, $ownerId)); + $this->assertTrue($this->cache->containsCollection(Attraction::class, 'infos', $ownerId)); - $this->assertInstanceOf(AttractionContactInfo::CLASSNAME, $entity->getInfos()->get(0)); + $this->assertInstanceOf(AttractionContactInfo::class, $entity->getInfos()->get(0)); $this->assertEquals($this->attractionsInfo[0]->getFone(), $entity->getInfos()->get(0)->getFone()); $this->_em->clear(); - $entity = $this->_em->find(Attraction::CLASSNAME, $this->attractions[0]->getId()); + $entity = $this->_em->find(Attraction::class, $this->attractions[0]->getId()); - $this->assertInstanceOf(Attraction::CLASSNAME, $entity); - $this->assertInstanceOf('Doctrine\ORM\PersistentCollection', $entity->getInfos()); + $this->assertInstanceOf(Attraction::class, $entity); + $this->assertInstanceOf(PersistentCollection::class, $entity->getInfos()); $this->assertCount(1, $entity->getInfos()); - $this->assertInstanceOf(AttractionContactInfo::CLASSNAME, $entity->getInfos()->get(0)); + $this->assertInstanceOf(AttractionContactInfo::class, $entity->getInfos()->get(0)); $this->assertEquals($this->attractionsInfo[0]->getFone(), $entity->getInfos()->get(0)->getFone()); } -} \ No newline at end of file + + public function testQueryCacheShouldBeEvictedOnTimestampUpdate() + { + $this->loadFixturesCountries(); + $this->loadFixturesStates(); + $this->loadFixturesCities(); + $this->loadFixturesAttractions(); + $this->loadFixturesAttractionsInfo(); + $this->evictRegions(); + $this->_em->clear(); + + $queryCount = $this->getCurrentQueryCount(); + $dql = 'SELECT attractionInfo FROM Doctrine\Tests\Models\Cache\AttractionInfo attractionInfo'; + + $result1 = $this->_em->createQuery($dql) + ->setCacheable(true) + ->getResult(); + + $this->assertCount(count($this->attractionsInfo), $result1); + $this->assertEquals($queryCount + 5, $this->getCurrentQueryCount()); + + $contact = new AttractionContactInfo( + '1234-1234', + $this->_em->find(Attraction::class, $this->attractions[5]->getId()) + ); + + $this->_em->persist($contact); + $this->_em->flush(); + $this->_em->clear(); + + $queryCount = $this->getCurrentQueryCount(); + + $result2 = $this->_em->createQuery($dql) + ->setCacheable(true) + ->getResult(); + + $this->assertCount(count($this->attractionsInfo) + 1, $result2); + $this->assertEquals($queryCount + 6, $this->getCurrentQueryCount()); + + foreach ($result2 as $entity) { + $this->assertInstanceOf(AttractionInfo::class, $entity); + } + } +} diff --git a/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheManyToManyTest.php b/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheManyToManyTest.php index 0db9e1cbcdb..efe19f3e074 100644 --- a/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheManyToManyTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheManyToManyTest.php @@ -23,16 +23,16 @@ public function testShouldPutManyToManyCollectionOwningSideOnPersist() $this->loadFixturesTravels(); $this->_em->clear(); - $this->assertTrue($this->cache->containsEntity(Travel::CLASSNAME, $this->travels[0]->getId())); - $this->assertTrue($this->cache->containsEntity(Travel::CLASSNAME, $this->travels[1]->getId())); + $this->assertTrue($this->cache->containsEntity(Travel::class, $this->travels[0]->getId())); + $this->assertTrue($this->cache->containsEntity(Travel::class, $this->travels[1]->getId())); - $this->assertTrue($this->cache->containsCollection(Travel::CLASSNAME, 'visitedCities', $this->travels[0]->getId())); - $this->assertTrue($this->cache->containsCollection(Travel::CLASSNAME, 'visitedCities', $this->travels[1]->getId())); + $this->assertTrue($this->cache->containsCollection(Travel::class, 'visitedCities', $this->travels[0]->getId())); + $this->assertTrue($this->cache->containsCollection(Travel::class, 'visitedCities', $this->travels[1]->getId())); - $this->assertTrue($this->cache->containsEntity(City::CLASSNAME, $this->cities[0]->getId())); - $this->assertTrue($this->cache->containsEntity(City::CLASSNAME, $this->cities[1]->getId())); - $this->assertTrue($this->cache->containsEntity(City::CLASSNAME, $this->cities[2]->getId())); - $this->assertTrue($this->cache->containsEntity(City::CLASSNAME, $this->cities[3]->getId())); + $this->assertTrue($this->cache->containsEntity(City::class, $this->cities[0]->getId())); + $this->assertTrue($this->cache->containsEntity(City::class, $this->cities[1]->getId())); + $this->assertTrue($this->cache->containsEntity(City::class, $this->cities[2]->getId())); + $this->assertTrue($this->cache->containsEntity(City::class, $this->cities[3]->getId())); } public function testPutAndLoadManyToManyRelation() @@ -46,30 +46,30 @@ public function testPutAndLoadManyToManyRelation() $this->loadFixturesTravels(); $this->_em->clear(); - $this->cache->evictEntityRegion(City::CLASSNAME); - $this->cache->evictEntityRegion(Travel::CLASSNAME); - $this->cache->evictCollectionRegion(Travel::CLASSNAME, 'visitedCities'); + $this->cache->evictEntityRegion(City::class); + $this->cache->evictEntityRegion(Travel::class); + $this->cache->evictCollectionRegion(Travel::class, 'visitedCities'); $this->secondLevelCacheLogger->clearStats(); - $this->assertFalse($this->cache->containsEntity(Travel::CLASSNAME, $this->travels[0]->getId())); - $this->assertFalse($this->cache->containsEntity(Travel::CLASSNAME, $this->travels[1]->getId())); + $this->assertFalse($this->cache->containsEntity(Travel::class, $this->travels[0]->getId())); + $this->assertFalse($this->cache->containsEntity(Travel::class, $this->travels[1]->getId())); - $this->assertFalse($this->cache->containsCollection(Travel::CLASSNAME, 'visitedCities', $this->travels[0]->getId())); - $this->assertFalse($this->cache->containsCollection(Travel::CLASSNAME, 'visitedCities', $this->travels[1]->getId())); + $this->assertFalse($this->cache->containsCollection(Travel::class, 'visitedCities', $this->travels[0]->getId())); + $this->assertFalse($this->cache->containsCollection(Travel::class, 'visitedCities', $this->travels[1]->getId())); - $this->assertFalse($this->cache->containsEntity(City::CLASSNAME, $this->cities[0]->getId())); - $this->assertFalse($this->cache->containsEntity(City::CLASSNAME, $this->cities[1]->getId())); - $this->assertFalse($this->cache->containsEntity(City::CLASSNAME, $this->cities[2]->getId())); - $this->assertFalse($this->cache->containsEntity(City::CLASSNAME, $this->cities[3]->getId())); + $this->assertFalse($this->cache->containsEntity(City::class, $this->cities[0]->getId())); + $this->assertFalse($this->cache->containsEntity(City::class, $this->cities[1]->getId())); + $this->assertFalse($this->cache->containsEntity(City::class, $this->cities[2]->getId())); + $this->assertFalse($this->cache->containsEntity(City::class, $this->cities[3]->getId())); - $t1 = $this->_em->find(Travel::CLASSNAME, $this->travels[0]->getId()); - $t2 = $this->_em->find(Travel::CLASSNAME, $this->travels[1]->getId()); + $t1 = $this->_em->find(Travel::class, $this->travels[0]->getId()); + $t2 = $this->_em->find(Travel::class, $this->travels[1]->getId()); $this->assertEquals(2, $this->secondLevelCacheLogger->getPutCount()); $this->assertEquals(2, $this->secondLevelCacheLogger->getMissCount()); - $this->assertEquals(2, $this->secondLevelCacheLogger->getRegionPutCount($this->getEntityRegion(Travel::CLASSNAME))); - $this->assertEquals(2, $this->secondLevelCacheLogger->getRegionMissCount($this->getEntityRegion(Travel::CLASSNAME))); + $this->assertEquals(2, $this->secondLevelCacheLogger->getRegionPutCount($this->getEntityRegion(Travel::class))); + $this->assertEquals(2, $this->secondLevelCacheLogger->getRegionMissCount($this->getEntityRegion(Travel::class))); //trigger lazy load $this->assertCount(3, $t1->getVisitedCities()); @@ -77,49 +77,49 @@ public function testPutAndLoadManyToManyRelation() $this->assertEquals(4, $this->secondLevelCacheLogger->getPutCount()); $this->assertEquals(4, $this->secondLevelCacheLogger->getMissCount()); - $this->assertEquals(2, $this->secondLevelCacheLogger->getRegionPutCount($this->getCollectionRegion(Travel::CLASSNAME, 'visitedCities'))); - $this->assertEquals(2, $this->secondLevelCacheLogger->getRegionMissCount($this->getCollectionRegion(Travel::CLASSNAME, 'visitedCities'))); + $this->assertEquals(2, $this->secondLevelCacheLogger->getRegionPutCount($this->getCollectionRegion(Travel::class, 'visitedCities'))); + $this->assertEquals(2, $this->secondLevelCacheLogger->getRegionMissCount($this->getCollectionRegion(Travel::class, 'visitedCities'))); - $this->assertInstanceOf(City::CLASSNAME, $t1->getVisitedCities()->get(0)); - $this->assertInstanceOf(City::CLASSNAME, $t1->getVisitedCities()->get(1)); - $this->assertInstanceOf(City::CLASSNAME, $t1->getVisitedCities()->get(2)); + $this->assertInstanceOf(City::class, $t1->getVisitedCities()->get(0)); + $this->assertInstanceOf(City::class, $t1->getVisitedCities()->get(1)); + $this->assertInstanceOf(City::class, $t1->getVisitedCities()->get(2)); - $this->assertInstanceOf(City::CLASSNAME, $t2->getVisitedCities()->get(0)); - $this->assertInstanceOf(City::CLASSNAME, $t2->getVisitedCities()->get(1)); + $this->assertInstanceOf(City::class, $t2->getVisitedCities()->get(0)); + $this->assertInstanceOf(City::class, $t2->getVisitedCities()->get(1)); - $this->assertTrue($this->cache->containsEntity(Travel::CLASSNAME, $this->travels[0]->getId())); - $this->assertTrue($this->cache->containsEntity(Travel::CLASSNAME, $this->travels[1]->getId())); + $this->assertTrue($this->cache->containsEntity(Travel::class, $this->travels[0]->getId())); + $this->assertTrue($this->cache->containsEntity(Travel::class, $this->travels[1]->getId())); - $this->assertTrue($this->cache->containsCollection(Travel::CLASSNAME, 'visitedCities', $this->travels[0]->getId())); - $this->assertTrue($this->cache->containsCollection(Travel::CLASSNAME, 'visitedCities', $this->travels[1]->getId())); + $this->assertTrue($this->cache->containsCollection(Travel::class, 'visitedCities', $this->travels[0]->getId())); + $this->assertTrue($this->cache->containsCollection(Travel::class, 'visitedCities', $this->travels[1]->getId())); - $this->assertTrue($this->cache->containsEntity(City::CLASSNAME, $this->cities[0]->getId())); - $this->assertTrue($this->cache->containsEntity(City::CLASSNAME, $this->cities[1]->getId())); - $this->assertTrue($this->cache->containsEntity(City::CLASSNAME, $this->cities[2]->getId())); - $this->assertTrue($this->cache->containsEntity(City::CLASSNAME, $this->cities[3]->getId())); + $this->assertTrue($this->cache->containsEntity(City::class, $this->cities[0]->getId())); + $this->assertTrue($this->cache->containsEntity(City::class, $this->cities[1]->getId())); + $this->assertTrue($this->cache->containsEntity(City::class, $this->cities[2]->getId())); + $this->assertTrue($this->cache->containsEntity(City::class, $this->cities[3]->getId())); $this->_em->clear(); $this->secondLevelCacheLogger->clearStats(); $queryCount = $this->getCurrentQueryCount(); - $t3 = $this->_em->find(Travel::CLASSNAME, $this->travels[0]->getId()); - $t4 = $this->_em->find(Travel::CLASSNAME, $this->travels[1]->getId()); + $t3 = $this->_em->find(Travel::class, $this->travels[0]->getId()); + $t4 = $this->_em->find(Travel::class, $this->travels[1]->getId()); //trigger lazy load from cache $this->assertCount(3, $t3->getVisitedCities()); $this->assertCount(2, $t4->getVisitedCities()); - $this->assertInstanceOf(City::CLASSNAME, $t3->getVisitedCities()->get(0)); - $this->assertInstanceOf(City::CLASSNAME, $t3->getVisitedCities()->get(1)); - $this->assertInstanceOf(City::CLASSNAME, $t3->getVisitedCities()->get(2)); + $this->assertInstanceOf(City::class, $t3->getVisitedCities()->get(0)); + $this->assertInstanceOf(City::class, $t3->getVisitedCities()->get(1)); + $this->assertInstanceOf(City::class, $t3->getVisitedCities()->get(2)); - $this->assertInstanceOf(City::CLASSNAME, $t4->getVisitedCities()->get(0)); - $this->assertInstanceOf(City::CLASSNAME, $t4->getVisitedCities()->get(1)); + $this->assertInstanceOf(City::class, $t4->getVisitedCities()->get(0)); + $this->assertInstanceOf(City::class, $t4->getVisitedCities()->get(1)); $this->assertEquals(4, $this->secondLevelCacheLogger->getHitCount()); - $this->assertEquals(2, $this->secondLevelCacheLogger->getRegionHitCount($this->getEntityRegion(Travel::CLASSNAME))); - $this->assertEquals(2, $this->secondLevelCacheLogger->getRegionHitCount($this->getCollectionRegion(Travel::CLASSNAME, 'visitedCities'))); + $this->assertEquals(2, $this->secondLevelCacheLogger->getRegionHitCount($this->getEntityRegion(Travel::class))); + $this->assertEquals(2, $this->secondLevelCacheLogger->getRegionHitCount($this->getCollectionRegion(Travel::class, 'visitedCities'))); $this->assertNotSame($t1->getVisitedCities()->get(0), $t3->getVisitedCities()->get(0)); $this->assertEquals($t1->getVisitedCities()->get(0)->getId(), $t3->getVisitedCities()->get(0)->getId()); @@ -153,11 +153,11 @@ public function testStoreManyToManyAssociationWhitCascade() $this->loadFixturesStates(); $this->loadFixturesCities(); - $this->cache->evictEntityRegion(City::CLASSNAME); - $this->cache->evictEntityRegion(Traveler::CLASSNAME); - $this->cache->evictEntityRegion(Travel::CLASSNAME); - $this->cache->evictCollectionRegion(State::CLASSNAME, 'cities'); - $this->cache->evictCollectionRegion(Traveler::CLASSNAME, 'travels'); + $this->cache->evictEntityRegion(City::class); + $this->cache->evictEntityRegion(Traveler::class); + $this->cache->evictEntityRegion(Travel::class); + $this->cache->evictCollectionRegion(State::class, 'cities'); + $this->cache->evictCollectionRegion(Traveler::class, 'travels'); $traveler = new Traveler('Doctrine Bot'); $travel = new Travel($traveler); @@ -171,17 +171,17 @@ public function testStoreManyToManyAssociationWhitCascade() $this->_em->flush(); $this->_em->clear(); - $this->assertTrue($this->cache->containsEntity(Travel::CLASSNAME, $travel->getId())); - $this->assertTrue($this->cache->containsEntity(Traveler::CLASSNAME, $traveler->getId())); - $this->assertTrue($this->cache->containsEntity(City::CLASSNAME, $this->cities[0]->getId())); - $this->assertTrue($this->cache->containsEntity(City::CLASSNAME, $this->cities[1]->getId())); - $this->assertTrue($this->cache->containsEntity(City::CLASSNAME, $this->cities[3]->getId())); - $this->assertTrue($this->cache->containsCollection(Travel::CLASSNAME, 'visitedCities', $travel->getId())); + $this->assertTrue($this->cache->containsEntity(Travel::class, $travel->getId())); + $this->assertTrue($this->cache->containsEntity(Traveler::class, $traveler->getId())); + $this->assertTrue($this->cache->containsEntity(City::class, $this->cities[0]->getId())); + $this->assertTrue($this->cache->containsEntity(City::class, $this->cities[1]->getId())); + $this->assertTrue($this->cache->containsEntity(City::class, $this->cities[3]->getId())); + $this->assertTrue($this->cache->containsCollection(Travel::class, 'visitedCities', $travel->getId())); $queryCount1 = $this->getCurrentQueryCount(); - $t1 = $this->_em->find(Travel::CLASSNAME, $travel->getId()); + $t1 = $this->_em->find(Travel::class, $travel->getId()); - $this->assertInstanceOf(Travel::CLASSNAME, $t1); + $this->assertInstanceOf(Travel::class, $t1); $this->assertCount(3, $t1->getVisitedCities()); $this->assertEquals($queryCount1, $this->getCurrentQueryCount()); } @@ -202,10 +202,10 @@ public function testReadOnlyCollection() $this->_em->clear(); - $this->assertTrue($this->cache->containsEntity(Travel::CLASSNAME, $this->travels[0]->getId())); - $this->assertTrue($this->cache->containsCollection(Travel::CLASSNAME, 'visitedCities', $this->travels[0]->getId())); + $this->assertTrue($this->cache->containsEntity(Travel::class, $this->travels[0]->getId())); + $this->assertTrue($this->cache->containsCollection(Travel::class, 'visitedCities', $this->travels[0]->getId())); - $travel = $this->_em->find(Travel::CLASSNAME, $this->travels[0]->getId()); + $travel = $this->_em->find(Travel::class, $this->travels[0]->getId()); $this->assertCount(3, $travel->getVisitedCities()); @@ -229,18 +229,18 @@ public function testManyToManyWithEmptyRelation() $queryCount = $this->getCurrentQueryCount(); $entitiId = $this->travels[2]->getId(); //empty travel - $entity = $this->_em->find(Travel::CLASSNAME, $entitiId); + $entity = $this->_em->find(Travel::class, $entitiId); $this->assertEquals(0, $entity->getVisitedCities()->count()); $this->assertEquals($queryCount+2, $this->getCurrentQueryCount()); $this->_em->clear(); - $entity = $this->_em->find(Travel::CLASSNAME, $entitiId); + $entity = $this->_em->find(Travel::class, $entitiId); $queryCount = $this->getCurrentQueryCount(); $this->assertEquals(0, $entity->getVisitedCities()->count()); $this->assertEquals($queryCount, $this->getCurrentQueryCount()); } -} \ No newline at end of file +} diff --git a/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheManyToOneTest.php b/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheManyToOneTest.php index 00fa409736f..7af52f741c2 100644 --- a/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheManyToOneTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheManyToOneTest.php @@ -2,12 +2,13 @@ namespace Doctrine\Tests\ORM\Functional; +use Doctrine\ORM\Cache\Region; +use Doctrine\Tests\Models\Cache\Action; use Doctrine\Tests\Models\Cache\City; use Doctrine\Tests\Models\Cache\ComplexAction; use Doctrine\Tests\Models\Cache\Country; use Doctrine\Tests\Models\Cache\State; use Doctrine\Tests\Models\Cache\Token; -use Doctrine\Tests\Models\Cache\Action; /** * @group DDC-2183 @@ -20,10 +21,10 @@ public function testPutOnPersist() $this->loadFixturesStates(); $this->_em->clear(); - $this->assertTrue($this->cache->containsEntity(Country::CLASSNAME, $this->states[0]->getCountry()->getId())); - $this->assertTrue($this->cache->containsEntity(Country::CLASSNAME, $this->states[1]->getCountry()->getId())); - $this->assertTrue($this->cache->containsEntity(State::CLASSNAME, $this->states[0]->getId())); - $this->assertTrue($this->cache->containsEntity(State::CLASSNAME, $this->states[1]->getId())); + $this->assertTrue($this->cache->containsEntity(Country::class, $this->states[0]->getCountry()->getId())); + $this->assertTrue($this->cache->containsEntity(Country::class, $this->states[1]->getCountry()->getId())); + $this->assertTrue($this->cache->containsEntity(State::class, $this->states[0]->getId())); + $this->assertTrue($this->cache->containsEntity(State::class, $this->states[1]->getId())); } public function testPutAndLoadManyToOneRelation() @@ -32,30 +33,30 @@ public function testPutAndLoadManyToOneRelation() $this->loadFixturesStates(); $this->_em->clear(); - $this->cache->evictEntityRegion(State::CLASSNAME); - $this->cache->evictEntityRegion(Country::CLASSNAME); + $this->cache->evictEntityRegion(State::class); + $this->cache->evictEntityRegion(Country::class); - $this->assertFalse($this->cache->containsEntity(State::CLASSNAME, $this->states[0]->getId())); - $this->assertFalse($this->cache->containsEntity(State::CLASSNAME, $this->states[1]->getId())); - $this->assertFalse($this->cache->containsEntity(Country::CLASSNAME, $this->states[0]->getCountry()->getId())); - $this->assertFalse($this->cache->containsEntity(Country::CLASSNAME, $this->states[1]->getCountry()->getId())); + $this->assertFalse($this->cache->containsEntity(State::class, $this->states[0]->getId())); + $this->assertFalse($this->cache->containsEntity(State::class, $this->states[1]->getId())); + $this->assertFalse($this->cache->containsEntity(Country::class, $this->states[0]->getCountry()->getId())); + $this->assertFalse($this->cache->containsEntity(Country::class, $this->states[1]->getCountry()->getId())); - $c1 = $this->_em->find(State::CLASSNAME, $this->states[0]->getId()); - $c2 = $this->_em->find(State::CLASSNAME, $this->states[1]->getId()); + $c1 = $this->_em->find(State::class, $this->states[0]->getId()); + $c2 = $this->_em->find(State::class, $this->states[1]->getId()); //trigger lazy load $this->assertNotNull($c1->getCountry()->getName()); $this->assertNotNull($c2->getCountry()->getName()); - $this->assertTrue($this->cache->containsEntity(Country::CLASSNAME, $this->states[0]->getCountry()->getId())); - $this->assertTrue($this->cache->containsEntity(Country::CLASSNAME, $this->states[1]->getCountry()->getId())); - $this->assertTrue($this->cache->containsEntity(State::CLASSNAME, $this->states[0]->getId())); - $this->assertTrue($this->cache->containsEntity(State::CLASSNAME, $this->states[1]->getId())); + $this->assertTrue($this->cache->containsEntity(Country::class, $this->states[0]->getCountry()->getId())); + $this->assertTrue($this->cache->containsEntity(Country::class, $this->states[1]->getCountry()->getId())); + $this->assertTrue($this->cache->containsEntity(State::class, $this->states[0]->getId())); + $this->assertTrue($this->cache->containsEntity(State::class, $this->states[1]->getId())); - $this->assertInstanceOf(State::CLASSNAME, $c1); - $this->assertInstanceOf(State::CLASSNAME, $c2); - $this->assertInstanceOf(Country::CLASSNAME, $c1->getCountry()); - $this->assertInstanceOf(Country::CLASSNAME, $c2->getCountry()); + $this->assertInstanceOf(State::class, $c1); + $this->assertInstanceOf(State::class, $c2); + $this->assertInstanceOf(Country::class, $c1->getCountry()); + $this->assertInstanceOf(Country::class, $c2->getCountry()); $this->assertEquals($this->states[0]->getId(), $c1->getId()); $this->assertEquals($this->states[0]->getName(), $c1->getName()); @@ -71,8 +72,8 @@ public function testPutAndLoadManyToOneRelation() $queryCount = $this->getCurrentQueryCount(); - $c3 = $this->_em->find(State::CLASSNAME, $this->states[0]->getId()); - $c4 = $this->_em->find(State::CLASSNAME, $this->states[1]->getId()); + $c3 = $this->_em->find(State::class, $this->states[0]->getId()); + $c4 = $this->_em->find(State::class, $this->states[1]->getId()); $this->assertEquals($queryCount, $this->getCurrentQueryCount()); @@ -80,10 +81,10 @@ public function testPutAndLoadManyToOneRelation() $this->assertNotNull($c3->getCountry()->getName()); $this->assertNotNull($c4->getCountry()->getName()); - $this->assertInstanceOf(State::CLASSNAME, $c3); - $this->assertInstanceOf(State::CLASSNAME, $c4); - $this->assertInstanceOf(Country::CLASSNAME, $c3->getCountry()); - $this->assertInstanceOf(Country::CLASSNAME, $c4->getCountry()); + $this->assertInstanceOf(State::class, $c3); + $this->assertInstanceOf(State::class, $c4); + $this->assertInstanceOf(Country::class, $c3->getCountry()); + $this->assertInstanceOf(Country::class, $c4->getCountry()); $this->assertEquals($c1->getId(), $c3->getId()); $this->assertEquals($c1->getName(), $c3->getName()); @@ -105,11 +106,11 @@ public function testInverseSidePutShouldEvictCollection() $this->_em->clear(); - $this->cache->evictEntityRegion(State::CLASSNAME); - $this->cache->evictEntityRegion(Country::CLASSNAME); + $this->cache->evictEntityRegion(State::class); + $this->cache->evictEntityRegion(Country::class); //evict collection on add - $c3 = $this->_em->find(State::CLASSNAME, $this->states[0]->getId()); + $c3 = $this->_em->find(State::class, $this->states[0]->getId()); $prev = $c3->getCities(); $count = $prev->count(); $city = new City("Buenos Aires", $c3); @@ -121,7 +122,7 @@ public function testInverseSidePutShouldEvictCollection() $this->_em->flush(); $this->_em->clear(); - $state = $this->_em->find(State::CLASSNAME, $c3->getId()); + $state = $this->_em->find(State::class, $c3->getId()); $queryCount = $this->getCurrentQueryCount(); // Association was cleared from EM @@ -144,29 +145,29 @@ public function testShouldNotReloadWhenAssociationIsMissing() $countryId1 = $this->states[0]->getCountry()->getId(); $countryId2 = $this->states[3]->getCountry()->getId(); - $this->assertTrue($this->cache->containsEntity(Country::CLASSNAME, $countryId1)); - $this->assertTrue($this->cache->containsEntity(Country::CLASSNAME, $countryId2)); - $this->assertTrue($this->cache->containsEntity(State::CLASSNAME, $stateId1)); - $this->assertTrue($this->cache->containsEntity(State::CLASSNAME, $stateId2)); + $this->assertTrue($this->cache->containsEntity(Country::class, $countryId1)); + $this->assertTrue($this->cache->containsEntity(Country::class, $countryId2)); + $this->assertTrue($this->cache->containsEntity(State::class, $stateId1)); + $this->assertTrue($this->cache->containsEntity(State::class, $stateId2)); - $this->cache->evictEntityRegion(Country::CLASSNAME); + $this->cache->evictEntityRegion(Country::class); - $this->assertFalse($this->cache->containsEntity(Country::CLASSNAME, $countryId1)); - $this->assertFalse($this->cache->containsEntity(Country::CLASSNAME, $countryId2)); + $this->assertFalse($this->cache->containsEntity(Country::class, $countryId1)); + $this->assertFalse($this->cache->containsEntity(Country::class, $countryId2)); $this->_em->clear(); $queryCount = $this->getCurrentQueryCount(); - $state1 = $this->_em->find(State::CLASSNAME, $stateId1); - $state2 = $this->_em->find(State::CLASSNAME, $stateId2); + $state1 = $this->_em->find(State::class, $stateId1); + $state2 = $this->_em->find(State::class, $stateId2); $this->assertEquals($queryCount, $this->getCurrentQueryCount()); - $this->assertInstanceOf(State::CLASSNAME, $state1); - $this->assertInstanceOf(State::CLASSNAME, $state2); - $this->assertInstanceOf(Country::CLASSNAME, $state1->getCountry()); - $this->assertInstanceOf(Country::CLASSNAME, $state2->getCountry()); + $this->assertInstanceOf(State::class, $state1); + $this->assertInstanceOf(State::class, $state2); + $this->assertInstanceOf(Country::class, $state1->getCountry()); + $this->assertInstanceOf(Country::class, $state2->getCountry()); $queryCount = $this->getCurrentQueryCount(); @@ -180,8 +181,8 @@ public function testShouldNotReloadWhenAssociationIsMissing() public function testPutAndLoadNonCacheableManyToOne() { - $this->assertNull($this->cache->getEntityCacheRegion(Action::CLASSNAME)); - $this->assertInstanceOf('Doctrine\ORM\Cache\Region', $this->cache->getEntityCacheRegion(Token::CLASSNAME)); + $this->assertNull($this->cache->getEntityCacheRegion(Action::class)); + $this->assertInstanceOf(Region::class, $this->cache->getEntityCacheRegion(Token::class)); $token = new Token('token-hash'); $action = new Action('exec'); @@ -192,26 +193,26 @@ public function testPutAndLoadNonCacheableManyToOne() $this->_em->flush(); $this->_em->clear(); - $this->assertTrue($this->cache->containsEntity(Token::CLASSNAME, $token->token)); - $this->assertFalse($this->cache->containsEntity(Token::CLASSNAME, $action->id)); + $this->assertTrue($this->cache->containsEntity(Token::class, $token->token)); + $this->assertFalse($this->cache->containsEntity(Token::class, $action->name)); $queryCount = $this->getCurrentQueryCount(); - $entity = $this->_em->find(Token::CLASSNAME, $token->token); + $entity = $this->_em->find(Token::class, $token->token); - $this->assertInstanceOf(Token::CLASSNAME, $entity); + $this->assertInstanceOf(Token::class, $entity); $this->assertEquals('token-hash', $entity->token); - $this->assertInstanceOf(Action::CLASSNAME, $entity->getAction()); + $this->assertInstanceOf(Action::class, $entity->getAction()); $this->assertEquals('exec', $entity->getAction()->name); - $this->assertEquals($queryCount + 1, $this->getCurrentQueryCount()); + $this->assertEquals($queryCount, $this->getCurrentQueryCount()); } public function testPutAndLoadNonCacheableCompositeManyToOne() { - $this->assertNull($this->cache->getEntityCacheRegion(Action::CLASSNAME)); - $this->assertNull($this->cache->getEntityCacheRegion(ComplexAction::CLASSNAME)); - $this->assertInstanceOf('Doctrine\ORM\Cache\Region', $this->cache->getEntityCacheRegion(Token::CLASSNAME)); + $this->assertNull($this->cache->getEntityCacheRegion(Action::class)); + $this->assertNull($this->cache->getEntityCacheRegion(ComplexAction::class)); + $this->assertInstanceOf(Region::class, $this->cache->getEntityCacheRegion(Token::class)); $token = new Token('token-hash'); @@ -230,33 +231,33 @@ public function testPutAndLoadNonCacheableCompositeManyToOne() $this->_em->flush(); $this->_em->clear(); - $this->assertTrue($this->cache->containsEntity(Token::CLASSNAME, $token->token)); - $this->assertFalse($this->cache->containsEntity(Action::CLASSNAME, $action1->id)); - $this->assertFalse($this->cache->containsEntity(Action::CLASSNAME, $action2->id)); - $this->assertFalse($this->cache->containsEntity(Action::CLASSNAME, $action3->id)); + $this->assertTrue($this->cache->containsEntity(Token::class, $token->token)); + $this->assertFalse($this->cache->containsEntity(Action::class, $action1->name)); + $this->assertFalse($this->cache->containsEntity(Action::class, $action2->name)); + $this->assertFalse($this->cache->containsEntity(Action::class, $action3->name)); $queryCount = $this->getCurrentQueryCount(); /** * @var $entity Token */ - $entity = $this->_em->find(Token::CLASSNAME, $token->token); + $entity = $this->_em->find(Token::class, $token->token); - $this->assertInstanceOf(Token::CLASSNAME, $entity); + $this->assertInstanceOf(Token::class, $entity); $this->assertEquals('token-hash', $entity->token); $this->assertEquals($queryCount, $this->getCurrentQueryCount()); - $this->assertInstanceOf(Action::CLASSNAME, $entity->getAction()); - $this->assertInstanceOf(ComplexAction::CLASSNAME, $entity->getComplexAction()); + $this->assertInstanceOf(Action::class, $entity->getAction()); + $this->assertInstanceOf(ComplexAction::class, $entity->getComplexAction()); $this->assertEquals($queryCount, $this->getCurrentQueryCount()); - $this->assertInstanceOf(Action::CLASSNAME, $entity->getComplexAction()->getAction1()); - $this->assertInstanceOf(Action::CLASSNAME, $entity->getComplexAction()->getAction2()); + $this->assertInstanceOf(Action::class, $entity->getComplexAction()->getAction1()); + $this->assertInstanceOf(Action::class, $entity->getComplexAction()->getAction2()); $this->assertEquals($queryCount + 1, $this->getCurrentQueryCount()); $this->assertEquals('login', $entity->getComplexAction()->getAction1()->name); - $this->assertEquals($queryCount + 2, $this->getCurrentQueryCount()); + $this->assertEquals($queryCount + 1, $this->getCurrentQueryCount()); $this->assertEquals('rememberme', $entity->getComplexAction()->getAction2()->name); - $this->assertEquals($queryCount + 3, $this->getCurrentQueryCount()); + $this->assertEquals($queryCount + 1, $this->getCurrentQueryCount()); } -} \ No newline at end of file +} diff --git a/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheOneToManyTest.php b/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheOneToManyTest.php index 829cc4056b6..9f347cc5ba1 100644 --- a/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheOneToManyTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheOneToManyTest.php @@ -2,6 +2,7 @@ namespace Doctrine\Tests\ORM\Functional; +use Doctrine\ORM\Cache\Region; use Doctrine\Tests\Models\Cache\City; use Doctrine\Tests\Models\Cache\Login; use Doctrine\Tests\Models\Cache\State; @@ -22,10 +23,10 @@ public function testShouldPutCollectionInverseSideOnPersist() $this->_em->clear(); - $this->assertTrue($this->cache->containsEntity(State::CLASSNAME, $this->states[0]->getId())); - $this->assertTrue($this->cache->containsEntity(State::CLASSNAME, $this->states[1]->getId())); - $this->assertTrue($this->cache->containsCollection(State::CLASSNAME, 'cities', $this->states[0]->getId())); - $this->assertTrue($this->cache->containsCollection(State::CLASSNAME, 'cities', $this->states[1]->getId())); + $this->assertTrue($this->cache->containsEntity(State::class, $this->states[0]->getId())); + $this->assertTrue($this->cache->containsEntity(State::class, $this->states[1]->getId())); + $this->assertTrue($this->cache->containsCollection(State::class, 'cities', $this->states[0]->getId())); + $this->assertTrue($this->cache->containsCollection(State::class, 'cities', $this->states[1]->getId())); } public function testPutAndLoadOneToManyRelation() @@ -36,28 +37,28 @@ public function testPutAndLoadOneToManyRelation() $this->_em->clear(); $this->secondLevelCacheLogger->clearStats(); - $this->cache->evictEntityRegion(State::CLASSNAME); - $this->cache->evictEntityRegion(City::CLASSNAME); - $this->cache->evictCollectionRegion(State::CLASSNAME, 'cities'); + $this->cache->evictEntityRegion(State::class); + $this->cache->evictEntityRegion(City::class); + $this->cache->evictCollectionRegion(State::class, 'cities'); - $this->assertFalse($this->cache->containsEntity(State::CLASSNAME, $this->states[0]->getId())); - $this->assertFalse($this->cache->containsEntity(State::CLASSNAME, $this->states[1]->getId())); + $this->assertFalse($this->cache->containsEntity(State::class, $this->states[0]->getId())); + $this->assertFalse($this->cache->containsEntity(State::class, $this->states[1]->getId())); - $this->assertFalse($this->cache->containsCollection(State::CLASSNAME, 'cities', $this->states[0]->getId())); - $this->assertFalse($this->cache->containsCollection(State::CLASSNAME, 'cities', $this->states[1]->getId())); + $this->assertFalse($this->cache->containsCollection(State::class, 'cities', $this->states[0]->getId())); + $this->assertFalse($this->cache->containsCollection(State::class, 'cities', $this->states[1]->getId())); - $this->assertFalse($this->cache->containsEntity(City::CLASSNAME, $this->states[0]->getCities()->get(0)->getId())); - $this->assertFalse($this->cache->containsEntity(City::CLASSNAME, $this->states[0]->getCities()->get(1)->getId())); - $this->assertFalse($this->cache->containsEntity(City::CLASSNAME, $this->states[1]->getCities()->get(0)->getId())); - $this->assertFalse($this->cache->containsEntity(City::CLASSNAME, $this->states[1]->getCities()->get(1)->getId())); + $this->assertFalse($this->cache->containsEntity(City::class, $this->states[0]->getCities()->get(0)->getId())); + $this->assertFalse($this->cache->containsEntity(City::class, $this->states[0]->getCities()->get(1)->getId())); + $this->assertFalse($this->cache->containsEntity(City::class, $this->states[1]->getCities()->get(0)->getId())); + $this->assertFalse($this->cache->containsEntity(City::class, $this->states[1]->getCities()->get(1)->getId())); - $s1 = $this->_em->find(State::CLASSNAME, $this->states[0]->getId()); - $s2 = $this->_em->find(State::CLASSNAME, $this->states[1]->getId()); + $s1 = $this->_em->find(State::class, $this->states[0]->getId()); + $s2 = $this->_em->find(State::class, $this->states[1]->getId()); $this->assertEquals(2, $this->secondLevelCacheLogger->getPutCount()); $this->assertEquals(2, $this->secondLevelCacheLogger->getMissCount()); - $this->assertEquals(2, $this->secondLevelCacheLogger->getRegionPutCount($this->getEntityRegion(State::CLASSNAME))); - $this->assertEquals(2, $this->secondLevelCacheLogger->getRegionMissCount($this->getEntityRegion(State::CLASSNAME))); + $this->assertEquals(2, $this->secondLevelCacheLogger->getRegionPutCount($this->getEntityRegion(State::class))); + $this->assertEquals(2, $this->secondLevelCacheLogger->getRegionMissCount($this->getEntityRegion(State::class))); //trigger lazy load $this->assertCount(2, $s1->getCities()); @@ -65,46 +66,46 @@ public function testPutAndLoadOneToManyRelation() $this->assertEquals(4, $this->secondLevelCacheLogger->getPutCount()); $this->assertEquals(4, $this->secondLevelCacheLogger->getMissCount()); - $this->assertEquals(2, $this->secondLevelCacheLogger->getRegionPutCount($this->getCollectionRegion(State::CLASSNAME, 'cities'))); - $this->assertEquals(2, $this->secondLevelCacheLogger->getRegionMissCount($this->getCollectionRegion(State::CLASSNAME, 'cities'))); + $this->assertEquals(2, $this->secondLevelCacheLogger->getRegionPutCount($this->getCollectionRegion(State::class, 'cities'))); + $this->assertEquals(2, $this->secondLevelCacheLogger->getRegionMissCount($this->getCollectionRegion(State::class, 'cities'))); - $this->assertInstanceOf(City::CLASSNAME, $s1->getCities()->get(0)); - $this->assertInstanceOf(City::CLASSNAME, $s1->getCities()->get(1)); + $this->assertInstanceOf(City::class, $s1->getCities()->get(0)); + $this->assertInstanceOf(City::class, $s1->getCities()->get(1)); - $this->assertInstanceOf(City::CLASSNAME, $s2->getCities()->get(0)); - $this->assertInstanceOf(City::CLASSNAME, $s2->getCities()->get(1)); + $this->assertInstanceOf(City::class, $s2->getCities()->get(0)); + $this->assertInstanceOf(City::class, $s2->getCities()->get(1)); - $this->assertTrue($this->cache->containsEntity(State::CLASSNAME, $this->states[0]->getId())); - $this->assertTrue($this->cache->containsEntity(State::CLASSNAME, $this->states[1]->getId())); + $this->assertTrue($this->cache->containsEntity(State::class, $this->states[0]->getId())); + $this->assertTrue($this->cache->containsEntity(State::class, $this->states[1]->getId())); - $this->assertTrue($this->cache->containsCollection(State::CLASSNAME, 'cities', $this->states[0]->getId())); - $this->assertTrue($this->cache->containsCollection(State::CLASSNAME, 'cities', $this->states[1]->getId())); + $this->assertTrue($this->cache->containsCollection(State::class, 'cities', $this->states[0]->getId())); + $this->assertTrue($this->cache->containsCollection(State::class, 'cities', $this->states[1]->getId())); - $this->assertTrue($this->cache->containsEntity(City::CLASSNAME, $this->states[0]->getCities()->get(0)->getId())); - $this->assertTrue($this->cache->containsEntity(City::CLASSNAME, $this->states[0]->getCities()->get(1)->getId())); - $this->assertTrue($this->cache->containsEntity(City::CLASSNAME, $this->states[1]->getCities()->get(0)->getId())); - $this->assertTrue($this->cache->containsEntity(City::CLASSNAME, $this->states[1]->getCities()->get(1)->getId())); + $this->assertTrue($this->cache->containsEntity(City::class, $this->states[0]->getCities()->get(0)->getId())); + $this->assertTrue($this->cache->containsEntity(City::class, $this->states[0]->getCities()->get(1)->getId())); + $this->assertTrue($this->cache->containsEntity(City::class, $this->states[1]->getCities()->get(0)->getId())); + $this->assertTrue($this->cache->containsEntity(City::class, $this->states[1]->getCities()->get(1)->getId())); $this->_em->clear(); $this->secondLevelCacheLogger->clearStats(); $queryCount = $this->getCurrentQueryCount(); - $s3 = $this->_em->find(State::CLASSNAME, $this->states[0]->getId()); - $s4 = $this->_em->find(State::CLASSNAME, $this->states[1]->getId()); + $s3 = $this->_em->find(State::class, $this->states[0]->getId()); + $s4 = $this->_em->find(State::class, $this->states[1]->getId()); //trigger lazy load from cache $this->assertCount(2, $s3->getCities()); $this->assertCount(2, $s4->getCities()); $this->assertEquals(4, $this->secondLevelCacheLogger->getHitCount()); - $this->assertEquals(2, $this->secondLevelCacheLogger->getRegionHitCount($this->getEntityRegion(State::CLASSNAME))); - $this->assertEquals(2, $this->secondLevelCacheLogger->getRegionHitCount($this->getCollectionRegion(State::CLASSNAME, 'cities'))); + $this->assertEquals(2, $this->secondLevelCacheLogger->getRegionHitCount($this->getEntityRegion(State::class))); + $this->assertEquals(2, $this->secondLevelCacheLogger->getRegionHitCount($this->getCollectionRegion(State::class, 'cities'))); - $this->assertInstanceOf(City::CLASSNAME, $s3->getCities()->get(0)); - $this->assertInstanceOf(City::CLASSNAME, $s3->getCities()->get(1)); - $this->assertInstanceOf(City::CLASSNAME, $s4->getCities()->get(0)); - $this->assertInstanceOf(City::CLASSNAME, $s4->getCities()->get(1)); + $this->assertInstanceOf(City::class, $s3->getCities()->get(0)); + $this->assertInstanceOf(City::class, $s3->getCities()->get(1)); + $this->assertInstanceOf(City::class, $s4->getCities()->get(0)); + $this->assertInstanceOf(City::class, $s4->getCities()->get(1)); $this->assertNotSame($s1->getCities()->get(0), $s3->getCities()->get(0)); $this->assertEquals($s1->getCities()->get(0)->getId(), $s3->getCities()->get(0)->getId()); @@ -134,32 +135,32 @@ public function testLoadOneToManyCollectionFromDatabaseWhenEntityMissing() $this->_em->clear(); //trigger lazy load from database - $this->assertCount(2, $this->_em->find(State::CLASSNAME, $this->states[0]->getId())->getCities()); + $this->assertCount(2, $this->_em->find(State::class, $this->states[0]->getId())->getCities()); - $this->assertTrue($this->cache->containsEntity(State::CLASSNAME, $this->states[0]->getId())); - $this->assertTrue($this->cache->containsCollection(State::CLASSNAME, 'cities', $this->states[0]->getId())); - $this->assertTrue($this->cache->containsEntity(City::CLASSNAME, $this->states[0]->getCities()->get(0)->getId())); - $this->assertTrue($this->cache->containsEntity(City::CLASSNAME, $this->states[0]->getCities()->get(1)->getId())); + $this->assertTrue($this->cache->containsEntity(State::class, $this->states[0]->getId())); + $this->assertTrue($this->cache->containsCollection(State::class, 'cities', $this->states[0]->getId())); + $this->assertTrue($this->cache->containsEntity(City::class, $this->states[0]->getCities()->get(0)->getId())); + $this->assertTrue($this->cache->containsEntity(City::class, $this->states[0]->getCities()->get(1)->getId())); $queryCount = $this->getCurrentQueryCount(); $stateId = $this->states[0]->getId(); - $state = $this->_em->find(State::CLASSNAME, $stateId); + $state = $this->_em->find(State::class, $stateId); $cityId = $this->states[0]->getCities()->get(1)->getId(); //trigger lazy load from cache $this->assertCount(2, $state->getCities()); $this->assertEquals($queryCount, $this->getCurrentQueryCount()); - $this->assertTrue($this->cache->containsEntity(City::CLASSNAME, $cityId)); + $this->assertTrue($this->cache->containsEntity(City::class, $cityId)); - $this->cache->evictEntity(City::CLASSNAME, $cityId); + $this->cache->evictEntity(City::class, $cityId); - $this->assertFalse($this->cache->containsEntity(City::CLASSNAME, $cityId)); - $this->assertTrue($this->cache->containsEntity(State::CLASSNAME, $stateId)); - $this->assertTrue($this->cache->containsCollection(State::CLASSNAME, 'cities', $stateId)); + $this->assertFalse($this->cache->containsEntity(City::class, $cityId)); + $this->assertTrue($this->cache->containsEntity(State::class, $stateId)); + $this->assertTrue($this->cache->containsCollection(State::class, 'cities', $stateId)); $this->_em->clear(); - $state = $this->_em->find(State::CLASSNAME, $stateId); + $state = $this->_em->find(State::class, $stateId); //trigger lazy load from database $this->assertCount(2, $state->getCities()); @@ -178,8 +179,8 @@ public function testShoudNotPutOneToManyRelationOnPersist() $this->_em->flush(); $this->_em->clear(); - $this->assertTrue($this->cache->containsEntity(State::CLASSNAME, $state->getId())); - $this->assertFalse($this->cache->containsCollection(State::CLASSNAME, 'cities', $state->getId())); + $this->assertTrue($this->cache->containsEntity(State::class, $state->getId())); + $this->assertFalse($this->cache->containsCollection(State::class, 'cities', $state->getId())); } public function testOneToManyRemove() @@ -191,51 +192,51 @@ public function testOneToManyRemove() $this->_em->clear(); $this->secondLevelCacheLogger->clearStats(); - $this->cache->evictEntityRegion(State::CLASSNAME); - $this->cache->evictEntityRegion(City::CLASSNAME); - $this->cache->evictCollectionRegion(State::CLASSNAME, 'cities'); + $this->cache->evictEntityRegion(State::class); + $this->cache->evictEntityRegion(City::class); + $this->cache->evictCollectionRegion(State::class, 'cities'); - $this->assertFalse($this->cache->containsEntity(State::CLASSNAME, $this->states[0]->getId())); - $this->assertFalse($this->cache->containsCollection(State::CLASSNAME, 'cities', $this->states[0]->getId())); - $this->assertFalse($this->cache->containsEntity(City::CLASSNAME, $this->states[0]->getCities()->get(0)->getId())); - $this->assertFalse($this->cache->containsEntity(City::CLASSNAME, $this->states[0]->getCities()->get(1)->getId())); + $this->assertFalse($this->cache->containsEntity(State::class, $this->states[0]->getId())); + $this->assertFalse($this->cache->containsCollection(State::class, 'cities', $this->states[0]->getId())); + $this->assertFalse($this->cache->containsEntity(City::class, $this->states[0]->getCities()->get(0)->getId())); + $this->assertFalse($this->cache->containsEntity(City::class, $this->states[0]->getCities()->get(1)->getId())); - $entity = $this->_em->find(State::CLASSNAME, $this->states[0]->getId()); + $entity = $this->_em->find(State::class, $this->states[0]->getId()); $this->assertEquals(1, $this->secondLevelCacheLogger->getPutCount()); $this->assertEquals(1, $this->secondLevelCacheLogger->getMissCount()); - $this->assertEquals(1, $this->secondLevelCacheLogger->getRegionPutCount($this->getEntityRegion(State::CLASSNAME))); - $this->assertEquals(1, $this->secondLevelCacheLogger->getRegionMissCount($this->getEntityRegion(State::CLASSNAME))); + $this->assertEquals(1, $this->secondLevelCacheLogger->getRegionPutCount($this->getEntityRegion(State::class))); + $this->assertEquals(1, $this->secondLevelCacheLogger->getRegionMissCount($this->getEntityRegion(State::class))); //trigger lazy load $this->assertCount(2, $entity->getCities()); $this->assertEquals(2, $this->secondLevelCacheLogger->getPutCount()); $this->assertEquals(2, $this->secondLevelCacheLogger->getMissCount()); - $this->assertEquals(1, $this->secondLevelCacheLogger->getRegionPutCount($this->getCollectionRegion(State::CLASSNAME, 'cities'))); - $this->assertEquals(1, $this->secondLevelCacheLogger->getRegionMissCount($this->getCollectionRegion(State::CLASSNAME, 'cities'))); + $this->assertEquals(1, $this->secondLevelCacheLogger->getRegionPutCount($this->getCollectionRegion(State::class, 'cities'))); + $this->assertEquals(1, $this->secondLevelCacheLogger->getRegionMissCount($this->getCollectionRegion(State::class, 'cities'))); - $this->assertInstanceOf(City::CLASSNAME, $entity->getCities()->get(0)); - $this->assertInstanceOf(City::CLASSNAME, $entity->getCities()->get(1)); + $this->assertInstanceOf(City::class, $entity->getCities()->get(0)); + $this->assertInstanceOf(City::class, $entity->getCities()->get(1)); $this->_em->clear(); $this->secondLevelCacheLogger->clearStats(); $queryCount = $this->getCurrentQueryCount(); - $state = $this->_em->find(State::CLASSNAME, $this->states[0]->getId()); + $state = $this->_em->find(State::class, $this->states[0]->getId()); //trigger lazy load from cache $this->assertCount(2, $state->getCities()); $this->assertEquals(2, $this->secondLevelCacheLogger->getHitCount()); - $this->assertEquals(1, $this->secondLevelCacheLogger->getRegionHitCount($this->getEntityRegion(State::CLASSNAME))); - $this->assertEquals(1, $this->secondLevelCacheLogger->getRegionHitCount($this->getCollectionRegion(State::CLASSNAME, 'cities'))); + $this->assertEquals(1, $this->secondLevelCacheLogger->getRegionHitCount($this->getEntityRegion(State::class))); + $this->assertEquals(1, $this->secondLevelCacheLogger->getRegionHitCount($this->getCollectionRegion(State::class, 'cities'))); $city0 = $state->getCities()->get(0); $city1 = $state->getCities()->get(1); - $this->assertInstanceOf(City::CLASSNAME, $city0); - $this->assertInstanceOf(City::CLASSNAME, $city1); + $this->assertInstanceOf(City::class, $city0); + $this->assertInstanceOf(City::class, $city1); $this->assertEquals($entity->getCities()->get(0)->getName(), $city0->getName()); $this->assertEquals($entity->getCities()->get(1)->getName(), $city1->getName()); @@ -253,18 +254,18 @@ public function testOneToManyRemove() $this->secondLevelCacheLogger->clearStats(); $queryCount = $this->getCurrentQueryCount(); - $state = $this->_em->find(State::CLASSNAME, $this->states[0]->getId()); + $state = $this->_em->find(State::class, $this->states[0]->getId()); //trigger lazy load from cache $this->assertCount(1, $state->getCities()); $city1 = $state->getCities()->get(0); - $this->assertInstanceOf(City::CLASSNAME, $city1); + $this->assertInstanceOf(City::class, $city1); $this->assertEquals($entity->getCities()->get(1)->getName(), $city1->getName()); $this->assertEquals(2, $this->secondLevelCacheLogger->getHitCount()); - $this->assertEquals(1, $this->secondLevelCacheLogger->getRegionHitCount($this->getEntityRegion(State::CLASSNAME))); - $this->assertEquals(1, $this->secondLevelCacheLogger->getRegionHitCount($this->getCollectionRegion(State::CLASSNAME, 'cities'))); + $this->assertEquals(1, $this->secondLevelCacheLogger->getRegionHitCount($this->getEntityRegion(State::class))); + $this->assertEquals(1, $this->secondLevelCacheLogger->getRegionHitCount($this->getCollectionRegion(State::class, 'cities'))); $this->assertEquals($queryCount, $this->getCurrentQueryCount()); @@ -278,13 +279,13 @@ public function testOneToManyRemove() $this->secondLevelCacheLogger->clearStats(); $queryCount = $this->getCurrentQueryCount(); - $state = $this->_em->find(State::CLASSNAME, $this->states[0]->getId()); + $state = $this->_em->find(State::class, $this->states[0]->getId()); $this->assertCount(0, $state->getCities()); $this->assertEquals(2, $this->secondLevelCacheLogger->getHitCount()); - $this->assertEquals(1, $this->secondLevelCacheLogger->getRegionHitCount($this->getEntityRegion(State::CLASSNAME))); - $this->assertEquals(1, $this->secondLevelCacheLogger->getRegionHitCount($this->getCollectionRegion(State::CLASSNAME, 'cities'))); + $this->assertEquals(1, $this->secondLevelCacheLogger->getRegionHitCount($this->getEntityRegion(State::class))); + $this->assertEquals(1, $this->secondLevelCacheLogger->getRegionHitCount($this->getCollectionRegion(State::class, 'cities'))); } public function testOneToManyWithEmptyRelation() @@ -294,14 +295,14 @@ public function testOneToManyWithEmptyRelation() $this->loadFixturesCities(); $this->secondLevelCacheLogger->clearStats(); - $this->cache->evictEntityRegion(City::CLASSNAME); - $this->cache->evictEntityRegion(State::CLASSNAME); - $this->cache->evictCollectionRegion(State::CLASSNAME, 'cities'); + $this->cache->evictEntityRegion(City::class); + $this->cache->evictEntityRegion(State::class); + $this->cache->evictCollectionRegion(State::class, 'cities'); $this->_em->clear(); $entitiId = $this->states[2]->getId(); // bavaria (cities count = 0) $queryCount = $this->getCurrentQueryCount(); - $entity = $this->_em->find(State::CLASSNAME, $entitiId); + $entity = $this->_em->find(State::class, $entitiId); $this->assertEquals(0, $entity->getCities()->count()); $this->assertEquals($queryCount + 2, $this->getCurrentQueryCount()); @@ -309,7 +310,7 @@ public function testOneToManyWithEmptyRelation() $this->_em->clear(); $queryCount = $this->getCurrentQueryCount(); - $entity = $this->_em->find(State::CLASSNAME, $entitiId); + $entity = $this->_em->find(State::class, $entitiId); $this->assertEquals(0, $entity->getCities()->count()); $this->assertEquals($queryCount, $this->getCurrentQueryCount()); @@ -323,14 +324,14 @@ public function testOneToManyCount() $this->loadFixturesCities(); $this->secondLevelCacheLogger->clearStats(); - $this->cache->evictEntityRegion(City::CLASSNAME); - $this->cache->evictEntityRegion(State::CLASSNAME); - $this->cache->evictCollectionRegion(State::CLASSNAME, 'cities'); + $this->cache->evictEntityRegion(City::class); + $this->cache->evictEntityRegion(State::class); + $this->cache->evictCollectionRegion(State::class, 'cities'); $this->_em->clear(); $entityId = $this->states[0]->getId(); $queryCount = $this->getCurrentQueryCount(); - $entity = $this->_em->find(State::CLASSNAME, $entityId); + $entity = $this->_em->find(State::class, $entityId); $this->assertEquals(2, $entity->getCities()->count()); $this->assertEquals($queryCount + 2, $this->getCurrentQueryCount()); @@ -338,7 +339,7 @@ public function testOneToManyCount() $this->_em->clear(); $queryCount = $this->getCurrentQueryCount(); - $entity = $this->_em->find(State::CLASSNAME, $entityId); + $entity = $this->_em->find(State::class, $entityId); $this->assertEquals(2, $entity->getCities()->count()); $this->assertEquals($queryCount, $this->getCurrentQueryCount()); @@ -364,7 +365,7 @@ public function testCacheInitializeCollectionWithNewObjects() $travelerId = $traveler->getId(); $queryCount = $this->getCurrentQueryCount(); - $entity = $this->_em->find(Traveler::CLASSNAME, $travelerId); + $entity = $this->_em->find(Traveler::class, $travelerId); $this->assertEquals($queryCount, $this->getCurrentQueryCount()); $this->assertFalse($entity->getTravels()->isInitialized()); @@ -388,8 +389,8 @@ public function testCacheInitializeCollectionWithNewObjects() public function testPutAndLoadNonCacheableOneToMany() { - $this->assertNull($this->cache->getEntityCacheRegion(Login::CLASSNAME)); - $this->assertInstanceOf('Doctrine\ORM\Cache\Region', $this->cache->getEntityCacheRegion(Token::CLASSNAME)); + $this->assertNull($this->cache->getEntityCacheRegion(Login::class)); + $this->assertInstanceOf(Region::class, $this->cache->getEntityCacheRegion(Token::class)); $l1 = new Login('session1'); $l2 = new Login('session2'); @@ -401,13 +402,13 @@ public function testPutAndLoadNonCacheableOneToMany() $this->_em->flush(); $this->_em->clear(); - $this->assertTrue($this->cache->containsEntity(Token::CLASSNAME, $token->token)); + $this->assertTrue($this->cache->containsEntity(Token::class, $token->token)); $queryCount = $this->getCurrentQueryCount(); - $entity = $this->_em->find(Token::CLASSNAME, $token->token); + $entity = $this->_em->find(Token::class, $token->token); - $this->assertInstanceOf(Token::CLASSNAME, $entity); + $this->assertInstanceOf(Token::class, $entity); $this->assertEquals('token-hash', $entity->token); $this->assertEquals($queryCount, $this->getCurrentQueryCount()); diff --git a/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheOneToOneTest.php b/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheOneToOneTest.php index 316620f82d2..6e428814d3f 100644 --- a/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheOneToOneTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheOneToOneTest.php @@ -2,6 +2,7 @@ namespace Doctrine\Tests\ORM\Functional; +use Doctrine\ORM\Cache\Region; use Doctrine\Tests\Models\Cache\Address; use Doctrine\Tests\Models\Cache\Client; use Doctrine\Tests\Models\Cache\Person; @@ -27,10 +28,10 @@ public function testPutOneToOneOnUnidirectionalPersist() $entity1 = $this->travelersWithProfile[0]; $entity2 = $this->travelersWithProfile[1]; - $this->assertTrue($this->cache->containsEntity(Traveler::CLASSNAME, $entity1->getId())); - $this->assertTrue($this->cache->containsEntity(Traveler::CLASSNAME, $entity2->getId())); - $this->assertTrue($this->cache->containsEntity(TravelerProfile::CLASSNAME, $entity1->getProfile()->getId())); - $this->assertTrue($this->cache->containsEntity(TravelerProfile::CLASSNAME, $entity2->getProfile()->getId())); + $this->assertTrue($this->cache->containsEntity(Traveler::class, $entity1->getId())); + $this->assertTrue($this->cache->containsEntity(Traveler::class, $entity2->getId())); + $this->assertTrue($this->cache->containsEntity(TravelerProfile::class, $entity1->getProfile()->getId())); + $this->assertTrue($this->cache->containsEntity(TravelerProfile::class, $entity2->getProfile()->getId())); } public function testPutOneToOneOnBidirectionalPersist() @@ -46,12 +47,12 @@ public function testPutOneToOneOnBidirectionalPersist() $entity1 = $this->travelersWithProfile[0]; $entity2 = $this->travelersWithProfile[1]; - $this->assertTrue($this->cache->containsEntity(Traveler::CLASSNAME, $entity1->getId())); - $this->assertTrue($this->cache->containsEntity(Traveler::CLASSNAME, $entity2->getId())); - $this->assertTrue($this->cache->containsEntity(TravelerProfile::CLASSNAME, $entity1->getProfile()->getId())); - $this->assertTrue($this->cache->containsEntity(TravelerProfile::CLASSNAME, $entity2->getProfile()->getId())); - $this->assertTrue($this->cache->containsEntity(TravelerProfileInfo::CLASSNAME, $entity1->getProfile()->getInfo()->getId())); - $this->assertTrue($this->cache->containsEntity(TravelerProfileInfo::CLASSNAME, $entity2->getProfile()->getInfo()->getId())); + $this->assertTrue($this->cache->containsEntity(Traveler::class, $entity1->getId())); + $this->assertTrue($this->cache->containsEntity(Traveler::class, $entity2->getId())); + $this->assertTrue($this->cache->containsEntity(TravelerProfile::class, $entity1->getProfile()->getId())); + $this->assertTrue($this->cache->containsEntity(TravelerProfile::class, $entity2->getProfile()->getId())); + $this->assertTrue($this->cache->containsEntity(TravelerProfileInfo::class, $entity1->getProfile()->getInfo()->getId())); + $this->assertTrue($this->cache->containsEntity(TravelerProfileInfo::class, $entity2->getProfile()->getInfo()->getId())); } public function testPutAndLoadOneToOneUnidirectionalRelation() @@ -64,30 +65,30 @@ public function testPutAndLoadOneToOneUnidirectionalRelation() $this->_em->clear(); - $this->cache->evictEntityRegion(Traveler::CLASSNAME); - $this->cache->evictEntityRegion(TravelerProfile::CLASSNAME); + $this->cache->evictEntityRegion(Traveler::class); + $this->cache->evictEntityRegion(TravelerProfile::class); $entity1 = $this->travelersWithProfile[0]; $entity2 = $this->travelersWithProfile[1]; - $this->assertFalse($this->cache->containsEntity(Traveler::CLASSNAME, $entity1->getId())); - $this->assertFalse($this->cache->containsEntity(Traveler::CLASSNAME, $entity2->getId())); - $this->assertFalse($this->cache->containsEntity(TravelerProfile::CLASSNAME, $entity1->getProfile()->getId())); - $this->assertFalse($this->cache->containsEntity(TravelerProfile::CLASSNAME, $entity2->getProfile()->getId())); + $this->assertFalse($this->cache->containsEntity(Traveler::class, $entity1->getId())); + $this->assertFalse($this->cache->containsEntity(Traveler::class, $entity2->getId())); + $this->assertFalse($this->cache->containsEntity(TravelerProfile::class, $entity1->getProfile()->getId())); + $this->assertFalse($this->cache->containsEntity(TravelerProfile::class, $entity2->getProfile()->getId())); - $t1 = $this->_em->find(Traveler::CLASSNAME, $entity1->getId()); - $t2 = $this->_em->find(Traveler::CLASSNAME, $entity2->getId()); + $t1 = $this->_em->find(Traveler::class, $entity1->getId()); + $t2 = $this->_em->find(Traveler::class, $entity2->getId()); - $this->assertTrue($this->cache->containsEntity(Traveler::CLASSNAME, $entity1->getId())); - $this->assertTrue($this->cache->containsEntity(Traveler::CLASSNAME, $entity2->getId())); + $this->assertTrue($this->cache->containsEntity(Traveler::class, $entity1->getId())); + $this->assertTrue($this->cache->containsEntity(Traveler::class, $entity2->getId())); // The inverse side its not cached - $this->assertFalse($this->cache->containsEntity(TravelerProfile::CLASSNAME, $entity1->getProfile()->getId())); - $this->assertFalse($this->cache->containsEntity(TravelerProfile::CLASSNAME, $entity2->getProfile()->getId())); + $this->assertFalse($this->cache->containsEntity(TravelerProfile::class, $entity1->getProfile()->getId())); + $this->assertFalse($this->cache->containsEntity(TravelerProfile::class, $entity2->getProfile()->getId())); - $this->assertInstanceOf(Traveler::CLASSNAME, $t1); - $this->assertInstanceOf(Traveler::CLASSNAME, $t2); - $this->assertInstanceOf(TravelerProfile::CLASSNAME, $t1->getProfile()); - $this->assertInstanceOf(TravelerProfile::CLASSNAME, $t2->getProfile()); + $this->assertInstanceOf(Traveler::class, $t1); + $this->assertInstanceOf(Traveler::class, $t2); + $this->assertInstanceOf(TravelerProfile::class, $t1->getProfile()); + $this->assertInstanceOf(TravelerProfile::class, $t2->getProfile()); $this->assertEquals($entity1->getId(), $t1->getId()); $this->assertEquals($entity1->getName(), $t1->getName()); @@ -100,22 +101,22 @@ public function testPutAndLoadOneToOneUnidirectionalRelation() $this->assertEquals($entity2->getProfile()->getName(), $t2->getProfile()->getName()); // its all cached now - $this->assertTrue($this->cache->containsEntity(Traveler::CLASSNAME, $entity1->getId())); - $this->assertTrue($this->cache->containsEntity(Traveler::CLASSNAME, $entity2->getId())); - $this->assertTrue($this->cache->containsEntity(TravelerProfile::CLASSNAME, $entity1->getProfile()->getId())); - $this->assertTrue($this->cache->containsEntity(TravelerProfile::CLASSNAME, $entity1->getProfile()->getId())); + $this->assertTrue($this->cache->containsEntity(Traveler::class, $entity1->getId())); + $this->assertTrue($this->cache->containsEntity(Traveler::class, $entity2->getId())); + $this->assertTrue($this->cache->containsEntity(TravelerProfile::class, $entity1->getProfile()->getId())); + $this->assertTrue($this->cache->containsEntity(TravelerProfile::class, $entity1->getProfile()->getId())); $this->_em->clear(); $queryCount = $this->getCurrentQueryCount(); // load from cache - $t3 = $this->_em->find(Traveler::CLASSNAME, $entity1->getId()); - $t4 = $this->_em->find(Traveler::CLASSNAME, $entity2->getId()); + $t3 = $this->_em->find(Traveler::class, $entity1->getId()); + $t4 = $this->_em->find(Traveler::class, $entity2->getId()); - $this->assertInstanceOf(Traveler::CLASSNAME, $t3); - $this->assertInstanceOf(Traveler::CLASSNAME, $t4); - $this->assertInstanceOf(TravelerProfile::CLASSNAME, $t3->getProfile()); - $this->assertInstanceOf(TravelerProfile::CLASSNAME, $t4->getProfile()); + $this->assertInstanceOf(Traveler::class, $t3); + $this->assertInstanceOf(Traveler::class, $t4); + $this->assertInstanceOf(TravelerProfile::class, $t3->getProfile()); + $this->assertInstanceOf(TravelerProfile::class, $t4->getProfile()); $this->assertEquals($entity1->getProfile()->getId(), $t3->getProfile()->getId()); $this->assertEquals($entity2->getProfile()->getId(), $t4->getProfile()->getId()); @@ -136,20 +137,20 @@ public function testPutAndLoadOneToOneBidirectionalRelation() $this->_em->clear(); - $this->cache->evictEntityRegion(Traveler::CLASSNAME); - $this->cache->evictEntityRegion(TravelerProfile::CLASSNAME); - $this->cache->evictEntityRegion(TravelerProfileInfo::CLASSNAME); + $this->cache->evictEntityRegion(Traveler::class); + $this->cache->evictEntityRegion(TravelerProfile::class); + $this->cache->evictEntityRegion(TravelerProfileInfo::class); $entity1 = $this->travelersWithProfile[0]->getProfile(); $entity2 = $this->travelersWithProfile[1]->getProfile(); - $this->assertFalse($this->cache->containsEntity(TravelerProfile::CLASSNAME, $entity1->getId())); - $this->assertFalse($this->cache->containsEntity(TravelerProfile::CLASSNAME, $entity2->getId())); - $this->assertFalse($this->cache->containsEntity(TravelerProfileInfo::CLASSNAME, $entity1->getInfo()->getId())); - $this->assertFalse($this->cache->containsEntity(TravelerProfileInfo::CLASSNAME, $entity2->getInfo()->getId())); + $this->assertFalse($this->cache->containsEntity(TravelerProfile::class, $entity1->getId())); + $this->assertFalse($this->cache->containsEntity(TravelerProfile::class, $entity2->getId())); + $this->assertFalse($this->cache->containsEntity(TravelerProfileInfo::class, $entity1->getInfo()->getId())); + $this->assertFalse($this->cache->containsEntity(TravelerProfileInfo::class, $entity2->getInfo()->getId())); - $p1 = $this->_em->find(TravelerProfile::CLASSNAME, $entity1->getId()); - $p2 = $this->_em->find(TravelerProfile::CLASSNAME, $entity2->getId()); + $p1 = $this->_em->find(TravelerProfile::class, $entity1->getId()); + $p2 = $this->_em->find(TravelerProfile::class, $entity2->getId()); $this->assertEquals($entity1->getId(), $p1->getId()); $this->assertEquals($entity1->getName(), $p1->getName()); @@ -161,22 +162,22 @@ public function testPutAndLoadOneToOneBidirectionalRelation() $this->assertEquals($entity2->getInfo()->getId(), $p2->getInfo()->getId()); $this->assertEquals($entity2->getInfo()->getDescription(), $p2->getInfo()->getDescription()); - $this->assertTrue($this->cache->containsEntity(TravelerProfile::CLASSNAME, $entity1->getId())); - $this->assertTrue($this->cache->containsEntity(TravelerProfile::CLASSNAME, $entity2->getId())); - $this->assertTrue($this->cache->containsEntity(TravelerProfileInfo::CLASSNAME, $entity1->getInfo()->getId())); - $this->assertTrue($this->cache->containsEntity(TravelerProfileInfo::CLASSNAME, $entity2->getInfo()->getId())); + $this->assertTrue($this->cache->containsEntity(TravelerProfile::class, $entity1->getId())); + $this->assertTrue($this->cache->containsEntity(TravelerProfile::class, $entity2->getId())); + $this->assertTrue($this->cache->containsEntity(TravelerProfileInfo::class, $entity1->getInfo()->getId())); + $this->assertTrue($this->cache->containsEntity(TravelerProfileInfo::class, $entity2->getInfo()->getId())); $this->_em->clear(); $queryCount = $this->getCurrentQueryCount(); - $p3 = $this->_em->find(TravelerProfile::CLASSNAME, $entity1->getId()); - $p4 = $this->_em->find(TravelerProfile::CLASSNAME, $entity2->getId()); + $p3 = $this->_em->find(TravelerProfile::class, $entity1->getId()); + $p4 = $this->_em->find(TravelerProfile::class, $entity2->getId()); - $this->assertInstanceOf(TravelerProfile::CLASSNAME, $p3); - $this->assertInstanceOf(TravelerProfile::CLASSNAME, $p4); - $this->assertInstanceOf(TravelerProfileInfo::CLASSNAME, $p3->getInfo()); - $this->assertInstanceOf(TravelerProfileInfo::CLASSNAME, $p4->getInfo()); + $this->assertInstanceOf(TravelerProfile::class, $p3); + $this->assertInstanceOf(TravelerProfile::class, $p4); + $this->assertInstanceOf(TravelerProfileInfo::class, $p3->getInfo()); + $this->assertInstanceOf(TravelerProfileInfo::class, $p4->getInfo()); $this->assertEquals($entity1->getId(), $p3->getId()); $this->assertEquals($entity1->getName(), $p3->getName()); @@ -197,19 +198,19 @@ public function testInverseSidePutAndLoadOneToOneBidirectionalRelation() $this->_em->clear(); - $this->cache->evictEntityRegion(Person::CLASSNAME); - $this->cache->evictEntityRegion(Address::CLASSNAME); + $this->cache->evictEntityRegion(Person::class); + $this->cache->evictEntityRegion(Address::class); $entity1 = $this->addresses[0]->person; $entity2 = $this->addresses[1]->person; - $this->assertFalse($this->cache->containsEntity(Person::CLASSNAME, $entity1->id)); - $this->assertFalse($this->cache->containsEntity(Person::CLASSNAME, $entity2->id)); - $this->assertFalse($this->cache->containsEntity(Address::CLASSNAME, $entity1->address->id)); - $this->assertFalse($this->cache->containsEntity(Address::CLASSNAME, $entity2->address->id)); + $this->assertFalse($this->cache->containsEntity(Person::class, $entity1->id)); + $this->assertFalse($this->cache->containsEntity(Person::class, $entity2->id)); + $this->assertFalse($this->cache->containsEntity(Address::class, $entity1->address->id)); + $this->assertFalse($this->cache->containsEntity(Address::class, $entity2->address->id)); - $p1 = $this->_em->find(Person::CLASSNAME, $entity1->id); - $p2 = $this->_em->find(Person::CLASSNAME, $entity2->id); + $p1 = $this->_em->find(Person::class, $entity1->id); + $p2 = $this->_em->find(Person::class, $entity2->id); $this->assertEquals($entity1->id, $p1->id); $this->assertEquals($entity1->name, $p1->name); @@ -221,23 +222,23 @@ public function testInverseSidePutAndLoadOneToOneBidirectionalRelation() $this->assertEquals($entity2->address->id, $p2->address->id); $this->assertEquals($entity2->address->location, $p2->address->location); - $this->assertTrue($this->cache->containsEntity(Person::CLASSNAME, $entity1->id)); - $this->assertTrue($this->cache->containsEntity(Person::CLASSNAME, $entity2->id)); + $this->assertTrue($this->cache->containsEntity(Person::class, $entity1->id)); + $this->assertTrue($this->cache->containsEntity(Person::class, $entity2->id)); // The inverse side its not cached - $this->assertFalse($this->cache->containsEntity(Address::CLASSNAME, $entity1->address->id)); - $this->assertFalse($this->cache->containsEntity(Address::CLASSNAME, $entity2->address->id)); + $this->assertFalse($this->cache->containsEntity(Address::class, $entity1->address->id)); + $this->assertFalse($this->cache->containsEntity(Address::class, $entity2->address->id)); $this->_em->clear(); $queryCount = $this->getCurrentQueryCount(); - $p3 = $this->_em->find(Person::CLASSNAME, $entity1->id); - $p4 = $this->_em->find(Person::CLASSNAME, $entity2->id); + $p3 = $this->_em->find(Person::class, $entity1->id); + $p4 = $this->_em->find(Person::class, $entity2->id); - $this->assertInstanceOf(Person::CLASSNAME, $p3); - $this->assertInstanceOf(Person::CLASSNAME, $p4); - $this->assertInstanceOf(Address::CLASSNAME, $p3->address); - $this->assertInstanceOf(Address::CLASSNAME, $p4->address); + $this->assertInstanceOf(Person::class, $p3); + $this->assertInstanceOf(Person::class, $p4); + $this->assertInstanceOf(Address::class, $p3->address); + $this->assertInstanceOf(Address::class, $p4->address); $this->assertEquals($entity1->id, $p3->id); $this->assertEquals($entity1->name, $p3->name); @@ -254,8 +255,8 @@ public function testInverseSidePutAndLoadOneToOneBidirectionalRelation() public function testPutAndLoadNonCacheableOneToOne() { - $this->assertNull($this->cache->getEntityCacheRegion(Client::CLASSNAME)); - $this->assertInstanceOf('Doctrine\ORM\Cache\Region', $this->cache->getEntityCacheRegion(Token::CLASSNAME)); + $this->assertNull($this->cache->getEntityCacheRegion(Client::class)); + $this->assertInstanceOf(Region::class, $this->cache->getEntityCacheRegion(Token::class)); $client = new Client('FabioBatSilva'); $token = new Token('token-hash', $client); @@ -267,17 +268,17 @@ public function testPutAndLoadNonCacheableOneToOne() $queryCount = $this->getCurrentQueryCount(); - $this->assertTrue($this->cache->containsEntity(Token::CLASSNAME, $token->token)); - $this->assertFalse($this->cache->containsEntity(Client::CLASSNAME, $client->id)); + $this->assertTrue($this->cache->containsEntity(Token::class, $token->token)); + $this->assertFalse($this->cache->containsEntity(Client::class, $client->id)); - $entity = $this->_em->find(Token::CLASSNAME, $token->token); + $entity = $this->_em->find(Token::class, $token->token); - $this->assertInstanceOf(Token::CLASSNAME, $entity); - $this->assertInstanceOf(Client::CLASSNAME, $entity->getClient()); + $this->assertInstanceOf(Token::class, $entity); + $this->assertInstanceOf(Client::class, $entity->getClient()); $this->assertEquals('token-hash', $entity->token); $this->assertEquals($queryCount, $this->getCurrentQueryCount()); $this->assertEquals('FabioBatSilva', $entity->getClient()->name); $this->assertEquals($queryCount + 1, $this->getCurrentQueryCount()); } -} \ No newline at end of file +} diff --git a/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheQueryCacheTest.php b/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheQueryCacheTest.php index 97d8ce82a1c..0a32886dd0f 100644 --- a/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheQueryCacheTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheQueryCacheTest.php @@ -3,16 +3,17 @@ namespace Doctrine\Tests\ORM\Functional; use Doctrine\ORM\AbstractQuery; +use Doctrine\ORM\Cache; +use Doctrine\ORM\Cache\EntityCacheEntry; +use Doctrine\ORM\Cache\EntityCacheKey; +use Doctrine\ORM\Cache\QueryCacheKey; +use Doctrine\ORM\Proxy\Proxy; +use Doctrine\ORM\Query; use Doctrine\ORM\Query\ResultSetMapping; +use Doctrine\Tests\Models\Cache\Attraction; use Doctrine\Tests\Models\Cache\City; -use Doctrine\Tests\Models\Cache\State; use Doctrine\Tests\Models\Cache\Country; -use Doctrine\Tests\Models\Cache\Attraction; -use Doctrine\ORM\Cache\QueryCacheKey; -use Doctrine\ORM\Cache\EntityCacheKey; -use Doctrine\ORM\Cache\EntityCacheEntry; -use Doctrine\ORM\Query; -use Doctrine\ORM\Cache; +use Doctrine\Tests\Models\Cache\State; /** * @group DDC-2183 @@ -27,8 +28,8 @@ public function testBasicQueryCache() $this->secondLevelCacheLogger->clearStats(); $this->_em->clear(); - $this->assertTrue($this->cache->containsEntity(Country::CLASSNAME, $this->countries[0]->getId())); - $this->assertTrue($this->cache->containsEntity(Country::CLASSNAME, $this->countries[1]->getId())); + $this->assertTrue($this->cache->containsEntity(Country::class, $this->countries[0]->getId())); + $this->assertTrue($this->cache->containsEntity(Country::class, $this->countries[1]->getId())); $queryCount = $this->getCurrentQueryCount(); $dql = 'SELECT c FROM Doctrine\Tests\Models\Cache\Country c'; @@ -63,8 +64,8 @@ public function testBasicQueryCache() $this->assertEquals(1, $this->secondLevelCacheLogger->getRegionHitCount($this->getDefaultQueryRegionName())); $this->assertEquals(1, $this->secondLevelCacheLogger->getRegionMissCount($this->getDefaultQueryRegionName())); - $this->assertInstanceOf('Doctrine\Tests\Models\Cache\Country', $result2[0]); - $this->assertInstanceOf('Doctrine\Tests\Models\Cache\Country', $result2[1]); + $this->assertInstanceOf(Country::class, $result2[0]); + $this->assertInstanceOf(Country::class, $result2[1]); $this->assertEquals($result1[0]->getId(), $result2[0]->getId()); $this->assertEquals($result1[1]->getId(), $result2[1]->getId()); @@ -90,8 +91,8 @@ public function testQueryCacheModeGet() $this->secondLevelCacheLogger->clearStats(); $this->_em->clear(); - $this->assertFalse($this->cache->containsEntity(Country::CLASSNAME, $this->countries[0]->getId())); - $this->assertFalse($this->cache->containsEntity(Country::CLASSNAME, $this->countries[1]->getId())); + $this->assertFalse($this->cache->containsEntity(Country::class, $this->countries[0]->getId())); + $this->assertFalse($this->cache->containsEntity(Country::class, $this->countries[1]->getId())); $queryCount = $this->getCurrentQueryCount(); $dql = 'SELECT c FROM Doctrine\Tests\Models\Cache\Country c'; @@ -113,8 +114,8 @@ public function testQueryCacheModeGet() $this->assertCount(2, $result); $this->assertEquals($queryCount + 3, $this->getCurrentQueryCount()); - $this->assertTrue($this->cache->containsEntity(Country::CLASSNAME, $this->countries[0]->getId())); - $this->assertTrue($this->cache->containsEntity(Country::CLASSNAME, $this->countries[1]->getId())); + $this->assertTrue($this->cache->containsEntity(Country::class, $this->countries[0]->getId())); + $this->assertTrue($this->cache->containsEntity(Country::class, $this->countries[1]->getId())); // MODE_GET should read items if exists. $this->assertCount(2, $queryGet->getResult()); @@ -130,8 +131,8 @@ public function testQueryCacheModePut() $this->secondLevelCacheLogger->clearStats(); $this->_em->clear(); - $this->assertFalse($this->cache->containsEntity(Country::CLASSNAME, $this->countries[0]->getId())); - $this->assertFalse($this->cache->containsEntity(Country::CLASSNAME, $this->countries[1]->getId())); + $this->assertFalse($this->cache->containsEntity(Country::class, $this->countries[0]->getId())); + $this->assertFalse($this->cache->containsEntity(Country::class, $this->countries[1]->getId())); $queryCount = $this->getCurrentQueryCount(); $dql = 'SELECT c FROM Doctrine\Tests\Models\Cache\Country c'; @@ -139,8 +140,8 @@ public function testQueryCacheModePut() ->setCacheable(true) ->getResult(); - $this->assertTrue($this->cache->containsEntity(Country::CLASSNAME, $this->countries[0]->getId())); - $this->assertTrue($this->cache->containsEntity(Country::CLASSNAME, $this->countries[1]->getId())); + $this->assertTrue($this->cache->containsEntity(Country::class, $this->countries[0]->getId())); + $this->assertTrue($this->cache->containsEntity(Country::class, $this->countries[1]->getId())); $this->assertCount(2, $result); $this->assertEquals($queryCount + 1, $this->getCurrentQueryCount()); @@ -152,13 +153,13 @@ public function testQueryCacheModePut() // MODE_PUT should never read itens from cache. $this->assertCount(2, $queryPut->getResult()); $this->assertEquals($queryCount + 2, $this->getCurrentQueryCount()); - $this->assertTrue($this->cache->containsEntity(Country::CLASSNAME, $this->countries[0]->getId())); - $this->assertTrue($this->cache->containsEntity(Country::CLASSNAME, $this->countries[1]->getId())); + $this->assertTrue($this->cache->containsEntity(Country::class, $this->countries[0]->getId())); + $this->assertTrue($this->cache->containsEntity(Country::class, $this->countries[1]->getId())); $this->assertCount(2, $queryPut->getResult()); $this->assertEquals($queryCount + 3, $this->getCurrentQueryCount()); - $this->assertTrue($this->cache->containsEntity(Country::CLASSNAME, $this->countries[0]->getId())); - $this->assertTrue($this->cache->containsEntity(Country::CLASSNAME, $this->countries[1]->getId())); + $this->assertTrue($this->cache->containsEntity(Country::class, $this->countries[0]->getId())); + $this->assertTrue($this->cache->containsEntity(Country::class, $this->countries[1]->getId())); } public function testQueryCacheModeRefresh() @@ -170,18 +171,18 @@ public function testQueryCacheModeRefresh() $this->secondLevelCacheLogger->clearStats(); $this->_em->clear(); - $this->assertFalse($this->cache->containsEntity(Country::CLASSNAME, $this->countries[0]->getId())); - $this->assertFalse($this->cache->containsEntity(Country::CLASSNAME, $this->countries[1]->getId())); + $this->assertFalse($this->cache->containsEntity(Country::class, $this->countries[0]->getId())); + $this->assertFalse($this->cache->containsEntity(Country::class, $this->countries[1]->getId())); - $region = $this->cache->getEntityCacheRegion(Country::CLASSNAME); + $region = $this->cache->getEntityCacheRegion(Country::class); $queryCount = $this->getCurrentQueryCount(); $dql = 'SELECT c FROM Doctrine\Tests\Models\Cache\Country c'; $result = $this->_em->createQuery($dql) ->setCacheable(true) ->getResult(); - $this->assertTrue($this->cache->containsEntity(Country::CLASSNAME, $this->countries[0]->getId())); - $this->assertTrue($this->cache->containsEntity(Country::CLASSNAME, $this->countries[1]->getId())); + $this->assertTrue($this->cache->containsEntity(Country::class, $this->countries[0]->getId())); + $this->assertTrue($this->cache->containsEntity(Country::class, $this->countries[1]->getId())); $this->assertCount(2, $result); $this->assertEquals($queryCount + 1, $this->getCurrentQueryCount()); @@ -191,10 +192,10 @@ public function testQueryCacheModeRefresh() $countryName1 = $this->countries[0]->getName(); $countryName2 = $this->countries[1]->getName(); - $key1 = new EntityCacheKey(Country::CLASSNAME, array('id'=>$countryId1)); - $key2 = new EntityCacheKey(Country::CLASSNAME, array('id'=>$countryId2)); - $entry1 = new EntityCacheEntry(Country::CLASSNAME, array('id'=>$countryId1, 'name'=>'outdated')); - $entry2 = new EntityCacheEntry(Country::CLASSNAME, array('id'=>$countryId2, 'name'=>'outdated')); + $key1 = new EntityCacheKey(Country::class, ['id'=>$countryId1]); + $key2 = new EntityCacheKey(Country::class, ['id'=>$countryId2]); + $entry1 = new EntityCacheEntry(Country::class, ['id'=>$countryId1, 'name'=>'outdated']); + $entry2 = new EntityCacheEntry(Country::class, ['id'=>$countryId2, 'name'=>'outdated']); $region->put($key1, $entry1); $region->put($key2, $entry2); @@ -240,14 +241,14 @@ public function testBasicQueryCachePutEntityCache() $this->assertEquals($this->countries[0]->getName(), $result1[0]->getName()); $this->assertEquals($this->countries[1]->getName(), $result1[1]->getName()); - $this->assertTrue($this->cache->containsEntity(Country::CLASSNAME, $this->countries[0]->getId())); - $this->assertTrue($this->cache->containsEntity(Country::CLASSNAME, $this->countries[1]->getId())); + $this->assertTrue($this->cache->containsEntity(Country::class, $this->countries[0]->getId())); + $this->assertTrue($this->cache->containsEntity(Country::class, $this->countries[1]->getId())); $this->assertEquals(3, $this->secondLevelCacheLogger->getPutCount()); $this->assertEquals(1, $this->secondLevelCacheLogger->getMissCount()); $this->assertEquals(1, $this->secondLevelCacheLogger->getRegionPutCount($this->getDefaultQueryRegionName())); $this->assertEquals(1, $this->secondLevelCacheLogger->getRegionMissCount($this->getDefaultQueryRegionName())); - $this->assertEquals(2, $this->secondLevelCacheLogger->getRegionPutCount($this->getEntityRegion(Country::CLASSNAME))); + $this->assertEquals(2, $this->secondLevelCacheLogger->getRegionPutCount($this->getEntityRegion(Country::class))); $this->_em->clear(); @@ -266,8 +267,8 @@ public function testBasicQueryCachePutEntityCache() $this->assertEquals(1, $this->secondLevelCacheLogger->getRegionHitCount($this->getDefaultQueryRegionName())); $this->assertEquals(1, $this->secondLevelCacheLogger->getRegionMissCount($this->getDefaultQueryRegionName())); - $this->assertInstanceOf('Doctrine\Tests\Models\Cache\Country', $result2[0]); - $this->assertInstanceOf('Doctrine\Tests\Models\Cache\Country', $result2[1]); + $this->assertInstanceOf(Country::class, $result2[0]); + $this->assertInstanceOf(Country::class, $result2[1]); $this->assertEquals($result1[0]->getId(), $result2[0]->getId()); $this->assertEquals($result1[1]->getId(), $result2[1]->getId()); @@ -295,9 +296,9 @@ public function testMultipleNestedDQLAliases() $this->loadFixturesAttractions(); $queryRegionName = $this->getDefaultQueryRegionName(); - $cityRegionName = $this->getEntityRegion(City::CLASSNAME); - $stateRegionName = $this->getEntityRegion(State::CLASSNAME); - $attractionRegionName = $this->getEntityRegion(Attraction::CLASSNAME); + $cityRegionName = $this->getEntityRegion(City::class); + $stateRegionName = $this->getEntityRegion(State::class); + $attractionRegionName = $this->getEntityRegion(Attraction::class); $this->secondLevelCacheLogger->clearStats(); $this->evictRegions(); @@ -312,29 +313,29 @@ public function testMultipleNestedDQLAliases() $this->assertCount(2, $result1); $this->assertEquals($queryCount + 1, $this->getCurrentQueryCount()); - $this->assertTrue($this->cache->containsEntity(State::CLASSNAME, $this->states[0]->getId())); - $this->assertTrue($this->cache->containsEntity(State::CLASSNAME, $this->states[1]->getId())); + $this->assertTrue($this->cache->containsEntity(State::class, $this->states[0]->getId())); + $this->assertTrue($this->cache->containsEntity(State::class, $this->states[1]->getId())); - $this->assertTrue($this->cache->containsEntity(City::CLASSNAME, $this->cities[0]->getId())); - $this->assertTrue($this->cache->containsEntity(City::CLASSNAME, $this->cities[1]->getId())); - $this->assertTrue($this->cache->containsEntity(City::CLASSNAME, $this->cities[2]->getId())); - $this->assertTrue($this->cache->containsEntity(City::CLASSNAME, $this->cities[3]->getId())); + $this->assertTrue($this->cache->containsEntity(City::class, $this->cities[0]->getId())); + $this->assertTrue($this->cache->containsEntity(City::class, $this->cities[1]->getId())); + $this->assertTrue($this->cache->containsEntity(City::class, $this->cities[2]->getId())); + $this->assertTrue($this->cache->containsEntity(City::class, $this->cities[3]->getId())); - $this->assertTrue($this->cache->containsEntity(Attraction::CLASSNAME, $this->attractions[0]->getId())); - $this->assertTrue($this->cache->containsEntity(Attraction::CLASSNAME, $this->attractions[1]->getId())); - $this->assertTrue($this->cache->containsEntity(Attraction::CLASSNAME, $this->attractions[2]->getId())); - $this->assertTrue($this->cache->containsEntity(Attraction::CLASSNAME, $this->attractions[3]->getId())); + $this->assertTrue($this->cache->containsEntity(Attraction::class, $this->attractions[0]->getId())); + $this->assertTrue($this->cache->containsEntity(Attraction::class, $this->attractions[1]->getId())); + $this->assertTrue($this->cache->containsEntity(Attraction::class, $this->attractions[2]->getId())); + $this->assertTrue($this->cache->containsEntity(Attraction::class, $this->attractions[3]->getId())); - $this->assertInstanceOf(State::CLASSNAME, $result1[0]); - $this->assertInstanceOf(State::CLASSNAME, $result1[1]); + $this->assertInstanceOf(State::class, $result1[0]); + $this->assertInstanceOf(State::class, $result1[1]); $this->assertCount(2, $result1[0]->getCities()); $this->assertCount(2, $result1[1]->getCities()); - $this->assertInstanceOf(City::CLASSNAME, $result1[0]->getCities()->get(0)); - $this->assertInstanceOf(City::CLASSNAME, $result1[0]->getCities()->get(1)); - $this->assertInstanceOf(City::CLASSNAME, $result1[1]->getCities()->get(0)); - $this->assertInstanceOf(City::CLASSNAME, $result1[1]->getCities()->get(1)); + $this->assertInstanceOf(City::class, $result1[0]->getCities()->get(0)); + $this->assertInstanceOf(City::class, $result1[0]->getCities()->get(1)); + $this->assertInstanceOf(City::class, $result1[1]->getCities()->get(0)); + $this->assertInstanceOf(City::class, $result1[1]->getCities()->get(1)); $this->assertCount(2, $result1[0]->getCities()->get(0)->getAttractions()); $this->assertCount(2, $result1[0]->getCities()->get(1)->getAttractions()); @@ -350,16 +351,16 @@ public function testMultipleNestedDQLAliases() $this->assertCount(2, $result2); $this->assertEquals($queryCount + 1, $this->getCurrentQueryCount()); - $this->assertInstanceOf(State::CLASSNAME, $result2[0]); - $this->assertInstanceOf(State::CLASSNAME, $result2[1]); + $this->assertInstanceOf(State::class, $result2[0]); + $this->assertInstanceOf(State::class, $result2[1]); $this->assertCount(2, $result2[0]->getCities()); $this->assertCount(2, $result2[1]->getCities()); - $this->assertInstanceOf(City::CLASSNAME, $result2[0]->getCities()->get(0)); - $this->assertInstanceOf(City::CLASSNAME, $result2[0]->getCities()->get(1)); - $this->assertInstanceOf(City::CLASSNAME, $result2[1]->getCities()->get(0)); - $this->assertInstanceOf(City::CLASSNAME, $result2[1]->getCities()->get(1)); + $this->assertInstanceOf(City::class, $result2[0]->getCities()->get(0)); + $this->assertInstanceOf(City::class, $result2[0]->getCities()->get(1)); + $this->assertInstanceOf(City::class, $result2[1]->getCities()->get(0)); + $this->assertInstanceOf(City::class, $result2[1]->getCities()->get(1)); $this->assertCount(2, $result2[0]->getCities()->get(0)->getAttractions()); $this->assertCount(2, $result2[0]->getCities()->get(1)->getAttractions()); @@ -374,8 +375,8 @@ public function testBasicQueryParams() $this->loadFixturesCountries(); $this->_em->clear(); - $this->assertTrue($this->cache->containsEntity(Country::CLASSNAME, $this->countries[0]->getId())); - $this->assertTrue($this->cache->containsEntity(Country::CLASSNAME, $this->countries[1]->getId())); + $this->assertTrue($this->cache->containsEntity(Country::class, $this->countries[0]->getId())); + $this->assertTrue($this->cache->containsEntity(Country::class, $this->countries[1]->getId())); $queryCount = $this->getCurrentQueryCount(); $name = $this->countries[0]->getName(); @@ -398,7 +399,7 @@ public function testBasicQueryParams() $this->assertEquals($queryCount + 1, $this->getCurrentQueryCount()); $this->assertCount(1, $result2); - $this->assertInstanceOf('Doctrine\Tests\Models\Cache\Country', $result2[0]); + $this->assertInstanceOf(Country::class, $result2[0]); $this->assertEquals($result1[0]->getId(), $result2[0]->getId()); $this->assertEquals($result1[0]->getName(), $result2[0]->getName()); @@ -411,8 +412,8 @@ public function testLoadFromDatabaseWhenEntityMissing() $this->loadFixturesCountries(); $this->_em->clear(); - $this->assertTrue($this->cache->containsEntity(Country::CLASSNAME, $this->countries[0]->getId())); - $this->assertTrue($this->cache->containsEntity(Country::CLASSNAME, $this->countries[1]->getId())); + $this->assertTrue($this->cache->containsEntity(Country::class, $this->countries[0]->getId())); + $this->assertTrue($this->cache->containsEntity(Country::class, $this->countries[1]->getId())); $queryCount = $this->getCurrentQueryCount(); $dql = 'SELECT c FROM Doctrine\Tests\Models\Cache\Country c'; @@ -430,8 +431,8 @@ public function testLoadFromDatabaseWhenEntityMissing() $this->assertEquals(1, $this->secondLevelCacheLogger->getRegionPutCount($this->getDefaultQueryRegionName())); $this->assertEquals(1, $this->secondLevelCacheLogger->getRegionMissCount($this->getDefaultQueryRegionName())); - $this->cache->evictEntity(Country::CLASSNAME, $result1[0]->getId()); - $this->assertFalse($this->cache->containsEntity(Country::CLASSNAME, $result1[0]->getId())); + $this->cache->evictEntity(Country::class, $result1[0]->getId()); + $this->assertFalse($this->cache->containsEntity(Country::class, $result1[0]->getId())); $this->_em->clear(); @@ -447,8 +448,8 @@ public function testLoadFromDatabaseWhenEntityMissing() $this->assertEquals(2, $this->secondLevelCacheLogger->getRegionPutCount($this->getDefaultQueryRegionName())); $this->assertEquals(2, $this->secondLevelCacheLogger->getRegionMissCount($this->getDefaultQueryRegionName())); - $this->assertInstanceOf('Doctrine\Tests\Models\Cache\Country', $result2[0]); - $this->assertInstanceOf('Doctrine\Tests\Models\Cache\Country', $result2[1]); + $this->assertInstanceOf(Country::class, $result2[0]); + $this->assertInstanceOf(Country::class, $result2[1]); $this->assertEquals($result1[0]->getId(), $result2[0]->getId()); $this->assertEquals($result1[1]->getId(), $result2[1]->getId()); @@ -475,15 +476,15 @@ public function testBasicQueryFetchJoinsOneToMany() ->getResult(); $this->assertEquals($queryCount + 1, $this->getCurrentQueryCount()); - $this->assertInstanceOf(State::CLASSNAME, $result1[0]); - $this->assertInstanceOf(State::CLASSNAME, $result1[1]); + $this->assertInstanceOf(State::class, $result1[0]); + $this->assertInstanceOf(State::class, $result1[1]); $this->assertCount(2, $result1[0]->getCities()); $this->assertCount(2, $result1[1]->getCities()); - $this->assertInstanceOf(City::CLASSNAME, $result1[0]->getCities()->get(0)); - $this->assertInstanceOf(City::CLASSNAME, $result1[0]->getCities()->get(1)); - $this->assertInstanceOf(City::CLASSNAME, $result1[1]->getCities()->get(0)); - $this->assertInstanceOf(City::CLASSNAME, $result1[1]->getCities()->get(1)); + $this->assertInstanceOf(City::class, $result1[0]->getCities()->get(0)); + $this->assertInstanceOf(City::class, $result1[0]->getCities()->get(1)); + $this->assertInstanceOf(City::class, $result1[1]->getCities()->get(0)); + $this->assertInstanceOf(City::class, $result1[1]->getCities()->get(1)); $this->assertNotNull($result1[0]->getCities()->get(0)->getId()); $this->assertNotNull($result1[0]->getCities()->get(1)->getId()); @@ -501,15 +502,15 @@ public function testBasicQueryFetchJoinsOneToMany() ->setCacheable(true) ->getResult(); - $this->assertInstanceOf(State::CLASSNAME, $result2[0]); - $this->assertInstanceOf(State::CLASSNAME, $result2[1]); + $this->assertInstanceOf(State::class, $result2[0]); + $this->assertInstanceOf(State::class, $result2[1]); $this->assertCount(2, $result2[0]->getCities()); $this->assertCount(2, $result2[1]->getCities()); - $this->assertInstanceOf(City::CLASSNAME, $result2[0]->getCities()->get(0)); - $this->assertInstanceOf(City::CLASSNAME, $result2[0]->getCities()->get(1)); - $this->assertInstanceOf(City::CLASSNAME, $result2[1]->getCities()->get(0)); - $this->assertInstanceOf(City::CLASSNAME, $result2[1]->getCities()->get(1)); + $this->assertInstanceOf(City::class, $result2[0]->getCities()->get(0)); + $this->assertInstanceOf(City::class, $result2[0]->getCities()->get(1)); + $this->assertInstanceOf(City::class, $result2[1]->getCities()->get(0)); + $this->assertInstanceOf(City::class, $result2[1]->getCities()->get(1)); $this->assertNotNull($result2[0]->getCities()->get(0)->getId()); $this->assertNotNull($result2[0]->getCities()->get(1)->getId()); @@ -541,22 +542,22 @@ public function testBasicQueryFetchJoinsManyToOne() ->getResult(); $this->assertCount(4, $result1); - $this->assertInstanceOf(City::CLASSNAME, $result1[0]); - $this->assertInstanceOf(City::CLASSNAME, $result1[1]); - $this->assertInstanceOf(State::CLASSNAME, $result1[0]->getState()); - $this->assertInstanceOf(State::CLASSNAME, $result1[1]->getState()); + $this->assertInstanceOf(City::class, $result1[0]); + $this->assertInstanceOf(City::class, $result1[1]); + $this->assertInstanceOf(State::class, $result1[0]->getState()); + $this->assertInstanceOf(State::class, $result1[1]->getState()); - $this->assertTrue($this->cache->containsEntity(City::CLASSNAME, $result1[0]->getId())); - $this->assertTrue($this->cache->containsEntity(City::CLASSNAME, $result1[1]->getId())); - $this->assertTrue($this->cache->containsEntity(State::CLASSNAME, $result1[0]->getState()->getId())); - $this->assertTrue($this->cache->containsEntity(State::CLASSNAME, $result1[1]->getState()->getId())); + $this->assertTrue($this->cache->containsEntity(City::class, $result1[0]->getId())); + $this->assertTrue($this->cache->containsEntity(City::class, $result1[1]->getId())); + $this->assertTrue($this->cache->containsEntity(State::class, $result1[0]->getState()->getId())); + $this->assertTrue($this->cache->containsEntity(State::class, $result1[1]->getState()->getId())); $this->assertEquals(7, $this->secondLevelCacheLogger->getPutCount()); $this->assertEquals(1, $this->secondLevelCacheLogger->getMissCount()); $this->assertEquals(1, $this->secondLevelCacheLogger->getRegionPutCount($this->getDefaultQueryRegionName())); $this->assertEquals(1, $this->secondLevelCacheLogger->getRegionMissCount($this->getDefaultQueryRegionName())); - $this->assertEquals(2, $this->secondLevelCacheLogger->getRegionPutCount($this->getEntityRegion(State::CLASSNAME))); - $this->assertEquals(4, $this->secondLevelCacheLogger->getRegionPutCount($this->getEntityRegion(City::CLASSNAME))); + $this->assertEquals(2, $this->secondLevelCacheLogger->getRegionPutCount($this->getEntityRegion(State::class))); + $this->assertEquals(4, $this->secondLevelCacheLogger->getRegionPutCount($this->getEntityRegion(City::class))); $this->assertEquals($queryCount + 1, $this->getCurrentQueryCount()); @@ -568,10 +569,10 @@ public function testBasicQueryFetchJoinsManyToOne() ->getResult(); $this->assertCount(4, $result1); - $this->assertInstanceOf(City::CLASSNAME, $result2[0]); - $this->assertInstanceOf(City::CLASSNAME, $result2[1]); - $this->assertInstanceOf(State::CLASSNAME, $result2[0]->getState()); - $this->assertInstanceOf(State::CLASSNAME, $result2[1]->getState()); + $this->assertInstanceOf(City::class, $result2[0]); + $this->assertInstanceOf(City::class, $result2[1]); + $this->assertInstanceOf(State::class, $result2[0]->getState()); + $this->assertInstanceOf(State::class, $result2[1]->getState()); $this->assertNotNull($result2[0]->getId()); $this->assertNotNull($result2[0]->getId()); @@ -608,30 +609,30 @@ public function testReloadQueryIfToOneIsNotFound() ->getResult(); $this->assertCount(4, $result1); - $this->assertInstanceOf(City::CLASSNAME, $result1[0]); - $this->assertInstanceOf(City::CLASSNAME, $result1[1]); - $this->assertInstanceOf(State::CLASSNAME, $result1[0]->getState()); - $this->assertInstanceOf(State::CLASSNAME, $result1[1]->getState()); - - $this->assertTrue($this->cache->containsEntity(City::CLASSNAME, $result1[0]->getId())); - $this->assertTrue($this->cache->containsEntity(City::CLASSNAME, $result1[1]->getId())); - $this->assertTrue($this->cache->containsEntity(State::CLASSNAME, $result1[0]->getState()->getId())); - $this->assertTrue($this->cache->containsEntity(State::CLASSNAME, $result1[1]->getState()->getId())); + $this->assertInstanceOf(City::class, $result1[0]); + $this->assertInstanceOf(City::class, $result1[1]); + $this->assertInstanceOf(State::class, $result1[0]->getState()); + $this->assertInstanceOf(State::class, $result1[1]->getState()); + + $this->assertTrue($this->cache->containsEntity(City::class, $result1[0]->getId())); + $this->assertTrue($this->cache->containsEntity(City::class, $result1[1]->getId())); + $this->assertTrue($this->cache->containsEntity(State::class, $result1[0]->getState()->getId())); + $this->assertTrue($this->cache->containsEntity(State::class, $result1[1]->getState()->getId())); $this->assertEquals($queryCount + 1, $this->getCurrentQueryCount()); $this->_em->clear(); - $this->cache->evictEntityRegion(State::CLASSNAME); + $this->cache->evictEntityRegion(State::class); $result2 = $this->_em->createQuery($dql) ->setCacheable(true) ->getResult(); $this->assertCount(4, $result1); - $this->assertInstanceOf(City::CLASSNAME, $result2[0]); - $this->assertInstanceOf(City::CLASSNAME, $result2[1]); - $this->assertInstanceOf(State::CLASSNAME, $result2[0]->getState()); - $this->assertInstanceOf(State::CLASSNAME, $result2[1]->getState()); + $this->assertInstanceOf(City::class, $result2[0]); + $this->assertInstanceOf(City::class, $result2[1]); + $this->assertInstanceOf(State::class, $result2[0]->getState()); + $this->assertInstanceOf(State::class, $result2[1]->getState()); $this->assertEquals($queryCount + 2, $this->getCurrentQueryCount()); } @@ -652,33 +653,33 @@ public function testReloadQueryIfToManyAssociationItemIsNotFound() ->getResult(); $this->assertEquals($queryCount + 1, $this->getCurrentQueryCount()); - $this->assertInstanceOf(State::CLASSNAME, $result1[0]); - $this->assertInstanceOf(State::CLASSNAME, $result1[1]); + $this->assertInstanceOf(State::class, $result1[0]); + $this->assertInstanceOf(State::class, $result1[1]); $this->assertCount(2, $result1[0]->getCities()); $this->assertCount(2, $result1[1]->getCities()); - $this->assertInstanceOf(City::CLASSNAME, $result1[0]->getCities()->get(0)); - $this->assertInstanceOf(City::CLASSNAME, $result1[0]->getCities()->get(1)); - $this->assertInstanceOf(City::CLASSNAME, $result1[1]->getCities()->get(0)); - $this->assertInstanceOf(City::CLASSNAME, $result1[1]->getCities()->get(1)); + $this->assertInstanceOf(City::class, $result1[0]->getCities()->get(0)); + $this->assertInstanceOf(City::class, $result1[0]->getCities()->get(1)); + $this->assertInstanceOf(City::class, $result1[1]->getCities()->get(0)); + $this->assertInstanceOf(City::class, $result1[1]->getCities()->get(1)); $this->_em->clear(); - $this->cache->evictEntityRegion(City::CLASSNAME); + $this->cache->evictEntityRegion(City::class); $result2 = $this->_em->createQuery($dql) ->setCacheable(true) ->getResult(); - $this->assertInstanceOf(State::CLASSNAME, $result2[0]); - $this->assertInstanceOf(State::CLASSNAME, $result2[1]); + $this->assertInstanceOf(State::class, $result2[0]); + $this->assertInstanceOf(State::class, $result2[1]); $this->assertCount(2, $result2[0]->getCities()); $this->assertCount(2, $result2[1]->getCities()); - $this->assertInstanceOf(City::CLASSNAME, $result2[0]->getCities()->get(0)); - $this->assertInstanceOf(City::CLASSNAME, $result2[0]->getCities()->get(1)); - $this->assertInstanceOf(City::CLASSNAME, $result2[1]->getCities()->get(0)); - $this->assertInstanceOf(City::CLASSNAME, $result2[1]->getCities()->get(1)); + $this->assertInstanceOf(City::class, $result2[0]->getCities()->get(0)); + $this->assertInstanceOf(City::class, $result2[0]->getCities()->get(1)); + $this->assertInstanceOf(City::class, $result2[1]->getCities()->get(0)); + $this->assertInstanceOf(City::class, $result2[1]->getCities()->get(1)); $this->assertEquals($queryCount + 2, $this->getCurrentQueryCount()); } @@ -691,11 +692,11 @@ public function testBasicNativeQueryCache() $this->secondLevelCacheLogger->clearStats(); $this->_em->clear(); - $this->assertTrue($this->cache->containsEntity(Country::CLASSNAME, $this->countries[0]->getId())); - $this->assertTrue($this->cache->containsEntity(Country::CLASSNAME, $this->countries[1]->getId())); + $this->assertTrue($this->cache->containsEntity(Country::class, $this->countries[0]->getId())); + $this->assertTrue($this->cache->containsEntity(Country::class, $this->countries[1]->getId())); $rsm = new ResultSetMapping; - $rsm->addEntityResult(Country::CLASSNAME, 'c'); + $rsm->addEntityResult(Country::class, 'c'); $rsm->addFieldResult('c', 'name', 'name'); $rsm->addFieldResult('c', 'id', 'id'); @@ -732,8 +733,8 @@ public function testBasicNativeQueryCache() $this->assertEquals(1, $this->secondLevelCacheLogger->getRegionHitCount($this->getDefaultQueryRegionName())); $this->assertEquals(1, $this->secondLevelCacheLogger->getRegionMissCount($this->getDefaultQueryRegionName())); - $this->assertInstanceOf('Doctrine\Tests\Models\Cache\Country', $result2[0]); - $this->assertInstanceOf('Doctrine\Tests\Models\Cache\Country', $result2[1]); + $this->assertInstanceOf(Country::class, $result2[0]); + $this->assertInstanceOf(Country::class, $result2[1]); $this->assertEquals($result1[0]->getId(), $result2[0]->getId()); $this->assertEquals($result1[1]->getId(), $result2[1]->getId()); @@ -827,7 +828,7 @@ public function testQueryCacheLifetime() ->getRegion() ->get($key); - $this->assertInstanceOf('Doctrine\ORM\Cache\QueryCacheEntry', $entry); + $this->assertInstanceOf(Cache\QueryCacheEntry::class, $entry); $entry->time = $entry->time / 2; $this->cache->getQueryCache() @@ -936,8 +937,8 @@ public function testResolveAssociationCacheEntry() $this->assertNotNull($state1); $this->assertNotNull($state1->getCountry()); $this->assertEquals($queryCount + 1, $this->getCurrentQueryCount()); - $this->assertInstanceOf('Doctrine\Tests\Models\Cache\State', $state1); - $this->assertInstanceOf('Doctrine\ORM\Proxy\Proxy', $state1->getCountry()); + $this->assertInstanceOf(State::class, $state1); + $this->assertInstanceOf(Proxy::class, $state1->getCountry()); $this->assertEquals($countryName, $state1->getCountry()->getName()); $this->assertEquals($stateId, $state1->getId()); @@ -954,8 +955,8 @@ public function testResolveAssociationCacheEntry() $this->assertNotNull($state2); $this->assertNotNull($state2->getCountry()); $this->assertEquals($queryCount, $this->getCurrentQueryCount()); - $this->assertInstanceOf('Doctrine\Tests\Models\Cache\State', $state2); - $this->assertInstanceOf('Doctrine\ORM\Proxy\Proxy', $state2->getCountry()); + $this->assertInstanceOf(State::class, $state2); + $this->assertInstanceOf(Proxy::class, $state2->getCountry()); $this->assertEquals($countryName, $state2->getCountry()->getName()); $this->assertEquals($stateId, $state2->getId()); } @@ -983,10 +984,10 @@ public function testResolveToOneAssociationCacheEntry() ->getSingleResult(); $this->assertEquals($queryCount + 1, $this->getCurrentQueryCount()); - $this->assertInstanceOf('Doctrine\Tests\Models\Cache\City', $city1); - $this->assertInstanceOf('Doctrine\Tests\Models\Cache\State', $city1->getState()); - $this->assertInstanceOf('Doctrine\Tests\Models\Cache\City', $city1->getState()->getCities()->get(0)); - $this->assertInstanceOf('Doctrine\Tests\Models\Cache\State', $city1->getState()->getCities()->get(0)->getState()); + $this->assertInstanceOf(City::class, $city1); + $this->assertInstanceOf(State::class, $city1->getState()); + $this->assertInstanceOf(City::class, $city1->getState()->getCities()->get(0)); + $this->assertInstanceOf(State::class, $city1->getState()->getCities()->get(0)->getState()); $this->_em->clear(); @@ -999,10 +1000,10 @@ public function testResolveToOneAssociationCacheEntry() ->getSingleResult(); $this->assertEquals($queryCount, $this->getCurrentQueryCount()); - $this->assertInstanceOf('Doctrine\Tests\Models\Cache\City', $city2); - $this->assertInstanceOf('Doctrine\Tests\Models\Cache\State', $city2->getState()); - $this->assertInstanceOf('Doctrine\Tests\Models\Cache\City', $city2->getState()->getCities()->get(0)); - $this->assertInstanceOf('Doctrine\Tests\Models\Cache\State', $city2->getState()->getCities()->get(0)->getState()); + $this->assertInstanceOf(City::class, $city2); + $this->assertInstanceOf(State::class, $city2->getState()); + $this->assertInstanceOf(City::class, $city2->getState()->getCities()->get(0)); + $this->assertInstanceOf(State::class, $city2->getState()->getCities()->get(0)->getState()); } public function testResolveToManyAssociationCacheEntry() @@ -1028,10 +1029,10 @@ public function testResolveToManyAssociationCacheEntry() ->getSingleResult(); $this->assertEquals($queryCount + 1, $this->getCurrentQueryCount()); - $this->assertInstanceOf('Doctrine\Tests\Models\Cache\State', $state1); - $this->assertInstanceOf('Doctrine\ORM\Proxy\Proxy', $state1->getCountry()); - $this->assertInstanceOf('Doctrine\Tests\Models\Cache\City', $state1->getCities()->get(0)); - $this->assertInstanceOf('Doctrine\Tests\Models\Cache\State', $state1->getCities()->get(0)->getState()); + $this->assertInstanceOf(State::class, $state1); + $this->assertInstanceOf(Proxy::class, $state1->getCountry()); + $this->assertInstanceOf(City::class, $state1->getCities()->get(0)); + $this->assertInstanceOf(State::class, $state1->getCities()->get(0)->getState()); $this->assertSame($state1, $state1->getCities()->get(0)->getState()); $this->_em->clear(); @@ -1045,10 +1046,10 @@ public function testResolveToManyAssociationCacheEntry() ->getSingleResult(); $this->assertEquals($queryCount, $this->getCurrentQueryCount()); - $this->assertInstanceOf('Doctrine\Tests\Models\Cache\State', $state2); - $this->assertInstanceOf('Doctrine\ORM\Proxy\Proxy', $state2->getCountry()); - $this->assertInstanceOf('Doctrine\Tests\Models\Cache\City', $state2->getCities()->get(0)); - $this->assertInstanceOf('Doctrine\Tests\Models\Cache\State', $state2->getCities()->get(0)->getState()); + $this->assertInstanceOf(State::class, $state2); + $this->assertInstanceOf(Proxy::class, $state2->getCountry()); + $this->assertInstanceOf(City::class, $state2->getCities()->get(0)); + $this->assertInstanceOf(State::class, $state2->getCities()->get(0)->getState()); $this->assertSame($state2, $state2->getCities()->get(0)->getState()); } @@ -1057,15 +1058,15 @@ public function testHintClearEntityRegionUpdateStatement() $this->evictRegions(); $this->loadFixturesCountries(); - $this->assertTrue($this->cache->containsEntity('Doctrine\Tests\Models\Cache\Country', $this->countries[0]->getId())); - $this->assertTrue($this->cache->containsEntity('Doctrine\Tests\Models\Cache\Country', $this->countries[1]->getId())); + $this->assertTrue($this->cache->containsEntity(Country::class, $this->countries[0]->getId())); + $this->assertTrue($this->cache->containsEntity(Country::class, $this->countries[1]->getId())); $this->_em->createQuery('DELETE Doctrine\Tests\Models\Cache\Country u WHERE u.id = 4') ->setHint(Query::HINT_CACHE_EVICT, true) ->execute(); - $this->assertFalse($this->cache->containsEntity('Doctrine\Tests\Models\Cache\Country', $this->countries[0]->getId())); - $this->assertFalse($this->cache->containsEntity('Doctrine\Tests\Models\Cache\Country', $this->countries[1]->getId())); + $this->assertFalse($this->cache->containsEntity(Country::class, $this->countries[0]->getId())); + $this->assertFalse($this->cache->containsEntity(Country::class, $this->countries[1]->getId())); } public function testHintClearEntityRegionDeleteStatement() @@ -1073,15 +1074,15 @@ public function testHintClearEntityRegionDeleteStatement() $this->evictRegions(); $this->loadFixturesCountries(); - $this->assertTrue($this->cache->containsEntity('Doctrine\Tests\Models\Cache\Country', $this->countries[0]->getId())); - $this->assertTrue($this->cache->containsEntity('Doctrine\Tests\Models\Cache\Country', $this->countries[1]->getId())); + $this->assertTrue($this->cache->containsEntity(Country::class, $this->countries[0]->getId())); + $this->assertTrue($this->cache->containsEntity(Country::class, $this->countries[1]->getId())); $this->_em->createQuery("UPDATE Doctrine\Tests\Models\Cache\Country u SET u.name = 'foo' WHERE u.id = 1") ->setHint(Query::HINT_CACHE_EVICT, true) ->execute(); - $this->assertFalse($this->cache->containsEntity('Doctrine\Tests\Models\Cache\Country', $this->countries[0]->getId())); - $this->assertFalse($this->cache->containsEntity('Doctrine\Tests\Models\Cache\Country', $this->countries[1]->getId())); + $this->assertFalse($this->cache->containsEntity(Country::class, $this->countries[0]->getId())); + $this->assertFalse($this->cache->containsEntity(Country::class, $this->countries[1]->getId())); } /** @@ -1120,4 +1121,37 @@ public function testNonCacheableQueryUpdateStatementException() ->setCacheable(true) ->getResult(); } -} \ No newline at end of file + + public function testQueryCacheShouldBeEvictedOnTimestampUpdate() + { + $this->loadFixturesCountries(); + $this->_em->clear(); + + $queryCount = $this->getCurrentQueryCount(); + $dql = 'SELECT country FROM Doctrine\Tests\Models\Cache\Country country'; + + $result1 = $this->_em->createQuery($dql) + ->setCacheable(true) + ->getResult(); + + $this->assertCount(2, $result1); + $this->assertEquals($queryCount + 1, $this->getCurrentQueryCount()); + + $this->_em->persist(new Country('France')); + $this->_em->flush(); + $this->_em->clear(); + + $queryCount = $this->getCurrentQueryCount(); + + $result2 = $this->_em->createQuery($dql) + ->setCacheable(true) + ->getResult(); + + $this->assertCount(3, $result2); + $this->assertEquals($queryCount + 1, $this->getCurrentQueryCount()); + + foreach ($result2 as $entity) { + $this->assertInstanceOf(Country::class, $entity); + } + } +} diff --git a/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheRepositoryTest.php b/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheRepositoryTest.php index 71f7d952f4f..c8c4303c4da 100644 --- a/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheRepositoryTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheRepositoryTest.php @@ -2,6 +2,7 @@ namespace Doctrine\Tests\ORM\Functional; +use Doctrine\ORM\Proxy\Proxy; use Doctrine\Tests\Models\Cache\Country; use Doctrine\Tests\Models\Cache\State; @@ -18,22 +19,22 @@ public function testRepositoryCacheFind() $this->secondLevelCacheLogger->clearStats(); $this->_em->clear(); - $this->assertTrue($this->cache->containsEntity(Country::CLASSNAME, $this->countries[0]->getId())); - $this->assertTrue($this->cache->containsEntity(Country::CLASSNAME, $this->countries[1]->getId())); + $this->assertTrue($this->cache->containsEntity(Country::class, $this->countries[0]->getId())); + $this->assertTrue($this->cache->containsEntity(Country::class, $this->countries[1]->getId())); $queryCount = $this->getCurrentQueryCount(); - $repository = $this->_em->getRepository(Country::CLASSNAME); + $repository = $this->_em->getRepository(Country::class); $country1 = $repository->find($this->countries[0]->getId()); $country2 = $repository->find($this->countries[1]->getId()); $this->assertEquals($queryCount, $this->getCurrentQueryCount()); - $this->assertInstanceOf(Country::CLASSNAME, $country1); - $this->assertInstanceOf(Country::CLASSNAME, $country2); + $this->assertInstanceOf(Country::class, $country1); + $this->assertInstanceOf(Country::class, $country2); $this->assertEquals(2, $this->secondLevelCacheLogger->getHitCount()); $this->assertEquals(0, $this->secondLevelCacheLogger->getMissCount()); - $this->assertEquals(2, $this->secondLevelCacheLogger->getRegionHitCount($this->getEntityRegion(Country::CLASSNAME))); + $this->assertEquals(2, $this->secondLevelCacheLogger->getRegionHitCount($this->getEntityRegion(Country::class))); } @@ -44,10 +45,10 @@ public function testRepositoryCacheFindAll() $this->secondLevelCacheLogger->clearStats(); $this->_em->clear(); - $this->assertFalse($this->cache->containsEntity(Country::CLASSNAME, $this->countries[0]->getId())); - $this->assertFalse($this->cache->containsEntity(Country::CLASSNAME, $this->countries[1]->getId())); + $this->assertFalse($this->cache->containsEntity(Country::class, $this->countries[0]->getId())); + $this->assertFalse($this->cache->containsEntity(Country::class, $this->countries[1]->getId())); - $repository = $this->_em->getRepository(Country::CLASSNAME); + $repository = $this->_em->getRepository(Country::class); $queryCount = $this->getCurrentQueryCount(); $this->assertCount(2, $repository->findAll()); @@ -58,14 +59,14 @@ public function testRepositoryCacheFindAll() $this->assertEquals($queryCount, $this->getCurrentQueryCount()); - $this->assertInstanceOf(Country::CLASSNAME, $countries[0]); - $this->assertInstanceOf(Country::CLASSNAME, $countries[1]); + $this->assertInstanceOf(Country::class, $countries[0]); + $this->assertInstanceOf(Country::class, $countries[1]); $this->assertEquals(3, $this->secondLevelCacheLogger->getHitCount()); $this->assertEquals(1, $this->secondLevelCacheLogger->getMissCount()); - $this->assertTrue($this->cache->containsEntity(Country::CLASSNAME, $this->countries[0]->getId())); - $this->assertTrue($this->cache->containsEntity(Country::CLASSNAME, $this->countries[1]->getId())); + $this->assertTrue($this->cache->containsEntity(Country::class, $this->countries[0]->getId())); + $this->assertTrue($this->cache->containsEntity(Country::class, $this->countries[1]->getId())); } public function testRepositoryCacheFindAllInvalidation() @@ -75,10 +76,10 @@ public function testRepositoryCacheFindAllInvalidation() $this->secondLevelCacheLogger->clearStats(); $this->_em->clear(); - $this->assertFalse($this->cache->containsEntity(Country::CLASSNAME, $this->countries[0]->getId())); - $this->assertFalse($this->cache->containsEntity(Country::CLASSNAME, $this->countries[1]->getId())); + $this->assertFalse($this->cache->containsEntity(Country::class, $this->countries[0]->getId())); + $this->assertFalse($this->cache->containsEntity(Country::class, $this->countries[1]->getId())); - $repository = $this->_em->getRepository(Country::CLASSNAME); + $repository = $this->_em->getRepository(Country::class); $queryCount = $this->getCurrentQueryCount(); $this->assertCount(2, $repository->findAll()); @@ -90,9 +91,9 @@ public function testRepositoryCacheFindAllInvalidation() $this->assertEquals($queryCount, $this->getCurrentQueryCount()); $this->assertCount(2, $countries); - $this->assertInstanceOf(Country::CLASSNAME, $countries[0]); - $this->assertInstanceOf(Country::CLASSNAME, $countries[1]); - + $this->assertInstanceOf(Country::class, $countries[0]); + $this->assertInstanceOf(Country::class, $countries[1]); + $country = new Country('foo'); $this->_em->persist($country); @@ -105,7 +106,7 @@ public function testRepositoryCacheFindAllInvalidation() $this->assertEquals($queryCount + 1, $this->getCurrentQueryCount()); $country = $repository->find($country->getId()); - + $this->_em->remove($country); $this->_em->flush(); $this->_em->clear(); @@ -123,10 +124,10 @@ public function testRepositoryCacheFindBy() $this->secondLevelCacheLogger->clearStats(); $this->_em->clear(); - $this->assertFalse($this->cache->containsEntity(Country::CLASSNAME, $this->countries[0]->getId())); + $this->assertFalse($this->cache->containsEntity(Country::class, $this->countries[0]->getId())); - $criteria = array('name'=>$this->countries[0]->getName()); - $repository = $this->_em->getRepository(Country::CLASSNAME); + $criteria = ['name'=>$this->countries[0]->getName()]; + $repository = $this->_em->getRepository(Country::class); $queryCount = $this->getCurrentQueryCount(); $this->assertCount(1, $repository->findBy($criteria)); @@ -138,12 +139,12 @@ public function testRepositoryCacheFindBy() $this->assertEquals($queryCount, $this->getCurrentQueryCount()); $this->assertCount(1, $countries); - $this->assertInstanceOf(Country::CLASSNAME, $countries[0]); + $this->assertInstanceOf(Country::class, $countries[0]); $this->assertEquals(2, $this->secondLevelCacheLogger->getHitCount()); $this->assertEquals(1, $this->secondLevelCacheLogger->getMissCount()); - $this->assertTrue($this->cache->containsEntity(Country::CLASSNAME, $this->countries[0]->getId())); + $this->assertTrue($this->cache->containsEntity(Country::class, $this->countries[0]->getId())); } public function testRepositoryCacheFindOneBy() @@ -153,10 +154,10 @@ public function testRepositoryCacheFindOneBy() $this->secondLevelCacheLogger->clearStats(); $this->_em->clear(); - $this->assertFalse($this->cache->containsEntity(Country::CLASSNAME, $this->countries[0]->getId())); + $this->assertFalse($this->cache->containsEntity(Country::class, $this->countries[0]->getId())); - $criteria = array('name'=>$this->countries[0]->getName()); - $repository = $this->_em->getRepository(Country::CLASSNAME); + $criteria = ['name'=>$this->countries[0]->getName()]; + $repository = $this->_em->getRepository(Country::class); $queryCount = $this->getCurrentQueryCount(); $this->assertNotNull($repository->findOneBy($criteria)); @@ -167,12 +168,12 @@ public function testRepositoryCacheFindOneBy() $this->assertEquals($queryCount, $this->getCurrentQueryCount()); - $this->assertInstanceOf(Country::CLASSNAME, $country); + $this->assertInstanceOf(Country::class, $country); $this->assertEquals(2, $this->secondLevelCacheLogger->getHitCount()); $this->assertEquals(1, $this->secondLevelCacheLogger->getMissCount()); - $this->assertTrue($this->cache->containsEntity(Country::CLASSNAME, $this->countries[0]->getId())); + $this->assertTrue($this->cache->containsEntity(Country::class, $this->countries[0]->getId())); } public function testRepositoryCacheFindAllToOneAssociation() @@ -186,19 +187,19 @@ public function testRepositoryCacheFindAllToOneAssociation() $this->_em->clear(); // load from database - $repository = $this->_em->getRepository(State::CLASSNAME); + $repository = $this->_em->getRepository(State::class); $queryCount = $this->getCurrentQueryCount(); $entities = $repository->findAll(); $this->assertCount(4, $entities); $this->assertEquals($queryCount + 1, $this->getCurrentQueryCount()); - $this->assertInstanceOf(State::CLASSNAME, $entities[0]); - $this->assertInstanceOf(State::CLASSNAME, $entities[1]); - $this->assertInstanceOf(Country::CLASSNAME, $entities[0]->getCountry()); - $this->assertInstanceOf(Country::CLASSNAME, $entities[0]->getCountry()); - $this->assertInstanceOf('Doctrine\ORM\Proxy\Proxy', $entities[0]->getCountry()); - $this->assertInstanceOf('Doctrine\ORM\Proxy\Proxy', $entities[1]->getCountry()); + $this->assertInstanceOf(State::class, $entities[0]); + $this->assertInstanceOf(State::class, $entities[1]); + $this->assertInstanceOf(Country::class, $entities[0]->getCountry()); + $this->assertInstanceOf(Country::class, $entities[0]->getCountry()); + $this->assertInstanceOf(Proxy::class, $entities[0]->getCountry()); + $this->assertInstanceOf(Proxy::class, $entities[1]->getCountry()); // load from cache $queryCount = $this->getCurrentQueryCount(); @@ -207,15 +208,15 @@ public function testRepositoryCacheFindAllToOneAssociation() $this->assertCount(4, $entities); $this->assertEquals($queryCount, $this->getCurrentQueryCount()); - $this->assertInstanceOf(State::CLASSNAME, $entities[0]); - $this->assertInstanceOf(State::CLASSNAME, $entities[1]); - $this->assertInstanceOf(Country::CLASSNAME, $entities[0]->getCountry()); - $this->assertInstanceOf(Country::CLASSNAME, $entities[1]->getCountry()); - $this->assertInstanceOf('Doctrine\ORM\Proxy\Proxy', $entities[0]->getCountry()); - $this->assertInstanceOf('Doctrine\ORM\Proxy\Proxy', $entities[1]->getCountry()); + $this->assertInstanceOf(State::class, $entities[0]); + $this->assertInstanceOf(State::class, $entities[1]); + $this->assertInstanceOf(Country::class, $entities[0]->getCountry()); + $this->assertInstanceOf(Country::class, $entities[1]->getCountry()); + $this->assertInstanceOf(Proxy::class, $entities[0]->getCountry()); + $this->assertInstanceOf(Proxy::class, $entities[1]->getCountry()); // invalidate cache - $this->_em->persist(new State('foo', $this->_em->find(Country::CLASSNAME, $this->countries[0]->getId()))); + $this->_em->persist(new State('foo', $this->_em->find(Country::class, $this->countries[0]->getId()))); $this->_em->flush(); $this->_em->clear(); @@ -226,12 +227,12 @@ public function testRepositoryCacheFindAllToOneAssociation() $this->assertCount(5, $entities); $this->assertEquals($queryCount + 1, $this->getCurrentQueryCount()); - $this->assertInstanceOf(State::CLASSNAME, $entities[0]); - $this->assertInstanceOf(State::CLASSNAME, $entities[1]); - $this->assertInstanceOf(Country::CLASSNAME, $entities[0]->getCountry()); - $this->assertInstanceOf(Country::CLASSNAME, $entities[1]->getCountry()); - $this->assertInstanceOf('Doctrine\ORM\Proxy\Proxy', $entities[0]->getCountry()); - $this->assertInstanceOf('Doctrine\ORM\Proxy\Proxy', $entities[1]->getCountry()); + $this->assertInstanceOf(State::class, $entities[0]); + $this->assertInstanceOf(State::class, $entities[1]); + $this->assertInstanceOf(Country::class, $entities[0]->getCountry()); + $this->assertInstanceOf(Country::class, $entities[1]->getCountry()); + $this->assertInstanceOf(Proxy::class, $entities[0]->getCountry()); + $this->assertInstanceOf(Proxy::class, $entities[1]->getCountry()); // load from cache $queryCount = $this->getCurrentQueryCount(); @@ -240,11 +241,11 @@ public function testRepositoryCacheFindAllToOneAssociation() $this->assertCount(5, $entities); $this->assertEquals($queryCount, $this->getCurrentQueryCount()); - $this->assertInstanceOf(State::CLASSNAME, $entities[0]); - $this->assertInstanceOf(State::CLASSNAME, $entities[1]); - $this->assertInstanceOf(Country::CLASSNAME, $entities[0]->getCountry()); - $this->assertInstanceOf(Country::CLASSNAME, $entities[1]->getCountry()); - $this->assertInstanceOf('Doctrine\ORM\Proxy\Proxy', $entities[0]->getCountry()); - $this->assertInstanceOf('Doctrine\ORM\Proxy\Proxy', $entities[1]->getCountry()); + $this->assertInstanceOf(State::class, $entities[0]); + $this->assertInstanceOf(State::class, $entities[1]); + $this->assertInstanceOf(Country::class, $entities[0]->getCountry()); + $this->assertInstanceOf(Country::class, $entities[1]->getCountry()); + $this->assertInstanceOf(Proxy::class, $entities[0]->getCountry()); + $this->assertInstanceOf(Proxy::class, $entities[1]->getCountry()); } -} \ No newline at end of file +} diff --git a/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheSingleTableInheritanceTest.php b/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheSingleTableInheritanceTest.php index 3f8487d9946..858adb3a19c 100644 --- a/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheSingleTableInheritanceTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheSingleTableInheritanceTest.php @@ -2,11 +2,12 @@ namespace Doctrine\Tests\ORM\Functional; +use Doctrine\ORM\PersistentCollection; use Doctrine\Tests\Models\Cache\Attraction; -use Doctrine\Tests\Models\Cache\Restaurant; +use Doctrine\Tests\Models\Cache\Bar; use Doctrine\Tests\Models\Cache\Beach; use Doctrine\Tests\Models\Cache\City; -use Doctrine\Tests\Models\Cache\Bar; +use Doctrine\Tests\Models\Cache\Restaurant; /** * @group DDC-2183 @@ -15,10 +16,10 @@ class SecondLevelCacheSingleTableInheritanceTest extends SecondLevelCacheAbstrac { public function testUseSameRegion() { - $attractionRegion = $this->cache->getEntityCacheRegion(Attraction::CLASSNAME); - $restaurantRegion = $this->cache->getEntityCacheRegion(Restaurant::CLASSNAME); - $beachRegion = $this->cache->getEntityCacheRegion(Beach::CLASSNAME); - $barRegion = $this->cache->getEntityCacheRegion(Bar::CLASSNAME); + $attractionRegion = $this->cache->getEntityCacheRegion(Attraction::class); + $restaurantRegion = $this->cache->getEntityCacheRegion(Restaurant::class); + $beachRegion = $this->cache->getEntityCacheRegion(Beach::class); + $barRegion = $this->cache->getEntityCacheRegion(Bar::class); $this->assertEquals($attractionRegion->getName(), $restaurantRegion->getName()); $this->assertEquals($attractionRegion->getName(), $beachRegion->getName()); @@ -34,8 +35,8 @@ public function testPutOnPersistSingleTableInheritance() $this->_em->clear(); - $this->assertTrue($this->cache->containsEntity(Bar::CLASSNAME, $this->attractions[0]->getId())); - $this->assertTrue($this->cache->containsEntity(Bar::CLASSNAME, $this->attractions[1]->getId())); + $this->assertTrue($this->cache->containsEntity(Bar::class, $this->attractions[0]->getId())); + $this->assertTrue($this->cache->containsEntity(Bar::class, $this->attractions[1]->getId())); } public function testCountaisRootClass() @@ -48,7 +49,7 @@ public function testCountaisRootClass() $this->_em->clear(); foreach ($this->attractions as $attraction) { - $this->assertTrue($this->cache->containsEntity(Attraction::CLASSNAME, $attraction->getId())); + $this->assertTrue($this->cache->containsEntity(Attraction::class, $attraction->getId())); $this->assertTrue($this->cache->containsEntity(get_class($attraction), $attraction->getId())); } } @@ -62,28 +63,28 @@ public function testPutAndLoadEntities() $this->_em->clear(); - $this->cache->evictEntityRegion(Attraction::CLASSNAME); + $this->cache->evictEntityRegion(Attraction::class); $entityId1 = $this->attractions[0]->getId(); $entityId2 = $this->attractions[1]->getId(); - $this->assertFalse($this->cache->containsEntity(Attraction::CLASSNAME, $entityId1)); - $this->assertFalse($this->cache->containsEntity(Attraction::CLASSNAME, $entityId2)); - $this->assertFalse($this->cache->containsEntity(Bar::CLASSNAME, $entityId1)); - $this->assertFalse($this->cache->containsEntity(Bar::CLASSNAME, $entityId2)); + $this->assertFalse($this->cache->containsEntity(Attraction::class, $entityId1)); + $this->assertFalse($this->cache->containsEntity(Attraction::class, $entityId2)); + $this->assertFalse($this->cache->containsEntity(Bar::class, $entityId1)); + $this->assertFalse($this->cache->containsEntity(Bar::class, $entityId2)); - $entity1 = $this->_em->find(Attraction::CLASSNAME, $entityId1); - $entity2 = $this->_em->find(Attraction::CLASSNAME, $entityId2); + $entity1 = $this->_em->find(Attraction::class, $entityId1); + $entity2 = $this->_em->find(Attraction::class, $entityId2); - $this->assertTrue($this->cache->containsEntity(Attraction::CLASSNAME, $entityId1)); - $this->assertTrue($this->cache->containsEntity(Attraction::CLASSNAME, $entityId2)); - $this->assertTrue($this->cache->containsEntity(Bar::CLASSNAME, $entityId1)); - $this->assertTrue($this->cache->containsEntity(Bar::CLASSNAME, $entityId2)); + $this->assertTrue($this->cache->containsEntity(Attraction::class, $entityId1)); + $this->assertTrue($this->cache->containsEntity(Attraction::class, $entityId2)); + $this->assertTrue($this->cache->containsEntity(Bar::class, $entityId1)); + $this->assertTrue($this->cache->containsEntity(Bar::class, $entityId2)); - $this->assertInstanceOf(Attraction::CLASSNAME, $entity1); - $this->assertInstanceOf(Attraction::CLASSNAME, $entity2); - $this->assertInstanceOf(Bar::CLASSNAME, $entity1); - $this->assertInstanceOf(Bar::CLASSNAME, $entity2); + $this->assertInstanceOf(Attraction::class, $entity1); + $this->assertInstanceOf(Attraction::class, $entity2); + $this->assertInstanceOf(Bar::class, $entity1); + $this->assertInstanceOf(Bar::class, $entity2); $this->assertEquals($this->attractions[0]->getId(), $entity1->getId()); $this->assertEquals($this->attractions[0]->getName(), $entity1->getName()); @@ -95,15 +96,15 @@ public function testPutAndLoadEntities() $queryCount = $this->getCurrentQueryCount(); - $entity3 = $this->_em->find(Attraction::CLASSNAME, $entityId1); - $entity4 = $this->_em->find(Attraction::CLASSNAME, $entityId2); + $entity3 = $this->_em->find(Attraction::class, $entityId1); + $entity4 = $this->_em->find(Attraction::class, $entityId2); $this->assertEquals($queryCount, $this->getCurrentQueryCount()); - $this->assertInstanceOf(Attraction::CLASSNAME, $entity3); - $this->assertInstanceOf(Attraction::CLASSNAME, $entity4); - $this->assertInstanceOf(Bar::CLASSNAME, $entity3); - $this->assertInstanceOf(Bar::CLASSNAME, $entity4); + $this->assertInstanceOf(Attraction::class, $entity3); + $this->assertInstanceOf(Attraction::class, $entity4); + $this->assertInstanceOf(Bar::class, $entity3); + $this->assertInstanceOf(Bar::class, $entity4); $this->assertNotSame($entity1, $entity3); $this->assertEquals($entity1->getId(), $entity3->getId()); @@ -142,7 +143,7 @@ public function testQueryCacheFindAll() $this->assertEquals($queryCount + 1, $this->getCurrentQueryCount()); foreach ($result2 as $entity) { - $this->assertInstanceOf(Attraction::CLASSNAME, $entity); + $this->assertInstanceOf(Attraction::class, $entity); } } @@ -156,12 +157,12 @@ public function testShouldNotPutOneToManyRelationOnPersist() $this->_em->clear(); foreach ($this->cities as $city) { - $this->assertTrue($this->cache->containsEntity(City::CLASSNAME, $city->getId())); - $this->assertFalse($this->cache->containsCollection(City::CLASSNAME, 'attractions', $city->getId())); + $this->assertTrue($this->cache->containsEntity(City::class, $city->getId())); + $this->assertFalse($this->cache->containsCollection(City::class, 'attractions', $city->getId())); } foreach ($this->attractions as $attraction) { - $this->assertTrue($this->cache->containsEntity(Attraction::CLASSNAME, $attraction->getId())); + $this->assertTrue($this->cache->containsEntity(Attraction::class, $attraction->getId())); } } @@ -172,42 +173,83 @@ public function testOneToManyRelationSingleTable() $this->loadFixturesCities(); $this->loadFixturesAttractions(); - $this->cache->evictEntityRegion(City::CLASSNAME); - $this->cache->evictEntityRegion(Attraction::CLASSNAME); - $this->cache->evictCollectionRegion(City::CLASSNAME, 'attractions'); + $this->cache->evictEntityRegion(City::class); + $this->cache->evictEntityRegion(Attraction::class); + $this->cache->evictCollectionRegion(City::class, 'attractions'); $this->_em->clear(); - $entity = $this->_em->find(City::CLASSNAME, $this->cities[0]->getId()); + $entity = $this->_em->find(City::class, $this->cities[0]->getId()); - $this->assertInstanceOf(City::CLASSNAME, $entity); - $this->assertInstanceOf('Doctrine\ORM\PersistentCollection', $entity->getAttractions()); + $this->assertInstanceOf(City::class, $entity); + $this->assertInstanceOf(PersistentCollection::class, $entity->getAttractions()); $this->assertCount(2, $entity->getAttractions()); $ownerId = $this->cities[0]->getId(); $queryCount = $this->getCurrentQueryCount(); - $this->assertTrue($this->cache->containsEntity(City::CLASSNAME, $ownerId)); - $this->assertTrue($this->cache->containsCollection(City::CLASSNAME, 'attractions', $ownerId)); + $this->assertTrue($this->cache->containsEntity(City::class, $ownerId)); + $this->assertTrue($this->cache->containsCollection(City::class, 'attractions', $ownerId)); - $this->assertInstanceOf(Bar::CLASSNAME, $entity->getAttractions()->get(0)); - $this->assertInstanceOf(Bar::CLASSNAME, $entity->getAttractions()->get(1)); + $this->assertInstanceOf(Bar::class, $entity->getAttractions()->get(0)); + $this->assertInstanceOf(Bar::class, $entity->getAttractions()->get(1)); $this->assertEquals($this->attractions[0]->getName(), $entity->getAttractions()->get(0)->getName()); $this->assertEquals($this->attractions[1]->getName(), $entity->getAttractions()->get(1)->getName()); $this->_em->clear(); - $entity = $this->_em->find(City::CLASSNAME, $ownerId); + $entity = $this->_em->find(City::class, $ownerId); - $this->assertInstanceOf(City::CLASSNAME, $entity); - $this->assertInstanceOf('Doctrine\ORM\PersistentCollection', $entity->getAttractions()); + $this->assertInstanceOf(City::class, $entity); + $this->assertInstanceOf(PersistentCollection::class, $entity->getAttractions()); $this->assertCount(2, $entity->getAttractions()); $this->assertEquals($queryCount, $this->getCurrentQueryCount()); - $this->assertInstanceOf(Bar::CLASSNAME, $entity->getAttractions()->get(0)); - $this->assertInstanceOf(Bar::CLASSNAME, $entity->getAttractions()->get(1)); + $this->assertInstanceOf(Bar::class, $entity->getAttractions()->get(0)); + $this->assertInstanceOf(Bar::class, $entity->getAttractions()->get(1)); $this->assertEquals($this->attractions[0]->getName(), $entity->getAttractions()->get(0)->getName()); $this->assertEquals($this->attractions[1]->getName(), $entity->getAttractions()->get(1)->getName()); } -} \ No newline at end of file + + public function testQueryCacheShouldBeEvictedOnTimestampUpdate() + { + $this->loadFixturesCountries(); + $this->loadFixturesStates(); + $this->loadFixturesCities(); + $this->loadFixturesAttractions(); + $this->_em->clear(); + + $queryCount = $this->getCurrentQueryCount(); + $dql = 'SELECT attraction FROM Doctrine\Tests\Models\Cache\Attraction attraction'; + + $result1 = $this->_em->createQuery($dql) + ->setCacheable(true) + ->getResult(); + + $this->assertCount(count($this->attractions), $result1); + $this->assertEquals($queryCount + 1, $this->getCurrentQueryCount()); + + $contact = new Beach( + 'Botafogo', + $this->_em->find(City::class, $this->cities[1]->getId()) + ); + + $this->_em->persist($contact); + $this->_em->flush(); + $this->_em->clear(); + + $queryCount = $this->getCurrentQueryCount(); + + $result2 = $this->_em->createQuery($dql) + ->setCacheable(true) + ->getResult(); + + $this->assertCount(count($this->attractions) + 1, $result2); + $this->assertEquals($queryCount + 1, $this->getCurrentQueryCount()); + + foreach ($result2 as $entity) { + $this->assertInstanceOf(Attraction::class, $entity); + } + } +} diff --git a/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheTest.php b/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheTest.php index 56735840a4a..32047dda39b 100644 --- a/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/SecondLevelCacheTest.php @@ -16,10 +16,10 @@ public function testPutOnPersist() $this->loadFixturesCountries(); $this->_em->clear(); - $this->assertTrue($this->cache->containsEntity(Country::CLASSNAME, $this->countries[0]->getId())); - $this->assertTrue($this->cache->containsEntity(Country::CLASSNAME, $this->countries[1]->getId())); + $this->assertTrue($this->cache->containsEntity(Country::class, $this->countries[0]->getId())); + $this->assertTrue($this->cache->containsEntity(Country::class, $this->countries[1]->getId())); $this->assertEquals(2, $this->secondLevelCacheLogger->getPutCount()); - $this->assertEquals(2, $this->secondLevelCacheLogger->getRegionPutCount($this->getEntityRegion(Country::CLASSNAME))); + $this->assertEquals(2, $this->secondLevelCacheLogger->getRegionPutCount($this->getEntityRegion(Country::class))); } public function testPutAndLoadEntities() @@ -28,21 +28,21 @@ public function testPutAndLoadEntities() $this->_em->clear(); $this->assertEquals(2, $this->secondLevelCacheLogger->getPutCount()); - $this->assertEquals(2, $this->secondLevelCacheLogger->getRegionPutCount($this->getEntityRegion(Country::CLASSNAME))); + $this->assertEquals(2, $this->secondLevelCacheLogger->getRegionPutCount($this->getEntityRegion(Country::class))); - $this->cache->evictEntityRegion(Country::CLASSNAME); + $this->cache->evictEntityRegion(Country::class); - $this->assertFalse($this->cache->containsEntity(Country::CLASSNAME, $this->countries[0]->getId())); - $this->assertFalse($this->cache->containsEntity(Country::CLASSNAME, $this->countries[1]->getId())); + $this->assertFalse($this->cache->containsEntity(Country::class, $this->countries[0]->getId())); + $this->assertFalse($this->cache->containsEntity(Country::class, $this->countries[1]->getId())); - $c1 = $this->_em->find(Country::CLASSNAME, $this->countries[0]->getId()); - $c2 = $this->_em->find(Country::CLASSNAME, $this->countries[1]->getId()); + $c1 = $this->_em->find(Country::class, $this->countries[0]->getId()); + $c2 = $this->_em->find(Country::class, $this->countries[1]->getId()); - $this->assertTrue($this->cache->containsEntity(Country::CLASSNAME, $this->countries[0]->getId())); - $this->assertTrue($this->cache->containsEntity(Country::CLASSNAME, $this->countries[1]->getId())); + $this->assertTrue($this->cache->containsEntity(Country::class, $this->countries[0]->getId())); + $this->assertTrue($this->cache->containsEntity(Country::class, $this->countries[1]->getId())); - $this->assertInstanceOf(Country::CLASSNAME, $c1); - $this->assertInstanceOf(Country::CLASSNAME, $c2); + $this->assertInstanceOf(Country::class, $c1); + $this->assertInstanceOf(Country::class, $c2); $this->assertEquals($this->countries[0]->getId(), $c1->getId()); $this->assertEquals($this->countries[0]->getName(), $c1->getName()); @@ -54,16 +54,16 @@ public function testPutAndLoadEntities() $queryCount = $this->getCurrentQueryCount(); - $c3 = $this->_em->find(Country::CLASSNAME, $this->countries[0]->getId()); - $c4 = $this->_em->find(Country::CLASSNAME, $this->countries[1]->getId()); + $c3 = $this->_em->find(Country::class, $this->countries[0]->getId()); + $c4 = $this->_em->find(Country::class, $this->countries[1]->getId()); $this->assertEquals($queryCount, $this->getCurrentQueryCount()); $this->assertEquals(2, $this->secondLevelCacheLogger->getHitCount()); - $this->assertEquals(2, $this->secondLevelCacheLogger->getRegionHitCount($this->getEntityRegion(Country::CLASSNAME))); + $this->assertEquals(2, $this->secondLevelCacheLogger->getRegionHitCount($this->getEntityRegion(Country::class))); + + $this->assertInstanceOf(Country::class, $c3); + $this->assertInstanceOf(Country::class, $c4); - $this->assertInstanceOf(Country::CLASSNAME, $c3); - $this->assertInstanceOf(Country::CLASSNAME, $c4); - $this->assertEquals($c1->getId(), $c3->getId()); $this->assertEquals($c1->getName(), $c3->getName()); @@ -78,23 +78,23 @@ public function testRemoveEntities() $this->assertEquals(2, $this->secondLevelCacheLogger->getPutCount()); - $this->cache->evictEntityRegion(Country::CLASSNAME); - $this->secondLevelCacheLogger->clearRegionStats($this->getEntityRegion(Country::CLASSNAME)); + $this->cache->evictEntityRegion(Country::class); + $this->secondLevelCacheLogger->clearRegionStats($this->getEntityRegion(Country::class)); - $this->assertFalse($this->cache->containsEntity(Country::CLASSNAME, $this->countries[0]->getId())); - $this->assertFalse($this->cache->containsEntity(Country::CLASSNAME, $this->countries[1]->getId())); + $this->assertFalse($this->cache->containsEntity(Country::class, $this->countries[0]->getId())); + $this->assertFalse($this->cache->containsEntity(Country::class, $this->countries[1]->getId())); - $c1 = $this->_em->find(Country::CLASSNAME, $this->countries[0]->getId()); - $c2 = $this->_em->find(Country::CLASSNAME, $this->countries[1]->getId()); + $c1 = $this->_em->find(Country::class, $this->countries[0]->getId()); + $c2 = $this->_em->find(Country::class, $this->countries[1]->getId()); $this->assertEquals(2, $this->secondLevelCacheLogger->getPutCount()); $this->assertEquals(2, $this->secondLevelCacheLogger->getMissCount()); - $this->assertTrue($this->cache->containsEntity(Country::CLASSNAME, $this->countries[0]->getId())); - $this->assertTrue($this->cache->containsEntity(Country::CLASSNAME, $this->countries[1]->getId())); + $this->assertTrue($this->cache->containsEntity(Country::class, $this->countries[0]->getId())); + $this->assertTrue($this->cache->containsEntity(Country::class, $this->countries[1]->getId())); - $this->assertInstanceOf(Country::CLASSNAME, $c1); - $this->assertInstanceOf(Country::CLASSNAME, $c2); + $this->assertInstanceOf(Country::class, $c1); + $this->assertInstanceOf(Country::class, $c2); $this->assertEquals($this->countries[0]->getId(), $c1->getId()); $this->assertEquals($this->countries[0]->getName(), $c1->getName()); @@ -107,11 +107,11 @@ public function testRemoveEntities() $this->_em->flush(); $this->_em->clear(); - $this->assertFalse($this->cache->containsEntity(Country::CLASSNAME, $this->countries[0]->getId())); - $this->assertFalse($this->cache->containsEntity(Country::CLASSNAME, $this->countries[1]->getId())); + $this->assertFalse($this->cache->containsEntity(Country::class, $this->countries[0]->getId())); + $this->assertFalse($this->cache->containsEntity(Country::class, $this->countries[1]->getId())); - $this->assertNull($this->_em->find(Country::CLASSNAME, $this->countries[0]->getId())); - $this->assertNull($this->_em->find(Country::CLASSNAME, $this->countries[1]->getId())); + $this->assertNull($this->_em->find(Country::class, $this->countries[0]->getId())); + $this->assertNull($this->_em->find(Country::class, $this->countries[1]->getId())); $this->assertEquals(2, $this->secondLevelCacheLogger->getPutCount()); $this->assertEquals(2, $this->secondLevelCacheLogger->getMissCount()); @@ -124,27 +124,27 @@ public function testUpdateEntities() $this->_em->clear(); $this->assertEquals(6, $this->secondLevelCacheLogger->getPutCount()); - $this->assertEquals(2, $this->secondLevelCacheLogger->getRegionPutCount($this->getEntityRegion(Country::CLASSNAME))); - $this->assertEquals(4, $this->secondLevelCacheLogger->getRegionPutCount($this->getEntityRegion(State::CLASSNAME))); + $this->assertEquals(2, $this->secondLevelCacheLogger->getRegionPutCount($this->getEntityRegion(Country::class))); + $this->assertEquals(4, $this->secondLevelCacheLogger->getRegionPutCount($this->getEntityRegion(State::class))); - $this->cache->evictEntityRegion(State::CLASSNAME); - $this->secondLevelCacheLogger->clearRegionStats($this->getEntityRegion(State::CLASSNAME)); + $this->cache->evictEntityRegion(State::class); + $this->secondLevelCacheLogger->clearRegionStats($this->getEntityRegion(State::class)); - $this->assertFalse($this->cache->containsEntity(State::CLASSNAME, $this->states[0]->getId())); - $this->assertFalse($this->cache->containsEntity(State::CLASSNAME, $this->states[1]->getId())); + $this->assertFalse($this->cache->containsEntity(State::class, $this->states[0]->getId())); + $this->assertFalse($this->cache->containsEntity(State::class, $this->states[1]->getId())); - $s1 = $this->_em->find(State::CLASSNAME, $this->states[0]->getId()); - $s2 = $this->_em->find(State::CLASSNAME, $this->states[1]->getId()); + $s1 = $this->_em->find(State::class, $this->states[0]->getId()); + $s2 = $this->_em->find(State::class, $this->states[1]->getId()); $this->assertEquals(4, $this->secondLevelCacheLogger->getPutCount()); - $this->assertEquals(2, $this->secondLevelCacheLogger->getRegionPutCount($this->getEntityRegion(Country::CLASSNAME))); - $this->assertEquals(2, $this->secondLevelCacheLogger->getRegionPutCount($this->getEntityRegion(State::CLASSNAME))); + $this->assertEquals(2, $this->secondLevelCacheLogger->getRegionPutCount($this->getEntityRegion(Country::class))); + $this->assertEquals(2, $this->secondLevelCacheLogger->getRegionPutCount($this->getEntityRegion(State::class))); - $this->assertTrue($this->cache->containsEntity(State::CLASSNAME, $this->states[0]->getId())); - $this->assertTrue($this->cache->containsEntity(State::CLASSNAME, $this->states[1]->getId())); + $this->assertTrue($this->cache->containsEntity(State::class, $this->states[0]->getId())); + $this->assertTrue($this->cache->containsEntity(State::class, $this->states[1]->getId())); - $this->assertInstanceOf(State::CLASSNAME, $s1); - $this->assertInstanceOf(State::CLASSNAME, $s2); + $this->assertInstanceOf(State::class, $s1); + $this->assertInstanceOf(State::class, $s2); $this->assertEquals($this->states[0]->getId(), $s1->getId()); $this->assertEquals($this->states[0]->getName(), $s1->getName()); @@ -160,28 +160,28 @@ public function testUpdateEntities() $this->_em->flush(); $this->_em->clear(); - $this->assertTrue($this->cache->containsEntity(State::CLASSNAME, $this->states[0]->getId())); - $this->assertTrue($this->cache->containsEntity(State::CLASSNAME, $this->states[1]->getId())); + $this->assertTrue($this->cache->containsEntity(State::class, $this->states[0]->getId())); + $this->assertTrue($this->cache->containsEntity(State::class, $this->states[1]->getId())); $this->assertEquals(6, $this->secondLevelCacheLogger->getPutCount()); - $this->assertEquals(2, $this->secondLevelCacheLogger->getRegionPutCount($this->getEntityRegion(Country::CLASSNAME))); - $this->assertEquals(4, $this->secondLevelCacheLogger->getRegionPutCount($this->getEntityRegion(State::CLASSNAME))); + $this->assertEquals(2, $this->secondLevelCacheLogger->getRegionPutCount($this->getEntityRegion(Country::class))); + $this->assertEquals(4, $this->secondLevelCacheLogger->getRegionPutCount($this->getEntityRegion(State::class))); $queryCount = $this->getCurrentQueryCount(); - $c3 = $this->_em->find(State::CLASSNAME, $this->states[0]->getId()); - $c4 = $this->_em->find(State::CLASSNAME, $this->states[1]->getId()); + $c3 = $this->_em->find(State::class, $this->states[0]->getId()); + $c4 = $this->_em->find(State::class, $this->states[1]->getId()); $this->assertEquals(2, $this->secondLevelCacheLogger->getHitCount()); - $this->assertEquals(2, $this->secondLevelCacheLogger->getRegionHitCount($this->getEntityRegion(State::CLASSNAME))); + $this->assertEquals(2, $this->secondLevelCacheLogger->getRegionHitCount($this->getEntityRegion(State::class))); $this->assertEquals($queryCount, $this->getCurrentQueryCount()); - $this->assertTrue($this->cache->containsEntity(State::CLASSNAME, $this->states[0]->getId())); - $this->assertTrue($this->cache->containsEntity(State::CLASSNAME, $this->states[1]->getId())); + $this->assertTrue($this->cache->containsEntity(State::class, $this->states[0]->getId())); + $this->assertTrue($this->cache->containsEntity(State::class, $this->states[1]->getId())); - $this->assertInstanceOf(State::CLASSNAME, $c3); - $this->assertInstanceOf(State::CLASSNAME, $c4); + $this->assertInstanceOf(State::class, $c3); + $this->assertInstanceOf(State::class, $c4); $this->assertEquals($s1->getId(), $c3->getId()); $this->assertEquals("NEW NAME 1", $c3->getName()); @@ -190,21 +190,25 @@ public function testUpdateEntities() $this->assertEquals("NEW NAME 2", $c4->getName()); $this->assertEquals(2, $this->secondLevelCacheLogger->getHitCount()); - $this->assertEquals(2, $this->secondLevelCacheLogger->getRegionHitCount($this->getEntityRegion(State::CLASSNAME))); + $this->assertEquals(2, $this->secondLevelCacheLogger->getRegionHitCount($this->getEntityRegion(State::class))); } public function testPostFlushFailure() { - $listener = new ListenerSecondLevelCacheTest(array(Events::postFlush => function(){ + $listener = new ListenerSecondLevelCacheTest( + [ + Events::postFlush => function(){ throw new \RuntimeException('post flush failure'); - })); + } + ] + ); $this->_em->getEventManager() ->addEventListener(Events::postFlush, $listener); $country = new Country("Brazil"); - $this->cache->evictEntityRegion(Country::CLASSNAME); + $this->cache->evictEntityRegion(Country::class); try { @@ -215,7 +219,7 @@ public function testPostFlushFailure() } catch (\RuntimeException $exc) { $this->assertNotNull($country->getId()); $this->assertEquals('post flush failure', $exc->getMessage()); - $this->assertTrue($this->cache->containsEntity(Country::CLASSNAME, $country->getId())); + $this->assertTrue($this->cache->containsEntity(Country::class, $country->getId())); } } @@ -225,21 +229,25 @@ public function testPostUpdateFailure() $this->loadFixturesStates(); $this->_em->clear(); - $listener = new ListenerSecondLevelCacheTest(array(Events::postUpdate => function(){ + $listener = new ListenerSecondLevelCacheTest( + [ + Events::postUpdate => function(){ throw new \RuntimeException('post update failure'); - })); + } + ] + ); $this->_em->getEventManager() ->addEventListener(Events::postUpdate, $listener); - $this->cache->evictEntityRegion(State::CLASSNAME); + $this->cache->evictEntityRegion(State::class); $stateId = $this->states[0]->getId(); $stateName = $this->states[0]->getName(); - $state = $this->_em->find(State::CLASSNAME, $stateId); - - $this->assertTrue($this->cache->containsEntity(State::CLASSNAME, $stateId)); - $this->assertInstanceOf(State::CLASSNAME, $state); + $state = $this->_em->find(State::class, $stateId); + + $this->assertTrue($this->cache->containsEntity(State::class, $stateId)); + $this->assertInstanceOf(State::class, $state); $this->assertEquals($stateName, $state->getName()); $state->setName($stateName . uniqid()); @@ -256,11 +264,11 @@ public function testPostUpdateFailure() $this->_em->clear(); - $this->assertTrue($this->cache->containsEntity(State::CLASSNAME, $stateId)); + $this->assertTrue($this->cache->containsEntity(State::class, $stateId)); - $state = $this->_em->find(State::CLASSNAME, $stateId); + $state = $this->_em->find(State::class, $stateId); - $this->assertInstanceOf(State::CLASSNAME, $state); + $this->assertInstanceOf(State::class, $state); $this->assertEquals($stateName, $state->getName()); } @@ -269,20 +277,24 @@ public function testPostRemoveFailure() $this->loadFixturesCountries(); $this->_em->clear(); - $listener = new ListenerSecondLevelCacheTest(array(Events::postRemove => function(){ + $listener = new ListenerSecondLevelCacheTest( + [ + Events::postRemove => function(){ throw new \RuntimeException('post remove failure'); - })); + } + ] + ); $this->_em->getEventManager() ->addEventListener(Events::postRemove, $listener); - $this->cache->evictEntityRegion(Country::CLASSNAME); + $this->cache->evictEntityRegion(Country::class); $countryId = $this->countries[0]->getId(); - $country = $this->_em->find(Country::CLASSNAME, $countryId); + $country = $this->_em->find(Country::class, $countryId); - $this->assertTrue($this->cache->containsEntity(Country::CLASSNAME, $countryId)); - $this->assertInstanceOf(Country::CLASSNAME, $country); + $this->assertTrue($this->cache->containsEntity(Country::class, $countryId)); + $this->assertInstanceOf(Country::class, $country); $this->_em->remove($country); @@ -297,18 +309,18 @@ public function testPostRemoveFailure() $this->_em->clear(); $this->assertFalse( - $this->cache->containsEntity(Country::CLASSNAME, $countryId), + $this->cache->containsEntity(Country::class, $countryId), 'Removal attempts should clear the cache entry corresponding to the entity' ); - $this->assertInstanceOf(Country::CLASSNAME, $this->_em->find(Country::CLASSNAME, $countryId)); + $this->assertInstanceOf(Country::class, $this->_em->find(Country::class, $countryId)); } public function testCachedNewEntityExists() { $this->loadFixturesCountries(); - $persister = $this->_em->getUnitOfWork()->getEntityPersister(Country::CLASSNAME); + $persister = $this->_em->getUnitOfWork()->getEntityPersister(Country::class); $queryCount = $this->getCurrentQueryCount(); $this->assertTrue($persister->exists($this->countries[0])); @@ -324,7 +336,7 @@ class ListenerSecondLevelCacheTest { public $callbacks; - public function __construct(array $callbacks = array()) + public function __construct(array $callbacks = []) { $this->callbacks = $callbacks; } diff --git a/tests/Doctrine/Tests/ORM/Functional/SequenceEmulatedIdentityStrategyTest.php b/tests/Doctrine/Tests/ORM/Functional/SequenceEmulatedIdentityStrategyTest.php index 02c891e7557..d425936f5bd 100644 --- a/tests/Doctrine/Tests/ORM/Functional/SequenceEmulatedIdentityStrategyTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/SequenceEmulatedIdentityStrategyTest.php @@ -21,7 +21,7 @@ protected function setUp() } else { try { $this->_schemaTool->createSchema( - array($this->_em->getClassMetadata('Doctrine\Tests\ORM\Functional\SequenceEmulatedIdentityEntity')) + [$this->_em->getClassMetadata(SequenceEmulatedIdentityEntity::class)] ); } catch (\Exception $e) { // Swallow all exceptions. We do not test the schema tool here. diff --git a/tests/Doctrine/Tests/ORM/Functional/SequenceGeneratorTest.php b/tests/Doctrine/Tests/ORM/Functional/SequenceGeneratorTest.php index 2fcd6a1b907..290984f3584 100644 --- a/tests/Doctrine/Tests/ORM/Functional/SequenceGeneratorTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/SequenceGeneratorTest.php @@ -14,26 +14,29 @@ public function setUp() { parent::setUp(); - if (!$this->_em->getConnection()->getDatabasePlatform()->supportsSequences()) { + if ( ! $this->_em->getConnection()->getDatabasePlatform()->supportsSequences()) { $this->markTestSkipped('Only working for Databases that support sequences.'); } try { - $this->_schemaTool->createSchema(array( - $this->_em->getClassMetadata(__NAMESPACE__ . '\SequenceEntity'), - )); + $this->_schemaTool->createSchema( + [ + $this->_em->getClassMetadata(SequenceEntity::class), + ] + ); } catch(\Exception $e) { - } } public function testHighAllocationSizeSequence() { - for ($i = 0; $i < 11; $i++) { - $e = new SequenceEntity(); - $this->_em->persist($e); + for ($i = 0; $i < 11; ++$i) { + $this->_em->persist(new SequenceEntity()); } + $this->_em->flush(); + + self::assertCount(11, $this->_em->getRepository(SequenceEntity::class)->findAll()); } } @@ -46,7 +49,7 @@ class SequenceEntity * @Id * @column(type="integer") * @GeneratedValue(strategy="SEQUENCE") - * @SequenceGenerator(allocationSize=5,sequenceName="person_id_seq") + * @SequenceGenerator(allocationSize=5, sequenceName="person_id_seq") */ public $id; } diff --git a/tests/Doctrine/Tests/ORM/Functional/SingleTableCompositeKeyTest.php b/tests/Doctrine/Tests/ORM/Functional/SingleTableCompositeKeyTest.php index 53829a1c05e..091c79f5412 100644 --- a/tests/Doctrine/Tests/ORM/Functional/SingleTableCompositeKeyTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/SingleTableCompositeKeyTest.php @@ -1,8 +1,9 @@ _em->find( - 'Doctrine\Tests\Models\CompositeKeyInheritance\SingleRootClass', - array('keyPart1' => 'part-1', 'keyPart2' => 'part-2') - ); + return $this->_em->find(SingleRootClass::class, ['keyPart1' => 'part-1', 'keyPart2' => 'part-2']); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/SingleTableInheritanceTest.php b/tests/Doctrine/Tests/ORM/Functional/SingleTableInheritanceTest.php index 72be4c4d672..5bafffd790f 100644 --- a/tests/Doctrine/Tests/ORM/Functional/SingleTableInheritanceTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/SingleTableInheritanceTest.php @@ -2,9 +2,11 @@ namespace Doctrine\Tests\ORM\Functional; -use Doctrine\ORM\Mapping\ClassMetadata; use Doctrine\Common\Collections\Criteria; +use Doctrine\ORM\Mapping\ClassMetadata; use Doctrine\ORM\Persisters\PersisterException; +use Doctrine\ORM\Proxy\Proxy; +use Doctrine\Tests\Models\Company\CompanyContract; use Doctrine\Tests\Models\Company\CompanyEmployee; use Doctrine\Tests\Models\Company\CompanyFixContract; use Doctrine\Tests\Models\Company\CompanyFlexContract; @@ -14,7 +16,7 @@ class SingleTableInheritanceTest extends OrmFunctionalTestCase { private $salesPerson; - private $engineers = array(); + private $engineers = []; private $fix; private $flex; private $ultra; @@ -110,9 +112,9 @@ public function testPersistChildOfBaseClass() $this->_em->flush(); $this->_em->clear(); - $contract = $this->_em->find('Doctrine\Tests\Models\Company\CompanyFixContract', $fixContract->getId()); + $contract = $this->_em->find(CompanyFixContract::class, $fixContract->getId()); - $this->assertInstanceOf('Doctrine\Tests\Models\Company\CompanyFixContract', $contract); + $this->assertInstanceOf(CompanyFixContract::class, $contract); $this->assertEquals(1000, $contract->getFixPrice()); $this->assertEquals($this->salesPerson->getId(), $contract->getSalesPerson()->getId()); } @@ -131,9 +133,9 @@ public function testPersistDeepChildOfBaseClass() $this->_em->flush(); $this->_em->clear(); - $contract = $this->_em->find('Doctrine\Tests\Models\Company\CompanyFlexUltraContract', $ultraContract->getId()); + $contract = $this->_em->find(CompanyFlexUltraContract::class, $ultraContract->getId()); - $this->assertInstanceOf('Doctrine\Tests\Models\Company\CompanyFlexUltraContract', $contract); + $this->assertInstanceOf(CompanyFlexUltraContract::class, $contract); $this->assertEquals(7000, $contract->getMaxPrice()); $this->assertEquals(100, $contract->getHoursWorked()); $this->assertEquals(50, $contract->getPricePerHour()); @@ -143,13 +145,13 @@ public function testChildClassLifecycleUpdate() { $this->loadFullFixture(); - $fix = $this->_em->find('Doctrine\Tests\Models\Company\CompanyContract', $this->fix->getId()); + $fix = $this->_em->find(CompanyContract::class, $this->fix->getId()); $fix->setFixPrice(2500); $this->_em->flush(); $this->_em->clear(); - $newFix = $this->_em->find('Doctrine\Tests\Models\Company\CompanyContract', $this->fix->getId()); + $newFix = $this->_em->find(CompanyContract::class, $this->fix->getId()); $this->assertEquals(2500, $newFix->getFixPrice()); } @@ -157,38 +159,38 @@ public function testChildClassLifecycleRemove() { $this->loadFullFixture(); - $fix = $this->_em->find('Doctrine\Tests\Models\Company\CompanyContract', $this->fix->getId()); + $fix = $this->_em->find(CompanyContract::class, $this->fix->getId()); $this->_em->remove($fix); $this->_em->flush(); - $this->assertNull($this->_em->find('Doctrine\Tests\Models\Company\CompanyContract', $this->fix->getId())); + $this->assertNull($this->_em->find(CompanyContract::class, $this->fix->getId())); } public function testFindAllForAbstractBaseClass() { $this->loadFullFixture(); - $contracts = $this->_em->getRepository('Doctrine\Tests\Models\Company\CompanyContract')->findAll(); + $contracts = $this->_em->getRepository(CompanyContract::class)->findAll(); $this->assertEquals(3, count($contracts)); - $this->assertContainsOnly('Doctrine\Tests\Models\Company\CompanyContract', $contracts); + $this->assertContainsOnly(CompanyContract::class, $contracts); } public function testFindAllForChildClass() { $this->loadFullFixture(); - $this->assertEquals(1, count($this->_em->getRepository('Doctrine\Tests\Models\Company\CompanyFixContract')->findAll())); - $this->assertEquals(2, count($this->_em->getRepository('Doctrine\Tests\Models\Company\CompanyFlexContract')->findAll())); - $this->assertEquals(1, count($this->_em->getRepository('Doctrine\Tests\Models\Company\CompanyFlexUltraContract')->findAll())); + $this->assertEquals(1, count($this->_em->getRepository(CompanyFixContract::class)->findAll())); + $this->assertEquals(2, count($this->_em->getRepository(CompanyFlexContract::class)->findAll())); + $this->assertEquals(1, count($this->_em->getRepository(CompanyFlexUltraContract::class)->findAll())); } public function testFindForAbstractBaseClass() { $this->loadFullFixture(); - $contract = $this->_em->find('Doctrine\Tests\Models\Company\CompanyContract', $this->fix->getId()); + $contract = $this->_em->find(CompanyContract::class, $this->fix->getId()); - $this->assertInstanceOf('Doctrine\Tests\Models\Company\CompanyFixContract', $contract); + $this->assertInstanceOf(CompanyFixContract::class, $contract); $this->assertEquals(1000, $contract->getFixPrice()); } @@ -199,7 +201,7 @@ public function testQueryForAbstractBaseClass() $contracts = $this->_em->createQuery('SELECT c FROM Doctrine\Tests\Models\Company\CompanyContract c')->getResult(); $this->assertEquals(3, count($contracts)); - $this->assertContainsOnly('Doctrine\Tests\Models\Company\CompanyContract', $contracts); + $this->assertContainsOnly(CompanyContract::class, $contracts); } public function testQueryForChildClass() @@ -217,7 +219,7 @@ public function testQueryBaseClassWithJoin() $contracts = $this->_em->createQuery('SELECT c, p FROM Doctrine\Tests\Models\Company\CompanyContract c JOIN c.salesPerson p')->getResult(); $this->assertEquals(3, count($contracts)); - $this->assertContainsOnly('Doctrine\Tests\Models\Company\CompanyContract', $contracts); + $this->assertContainsOnly(CompanyContract::class, $contracts); } public function testQueryScalarWithDiscriminatorValue() @@ -232,7 +234,7 @@ public function testQueryScalarWithDiscriminatorValue() sort($discrValues); - $this->assertEquals(array('fix', 'flexible', 'flexultra'), $discrValues); + $this->assertEquals(['fix', 'flexible', 'flexultra'], $discrValues); } public function testQueryChildClassWithCondition() @@ -242,7 +244,7 @@ public function testQueryChildClassWithCondition() $dql = 'SELECT c FROM Doctrine\Tests\Models\Company\CompanyFixContract c WHERE c.fixPrice = ?1'; $contract = $this->_em->createQuery($dql)->setParameter(1, 1000)->getSingleResult(); - $this->assertInstanceOf('Doctrine\Tests\Models\Company\CompanyFixContract', $contract); + $this->assertInstanceOf(CompanyFixContract::class, $contract); $this->assertEquals(1000, $contract->getFixPrice()); } @@ -258,8 +260,8 @@ public function testUpdateChildClassWithCondition() $this->assertEquals(1, $affected); - $flexContract = $this->_em->find('Doctrine\Tests\Models\Company\CompanyContract', $this->flex->getId()); - $ultraContract = $this->_em->find('Doctrine\Tests\Models\Company\CompanyContract', $this->ultra->getId()); + $flexContract = $this->_em->find(CompanyContract::class, $this->flex->getId()); + $ultraContract = $this->_em->find(CompanyContract::class, $this->ultra->getId()); $this->assertEquals(300, $ultraContract->getHoursWorked()); $this->assertEquals(100, $flexContract->getHoursWorked()); @@ -326,20 +328,20 @@ public function testFindByAssociation() { $this->loadFullFixture(); - $repos = $this->_em->getRepository("Doctrine\Tests\Models\Company\CompanyContract"); - $contracts = $repos->findBy(array('salesPerson' => $this->salesPerson->getId())); + $repos = $this->_em->getRepository(CompanyContract::class); + $contracts = $repos->findBy(['salesPerson' => $this->salesPerson->getId()]); $this->assertEquals(3, count($contracts), "There should be 3 entities related to " . $this->salesPerson->getId() . " for 'Doctrine\Tests\Models\Company\CompanyContract'"); - $repos = $this->_em->getRepository("Doctrine\Tests\Models\Company\CompanyFixContract"); - $contracts = $repos->findBy(array('salesPerson' => $this->salesPerson->getId())); + $repos = $this->_em->getRepository(CompanyFixContract::class); + $contracts = $repos->findBy(['salesPerson' => $this->salesPerson->getId()]); $this->assertEquals(1, count($contracts), "There should be 1 entities related to " . $this->salesPerson->getId() . " for 'Doctrine\Tests\Models\Company\CompanyFixContract'"); - $repos = $this->_em->getRepository("Doctrine\Tests\Models\Company\CompanyFlexContract"); - $contracts = $repos->findBy(array('salesPerson' => $this->salesPerson->getId())); + $repos = $this->_em->getRepository(CompanyFlexContract::class); + $contracts = $repos->findBy(['salesPerson' => $this->salesPerson->getId()]); $this->assertEquals(2, count($contracts), "There should be 2 entities related to " . $this->salesPerson->getId() . " for 'Doctrine\Tests\Models\Company\CompanyFlexContract'"); - $repos = $this->_em->getRepository("Doctrine\Tests\Models\Company\CompanyFlexUltraContract"); - $contracts = $repos->findBy(array('salesPerson' => $this->salesPerson->getId())); + $repos = $this->_em->getRepository(CompanyFlexUltraContract::class); + $contracts = $repos->findBy(['salesPerson' => $this->salesPerson->getId()]); $this->assertEquals(1, count($contracts), "There should be 1 entities related to " . $this->salesPerson->getId() . " for 'Doctrine\Tests\Models\Company\CompanyFlexUltraContract'"); } @@ -350,13 +352,13 @@ public function testInheritanceMatching() { $this->loadFullFixture(); - $repository = $this->_em->getRepository("Doctrine\Tests\Models\Company\CompanyContract"); + $repository = $this->_em->getRepository(CompanyContract::class); $contracts = $repository->matching(new Criteria( Criteria::expr()->eq('salesPerson', $this->salesPerson) )); $this->assertEquals(3, count($contracts)); - $repository = $this->_em->getRepository("Doctrine\Tests\Models\Company\CompanyFixContract"); + $repository = $this->_em->getRepository(CompanyFixContract::class); $contracts = $repository->matching(new Criteria( Criteria::expr()->eq('salesPerson', $this->salesPerson) )); @@ -370,7 +372,7 @@ public function testMatchingNonObjectOnAssocationThrowsException() { $this->loadFullFixture(); - $repository = $this->_em->getRepository("Doctrine\Tests\Models\Company\CompanyContract"); + $repository = $this->_em->getRepository(CompanyContract::class); $this->expectException(PersisterException::class); $this->expectExceptionMessage('annot match on Doctrine\Tests\Models\Company\CompanyContract::salesPerson with a non-object value.'); @@ -390,14 +392,14 @@ public function testGetReferenceEntityWithSubclasses() { $this->loadFullFixture(); - $ref = $this->_em->getReference('Doctrine\Tests\Models\Company\CompanyContract', $this->fix->getId()); - $this->assertNotInstanceOf('Doctrine\ORM\Proxy\Proxy', $ref, "Cannot Request a proxy from a class that has subclasses."); - $this->assertInstanceOf('Doctrine\Tests\Models\Company\CompanyContract', $ref); - $this->assertInstanceOf('Doctrine\Tests\Models\Company\CompanyFixContract', $ref, "Direct fetch of the reference has to load the child class Employee directly."); + $ref = $this->_em->getReference(CompanyContract::class, $this->fix->getId()); + $this->assertNotInstanceOf(Proxy::class, $ref, "Cannot Request a proxy from a class that has subclasses."); + $this->assertInstanceOf(CompanyContract::class, $ref); + $this->assertInstanceOf(CompanyFixContract::class, $ref, "Direct fetch of the reference has to load the child class Employee directly."); $this->_em->clear(); - $ref = $this->_em->getReference('Doctrine\Tests\Models\Company\CompanyFixContract', $this->fix->getId()); - $this->assertInstanceOf('Doctrine\ORM\Proxy\Proxy', $ref, "A proxy can be generated only if no subclasses exists for the requested reference."); + $ref = $this->_em->getReference(CompanyFixContract::class, $this->fix->getId()); + $this->assertInstanceOf(Proxy::class, $ref, "A proxy can be generated only if no subclasses exists for the requested reference."); } /** @@ -409,10 +411,10 @@ public function testEagerLoadInheritanceHierarchy() $dql = 'SELECT f FROM Doctrine\Tests\Models\Company\CompanyFixContract f WHERE f.id = ?1'; $contract = $this->_em->createQuery($dql) - ->setFetchMode('Doctrine\Tests\Models\Company\CompanyFixContract', 'salesPerson', ClassMetadata::FETCH_EAGER) + ->setFetchMode(CompanyFixContract::class, 'salesPerson', ClassMetadata::FETCH_EAGER) ->setParameter(1, $this->fix->getId()) ->getSingleResult(); - $this->assertNotInstanceOf('Doctrine\ORM\Proxy\Proxy', $contract->getSalesPerson()); + $this->assertNotInstanceOf(Proxy::class, $contract->getSalesPerson()); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/StandardEntityPersisterTest.php b/tests/Doctrine/Tests/ORM/Functional/StandardEntityPersisterTest.php index a335b234e08..bef1f768212 100644 --- a/tests/Doctrine/Tests/ORM/Functional/StandardEntityPersisterTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/StandardEntityPersisterTest.php @@ -2,12 +2,11 @@ namespace Doctrine\Tests\ORM\Functional; -use Doctrine\Tests\Models\ECommerce\ECommerceCart, - Doctrine\Tests\Models\ECommerce\ECommerceFeature, - Doctrine\Tests\Models\ECommerce\ECommerceCustomer, - Doctrine\Tests\Models\ECommerce\ECommerceProduct; - -use Doctrine\ORM\Mapping\AssociationMapping; +use Doctrine\ORM\PersistentCollection; +use Doctrine\Tests\Models\ECommerce\ECommerceCart; +use Doctrine\Tests\Models\ECommerce\ECommerceCustomer; +use Doctrine\Tests\Models\ECommerce\ECommerceFeature; +use Doctrine\Tests\Models\ECommerce\ECommerceProduct; use Doctrine\Tests\OrmFunctionalTestCase; /** @@ -35,12 +34,12 @@ public function testAcceptsForeignKeysAsCriteria() $cardId = $cart->getId(); unset($cart); - $class = $this->_em->getClassMetadata('Doctrine\Tests\Models\ECommerce\ECommerceCart'); + $class = $this->_em->getClassMetadata(ECommerceCart::class); - $persister = $this->_em->getUnitOfWork()->getEntityPersister('Doctrine\Tests\Models\ECommerce\ECommerceCart'); + $persister = $this->_em->getUnitOfWork()->getEntityPersister(ECommerceCart::class); $newCart = new ECommerceCart(); - $this->_em->getUnitOfWork()->registerManaged($newCart, array('id' => $cardId), array()); - $persister->load(array('customer_id' => $customer->getId()), $newCart, $class->associationMappings['customer']); + $this->_em->getUnitOfWork()->registerManaged($newCart, ['id' => $cardId], []); + $persister->load(['customer_id' => $customer->getId()], $newCart, $class->associationMappings['customer']); $this->assertEquals('Credit card', $newCart->getPayment()); } @@ -63,7 +62,7 @@ public function testAddPersistRetrieve() $this->_em->flush(); $this->assertEquals(2, count($p->getFeatures())); - $this->assertInstanceOf('Doctrine\ORM\PersistentCollection', $p->getFeatures()); + $this->assertInstanceOf(PersistentCollection::class, $p->getFeatures()); $q = $this->_em->createQuery( 'SELECT p, f @@ -74,7 +73,7 @@ public function testAddPersistRetrieve() $res = $q->getResult(); $this->assertEquals(2, count($p->getFeatures())); - $this->assertInstanceOf('Doctrine\ORM\PersistentCollection', $p->getFeatures()); + $this->assertInstanceOf(PersistentCollection::class, $p->getFeatures()); // Check that the features are the same instances still foreach ($p->getFeatures() as $feature) { diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1041Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1041Test.php index ee1218187bc..ed27ed10044 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1041Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1041Test.php @@ -2,7 +2,7 @@ namespace Doctrine\Tests\ORM\Functional\Ticket; -use Doctrine\Tests\Models\Company\CompanyFixContract; +use Doctrine\Tests\Models; use Doctrine\Tests\OrmFunctionalTestCase; /** @@ -18,7 +18,7 @@ public function setUp() public function testGrabWrongSubtypeReturnsNull() { - $fix = new CompanyFixContract(); + $fix = new Models\Company\CompanyFixContract(); $fix->setFixPrice(2000); $this->_em->persist($fix); @@ -26,8 +26,8 @@ public function testGrabWrongSubtypeReturnsNull() $id = $fix->getId(); - $this->assertNull($this->_em->find('Doctrine\Tests\Models\Company\CompanyFlexContract', $id)); - $this->assertNull($this->_em->getReference('Doctrine\Tests\Models\Company\CompanyFlexContract', $id)); - $this->assertNull($this->_em->getPartialReference('Doctrine\Tests\Models\Company\CompanyFlexContract', $id)); + $this->assertNull($this->_em->find(Models\Company\CompanyFlexContract::class, $id)); + $this->assertNull($this->_em->getReference(Models\Company\CompanyFlexContract::class, $id)); + $this->assertNull($this->_em->getPartialReference(Models\Company\CompanyFlexContract::class, $id)); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1043Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1043Test.php index f3e255042c9..9b35eb006c2 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1043Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1043Test.php @@ -30,7 +30,7 @@ public function testChangeSetPlusWeirdPHPCastingIntCastingRule() $this->_em->flush(); $this->_em->clear(); - $user = $this->_em->find("Doctrine\Tests\Models\CMS\CmsUser", $user->id); + $user = $this->_em->find(CmsUser::class, $user->id); $this->assertSame("44", $user->status); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1050Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1050Test.php deleted file mode 100644 index fccb0fd4cdf..00000000000 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1050Test.php +++ /dev/null @@ -1,39 +0,0 @@ -markTestSkipped('performance skipped'); - - $this->useModelSet('cms'); - - parent::setUp(); - } - - public function testPerformance() - { - for ($i = 2; $i < 10000; ++$i) { - $user = new CmsUser(); - $user->status = 'developer'; - $user->username = 'jwage'.$i; - $user->name = 'Jonathan'; - $this->_em->persist($user); - } - $this->_em->flush(); - $this->_em->clear(); - - $s = microtime(true); - $users = $this->_em->getRepository('Doctrine\Tests\Models\CMS\CmsUser')->findAll(); - $e = microtime(true); - echo __FUNCTION__ . " - " . ($e - $s) . " seconds" . PHP_EOL; - } -} diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1080Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1080Test.php index 9369ca4c949..59ee4bb58ff 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1080Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1080Test.php @@ -11,11 +11,13 @@ class DDC1080Test extends OrmFunctionalTestCase { public function testHydration() { - $this->_schemaTool->createSchema(array( - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC1080Foo'), - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC1080Bar'), - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC1080FooBar'), - )); + $this->_schemaTool->createSchema( + [ + $this->_em->getClassMetadata(DDC1080Foo::class), + $this->_em->getClassMetadata(DDC1080Bar::class), + $this->_em->getClassMetadata(DDC1080FooBar::class), + ] + ); $foo1 = new DDC1080Foo(); $foo1->setFooTitle('foo title 1'); @@ -57,7 +59,7 @@ public function testHydration() $this->_em->flush(); $this->_em->clear(); - $foo = $this->_em->find('Doctrine\Tests\ORM\Functional\Ticket\DDC1080Foo', $foo1->getFooID()); + $foo = $this->_em->find(DDC1080Foo::class, $foo1->getFooID()); $fooBars = $foo->getFooBars(); $this->assertEquals(3, count($fooBars), "Should return three foobars."); diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1113Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1113Test.php index e40f27994d0..324e8481219 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1113Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1113Test.php @@ -8,19 +8,20 @@ */ class DDC1113Test extends \Doctrine\Tests\OrmFunctionalTestCase { - public function setUp() { parent::setUp(); + try { - $this->_schemaTool->createSchema(array( - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC1113Engine'), - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC1113Vehicle'), - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC1113Car'), - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC1113Bus'), - )); + $this->_schemaTool->createSchema( + [ + $this->_em->getClassMetadata(DDC1113Engine::class), + $this->_em->getClassMetadata(DDC1113Vehicle::class), + $this->_em->getClassMetadata(DDC1113Car::class), + $this->_em->getClassMetadata(DDC1113Bus::class), + ] + ); } catch (\Exception $e) { - } } @@ -41,8 +42,11 @@ public function testIssue() $this->_em->remove($bus); $this->_em->remove($car); $this->_em->flush(); - } + self::assertEmpty($this->_em->getRepository(DDC1113Car::class)->findAll()); + self::assertEmpty($this->_em->getRepository(DDC1113Bus::class)->findAll()); + self::assertEmpty($this->_em->getRepository(DDC1113Engine::class)->findAll()); + } } /** diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1129Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1129Test.php index 1f59d07baeb..81c95010298 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1129Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1129Test.php @@ -2,6 +2,8 @@ namespace Doctrine\Tests\ORM\Functional\Ticket; +use Doctrine\Tests\Models\CMS\CmsArticle; + /** * @group DDC-1129 */ @@ -15,7 +17,7 @@ public function setUp() public function testVersionFieldIgnoredInChangesetComputation() { - $article = new \Doctrine\Tests\Models\CMS\CmsArticle(); + $article = new CmsArticle(); $article->text = "I don't know."; $article->topic = "Who is John Galt?"; @@ -24,7 +26,7 @@ public function testVersionFieldIgnoredInChangesetComputation() $this->assertEquals(1, $article->version); - $class = $this->_em->getClassMetadata('Doctrine\Tests\Models\CMS\CmsArticle'); + $class = $this->_em->getClassMetadata(CmsArticle::class); $uow = $this->_em->getUnitOfWork(); $uow->computeChangeSet($class, $article); diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1151Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1151Test.php index 8e67b514f57..5677801b408 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1151Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1151Test.php @@ -13,10 +13,12 @@ public function testQuoteForeignKey() $this->markTestSkipped("This test is useful for all databases, but designed only for postgresql."); } - $sql = $this->_schemaTool->getCreateSchemaSql(array( - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC1151User'), - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC1151Group'), - )); + $sql = $this->_schemaTool->getCreateSchemaSql( + [ + $this->_em->getClassMetadata(DDC1151User::class), + $this->_em->getClassMetadata(DDC1151Group::class), + ] + ); $this->assertEquals("CREATE TABLE \"User\" (id INT NOT NULL, PRIMARY KEY(id))", $sql[0]); $this->assertEquals("CREATE TABLE ddc1151user_ddc1151group (ddc1151user_id INT NOT NULL, ddc1151group_id INT NOT NULL, PRIMARY KEY(ddc1151user_id, ddc1151group_id))", $sql[1]); diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1163Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1163Test.php index dad902b355c..f287034925a 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1163Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1163Test.php @@ -2,6 +2,8 @@ namespace Doctrine\Tests\ORM\Functional\Ticket; +use Doctrine\ORM\Proxy\Proxy; + /** * @group DDC-1163 */ @@ -11,12 +13,14 @@ protected function setUp() { parent::setUp(); //$this->_em->getConnection()->getConfiguration()->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger); - $this->_schemaTool->createSchema(array( - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC1163Product'), - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC1163SpecialProduct'), - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC1163ProxyHolder'), - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC1163Tag'), - )); + $this->_schemaTool->createSchema( + [ + $this->_em->getClassMetadata(DDC1163Product::class), + $this->_em->getClassMetadata(DDC1163SpecialProduct::class), + $this->_em->getClassMetadata(DDC1163ProxyHolder::class), + $this->_em->getClassMetadata(DDC1163Tag::class), + ] + ); } public function testIssue() @@ -57,25 +61,25 @@ private function createSpecialProductAndProxyHolderReferencingIt() */ private function createProxyForSpecialProduct() { - /* @var $proxyHolder ProxyHolder */ - $proxyHolder = $this->_em->find(__NAMESPACE__ . '\\DDC1163ProxyHolder', $this->proxyHolderId); + /* @var $proxyHolder DDC1163ProxyHolder */ + $proxyHolder = $this->_em->find(DDC1163ProxyHolder::class, $this->proxyHolderId); - $this->assertInstanceOf(__NAMESPACE__.'\\DDC1163SpecialProduct', $proxyHolder->getSpecialProduct()); + $this->assertInstanceOf(DDC1163SpecialProduct::class, $proxyHolder->getSpecialProduct()); } private function setPropertyAndAssignTagToSpecialProduct() { - /* @var $specialProduct SpecialProduct */ - $specialProduct = $this->_em->find(__NAMESPACE__ . '\\DDC1163SpecialProduct', $this->productId); + /* @var $specialProduct DDC1163SpecialProduct */ + $specialProduct = $this->_em->find(DDC1163SpecialProduct::class, $this->productId); - $this->assertInstanceOf(__NAMESPACE__.'\\DDC1163SpecialProduct', $specialProduct); - $this->assertInstanceOf('Doctrine\ORM\Proxy\Proxy', $specialProduct); + $this->assertInstanceOf(DDC1163SpecialProduct::class, $specialProduct); + $this->assertInstanceOf(Proxy::class, $specialProduct); $specialProduct->setSubclassProperty('foobar'); // this screams violation of law of demeter ;) $this->assertEquals( - __NAMESPACE__.'\\DDC1163SpecialProduct', + DDC1163SpecialProduct::class, $this->_em->getUnitOfWork()->getEntityPersister(get_class($specialProduct))->getClassMetadata()->name ); diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC117Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC117Test.php index 9c28b7e8858..f1685d60941 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC117Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC117Test.php @@ -9,19 +9,23 @@ use Doctrine\Tests\Models\DDC117\DDC117ApproveChanges; use Doctrine\Tests\Models\DDC117\DDC117Editor; use Doctrine\Tests\Models\DDC117\DDC117Link; +use Doctrine\Tests\VerifyDeprecations; /** * @group DDC-117 */ class DDC117Test extends \Doctrine\Tests\OrmFunctionalTestCase { + use VerifyDeprecations; + private $article1; private $article2; private $reference; private $translation; private $articleDetails; - protected function setUp() { + protected function setUp() + { $this->useModelSet('ddc117'); parent::setUp(); @@ -34,7 +38,7 @@ protected function setUp() { $link = new DDC117Link($this->article1, $this->article2, "Link-Description"); $this->_em->persist($link); - + $this->reference = new DDC117Reference($this->article1, $this->article2, "Test-Description"); $this->_em->persist($this->reference); @@ -53,35 +57,35 @@ protected function setUp() { */ public function testAssociationOnlyCompositeKey() { - $idCriteria = array('source' => $this->article1->id(), 'target' => $this->article2->id()); + $idCriteria = ['source' => $this->article1->id(), 'target' => $this->article2->id()]; - $mapRef = $this->_em->find("Doctrine\Tests\Models\DDC117\DDC117Reference", $idCriteria); - $this->assertInstanceOf("Doctrine\Tests\Models\DDC117\DDC117Reference", $mapRef); - $this->assertInstanceOf("Doctrine\Tests\Models\DDC117\DDC117Article", $mapRef->target()); - $this->assertInstanceOf("Doctrine\Tests\Models\DDC117\DDC117Article", $mapRef->source()); - $this->assertSame($mapRef, $this->_em->find("Doctrine\Tests\Models\DDC117\DDC117Reference", $idCriteria)); + $mapRef = $this->_em->find(DDC117Reference::class, $idCriteria); + $this->assertInstanceOf(DDC117Reference::class, $mapRef); + $this->assertInstanceOf(DDC117Article::class, $mapRef->target()); + $this->assertInstanceOf(DDC117Article::class, $mapRef->source()); + $this->assertSame($mapRef, $this->_em->find(DDC117Reference::class, $idCriteria)); $this->_em->clear(); - $dql = "SELECT r, s FROM "."Doctrine\Tests\Models\DDC117\DDC117Reference r JOIN r.source s WHERE r.source = ?1"; + $dql = 'SELECT r, s FROM ' . DDC117Reference::class . ' r JOIN r.source s WHERE r.source = ?1'; $dqlRef = $this->_em->createQuery($dql)->setParameter(1, 1)->getSingleResult(); - $this->assertInstanceOf("Doctrine\Tests\Models\DDC117\DDC117Reference", $mapRef); - $this->assertInstanceOf("Doctrine\Tests\Models\DDC117\DDC117Article", $mapRef->target()); - $this->assertInstanceOf("Doctrine\Tests\Models\DDC117\DDC117Article", $mapRef->source()); - $this->assertSame($dqlRef, $this->_em->find("Doctrine\Tests\Models\DDC117\DDC117Reference", $idCriteria)); + $this->assertInstanceOf(DDC117Reference::class, $mapRef); + $this->assertInstanceOf(DDC117Article::class, $mapRef->target()); + $this->assertInstanceOf(DDC117Article::class, $mapRef->source()); + $this->assertSame($dqlRef, $this->_em->find(DDC117Reference::class, $idCriteria)); $this->_em->clear(); - $dql = "SELECT r, s FROM "."Doctrine\Tests\Models\DDC117\DDC117Reference r JOIN r.source s WHERE s.title = ?1"; + $dql = 'SELECT r, s FROM ' . DDC117Reference::class . ' r JOIN r.source s WHERE s.title = ?1'; $dqlRef = $this->_em->createQuery($dql)->setParameter(1, 'Foo')->getSingleResult(); - $this->assertInstanceOf("Doctrine\Tests\Models\DDC117\DDC117Reference", $dqlRef); - $this->assertInstanceOf("Doctrine\Tests\Models\DDC117\DDC117Article", $dqlRef->target()); - $this->assertInstanceOf("Doctrine\Tests\Models\DDC117\DDC117Article", $dqlRef->source()); - $this->assertSame($dqlRef, $this->_em->find("Doctrine\Tests\Models\DDC117\DDC117Reference", $idCriteria)); + $this->assertInstanceOf(DDC117Reference::class, $dqlRef); + $this->assertInstanceOf(DDC117Article::class, $dqlRef->target()); + $this->assertInstanceOf(DDC117Article::class, $dqlRef->source()); + $this->assertSame($dqlRef, $this->_em->find(DDC117Reference::class, $idCriteria)); - $dql = "SELECT r, s FROM "."Doctrine\Tests\Models\DDC117\DDC117Reference r JOIN r.source s WHERE s.title = ?1"; + $dql = 'SELECT r, s FROM ' . DDC117Reference::class . ' r JOIN r.source s WHERE s.title = ?1'; $dqlRef = $this->_em->createQuery($dql)->setParameter(1, 'Foo')->getSingleResult(); $this->_em->contains($dqlRef); @@ -92,15 +96,15 @@ public function testAssociationOnlyCompositeKey() */ public function testUpdateAssociationEntity() { - $idCriteria = array('source' => $this->article1->id(), 'target' => $this->article2->id()); + $idCriteria = ['source' => $this->article1->id(), 'target' => $this->article2->id()]; - $mapRef = $this->_em->find("Doctrine\Tests\Models\DDC117\DDC117Reference", $idCriteria); + $mapRef = $this->_em->find(DDC117Reference::class, $idCriteria); $this->assertNotNull($mapRef); $mapRef->setDescription("New Description!!"); $this->_em->flush(); $this->_em->clear(); - $mapRef = $this->_em->find("Doctrine\Tests\Models\DDC117\DDC117Reference", $idCriteria); + $mapRef = $this->_em->find(DDC117Reference::class, $idCriteria); $this->assertEquals('New Description!!', $mapRef->getDescription()); } @@ -110,13 +114,13 @@ public function testUpdateAssociationEntity() */ public function testFetchDql() { - $dql = "SELECT r, s FROM "."Doctrine\Tests\Models\DDC117\DDC117Reference r JOIN r.source s WHERE s.title = ?1"; + $dql = "SELECT r, s FROM Doctrine\Tests\Models\DDC117\DDC117Reference r JOIN r.source s WHERE s.title = ?1"; $refs = $this->_em->createQuery($dql)->setParameter(1, 'Foo')->getResult(); $this->assertTrue(count($refs) > 0, "Has to contain at least one Reference."); foreach ($refs AS $ref) { - $this->assertInstanceOf("Doctrine\Tests\Models\DDC117\DDC117Reference", $ref, "Contains only Reference instances."); + $this->assertInstanceOf(DDC117Reference::class, $ref, "Contains only Reference instances."); $this->assertTrue($this->_em->contains($ref), "Contains Reference in the IdentityMap."); } } @@ -126,15 +130,15 @@ public function testFetchDql() */ public function testRemoveCompositeElement() { - $idCriteria = array('source' => $this->article1->id(), 'target' => $this->article2->id()); + $idCriteria = ['source' => $this->article1->id(), 'target' => $this->article2->id()]; - $refRep = $this->_em->find("Doctrine\Tests\Models\DDC117\DDC117Reference", $idCriteria); + $refRep = $this->_em->find(DDC117Reference::class, $idCriteria); $this->_em->remove($refRep); $this->_em->flush(); $this->_em->clear(); - $this->assertNull($this->_em->find("Doctrine\Tests\Models\DDC117\DDC117Reference", $idCriteria)); + $this->assertNull($this->_em->find(DDC117Reference::class, $idCriteria)); } /** @@ -143,15 +147,15 @@ public function testRemoveCompositeElement() */ public function testDqlRemoveCompositeElement() { - $idCriteria = array('source' => $this->article1->id(), 'target' => $this->article2->id()); + $idCriteria = ['source' => $this->article1->id(), 'target' => $this->article2->id()]; - $dql = "DELETE "."Doctrine\Tests\Models\DDC117\DDC117Reference r WHERE r.source = ?1 AND r.target = ?2"; + $dql = "DELETE Doctrine\Tests\Models\DDC117\DDC117Reference r WHERE r.source = ?1 AND r.target = ?2"; $this->_em->createQuery($dql) ->setParameter(1, $this->article1->id()) ->setParameter(2, $this->article2->id()) ->execute(); - $this->assertNull($this->_em->find("Doctrine\Tests\Models\DDC117\DDC117Reference", $idCriteria)); + $this->assertNull($this->_em->find(DDC117Reference::class, $idCriteria)); } /** @@ -159,18 +163,18 @@ public function testDqlRemoveCompositeElement() */ public function testInverseSideAccess() { - $this->article1 = $this->_em->find("Doctrine\Tests\Models\DDC117\DDC117Article", $this->article1->id()); + $this->article1 = $this->_em->find(DDC117Article::class, $this->article1->id()); $this->assertEquals(1, count($this->article1->references())); foreach ($this->article1->references() AS $this->reference) { - $this->assertInstanceOf("Doctrine\Tests\Models\DDC117\DDC117Reference", $this->reference); + $this->assertInstanceOf(DDC117Reference::class, $this->reference); $this->assertSame($this->article1, $this->reference->source()); } $this->_em->clear(); - $dql = 'SELECT a, r FROM '. 'Doctrine\Tests\Models\DDC117\DDC117Article a INNER JOIN a.references r WHERE a.id = ?1'; + $dql = 'SELECT a, r FROM Doctrine\Tests\Models\DDC117\DDC117Article a INNER JOIN a.references r WHERE a.id = ?1'; $articleDql = $this->_em->createQuery($dql) ->setParameter(1, $this->article1->id()) ->getSingleResult(); @@ -178,7 +182,7 @@ public function testInverseSideAccess() $this->assertEquals(1, count($this->article1->references())); foreach ($this->article1->references() AS $this->reference) { - $this->assertInstanceOf("Doctrine\Tests\Models\DDC117\DDC117Reference", $this->reference); + $this->assertInstanceOf(DDC117Reference::class, $this->reference); $this->assertSame($this->article1, $this->reference->source()); } } @@ -188,22 +192,22 @@ public function testInverseSideAccess() */ public function testMixedCompositeKey() { - $idCriteria = array('article' => $this->article1->id(), 'language' => 'en'); + $idCriteria = ['article' => $this->article1->id(), 'language' => 'en']; - $this->translation = $this->_em->find('Doctrine\Tests\Models\DDC117\DDC117Translation', $idCriteria); - $this->assertInstanceOf('Doctrine\Tests\Models\DDC117\DDC117Translation', $this->translation); + $this->translation = $this->_em->find(DDC117Translation::class, $idCriteria); + $this->assertInstanceOf(DDC117Translation::class, $this->translation); - $this->assertSame($this->translation, $this->_em->find('Doctrine\Tests\Models\DDC117\DDC117Translation', $idCriteria)); + $this->assertSame($this->translation, $this->_em->find(DDC117Translation::class, $idCriteria)); $this->_em->clear(); - $dql = 'SELECT t, a FROM ' . 'Doctrine\Tests\Models\DDC117\DDC117Translation t JOIN t.article a WHERE t.article = ?1 AND t.language = ?2'; + $dql = 'SELECT t, a FROM Doctrine\Tests\Models\DDC117\DDC117Translation t JOIN t.article a WHERE t.article = ?1 AND t.language = ?2'; $dqlTrans = $this->_em->createQuery($dql) ->setParameter(1, $this->article1->id()) ->setParameter(2, 'en') ->getSingleResult(); - $this->assertInstanceOf('Doctrine\Tests\Models\DDC117\DDC117Translation', $this->translation); + $this->assertInstanceOf(DDC117Translation::class, $this->translation); } /** @@ -211,7 +215,7 @@ public function testMixedCompositeKey() */ public function testMixedCompositeKeyViolateUniqueness() { - $this->article1 = $this->_em->find('Doctrine\Tests\Models\DDC117\DDC117Article', $this->article1->id()); + $this->article1 = $this->_em->find(DDC117Article::class, $this->article1->id()); $this->article1->addTranslation('en', 'Bar'); $this->article1->addTranslation('en', 'Baz'); @@ -265,16 +269,17 @@ public function testOneToOneCascadeRemove() */ public function testOneToOneCascadePersist() { - if (!$this->_em->getConnection()->getDatabasePlatform()->prefersSequences()) { + if ( ! $this->_em->getConnection()->getDatabasePlatform()->prefersSequences()) { $this->markTestSkipped('Test only works with databases that prefer sequences as ID strategy.'); } $this->article1 = new DDC117Article("Foo"); - $this->articleDetails = new DDC117ArticleDetails($this->article1, "Very long text"); $this->_em->persist($this->article1); $this->_em->flush(); + + self::assertSame($this->articleDetails, $this->_em->find(DDC117ArticleDetails::class, $this->article1)); } /** @@ -282,22 +287,22 @@ public function testOneToOneCascadePersist() */ public function testReferencesToForeignKeyEntities() { - $idCriteria = array('source' => $this->article1->id(), 'target' => $this->article2->id()); - $reference = $this->_em->find("Doctrine\Tests\Models\DDC117\DDC117Reference", $idCriteria); + $idCriteria = ['source' => $this->article1->id(), 'target' => $this->article2->id()]; + $reference = $this->_em->find(DDC117Reference::class, $idCriteria); - $idCriteria = array('article' => $this->article1->id(), 'language' => 'en'); - $translation = $this->_em->find('Doctrine\Tests\Models\DDC117\DDC117Translation', $idCriteria); + $idCriteria = ['article' => $this->article1->id(), 'language' => 'en']; + $translation = $this->_em->find(DDC117Translation::class, $idCriteria); $approveChanges = new DDC117ApproveChanges($reference->source()->getDetails(), $reference, $translation); $this->_em->persist($approveChanges); $this->_em->flush(); $this->_em->clear(); - $approveChanges = $this->_em->find("Doctrine\Tests\Models\DDC117\DDC117ApproveChanges", $approveChanges->getId()); + $approveChanges = $this->_em->find(DDC117ApproveChanges::class, $approveChanges->getId()); - $this->assertInstanceOf('Doctrine\Tests\Models\DDC117\DDC117ArticleDetails', $approveChanges->getArticleDetails()); - $this->assertInstanceOf('Doctrine\Tests\Models\DDC117\DDC117Reference', $approveChanges->getReference()); - $this->assertInstanceOf('Doctrine\Tests\Models\DDC117\DDC117Translation', $approveChanges->getTranslation()); + $this->assertInstanceOf(DDC117ArticleDetails::class, $approveChanges->getArticleDetails()); + $this->assertInstanceOf(DDC117Reference::class, $approveChanges->getReference()); + $this->assertInstanceOf(DDC117Translation::class, $approveChanges->getTranslation()); } /** @@ -310,7 +315,7 @@ public function testLoadOneToManyCollectionOfForeignKeyEntities() $translations = $article->getTranslations(); $this->assertFalse($translations->isInitialized()); - $this->assertContainsOnly('Doctrine\Tests\Models\DDC117\DDC117Translation', $translations); + $this->assertContainsOnly(DDC117Translation::class, $translations); $this->assertTrue($translations->isInitialized()); } @@ -322,7 +327,7 @@ public function testLoadManyToManyCollectionOfForeignKeyEntities() $editor = $this->loadEditorFixture(); $this->assertFalse($editor->reviewingTranslations->isInitialized()); - $this->assertContainsOnly("Doctrine\Tests\Models\DDC117\DDC117Translation", $editor->reviewingTranslations); + $this->assertContainsOnly(DDC117Translation::class, $editor->reviewingTranslations); $this->assertTrue($editor->reviewingTranslations->isInitialized()); $this->_em->clear(); @@ -330,7 +335,7 @@ public function testLoadManyToManyCollectionOfForeignKeyEntities() $dql = "SELECT e, t FROM Doctrine\Tests\Models\DDC117\DDC117Editor e JOIN e.reviewingTranslations t WHERE e.id = ?1"; $editor = $this->_em->createQuery($dql)->setParameter(1, $editor->id)->getSingleResult(); $this->assertTrue($editor->reviewingTranslations->isInitialized()); - $this->assertContainsOnly("Doctrine\Tests\Models\DDC117\DDC117Translation", $editor->reviewingTranslations); + $this->assertContainsOnly(DDC117Translation::class, $editor->reviewingTranslations); } /** @@ -356,7 +361,7 @@ public function testLoadInverseManyToManyCollection() { $editor = $this->loadEditorFixture(); - $this->assertInstanceOf('Doctrine\Tests\Models\DDC117\DDC117Translation', $editor->reviewingTranslations[0]); + $this->assertInstanceOf(DDC117Translation::class, $editor->reviewingTranslations[0]); $reviewedBy = $editor->reviewingTranslations[0]->getReviewedByEditors(); $this->assertEquals(1, count($reviewedBy)); @@ -371,8 +376,8 @@ public function testLoadInverseManyToManyCollection() ->setParameter(2, $this->translation->getLanguage()) ->getSingleResult(); - $this->assertInstanceOf('Doctrine\Tests\Models\DDC117\DDC117Translation', $trans); - $this->assertContainsOnly('Doctrine\Tests\Models\DDC117\DDC117Editor', $trans->reviewedByEditors); + $this->assertInstanceOf(DDC117Translation::class, $trans); + $this->assertContainsOnly(DDC117Editor::class, $trans->reviewedByEditors); $this->assertEquals(1, count($trans->reviewedByEditors)); } @@ -429,15 +434,16 @@ private function loadEditorFixture() */ public function testMergeForeignKeyIdentifierEntity() { - $idCriteria = array('source' => $this->article1->id(), 'target' => $this->article2->id()); + $idCriteria = ['source' => $this->article1->id(), 'target' => $this->article2->id()]; - $refRep = $this->_em->find("Doctrine\Tests\Models\DDC117\DDC117Reference", $idCriteria); + $refRep = $this->_em->find(DDC117Reference::class, $idCriteria); - $this->_em->detach($refRep); + $this->_em->clear(DDC117Reference::class); $refRep = $this->_em->merge($refRep); $this->assertEquals($this->article1->id(), $refRep->source()->id()); $this->assertEquals($this->article2->id(), $refRep->target()->id()); + $this->assertHasDeprecationMessages(); } /** @@ -448,8 +454,8 @@ public function testArrayHydrationWithCompositeKey() $dql = "SELECT r,s,t FROM Doctrine\Tests\Models\DDC117\DDC117Reference r INNER JOIN r.source s INNER JOIN r.target t"; $before = count($this->_em->createQuery($dql)->getResult()); - $this->article1 = $this->_em->find("Doctrine\Tests\Models\DDC117\DDC117Article", $this->article1->id()); - $this->article2 = $this->_em->find("Doctrine\Tests\Models\DDC117\DDC117Article", $this->article2->id()); + $this->article1 = $this->_em->find(DDC117Article::class, $this->article1->id()); + $this->article2 = $this->_em->find(DDC117Article::class, $this->article2->id()); $this->reference = new DDC117Reference($this->article2, $this->article1, "Test-Description"); $this->_em->persist($this->reference); @@ -477,15 +483,15 @@ public function testGetEntityState() $this->markTestIncomplete('Second level cache - not supported yet'); } - $this->article1 = $this->_em->find("Doctrine\Tests\Models\DDC117\DDC117Article", $this->article1->id()); - $this->article2 = $this->_em->find("Doctrine\Tests\Models\DDC117\DDC117Article", $this->article2->id()); + $this->article1 = $this->_em->find(DDC117Article::class, $this->article1->id()); + $this->article2 = $this->_em->find(DDC117Article::class, $this->article2->id()); $this->reference = new DDC117Reference($this->article2, $this->article1, "Test-Description"); $this->assertEquals(\Doctrine\ORM\UnitOfWork::STATE_NEW, $this->_em->getUnitOfWork()->getEntityState($this->reference)); - $idCriteria = array('source' => $this->article1->id(), 'target' => $this->article2->id()); - $reference = $this->_em->find("Doctrine\Tests\Models\DDC117\DDC117Reference", $idCriteria); + $idCriteria = ['source' => $this->article1->id(), 'target' => $this->article2->id()]; + $reference = $this->_em->find(DDC117Reference::class, $idCriteria); $this->assertEquals(\Doctrine\ORM\UnitOfWork::STATE_MANAGED, $this->_em->getUnitOfWork()->getEntityState($reference)); } @@ -494,9 +500,9 @@ public function testGetEntityState() */ public function testIndexByOnCompositeKeyField() { - $article = $this->_em->find("Doctrine\Tests\Models\DDC117\DDC117Article", $this->article1->id()); + $article = $this->_em->find(DDC117Article::class, $this->article1->id()); - $this->assertInstanceOf('Doctrine\Tests\Models\DDC117\DDC117Article', $article); + $this->assertInstanceOf(DDC117Article::class, $article); $this->assertEquals(1, count($article->getLinks())); $this->assertTrue($article->getLinks()->offsetExists($this->article2->id())); } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1181Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1181Test.php index b6d82816c0f..564e046e7d3 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1181Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1181Test.php @@ -9,11 +9,13 @@ class DDC1181Test extends OrmFunctionalTestCase public function setUp() { parent::setUp(); - $this->_schemaTool->createSchema(array( - $this->_em->getClassMetadata(__NAMESPACE__ . '\\DDC1181Hotel'), - $this->_em->getClassMetadata(__NAMESPACE__ . '\\DDC1181Booking'), - $this->_em->getClassMetadata(__NAMESPACE__ . '\\DDC1181Room'), - )); + $this->_schemaTool->createSchema( + [ + $this->_em->getClassMetadata(DDC1181Hotel::class), + $this->_em->getClassMetadata(DDC1181Booking::class), + $this->_em->getClassMetadata(DDC1181Room::class), + ] + ); } /** @@ -45,6 +47,8 @@ public function testIssue() $this->_em->remove($hotel); $this->_em->flush(); + + self::assertEmpty($this->_em->getRepository(DDC1181Booking::class)->findAll()); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1193Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1193Test.php index a4ecf5d39e5..f4d98cb23a4 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1193Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1193Test.php @@ -10,11 +10,13 @@ protected function setUp() { parent::setUp(); //$this->_em->getConnection()->getConfiguration()->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger); - $this->_schemaTool->createSchema(array( - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC1193Company'), - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC1193Person'), - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC1193Account') - )); + $this->_schemaTool->createSchema( + [ + $this->_em->getClassMetadata(DDC1193Company::class), + $this->_em->getClassMetadata(DDC1193Person::class), + $this->_em->getClassMetadata(DDC1193Account::class) + ] + ); } /** diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1209Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1209Test.php index 06dde7696a6..6c54da296be 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1209Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1209Test.php @@ -10,11 +10,13 @@ protected function setUp() { parent::setUp(); try { - $this->_schemaTool->createSchema(array( - $this->_em->getClassMetadata(__NAMESPACE__ . '\\DDC1209_1'), - $this->_em->getClassMetadata(__NAMESPACE__ . '\\DDC1209_2'), - $this->_em->getClassMetadata(__NAMESPACE__ . '\\DDC1209_3') - )); + $this->_schemaTool->createSchema( + [ + $this->_em->getClassMetadata(DDC1209_1::class), + $this->_em->getClassMetadata(DDC1209_2::class), + $this->_em->getClassMetadata(DDC1209_3::class) + ] + ); } catch(\Exception $e) { } } @@ -24,8 +26,12 @@ protected function setUp() */ public function testIdentifierCanHaveCustomType() { - $this->_em->persist(new DDC1209_3()); + $entity = new DDC1209_3(); + + $this->_em->persist($entity); $this->_em->flush(); + + self::assertSame($entity, $this->_em->find(DDC1209_3::class, $entity->date)); } /** @@ -34,14 +40,27 @@ public function testIdentifierCanHaveCustomType() public function testCompositeIdentifierCanHaveCustomType() { $future1 = new DDC1209_1(); - $this->_em->persist($future1); + $this->_em->persist($future1); $this->_em->flush(); $future2 = new DDC1209_2($future1); - $this->_em->persist($future2); + $this->_em->persist($future2); $this->_em->flush(); + + self::assertSame( + $future2, + $this->_em->find( + DDC1209_2::class, + [ + 'future1' => $future1, + 'starting_datetime' => $future2->starting_datetime, + 'during_datetime' => $future2->during_datetime, + 'ending_datetime' => $future2->ending_datetime, + ] + ) + ); } } @@ -76,17 +95,19 @@ class DDC1209_2 * @Id * @Column(type="datetime", nullable=false) */ - private $starting_datetime; + public $starting_datetime; + /** * @Id * @Column(type="datetime", nullable=false) */ - private $during_datetime; + public $during_datetime; + /** * @Id * @Column(type="datetime", nullable=false) */ - private $ending_datetime; + public $ending_datetime; public function __construct(DDC1209_1 $future1) { @@ -106,7 +127,7 @@ class DDC1209_3 * @Id * @Column(type="datetime", name="somedate") */ - private $date; + public $date; public function __construct() { diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1225Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1225Test.php index 95ff58fb587..1bfd6b91e15 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1225Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1225Test.php @@ -11,10 +11,12 @@ public function setUp() { parent::setUp(); try { - $this->_schemaTool->createSchema(array( - $this->_em->getClassMetadata(__NAMESPACE__ . '\\DDC1225_TestEntity1'), - $this->_em->getClassMetadata(__NAMESPACE__ . '\\DDC1225_TestEntity2'), - )); + $this->_schemaTool->createSchema( + [ + $this->_em->getClassMetadata(DDC1225_TestEntity1::class), + $this->_em->getClassMetadata(DDC1225_TestEntity2::class), + ] + ); } catch(\PDOException $e) { } @@ -23,7 +25,7 @@ public function setUp() public function testIssue() { $qb = $this->_em->createQueryBuilder(); - $qb->from('Doctrine\Tests\ORM\Functional\Ticket\DDC1225_TestEntity1', 'te1') + $qb->from(DDC1225_TestEntity1::class, 'te1') ->select('te1') ->where('te1.testEntity2 = ?1') ->setParameter(1, 0); diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1228Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1228Test.php index 913a3df768c..b4de087a359 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1228Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1228Test.php @@ -12,10 +12,12 @@ public function setUp() { parent::setUp(); try { - $this->_schemaTool->createSchema(array( - $this->_em->getClassMetadata(__NAMESPACE__ . '\\DDC1228User'), - $this->_em->getClassMetadata(__NAMESPACE__ . '\\DDC1228Profile'), - )); + $this->_schemaTool->createSchema( + [ + $this->_em->getClassMetadata(DDC1228User::class), + $this->_em->getClassMetadata(DDC1228Profile::class), + ] + ); } catch(\Exception $e) { } @@ -33,19 +35,19 @@ public function testOneToOnePersist() $this->_em->flush(); $this->_em->clear(); - $user = $this->_em->find(__NAMESPACE__ . '\\DDC1228User', $user->id); + $user = $this->_em->find(DDC1228User::class, $user->id); $this->assertFalse($user->getProfile()->__isInitialized__, "Proxy is not initialized"); $user->getProfile()->setName("Bar"); $this->assertTrue($user->getProfile()->__isInitialized__, "Proxy is not initialized"); $this->assertEquals("Bar", $user->getProfile()->getName()); - $this->assertEquals(array("id" => 1, "name" => "Foo"), $this->_em->getUnitOfWork()->getOriginalEntityData($user->getProfile())); + $this->assertEquals(["id" => 1, "name" => "Foo"], $this->_em->getUnitOfWork()->getOriginalEntityData($user->getProfile())); $this->_em->flush(); $this->_em->clear(); - $user = $this->_em->find(__NAMESPACE__ . '\\DDC1228User', $user->id); + $user = $this->_em->find(DDC1228User::class, $user->id); $this->assertEquals("Bar", $user->getProfile()->getName()); } @@ -61,14 +63,14 @@ public function testRefresh() $this->_em->flush(); $this->_em->clear(); - $user = $this->_em->getReference(__NAMESPACE__ . '\\DDC1228User', $user->id); + $user = $this->_em->getReference(DDC1228User::class, $user->id); $this->_em->refresh($user); $user->name = "Baz"; $this->_em->flush(); $this->_em->clear(); - $user = $this->_em->find(__NAMESPACE__ . '\\DDC1228User', $user->id); + $user = $this->_em->find(DDC1228User::class, $user->id); $this->assertEquals("Baz", $user->name); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1238Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1238Test.php index dd0f99d0327..00c621eeeef 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1238Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1238Test.php @@ -11,9 +11,11 @@ public function setUp() { parent::setUp(); try { - $this->_schemaTool->createSchema(array( - $this->_em->getClassMetadata(__NAMESPACE__ . '\\DDC1238User'), - )); + $this->_schemaTool->createSchema( + [ + $this->_em->getClassMetadata(DDC1238User::class), + ] + ); } catch(\Exception $e) { } @@ -31,7 +33,7 @@ public function testIssue() $userId = $user->getId(); $this->_em->clear(); - $user = $this->_em->getReference(__NAMESPACE__ . '\\DDC1238User', $userId); + $user = $this->_em->getReference(DDC1238User::class, $userId); $this->_em->clear(); $userId2 = $user->getId(); @@ -52,10 +54,10 @@ public function testIssueProxyClear() $userId = $user->getId(); $this->_em->clear(); - $user = $this->_em->getReference(__NAMESPACE__ . '\\DDC1238User', $userId); + $user = $this->_em->getReference(DDC1238User::class, $userId); $this->_em->clear(); - $user2 = $this->_em->getReference(__NAMESPACE__ . '\\DDC1238User', $userId); + $user2 = $this->_em->getReference(DDC1238User::class, $userId); // force proxy load, getId() doesn't work anymore $user->getName(); diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1250Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1250Test.php index 3d88b8cb164..a09b1761fea 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1250Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1250Test.php @@ -11,9 +11,11 @@ public function setUp() { parent::setUp(); try { - $this->_schemaTool->createSchema(array( - $this->_em->getClassMetadata(__NAMESPACE__ . '\\DDC1250ClientHistory'), - )); + $this->_schemaTool->createSchema( + [ + $this->_em->getClassMetadata(DDC1250ClientHistory::class), + ] + ); } catch(\PDOException $e) { } @@ -36,7 +38,7 @@ public function testIssue() $history = $this->_em->createQuery('SELECT h FROM ' . __NAMESPACE__ . '\\DDC1250ClientHistory h WHERE h.id = ?1') ->setParameter(1, $c2->id)->getSingleResult(); - $this->assertInstanceOf(__NAMESPACE__ . '\\DDC1250ClientHistory', $history); + $this->assertInstanceOf(DDC1250ClientHistory::class, $history); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1276Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1276Test.php index 197d3a2aa48..d340746863d 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1276Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1276Test.php @@ -2,14 +2,17 @@ namespace Doctrine\Tests\ORM\Functional\Ticket; -use Doctrine\Tests\Models\CMS\CmsUser; use Doctrine\Tests\Models\CMS\CmsGroup; +use Doctrine\Tests\Models\CMS\CmsUser; +use Doctrine\Tests\VerifyDeprecations; /** * @group DDC-1276 */ class DDC1276Test extends \Doctrine\Tests\OrmFunctionalTestCase { + use VerifyDeprecations; + public function setUp() { $this->useModelSet('cms'); @@ -33,7 +36,7 @@ public function testIssue() $this->_em->flush(); $this->_em->clear(); - $user = $this->_em->find('Doctrine\Tests\Models\CMS\CmsUser', $user->id); + $user = $this->_em->find(CmsUser::class, $user->id); $cloned = clone $user; $this->assertSame($user->groups, $cloned->groups); @@ -43,5 +46,6 @@ public function testIssue() $this->assertEquals(2, count($user->groups)); $this->_em->flush(); + $this->assertHasDeprecationMessages(); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1300Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1300Test.php index bffb48764f3..4f0038b1c89 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1300Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1300Test.php @@ -10,10 +10,12 @@ class DDC1300Test extends \Doctrine\Tests\OrmFunctionalTestCase public function setUp() { parent::setUp(); - $this->_schemaTool->createSchema(array( - $this->_em->getClassMetadata(__NAMESPACE__ . '\\DDC1300Foo'), - $this->_em->getClassMetadata(__NAMESPACE__ . '\\DDC1300FooLocale'), - )); + $this->_schemaTool->createSchema( + [ + $this->_em->getClassMetadata(DDC1300Foo::class), + $this->_em->getClassMetadata(DDC1300FooLocale::class), + ] + ); } public function testIssue() diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1301Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1301Test.php index f8ccc5a3e95..785b22187ed 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1301Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1301Test.php @@ -3,6 +3,7 @@ namespace Doctrine\Tests\ORM\Functional\Ticket; use Doctrine\ORM\Mapping\ClassMetadataInfo; +use Doctrine\Tests\Models; /** * @author asm89 @@ -19,7 +20,7 @@ public function setUp() $this->useModelSet('legacy'); parent::setUp(); - $class = $this->_em->getClassMetadata('Doctrine\Tests\Models\Legacy\LegacyUser'); + $class = $this->_em->getClassMetadata(Models\Legacy\LegacyUser::class); $class->associationMappings['_articles']['fetch'] = ClassMetadataInfo::FETCH_EXTRA_LAZY; $class->associationMappings['_references']['fetch'] = ClassMetadataInfo::FETCH_EXTRA_LAZY; $class->associationMappings['_cars']['fetch'] = ClassMetadataInfo::FETCH_EXTRA_LAZY; @@ -31,7 +32,7 @@ public function tearDown() { parent::tearDown(); - $class = $this->_em->getClassMetadata('Doctrine\Tests\Models\Legacy\LegacyUser'); + $class = $this->_em->getClassMetadata(Models\Legacy\LegacyUser::class); $class->associationMappings['_articles']['fetch'] = ClassMetadataInfo::FETCH_LAZY; $class->associationMappings['_references']['fetch'] = ClassMetadataInfo::FETCH_LAZY; $class->associationMappings['_cars']['fetch'] = ClassMetadataInfo::FETCH_LAZY; @@ -39,7 +40,7 @@ public function tearDown() public function testCountNotInitializesLegacyCollection() { - $user = $this->_em->find('Doctrine\Tests\Models\Legacy\LegacyUser', $this->userId); + $user = $this->_em->find(Models\Legacy\LegacyUser::class, $this->userId); $queryCount = $this->getCurrentQueryCount(); $this->assertFalse($user->_articles->isInitialized()); @@ -53,7 +54,7 @@ public function testCountNotInitializesLegacyCollection() public function testCountNotInitializesLegacyCollectionWithForeignIdentifier() { - $user = $this->_em->find('Doctrine\Tests\Models\Legacy\LegacyUser', $this->userId); + $user = $this->_em->find(Models\Legacy\LegacyUser::class, $this->userId); $queryCount = $this->getCurrentQueryCount(); $this->assertFalse($user->_references->isInitialized()); @@ -67,7 +68,7 @@ public function testCountNotInitializesLegacyCollectionWithForeignIdentifier() public function testCountNotInitializesLegacyManyToManyCollection() { - $user = $this->_em->find('Doctrine\Tests\Models\Legacy\LegacyUser', $this->userId); + $user = $this->_em->find(Models\Legacy\LegacyUser::class, $this->userId); $queryCount = $this->getCurrentQueryCount(); $this->assertFalse($user->_cars->isInitialized()); @@ -81,17 +82,17 @@ public function testCountNotInitializesLegacyManyToManyCollection() public function loadFixture() { - $user1 = new \Doctrine\Tests\Models\Legacy\LegacyUser(); + $user1 = new Models\Legacy\LegacyUser(); $user1->_username = "beberlei"; $user1->_name = "Benjamin"; $user1->_status = "active"; - $user2 = new \Doctrine\Tests\Models\Legacy\LegacyUser(); + $user2 = new Models\Legacy\LegacyUser(); $user2->_username = "jwage"; $user2->_name = "Jonathan"; $user2->_status = "active"; - $user3 = new \Doctrine\Tests\Models\Legacy\LegacyUser(); + $user3 = new Models\Legacy\LegacyUser(); $user3->_username = "romanb"; $user3->_name = "Roman"; $user3->_status = "active"; @@ -100,12 +101,12 @@ public function loadFixture() $this->_em->persist($user2); $this->_em->persist($user3); - $article1 = new \Doctrine\Tests\Models\Legacy\LegacyArticle(); + $article1 = new Models\Legacy\LegacyArticle(); $article1->_topic = "Test"; $article1->_text = "Test"; $article1->setAuthor($user1); - $article2 = new \Doctrine\Tests\Models\Legacy\LegacyArticle(); + $article2 = new Models\Legacy\LegacyArticle(); $article2->_topic = "Test"; $article2->_text = "Test"; $article2->setAuthor($user1); @@ -113,13 +114,13 @@ public function loadFixture() $this->_em->persist($article1); $this->_em->persist($article2); - $car1 = new \Doctrine\Tests\Models\Legacy\LegacyCar(); + $car1 = new Models\Legacy\LegacyCar(); $car1->_description = "Test1"; - $car2 = new \Doctrine\Tests\Models\Legacy\LegacyCar(); + $car2 = new Models\Legacy\LegacyCar(); $car2->_description = "Test2"; - $car3 = new \Doctrine\Tests\Models\Legacy\LegacyCar(); + $car3 = new Models\Legacy\LegacyCar(); $car3->_description = "Test3"; $user1->addCar($car1); @@ -135,8 +136,8 @@ public function loadFixture() $this->_em->flush(); - $detail1 = new \Doctrine\Tests\Models\Legacy\LegacyUserReference($user1, $user2, "foo"); - $detail2 = new \Doctrine\Tests\Models\Legacy\LegacyUserReference($user1, $user3, "bar"); + $detail1 = new Models\Legacy\LegacyUserReference($user1, $user2, "foo"); + $detail2 = new Models\Legacy\LegacyUserReference($user1, $user3, "bar"); $this->_em->persist($detail1); $this->_em->persist($detail2); diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1306Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1306Test.php index 4818c82ad4b..03c761a959c 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1306Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1306Test.php @@ -2,6 +2,7 @@ namespace Doctrine\Tests\ORM\Functional\Ticket; +use Doctrine\Tests\Models\CMS\CmsAddress; use Doctrine\Tests\Models\CMS\CmsUser; use Doctrine\Tests\Models\CMS\CmsPhonenumber; @@ -13,6 +14,7 @@ class DDC1306Test extends \Doctrine\Tests\OrmFunctionalTestCase public function setUp() { $this->useModelSet('cms'); + parent::setUp(); } @@ -25,7 +27,7 @@ public function testIssue() $this->_em->persist($phone); $this->_em->flush(); - $address = new \Doctrine\Tests\Models\CMS\CmsAddress(); + $address = new CmsAddress(); $address->city = "bonn"; $address->country = "Germany"; $address->street = "somestreet!"; @@ -46,5 +48,8 @@ public function testIssue() $this->_em->remove($user->getAddress()); $this->_em->remove($user); $this->_em->flush(); + + self::assertEmpty($this->_em->getRepository(CmsAddress::class)->findAll()); + self::assertEmpty($this->_em->getRepository(CmsUser::class)->findAll()); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1335Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1335Test.php index 911a4bf618b..dd475559472 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1335Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1335Test.php @@ -11,10 +11,12 @@ protected function setUp() { parent::setUp(); try { - $this->_schemaTool->createSchema(array( - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC1335User'), - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC1335Phone'), - )); + $this->_schemaTool->createSchema( + [ + $this->_em->getClassMetadata(DDC1335User::class), + $this->_em->getClassMetadata(DDC1335Phone::class), + ] + ); $this->loadFixture(); } catch(\Exception $e) { } @@ -65,7 +67,7 @@ public function testDql() public function testTicket() { $builder = $this->_em->createQueryBuilder(); - $builder->select('u')->from(__NAMESPACE__ . '\DDC1335User', 'u', 'u.id'); + $builder->select('u')->from(DDC1335User::class, 'u', 'u.id'); $dql = $builder->getQuery()->getDQL(); $result = $builder->getQuery()->getResult(); @@ -80,7 +82,7 @@ public function testTicket() public function testIndexByUnique() { $builder = $this->_em->createQueryBuilder(); - $builder->select('u')->from(__NAMESPACE__ . '\DDC1335User', 'u', 'u.email'); + $builder->select('u')->from(DDC1335User::class, 'u', 'u.email'); $dql = $builder->getQuery()->getDQL(); $result = $builder->getQuery()->getResult(); @@ -96,7 +98,7 @@ public function testIndexWithJoin() { $builder = $this->_em->createQueryBuilder(); $builder->select('u','p') - ->from(__NAMESPACE__ . '\DDC1335User', 'u', 'u.email') + ->from(DDC1335User::class, 'u', 'u.email') ->join('u.phones', 'p', null, null, 'p.id'); $dql = $builder->getQuery()->getDQL(); @@ -128,9 +130,9 @@ public function testIndexWithJoin() private function loadFixture() { - $p1 = array('11 xxxx-xxxx','11 yyyy-yyyy','11 zzzz-zzzz'); - $p2 = array('22 xxxx-xxxx','22 yyyy-yyyy','22 zzzz-zzzz'); - $p3 = array('33 xxxx-xxxx','33 yyyy-yyyy','33 zzzz-zzzz'); + $p1 = ['11 xxxx-xxxx','11 yyyy-yyyy','11 zzzz-zzzz']; + $p2 = ['22 xxxx-xxxx','22 yyyy-yyyy','22 zzzz-zzzz']; + $p3 = ['33 xxxx-xxxx','33 yyyy-yyyy','33 zzzz-zzzz']; $u1 = new DDC1335User("foo@foo.com", "Foo",$p1); $u2 = new DDC1335User("bar@bar.com", "Bar",$p2); @@ -171,7 +173,7 @@ class DDC1335User */ public $phones; - public function __construct($email, $name, array $numbers = array()) + public function __construct($email, $name, array $numbers = []) { $this->name = $name; $this->email = $email; diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1360Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1360Test.php index e423de5bbf8..6e71e6fc742 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1360Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1360Test.php @@ -15,15 +15,18 @@ public function testSchemaDoubleQuotedCreate() $this->markTestSkipped("PostgreSQL only test."); } - $sql = $this->_schemaTool->getCreateSchemaSql(array( - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC1360DoubleQuote') - )); + $sql = $this->_schemaTool->getCreateSchemaSql( + [ + $this->_em->getClassMetadata(DDC1360DoubleQuote::class) + ] + ); - $this->assertEquals(array( + $this->assertEquals( + [ 'CREATE SCHEMA user', 'CREATE TABLE "user"."user" (id INT NOT NULL, PRIMARY KEY(id))', 'CREATE SEQUENCE "user"."user_id_seq" INCREMENT BY 1 MINVALUE 1 START 1', - ), $sql); + ], $sql); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1383Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1383Test.php index fb6ae25e63f..ca75f905508 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1383Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1383Test.php @@ -2,20 +2,26 @@ namespace Doctrine\Tests\ORM\Functional\Ticket; +use Doctrine\Tests\VerifyDeprecations; + /** * @group DDC-1383 */ class DDC1383Test extends \Doctrine\Tests\OrmFunctionalTestCase { + use VerifyDeprecations; + protected function setUp() { parent::setUp(); try { - $this->_schemaTool->createSchema(array( - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC1383AbstractEntity'), - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC1383Entity'), - )); + $this->_schemaTool->createSchema( + [ + $this->_em->getClassMetadata(DDC1383AbstractEntity::class), + $this->_em->getClassMetadata(DDC1383Entity::class), + ] + ); } catch(\Exception $ignored) {} } @@ -45,6 +51,7 @@ public function testFailingCase() // Parent is NOT instance of entity self::assertTrue($parent instanceof DDC1383Entity, "Entity class is " . get_class($parent) . ', "DDC1383Entity" was expected'); + $this->assertHasDeprecationMessages(); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1392Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1392Test.php index 2e0df824b90..b872e413b50 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1392Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1392Test.php @@ -3,21 +3,26 @@ namespace Doctrine\Tests\ORM\Functional\Ticket; use Doctrine\ORM\UnitOfWork; +use Doctrine\Tests\VerifyDeprecations; /** * @group DDC-1392 */ class DDC1392Test extends \Doctrine\Tests\OrmFunctionalTestCase { + use VerifyDeprecations; + protected function setUp() { parent::setUp(); try { - $this->_schemaTool->createSchema(array( - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC1392File'), - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC1392Picture'), - )); + $this->_schemaTool->createSchema( + [ + $this->_em->getClassMetadata(DDC1392File::class), + $this->_em->getClassMetadata(DDC1392Picture::class), + ] + ); } catch (\Exception $ignored) { } } @@ -39,7 +44,7 @@ public function testFailingCase() $this->assertTrue($fileId > 0); - $picture = $em->find(__NAMESPACE__ . '\DDC1392Picture', $pictureId); + $picture = $em->find(DDC1392Picture::class, $pictureId); $this->assertEquals(UnitOfWork::STATE_MANAGED, $em->getUnitOfWork()->getEntityState($picture->getFile()), "Lazy Proxy should be marked MANAGED."); $file = $picture->getFile(); @@ -59,6 +64,7 @@ public function testFailingCase() $result = $q->getSingleScalarResult(); self::assertEquals(1, $result); + $this->assertHasDeprecationMessages(); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1400Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1400Test.php index 41183ffdda0..1248fe8412d 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1400Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1400Test.php @@ -12,11 +12,13 @@ protected function setUp() parent::setUp(); try { - $this->_schemaTool->createSchema(array( - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC1400Article'), - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC1400User'), - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC1400UserState'), - )); + $this->_schemaTool->createSchema( + [ + $this->_em->getClassMetadata(DDC1400Article::class), + $this->_em->getClassMetadata(DDC1400User::class), + $this->_em->getClassMetadata(DDC1400UserState::class), + ] + ); } catch (\Exception $ignored) { } } @@ -46,17 +48,20 @@ public function testFailingCase() $this->_em->persist($userState1); $this->_em->persist($userState2); - $this->_em->flush(); $this->_em->clear(); - $user1 = $this->_em->getReference(__NAMESPACE__.'\DDC1400User', $user1->id); + $user1 = $this->_em->getReference(DDC1400User::class, $user1->id); + + $this->_em->createQuery('SELECT a, s FROM ' . DDC1400Article::class . ' a JOIN a.userStates s WITH s.user = :activeUser') + ->setParameter('activeUser', $user1) + ->getResult(); - $q = $this->_em->createQuery("SELECT a, s FROM ".__NAMESPACE__."\DDC1400Article a JOIN a.userStates s WITH s.user = :activeUser"); - $q->setParameter('activeUser', $user1); - $articles = $q->getResult(); + $queryCount = $this->getCurrentQueryCount(); $this->_em->flush(); + + self::assertSame($queryCount, $this->getCurrentQueryCount(), 'No query should be executed during flush in this case'); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1404Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1404Test.php index 322582c20b4..b3a1a939d21 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1404Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1404Test.php @@ -13,10 +13,12 @@ protected function setUp() parent::setUp(); try { - $this->_schemaTool->createSchema(array( - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC1404ParentEntity'), - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC1404ChildEntity'), - )); + $this->_schemaTool->createSchema( + [ + $this->_em->getClassMetadata(DDC1404ParentEntity::class), + $this->_em->getClassMetadata(DDC1404ChildEntity::class), + ] + ); $this->loadFixtures(); @@ -26,7 +28,7 @@ protected function setUp() public function testTicket() { - $repository = $this->_em->getRepository(__NAMESPACE__ . '\DDC1404ChildEntity'); + $repository = $this->_em->getRepository(DDC1404ChildEntity::class); $queryAll = $repository->createNamedQuery('all'); $queryFirst = $repository->createNamedQuery('first'); $querySecond = $repository->createNamedQuery('second'); diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC142Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC142Test.php index c985d61acbf..ae455f546a2 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC142Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC142Test.php @@ -11,20 +11,11 @@ */ class DDC142Test extends \Doctrine\Tests\OrmFunctionalTestCase { - - protected function setUp() + protected function setUp() : void { - parent::setUp(); + $this->useModelSet('quote'); - try { - $this->_schemaTool->createSchema(array( - $this->_em->getClassMetadata('Doctrine\Tests\Models\Quote\User'), - $this->_em->getClassMetadata('Doctrine\Tests\Models\Quote\Group'), - $this->_em->getClassMetadata('Doctrine\Tests\Models\Quote\Phone'), - $this->_em->getClassMetadata('Doctrine\Tests\Models\Quote\Address'), - )); - } catch(\Exception $e) { - } + parent::setUp(); } public function testCreateRetrieveUpdateDelete() @@ -40,7 +31,7 @@ public function testCreateRetrieveUpdateDelete() $this->_em->flush(); - $addressRef = $this->_em->getReference('Doctrine\Tests\Models\Quote\Address', $address->getId()); + $addressRef = $this->_em->getReference(Address::class, $address->getId()); $user->setAddress($addressRef); @@ -50,12 +41,12 @@ public function testCreateRetrieveUpdateDelete() $id = $user->id; $this->assertNotNull($id); - - $user = $this->_em->find('Doctrine\Tests\Models\Quote\User', $id); + + $user = $this->_em->find(User::class, $id); $address = $user->getAddress(); - $this->assertInstanceOf('Doctrine\Tests\Models\Quote\User', $user); - $this->assertInstanceOf('Doctrine\Tests\Models\Quote\Address', $user->getAddress()); + $this->assertInstanceOf(User::class, $user); + $this->assertInstanceOf(Address::class, $user->getAddress()); $this->assertEquals('FabioBatSilva', $user->name); $this->assertEquals('12345', $address->zip); @@ -70,18 +61,18 @@ public function testCreateRetrieveUpdateDelete() $this->_em->clear(); - $user = $this->_em->find('Doctrine\Tests\Models\Quote\User', $id); - $this->assertInstanceOf('Doctrine\Tests\Models\Quote\User', $user); + $user = $this->_em->find(User::class, $id); + $this->assertInstanceOf(User::class, $user); $this->assertNull($user->getAddress()); $this->assertEquals('FabioBatSilva1', $user->name); - - + + $this->_em->remove($user); $this->_em->flush(); $this->_em->clear(); - $this->assertNull($this->_em->find('Doctrine\Tests\Models\Quote\User', $id)); + $this->assertNull($this->_em->find(User::class, $id)); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1430Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1430Test.php index 30e681d727b..6b08a832675 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1430Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1430Test.php @@ -13,10 +13,12 @@ protected function setUp() parent::setUp(); try { - $this->_schemaTool->createSchema(array( - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC1430Order'), - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC1430OrderProduct'), - )); + $this->_schemaTool->createSchema( + [ + $this->_em->getClassMetadata(DDC1430Order::class), + $this->_em->getClassMetadata(DDC1430OrderProduct::class), + ] + ); $this->loadFixtures(); } catch (\Exception $exc) { @@ -25,7 +27,7 @@ protected function setUp() public function testOrderByFields() { - $repository = $this->_em->getRepository(__NAMESPACE__ . '\DDC1430Order'); + $repository = $this->_em->getRepository(DDC1430Order::class); $builder = $repository->createQueryBuilder('o'); $query = $builder->select('o.id, o.date, COUNT(p.id) AS p_count') ->leftJoin('o.products', 'p') @@ -56,7 +58,7 @@ public function testOrderByFields() public function testOrderByAllObjectFields() { - $repository = $this->_em->getRepository(__NAMESPACE__ . '\DDC1430Order'); + $repository = $this->_em->getRepository(DDC1430Order::class); $builder = $repository->createQueryBuilder('o'); $query = $builder->select('o, COUNT(p.id) AS p_count') ->leftJoin('o.products', 'p') @@ -85,7 +87,7 @@ public function testOrderByAllObjectFields() public function testTicket() { - $repository = $this->_em->getRepository(__NAMESPACE__ . '\DDC1430Order'); + $repository = $this->_em->getRepository(DDC1430Order::class); $builder = $repository->createQueryBuilder('o'); $query = $builder->select('o, COUNT(p.id) AS p_count') ->leftJoin('o.products', 'p') diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1436Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1436Test.php index fa25c69e0aa..9ffa497cd4d 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1436Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1436Test.php @@ -12,9 +12,11 @@ protected function setUp() parent::setUp(); try { - $this->_schemaTool->createSchema(array( - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC1436Page'), - )); + $this->_schemaTool->createSchema( + [ + $this->_em->getClassMetadata(DDC1436Page::class), + ] + ); } catch (\Exception $ignored) { } } @@ -40,13 +42,13 @@ public function testIdentityMap() ->setParameter('id', $id) ->getOneOrNullResult(); - $this->assertInstanceOf(__NAMESPACE__ . '\DDC1436Page', $page); + $this->assertInstanceOf(DDC1436Page::class, $page); // step 2 - $page = $this->_em->find(__NAMESPACE__ . '\DDC1436Page', $id); - $this->assertInstanceOf(__NAMESPACE__ . '\DDC1436Page', $page); - $this->assertInstanceOf(__NAMESPACE__ . '\DDC1436Page', $page->getParent()); - $this->assertInstanceOf(__NAMESPACE__ . '\DDC1436Page', $page->getParent()->getParent()); + $page = $this->_em->find(DDC1436Page::class, $id); + $this->assertInstanceOf(DDC1436Page::class, $page); + $this->assertInstanceOf(DDC1436Page::class, $page->getParent()); + $this->assertInstanceOf(DDC1436Page::class, $page->getParent()->getParent()); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC144Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC144Test.php index 2fc8eef93e5..3866c588db0 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC144Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC144Test.php @@ -8,13 +8,13 @@ class DDC144Test extends OrmFunctionalTestCase { protected function setUp() { parent::setUp(); - //$this->_em->getConnection()->getConfiguration()->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger); - $this->_schemaTool->createSchema(array( - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC144FlowElement'), - // $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC144Expression'), - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC144Operand'), - )); + $this->_schemaTool->createSchema( + [ + $this->_em->getClassMetadata(DDC144FlowElement::class), + $this->_em->getClassMetadata(DDC144Operand::class), + ] + ); } @@ -23,13 +23,14 @@ protected function setUp() { */ public function testIssue() { - $operand = new DDC144Operand; $operand->property = 'flowValue'; $operand->operandProperty = 'operandValue'; + $this->_em->persist($operand); $this->_em->flush(); + self::assertSame($operand, $this->_em->find(DDC144Operand::class, $operand->id)); } } @@ -40,23 +41,30 @@ public function testIssue() * @DiscriminatorColumn(type="string", name="discr") * @DiscriminatorMap({"flowelement" = "DDC144FlowElement", "operand" = "DDC144Operand"}) */ -class DDC144FlowElement { +class DDC144FlowElement +{ /** * @Id @Column(type="integer") @GeneratedValue * @var int */ public $id; + /** @Column */ public $property; } -abstract class DDC144Expression extends DDC144FlowElement { - abstract function method(); +abstract class DDC144Expression extends DDC144FlowElement +{ + abstract public function method(); } /** @Entity @Table(name="ddc144_operands") */ -class DDC144Operand extends DDC144Expression { +class DDC144Operand extends DDC144Expression +{ /** @Column */ public $operandProperty; - function method() {} + + public function method() + { + } } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1452Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1452Test.php index 4db5fe0cb19..7e7ecc4f841 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1452Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1452Test.php @@ -3,6 +3,9 @@ namespace Doctrine\Tests\ORM\Functional\Ticket; use Doctrine\Common\Collections\ArrayCollection; +use Doctrine\Common\Collections\Collection; +use Doctrine\ORM\Proxy\Proxy; +use Doctrine\Tests\Models\CMS\CmsUser; /** * @group DDC-1452 @@ -15,10 +18,12 @@ protected function setUp() parent::setUp(); try { - $this->_schemaTool->createSchema(array( - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC1452EntityA'), - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC1452EntityB'), - )); + $this->_schemaTool->createSchema( + [ + $this->_em->getClassMetadata(DDC1452EntityA::class), + $this->_em->getClassMetadata(DDC1452EntityB::class), + ] + ); } catch (\Exception $ignored) { } } @@ -45,8 +50,8 @@ public function testIssue() $results = $this->_em->createQuery($dql)->setMaxResults(1)->getResult(); $this->assertSame($results[0], $results[0]->entitiesB[0]->entityAFrom); - $this->assertFalse( $results[0]->entitiesB[0]->entityATo instanceof \Doctrine\ORM\Proxy\Proxy ); - $this->assertInstanceOf('Doctrine\Common\Collections\Collection', $results[0]->entitiesB[0]->entityATo->getEntitiesB()); + $this->assertFalse( $results[0]->entitiesB[0]->entityATo instanceof Proxy); + $this->assertInstanceOf(Collection::class, $results[0]->entitiesB[0]->entityATo->getEntitiesB()); } public function testFetchJoinOneToOneFromInverse() @@ -57,7 +62,7 @@ public function testFetchJoinOneToOneFromInverse() $address->street = "Somestreet"; $address->zip = 12345; - $user = new \Doctrine\Tests\Models\CMS\CmsUser(); + $user = new CmsUser(); $user->name = "beberlei"; $user->username = "beberlei"; $user->status = "active"; @@ -73,12 +78,12 @@ public function testFetchJoinOneToOneFromInverse() $data = $this->_em->createQuery($dql)->getResult(); $this->_em->clear(); - $this->assertFalse($data[0]->user instanceof \Doctrine\ORM\Proxy\Proxy); + $this->assertFalse($data[0]->user instanceof Proxy); $dql = "SELECT u, a FROM Doctrine\Tests\Models\CMS\CmsUser u INNER JOIN u.address a"; $data = $this->_em->createQuery($dql)->getResult(); - $this->assertFalse($data[0]->address instanceof \Doctrine\ORM\Proxy\Proxy); + $this->assertFalse($data[0]->address instanceof Proxy); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1454Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1454Test.php index 02e9003170b..f10065cd887 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1454Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1454Test.php @@ -2,6 +2,8 @@ namespace Doctrine\Tests\ORM\Functional\Ticket; +use Doctrine\ORM\UnitOfWork; + /** * @group DDC-1454 */ @@ -12,21 +14,22 @@ protected function setUp() parent::setUp(); try { - $this->_schemaTool->createSchema(array( - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC1454File'), - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC1454Picture'), - )); + $this->_schemaTool->createSchema( + [ + $this->_em->getClassMetadata(DDC1454File::class), + $this->_em->getClassMetadata(DDC1454Picture::class), + ] + ); } catch (\Exception $ignored) { - } } public function testFailingCase() { $pic = new DDC1454Picture(); - $this->_em->getUnitOfWork()->getEntityState($pic); - } + self::assertSame(UnitOfWork::STATE_NEW, $this->_em->getUnitOfWork()->getEntityState($pic)); + } } /** @@ -34,7 +37,6 @@ public function testFailingCase() */ class DDC1454Picture extends DDC1454File { - } /** @@ -51,14 +53,16 @@ class DDC1454File */ public $fileId; - public function __construct() { - $this->fileId = rand(); + public function __construct() + { + $this->fileId = random_int(0, getrandmax()); } /** * Get fileId */ - public function getFileId() { + public function getFileId() + { return $this->fileId; } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1458Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1458Test.php index f04e6cb01a4..72d79cd432f 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1458Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1458Test.php @@ -9,10 +9,12 @@ class DDC1258Test extends OrmFunctionalTestCase public function setUp() { parent::setUp(); - $this->_schemaTool->createSchema(array( - $this->_em->getClassMetadata(__NAMESPACE__ . '\TestEntity'), - $this->_em->getClassMetadata(__NAMESPACE__ . '\TestAdditionalEntity') - )); + $this->_schemaTool->createSchema( + [ + $this->_em->getClassMetadata(TestEntity::class), + $this->_em->getClassMetadata(TestAdditionalEntity::class) + ] + ); } public function testIssue() @@ -27,7 +29,7 @@ public function testIssue() // So here the value is 3 $this->assertEquals(3, $testEntity->getValue()); - $test = $this->_em->getRepository(__NAMESPACE__ . '\TestEntity')->find(1); + $test = $this->_em->getRepository(TestEntity::class)->find(1); // New value is set $test->setValue(5); diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1461Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1461Test.php index bfa4691558c..da7100d683e 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1461Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1461Test.php @@ -12,10 +12,12 @@ public function setUp() parent::setUp(); try { - $this->_schemaTool->createSchema(array( - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC1461TwitterAccount'), - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC1461User') - )); + $this->_schemaTool->createSchema( + [ + $this->_em->getClassMetadata(DDC1461TwitterAccount::class), + $this->_em->getClassMetadata(DDC1461User::class) + ] + ); } catch(\Exception $e) { } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1509Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1509Test.php index edceef666ca..a2f9c1904a9 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1509Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1509Test.php @@ -2,22 +2,27 @@ namespace Doctrine\Tests\ORM\Functional\Ticket; +use Doctrine\Tests\VerifyDeprecations; + /** * @group DDC-1509 */ class DDC1509Test extends \Doctrine\Tests\OrmFunctionalTestCase { + use VerifyDeprecations; protected function setUp() { parent::setUp(); try { - $this->_schemaTool->createSchema(array( - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC1509AbstractFile'), - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC1509File'), - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC1509Picture'), - )); + $this->_schemaTool->createSchema( + [ + $this->_em->getClassMetadata(DDC1509AbstractFile::class), + $this->_em->getClassMetadata(DDC1509File::class), + $this->_em->getClassMetadata(DDC1509Picture::class), + ] + ); } catch (\Exception $ignored) { } @@ -46,6 +51,7 @@ public function testFailingCase() $this->assertNotNull($pic->getThumbnail()); $this->assertNotNull($pic->getFile()); + $this->assertHasDeprecationMessages(); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1514Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1514Test.php index daaa69b2a6f..1fc8a06efad 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1514Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1514Test.php @@ -14,11 +14,13 @@ protected function setUp() parent::setUp(); try { - $this->_schemaTool->createSchema(array( - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC1514EntityA'), - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC1514EntityB'), - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC1514EntityC'), - )); + $this->_schemaTool->createSchema( + [ + $this->_em->getClassMetadata(DDC1514EntityA::class), + $this->_em->getClassMetadata(DDC1514EntityB::class), + $this->_em->getClassMetadata(DDC1514EntityC::class), + ] + ); } catch (\Exception $ignored) { } } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1515Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1515Test.php index 9116a4df14d..294ae87388f 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1515Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1515Test.php @@ -11,10 +11,12 @@ class DDC1515Test extends \Doctrine\Tests\OrmFunctionalTestCase public function setUp() { parent::setUp(); - $this->_schemaTool->createSchema(array( - $this->_em->getClassMetadata(__NAMESPACE__ . '\\DDC1515Foo'), - $this->_em->getClassMetadata(__NAMESPACE__ . '\\DDC1515Bar'), - )); + $this->_schemaTool->createSchema( + [ + $this->_em->getClassMetadata(DDC1515Foo::class), + $this->_em->getClassMetadata(DDC1515Bar::class), + ] + ); } public function testIssue() @@ -29,8 +31,8 @@ public function testIssue() $this->_em->flush(); $this->_em->clear(); - $bar = $this->_em->find(__NAMESPACE__ . '\DDC1515Bar', $bar->id); - $this->assertInstanceOf(__NAMESPACE__.'\DDC1515Foo', $bar->foo); + $bar = $this->_em->find(DDC1515Bar::class, $bar->id); + $this->assertInstanceOf(DDC1515Foo::class, $bar->foo); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1526Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1526Test.php index e2d770a5348..7a76e3fb938 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1526Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1526Test.php @@ -10,14 +10,16 @@ class DDC1526Test extends \Doctrine\Tests\OrmFunctionalTestCase public function setUp() { parent::setUp(); - $this->_schemaTool->createSchema(array( - $this->_em->getClassMetadata(__NAMESPACE__ . '\\DDC1526Menu'), - )); + $this->_schemaTool->createSchema( + [ + $this->_em->getClassMetadata(DDC1526Menu::class), + ] + ); } public function testIssue() { - $parents = array(); + $parents = []; for ($i = 0; $i < 9; $i++) { $entity = new DDC1526Menu; diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1545Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1545Test.php index 7f79ac96ee7..20ebe424c5c 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1545Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1545Test.php @@ -58,9 +58,9 @@ public function testLinkObjects() $this->initDb(false); // don't join association - $article = $this->_em->find('Doctrine\Tests\Models\Cms\CmsArticle', $this->articleId); + $article = $this->_em->find(CmsArticle::class, $this->articleId); - $user = $this->_em->find('Doctrine\Tests\Models\Cms\CmsUser', $this->userId); + $user = $this->_em->find(CmsUser::class, $this->userId); $article->user = $user; @@ -86,7 +86,7 @@ public function testLinkObjectsWithAssociationLoaded() ->setParameter('id', $this->articleId) ->getOneOrNullResult(); - $user = $this->_em->find('Doctrine\Tests\Models\Cms\CmsUser', $this->userId); + $user = $this->_em->find(CmsUser::class, $this->userId); $article->user = $user; @@ -107,7 +107,7 @@ public function testUnlinkObjects() $this->initDb(true); // don't join association - $article = $this->_em->find('Doctrine\Tests\Models\Cms\CmsArticle', $this->articleId); + $article = $this->_em->find(CmsArticle::class, $this->articleId); $article->user = null; @@ -150,9 +150,9 @@ public function testChangeLink() $this->initDb(false); // don't join association - $article = $this->_em->find('Doctrine\Tests\Models\Cms\CmsArticle', $this->articleId); + $article = $this->_em->find(CmsArticle::class, $this->articleId); - $user2 = $this->_em->find('Doctrine\Tests\Models\Cms\CmsUser', $this->user2Id); + $user2 = $this->_em->find(CmsUser::class, $this->user2Id); $article->user = $user2; @@ -178,7 +178,7 @@ public function testChangeLinkWithAssociationLoaded() ->setParameter('id', $this->articleId) ->getOneOrNullResult(); - $user2 = $this->_em->find('Doctrine\Tests\Models\Cms\CmsUser', $this->user2Id); + $user2 = $this->_em->find(CmsUser::class, $this->user2Id); $article->user = $user2; diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1548Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1548Test.php index 74c1fe1d530..6628586cc91 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1548Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1548Test.php @@ -10,11 +10,13 @@ class DDC1548Test extends \Doctrine\Tests\OrmFunctionalTestCase public function setUp() { parent::setUp(); - $this->_schemaTool->createSchema(array( - $this->_em->getClassMetadata(__NAMESPACE__ . '\\DDC1548E1'), - $this->_em->getClassMetadata(__NAMESPACE__ . '\\DDC1548E2'), - $this->_em->getClassMetadata(__NAMESPACE__ . '\\DDC1548Rel'), - )); + $this->_schemaTool->createSchema( + [ + $this->_em->getClassMetadata(DDC1548E1::class), + $this->_em->getClassMetadata(DDC1548E2::class), + $this->_em->getClassMetadata(DDC1548Rel::class), + ] + ); } public function testIssue() @@ -29,7 +31,7 @@ public function testIssue() $this->_em->flush(); $this->_em->clear(); - $obt = $this->_em->find(__NAMESPACE__ . '\DDC1548Rel', $rel->id); + $obt = $this->_em->find(DDC1548Rel::class, $rel->id); $this->assertNull($obt->e2); } @@ -78,4 +80,4 @@ class DDC1548Rel * @OneToOne(targetEntity="DDC1548E2", mappedBy="rel") */ public $e2; -} \ No newline at end of file +} diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1594Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1594Test.php index 0c94f73d54c..00cd70a3c09 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1594Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1594Test.php @@ -3,12 +3,15 @@ namespace Doctrine\Tests\ORM\Functional\Ticket; use Doctrine\Tests\Models\CMS\CmsUser; +use Doctrine\Tests\VerifyDeprecations; /** * @group DDC-1594 */ class DDC1594Test extends \Doctrine\Tests\OrmFunctionalTestCase { + use VerifyDeprecations; + public function setUp() { $this->useModelSet('cms'); @@ -37,5 +40,6 @@ public function testIssue() $this->assertNotSame($mergedUser, $detachedUser); $this->assertEquals('bar', $detachedUser->getName()); $this->assertEquals('bar', $mergedUser->getName()); + $this->assertHasDeprecationMessages(); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1595Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1595Test.php index 144894f179d..5f0e128b5c0 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1595Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1595Test.php @@ -15,11 +15,13 @@ public function setUp() $this->_em->getConnection()->getConfiguration()->setSQLLogger(new \Doctrine\DBAL\Logging\DebugStack); - $this->_schemaTool->createSchema(array( - $this->_em->getClassMetadata(__NAMESPACE__ . '\\DDC1595BaseInheritance'), - $this->_em->getClassMetadata(__NAMESPACE__ . '\\DDC1595InheritedEntity1'), - $this->_em->getClassMetadata(__NAMESPACE__ . '\\DDC1595InheritedEntity2'), - )); + $this->_schemaTool->createSchema( + [ + $this->_em->getClassMetadata(DDC1595BaseInheritance::class), + $this->_em->getClassMetadata(DDC1595InheritedEntity1::class), + $this->_em->getClassMetadata(DDC1595InheritedEntity2::class), + ] + ); } public function testIssue() @@ -31,7 +33,7 @@ public function testIssue() $this->_em->clear(); $sqlLogger = $this->_em->getConnection()->getConfiguration()->getSQLLogger(); - $repository = $this->_em->getRepository(__NAMESPACE__ . '\\DDC1595InheritedEntity1'); + $repository = $this->_em->getRepository(DDC1595InheritedEntity1::class); $entity1 = $repository->find($e1->id); diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1654Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1654Test.php index a63eab8eb0d..a5a620f63da 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1654Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1654Test.php @@ -10,10 +10,12 @@ class DDC1654Test extends \Doctrine\Tests\OrmFunctionalTestCase public function setUp() { parent::setUp(); - $this->setUpEntitySchema(array( - __NAMESPACE__ . '\\DDC1654Post', - __NAMESPACE__ . '\\DDC1654Comment', - )); + $this->setUpEntitySchema( + [ + DDC1654Post::class, + DDC1654Comment::class, + ] + ); } public function tearDown() @@ -39,7 +41,7 @@ public function testManyToManyRemoveFromCollectionOrphanRemoval() $this->_em->flush(); $this->_em->clear(); - $comments = $this->_em->getRepository(__NAMESPACE__ . '\\DDC1654Comment')->findAll(); + $comments = $this->_em->getRepository(DDC1654Comment::class)->findAll(); $this->assertEquals(0, count($comments)); } @@ -58,7 +60,7 @@ public function testManyToManyRemoveElementFromCollectionOrphanRemoval() $this->_em->flush(); $this->_em->clear(); - $comments = $this->_em->getRepository(__NAMESPACE__ . '\\DDC1654Comment')->findAll(); + $comments = $this->_em->getRepository(DDC1654Comment::class)->findAll(); $this->assertEquals(0, count($comments)); } @@ -81,7 +83,7 @@ public function testManyToManyRemoveElementFromReAddToCollectionOrphanRemoval() $this->_em->flush(); $this->_em->clear(); - $comments = $this->_em->getRepository(__NAMESPACE__ . '\\DDC1654Comment')->findAll(); + $comments = $this->_em->getRepository(DDC1654Comment::class)->findAll(); $this->assertEquals(2, count($comments)); } @@ -99,7 +101,7 @@ public function testManyToManyClearCollectionOrphanRemoval() $this->_em->flush(); $this->_em->clear(); - $comments = $this->_em->getRepository(__NAMESPACE__ . '\\DDC1654Comment')->findAll(); + $comments = $this->_em->getRepository(DDC1654Comment::class)->findAll(); $this->assertEquals(0, count($comments)); } @@ -123,7 +125,7 @@ public function testManyToManyClearCollectionReAddOrphanRemoval() $this->_em->flush(); $this->_em->clear(); - $comments = $this->_em->getRepository(__NAMESPACE__ . '\\DDC1654Comment')->findAll(); + $comments = $this->_em->getRepository(DDC1654Comment::class)->findAll(); $this->assertEquals(1, count($comments)); } } @@ -142,7 +144,7 @@ class DDC1654Post * @ManyToMany(targetEntity="DDC1654Comment", orphanRemoval=true, * cascade={"persist"}) */ - public $comments = array(); + public $comments = []; } /** diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1655Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1655Test.php index cb5023a8605..a63d3635fe5 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1655Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1655Test.php @@ -14,22 +14,24 @@ public function setUp() parent::setUp(); try { - $this->_schemaTool->createSchema(array( - $this->_em->getClassMetadata(__NAMESPACE__ . '\\DDC1655Foo'), - $this->_em->getClassMetadata(__NAMESPACE__ . '\\DDC1655Bar'), - $this->_em->getClassMetadata(__NAMESPACE__ . '\\DDC1655Baz'), - )); + $this->_schemaTool->createSchema( + [ + $this->_em->getClassMetadata(DDC1655Foo::class), + $this->_em->getClassMetadata(DDC1655Bar::class), + $this->_em->getClassMetadata(DDC1655Baz::class), + ] + ); } catch(\Exception $e) { } } public function testPostLoadOneToManyInheritance() { - $cm = $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC1655Foo'); - $this->assertEquals(array("postLoad" => array("postLoad")), $cm->lifecycleCallbacks); + $cm = $this->_em->getClassMetadata(DDC1655Foo::class); + $this->assertEquals(["postLoad" => ["postLoad"]], $cm->lifecycleCallbacks); - $cm = $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC1655Bar'); - $this->assertEquals(array("postLoad" => array("postLoad", "postSubLoaded")), $cm->lifecycleCallbacks); + $cm = $this->_em->getClassMetadata(DDC1655Bar::class); + $this->assertEquals(["postLoad" => ["postLoad", "postSubLoaded"]], $cm->lifecycleCallbacks); $baz = new DDC1655Baz(); $foo = new DDC1655Foo(); @@ -140,5 +142,5 @@ class DDC1655Baz /** * @OneToMany(targetEntity="DDC1655Foo", mappedBy="baz") */ - public $foos = array(); + public $foos = []; } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1685Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1685Test.php index 52e02839460..b2cbf513abb 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1685Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1685Test.php @@ -29,6 +29,7 @@ protected function setUp() $dql = "SELECT ad FROM Doctrine\Tests\Models\DDC117\DDC117ArticleDetails ad"; $query = $this->_em->createQuery($dql); + $query->setMaxResults(1); $this->paginator = new Paginator($query); } @@ -41,7 +42,7 @@ public function testPaginateCount() public function testPaginateIterate() { foreach ($this->paginator as $ad) { - $this->assertInstanceOf('Doctrine\Tests\Models\DDC117\DDC117ArticleDetails', $ad); + $this->assertInstanceOf(DDC117ArticleDetails::class, $ad); } } @@ -59,7 +60,7 @@ public function testPaginateIterateNoOutputWalkers() $this->expectExceptionMessage('Paginating an entity with foreign key as identifier only works when using the Output Walkers. Call Paginator#setUseOutputWalkers(true) before iterating the paginator.'); foreach ($this->paginator as $ad) { - $this->assertInstanceOf('Doctrine\Tests\Models\DDC117\DDC117ArticleDetails', $ad); + $this->assertInstanceOf(DDC117ArticleDetails::class, $ad); } } } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC168Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC168Test.php index 75924f135aa..ddaa83d80eb 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC168Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC168Test.php @@ -12,16 +12,16 @@ protected function setUp() { $this->useModelSet('company'); parent::setUp(); - $this->oldMetadata = $this->_em->getClassMetadata('Doctrine\Tests\Models\Company\CompanyEmployee'); + $this->oldMetadata = $this->_em->getClassMetadata(CompanyEmployee::class); $metadata = clone $this->oldMetadata; ksort($metadata->reflFields); - $this->_em->getMetadataFactory()->setMetadataFor('Doctrine\Tests\Models\Company\CompanyEmployee', $metadata); + $this->_em->getMetadataFactory()->setMetadataFor(CompanyEmployee::class, $metadata); } public function tearDown() { - $this->_em->getMetadataFactory()->setMetadataFor('Doctrine\Tests\Models\Company\CompanyEmployee', $this->oldMetadata); + $this->_em->getMetadataFactory()->setMetadataFor(CompanyEmployee::class, $this->oldMetadata); parent::tearDown(); } @@ -56,7 +56,7 @@ public function testJoinedSubclassPersisterRequiresSpecificOrderOfMetadataReflFi $this->assertEquals("bar", $theEmployee->getDepartment()); $this->assertEquals("Foo", $theEmployee->getName()); $this->assertEquals(1000, $theEmployee->getSalary()); - $this->assertInstanceOf('Doctrine\Tests\Models\Company\CompanyEmployee', $theEmployee); - $this->assertInstanceOf('Doctrine\Tests\Models\Company\CompanyEmployee', $theEmployee->getSpouse()); + $this->assertInstanceOf(CompanyEmployee::class, $theEmployee); + $this->assertInstanceOf(CompanyEmployee::class, $theEmployee->getSpouse()); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1690Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1690Test.php index ed1cb4257bb..47e79ed7aee 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1690Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1690Test.php @@ -2,18 +2,21 @@ namespace Doctrine\Tests\ORM\Functional\Ticket; -use Doctrine\Common\NotifyPropertyChanged, - Doctrine\Common\PropertyChangedListener; +use Doctrine\Common\NotifyPropertyChanged; +use Doctrine\Common\PropertyChangedListener; +use Doctrine\ORM\Proxy\Proxy; class DDC1690Test extends \Doctrine\Tests\OrmFunctionalTestCase { protected function setUp() { parent::setUp(); try { - $this->_schemaTool->createSchema(array( - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC1690Parent'), - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC1690Child') - )); + $this->_schemaTool->createSchema( + [ + $this->_em->getClassMetadata(DDC1690Parent::class), + $this->_em->getClassMetadata(DDC1690Child::class) + ] + ); } catch (\Exception $e) { // Swallow all exceptions. We do not test the schema tool here. } @@ -45,28 +48,24 @@ public function testChangeTracking() $childId = $child->getId(); unset($parent, $child); - $parent = $this->_em->find(__NAMESPACE__.'\DDC1690Parent', $parentId); - $child = $this->_em->find(__NAMESPACE__.'\DDC1690Child', $childId); + $parent = $this->_em->find(DDC1690Parent::class, $parentId); + $child = $this->_em->find(DDC1690Child::class, $childId); $this->assertEquals(1, count($parent->listeners)); - $this->assertInstanceOf( - 'Doctrine\\ORM\\Proxy\\Proxy', - $child, - 'Verifying that $child is a proxy before using proxy API' - ); + $this->assertInstanceOf(Proxy::class, $child, 'Verifying that $child is a proxy before using proxy API'); $this->assertCount(0, $child->listeners); $child->__load(); $this->assertCount(1, $child->listeners); unset($parent, $child); - $parent = $this->_em->find(__NAMESPACE__.'\DDC1690Parent', $parentId); + $parent = $this->_em->find(DDC1690Parent::class, $parentId); $child = $parent->getChild(); $this->assertEquals(1, count($parent->listeners)); $this->assertEquals(1, count($child->listeners)); unset($parent, $child); - $child = $this->_em->find(__NAMESPACE__.'\DDC1690Child', $childId); + $child = $this->_em->find(DDC1690Child::class, $childId); $parent = $child->getParent(); $this->assertEquals(1, count($parent->listeners)); @@ -75,7 +74,7 @@ public function testChangeTracking() } class NotifyBaseEntity implements NotifyPropertyChanged { - public $listeners = array(); + public $listeners = []; public function addPropertyChangedListener(PropertyChangedListener $listener) { if (!in_array($listener, $this->listeners)) { diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1707Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1707Test.php index 5e587c4dfa8..54b52a57bd1 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1707Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1707Test.php @@ -15,10 +15,12 @@ public function setUp() parent::setUp(); try { - $this->_schemaTool->createSchema(array( - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC1509File'), - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC1509Picture'), - )); + $this->_schemaTool->createSchema( + [ + $this->_em->getClassMetadata(DDC1509File::class), + $this->_em->getClassMetadata(DDC1509Picture::class), + ] + ); } catch (\Exception $ignored) { } @@ -26,7 +28,7 @@ public function setUp() public function testPostLoadOnChild() { - $class = $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC1707Child'); + $class = $this->_em->getClassMetadata(DDC1707Child::class); $entity = new DDC1707Child(); $class->invokeLifecycleCallbacks(Events::postLoad, $entity); diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1719Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1719Test.php index a9cadb3ccc9..b3784ff8a7c 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1719Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1719Test.php @@ -2,31 +2,31 @@ namespace Doctrine\Tests\ORM\Functional\Ticket; -use Doctrine\Tests\Models\Quote\SimpleEntity; - /** * @group DDC-1719 */ class DDC1719Test extends \Doctrine\Tests\OrmFunctionalTestCase { - const CLASS_NAME = 'Doctrine\Tests\ORM\Functional\Ticket\DDC1719SimpleEntity'; - protected function setUp() { parent::setUp(); - $this->_schemaTool->createSchema(array( - $this->_em->getClassMetadata(self::CLASS_NAME), - )); + $this->_schemaTool->createSchema( + [ + $this->_em->getClassMetadata(DDC1719SimpleEntity::class), + ] + ); } protected function tearDown() { parent::tearDown(); - $this->_schemaTool->dropSchema(array( - $this->_em->getClassMetadata(self::CLASS_NAME), - )); + $this->_schemaTool->dropSchema( + [ + $this->_em->getClassMetadata(DDC1719SimpleEntity::class), + ] + ); } public function testCreateRetrieveUpdateDelete() @@ -44,11 +44,11 @@ public function testCreateRetrieveUpdateDelete() $e2Id = $e2->id; // Retrieve - $e1 = $this->_em->find(self::CLASS_NAME, $e1Id); - $e2 = $this->_em->find(self::CLASS_NAME, $e2Id); + $e1 = $this->_em->find(DDC1719SimpleEntity::class, $e1Id); + $e2 = $this->_em->find(DDC1719SimpleEntity::class, $e2Id); - $this->assertInstanceOf(self::CLASS_NAME, $e1); - $this->assertInstanceOf(self::CLASS_NAME, $e2); + $this->assertInstanceOf(DDC1719SimpleEntity::class, $e1); + $this->assertInstanceOf(DDC1719SimpleEntity::class, $e2); $this->assertEquals($e1Id, $e1->id); $this->assertEquals($e2Id, $e2->id); @@ -67,8 +67,8 @@ public function testCreateRetrieveUpdateDelete() $this->assertEquals('Bar 2', $e1->value); $this->assertEquals('Foo 2', $e2->value); - $this->assertInstanceOf(self::CLASS_NAME, $e1); - $this->assertInstanceOf(self::CLASS_NAME, $e2); + $this->assertInstanceOf(DDC1719SimpleEntity::class, $e1); + $this->assertInstanceOf(DDC1719SimpleEntity::class, $e2); $this->assertEquals($e1Id, $e1->id); $this->assertEquals($e2Id, $e2->id); @@ -82,8 +82,8 @@ public function testCreateRetrieveUpdateDelete() $this->_em->flush(); - $e1 = $this->_em->find(self::CLASS_NAME, $e1Id); - $e2 = $this->_em->find(self::CLASS_NAME, $e2Id); + $e1 = $this->_em->find(DDC1719SimpleEntity::class, $e1Id); + $e2 = $this->_em->find(DDC1719SimpleEntity::class, $e2Id); $this->assertNull($e1); $this->assertNull($e2); diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1734Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1734Test.php index f0abda67ddb..64199eb07c0 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1734Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1734Test.php @@ -2,10 +2,14 @@ namespace Doctrine\Tests\ORM\Functional\Ticket; +use Doctrine\ORM\Proxy\Proxy; use Doctrine\Tests\Models\CMS\CmsGroup; +use Doctrine\Tests\VerifyDeprecations; class DDC1734Test extends \Doctrine\Tests\OrmFunctionalTestCase { + use VerifyDeprecations; + /** * {@inheritDoc} */ @@ -15,6 +19,12 @@ protected function setUp() parent::setUp(); } + /** @after */ + public function ensureTestGeneratedDeprecationMessages() : void + { + $this->assertHasDeprecationMessages(); + } + /** * This test is DDC-1734 minus the serialization, i.e. it works * @@ -31,7 +41,7 @@ public function testMergeWorksOnNonSerializedProxies() $proxy = $this->getProxy($group); - $this->assertInstanceOf('Doctrine\ORM\Proxy\Proxy', $proxy); + $this->assertInstanceOf(Proxy::class, $proxy); $this->assertFalse($proxy->__isInitialized()); $this->_em->detach($proxy); @@ -61,7 +71,7 @@ public function testMergeWorksOnSerializedProxies() $proxy = $this->getProxy($group); - $this->assertInstanceOf('Doctrine\ORM\Proxy\Proxy', $proxy); + $this->assertInstanceOf(Proxy::class, $proxy); $this->assertFalse($proxy->__isInitialized()); $this->_em->detach($proxy); @@ -86,4 +96,4 @@ private function getProxy($object) return $this->_em->getProxyFactory()->getProxy($className, $identifier); } -} \ No newline at end of file +} diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1757Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1757Test.php index 13b1868d532..54245368a26 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1757Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1757Test.php @@ -12,8 +12,8 @@ public function testFailingCase() /* @var $qb \Doctrine\ORM\QueryBuilder */ $qb->select('_a') - ->from(__NAMESPACE__ . '\DDC1757A', '_a') - ->from(__NAMESPACE__ . '\DDC1757B', '_b') + ->from(DDC1757A::class, '_a') + ->from(DDC1757B::class, '_b') ->join('_b.c', '_c') ->join('_c.d', '_d'); diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1778Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1778Test.php index b2e02c26be1..09623f13535 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1778Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1778Test.php @@ -32,8 +32,8 @@ public function setUp() $this->_em->flush(); $this->_em->clear(); - $this->user = $this->_em->find('Doctrine\\Tests\\Models\\CMS\\CmsUser', $this->user->getId()); - $this->phone = $this->_em->find('Doctrine\\Tests\\Models\\CMS\\CmsPhonenumber', $this->phone->phonenumber); + $this->user = $this->_em->find(CmsUser::class, $this->user->getId()); + $this->phone = $this->_em->find(CmsPhonenumber::class, $this->phone->phonenumber); } public function testClear() @@ -43,7 +43,7 @@ public function testClear() $this->_em->flush(); $this->_em->clear(); - $this->user = $this->_em->find('Doctrine\\Tests\\Models\\CMS\\CmsUser', $this->user->getId()); + $this->user = $this->_em->find(CmsUser::class, $this->user->getId()); $this->assertCount(1, $this->user->getPhonenumbers()); } @@ -55,7 +55,7 @@ public function testRemove() $this->_em->flush(); $this->_em->clear(); - $this->user = $this->_em->find('Doctrine\\Tests\\Models\\CMS\\CmsUser', $this->user->getId()); + $this->user = $this->_em->find(CmsUser::class, $this->user->getId()); $this->assertCount(1, $this->user->getPhonenumbers()); } @@ -67,7 +67,7 @@ public function testRemoveElement() $this->_em->flush(); $this->_em->clear(); - $this->user = $this->_em->find('Doctrine\\Tests\\Models\\CMS\\CmsUser', $this->user->getId()); + $this->user = $this->_em->find(CmsUser::class, $this->user->getId()); $this->assertCount(1, $this->user->getPhonenumbers()); } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1787Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1787Test.php index 862d9196a8b..17f28658a5d 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1787Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1787Test.php @@ -10,10 +10,12 @@ class DDC1787Test extends \Doctrine\Tests\OrmFunctionalTestCase public function setUp() { parent::setUp(); - $this->_schemaTool->createSchema(array( - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC1787Foo'), - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC1787Bar'), - )); + $this->_schemaTool->createSchema( + [ + $this->_em->getClassMetadata(DDC1787Foo::class), + $this->_em->getClassMetadata(DDC1787Bar::class), + ] + ); } public function testIssue() diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1843Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1843Test.php index bf52e570b7c..c97ebb287a2 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1843Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1843Test.php @@ -10,20 +10,11 @@ */ class DDC1843Test extends \Doctrine\Tests\OrmFunctionalTestCase { - - protected function setUp() + protected function setUp() : void { - parent::setUp(); + $this->useModelSet('quote'); - try { - $this->_schemaTool->createSchema(array( - $this->_em->getClassMetadata('Doctrine\Tests\Models\Quote\User'), - $this->_em->getClassMetadata('Doctrine\Tests\Models\Quote\Group'), - $this->_em->getClassMetadata('Doctrine\Tests\Models\Quote\Phone'), - $this->_em->getClassMetadata('Doctrine\Tests\Models\Quote\Address'), - )); - } catch(\Exception $e) { - } + parent::setUp(); } public function testCreateRetrieveUpdateDelete() @@ -51,15 +42,15 @@ public function testCreateRetrieveUpdateDelete() $e4Id = $e4->id; // Retrieve - $e1 = $this->_em->find('Doctrine\Tests\Models\Quote\Group', $e1Id); - $e2 = $this->_em->find('Doctrine\Tests\Models\Quote\Group', $e2Id); - $e3 = $this->_em->find('Doctrine\Tests\Models\Quote\Group', $e3Id); - $e4 = $this->_em->find('Doctrine\Tests\Models\Quote\Group', $e4Id); + $e1 = $this->_em->find(Group::class, $e1Id); + $e2 = $this->_em->find(Group::class, $e2Id); + $e3 = $this->_em->find(Group::class, $e3Id); + $e4 = $this->_em->find(Group::class, $e4Id); - $this->assertInstanceOf('Doctrine\Tests\Models\Quote\Group', $e1); - $this->assertInstanceOf('Doctrine\Tests\Models\Quote\Group', $e2); - $this->assertInstanceOf('Doctrine\Tests\Models\Quote\Group', $e3); - $this->assertInstanceOf('Doctrine\Tests\Models\Quote\Group', $e4); + $this->assertInstanceOf(Group::class, $e1); + $this->assertInstanceOf(Group::class, $e2); + $this->assertInstanceOf(Group::class, $e3); + $this->assertInstanceOf(Group::class, $e4); $this->assertEquals($e1Id, $e1->id); $this->assertEquals($e2Id, $e2->id); @@ -89,10 +80,10 @@ public function testCreateRetrieveUpdateDelete() $this->assertEquals('Bar 33', $e3->name); $this->assertEquals('Foo 44', $e4->name); - $this->assertInstanceOf('Doctrine\Tests\Models\Quote\Group', $e1); - $this->assertInstanceOf('Doctrine\Tests\Models\Quote\Group', $e2); - $this->assertInstanceOf('Doctrine\Tests\Models\Quote\Group', $e3); - $this->assertInstanceOf('Doctrine\Tests\Models\Quote\Group', $e4); + $this->assertInstanceOf(Group::class, $e1); + $this->assertInstanceOf(Group::class, $e2); + $this->assertInstanceOf(Group::class, $e3); + $this->assertInstanceOf(Group::class, $e4); $this->assertEquals($e1Id, $e1->id); $this->assertEquals($e2Id, $e2->id); @@ -109,21 +100,21 @@ public function testCreateRetrieveUpdateDelete() $this->_em->remove($e3); $this->_em->remove($e2); $this->_em->remove($e1); - + $this->_em->flush(); $this->_em->clear(); - $this->assertInstanceOf('Doctrine\Tests\Models\Quote\Group', $e1); - $this->assertInstanceOf('Doctrine\Tests\Models\Quote\Group', $e2); - $this->assertInstanceOf('Doctrine\Tests\Models\Quote\Group', $e3); - $this->assertInstanceOf('Doctrine\Tests\Models\Quote\Group', $e4); + $this->assertInstanceOf(Group::class, $e1); + $this->assertInstanceOf(Group::class, $e2); + $this->assertInstanceOf(Group::class, $e3); + $this->assertInstanceOf(Group::class, $e4); // Retrieve - $e1 = $this->_em->find('Doctrine\Tests\Models\Quote\Group', $e1Id); - $e2 = $this->_em->find('Doctrine\Tests\Models\Quote\Group', $e2Id); - $e3 = $this->_em->find('Doctrine\Tests\Models\Quote\Group', $e3Id); - $e4 = $this->_em->find('Doctrine\Tests\Models\Quote\Group', $e4Id); + $e1 = $this->_em->find(Group::class, $e1Id); + $e2 = $this->_em->find(Group::class, $e2Id); + $e3 = $this->_em->find(Group::class, $e3Id); + $e4 = $this->_em->find(Group::class, $e4Id); $this->assertNull($e1); $this->assertNull($e2); diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1884Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1884Test.php index 46f7cca7f46..938459ad465 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1884Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1884Test.php @@ -1,8 +1,10 @@ useModelSet('taxi'); parent::setUp(); - list($bimmer, $crysler, $merc, $volvo) = $this->createCars('Doctrine\Tests\Models\Taxi\Car'); - list($john, $foo) = $this->createDrivers('Doctrine\Tests\Models\Taxi\Driver'); + list($bimmer, $crysler, $merc, $volvo) = $this->createCars(Car::class); + list($john, $foo) = $this->createDrivers(Driver::class); $this->_em->flush(); $ride1 = new Ride($john, $bimmer); @@ -72,7 +74,7 @@ private function createCars($class) $this->_em->persist($merc); $this->_em->persist($volvo); - return array($bimmer, $crysler, $merc, $volvo); + return [$bimmer, $crysler, $merc, $volvo]; } private function createDrivers($class) @@ -86,7 +88,7 @@ private function createDrivers($class) $this->_em->persist($foo); $this->_em->persist($john); - return array($john, $foo); + return [$john, $foo]; } /** @@ -98,7 +100,7 @@ public function testSelectFromInverseSideWithCompositePkAndSolelyIdentifierColum $qb = $this->_em->createQueryBuilder(); $result = $qb->select('d, dr, c') - ->from('Doctrine\Tests\Models\Taxi\Driver', 'd') + ->from(Driver::class, 'd') ->leftJoin('d.freeDriverRides', 'dr') ->leftJoin('dr.car', 'c') ->where('d.name = ?1') @@ -120,7 +122,7 @@ public function testSelectFromInverseSideWithCompositePkUsingFetchJoins() $qb = $this->_em->createQueryBuilder(); $result = $qb->select('d, dr, c') - ->from('Doctrine\Tests\Models\Taxi\Driver', 'd') + ->from(Driver::class, 'd') ->leftJoin('d.driverRides', 'dr') ->leftJoin('dr.car', 'c') ->where('d.name = ?1') @@ -140,7 +142,7 @@ public function testSelectFromOwningSideUsingFetchJoins() $qb = $this->_em->createQueryBuilder(); $result = $qb->select('r, d, c') - ->from('Doctrine\Tests\Models\Taxi\PaidRide', 'r') + ->from(PaidRide::class, 'r') ->leftJoin('r.driver', 'd') ->leftJoin('r.car', 'c') ->where('d.name = ?1') diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1885Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1885Test.php index 91f49282ee9..2c141151b29 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1885Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1885Test.php @@ -17,18 +17,11 @@ class DDC1885Test extends \Doctrine\Tests\OrmFunctionalTestCase */ private $user; - protected function setUp() + protected function setUp() : void { - parent::setUp(); + $this->useModelSet('quote'); - try { - $this->_schemaTool->createSchema(array( - $this->_em->getClassMetadata('Doctrine\Tests\Models\Quote\User'), - $this->_em->getClassMetadata('Doctrine\Tests\Models\Quote\Group'), - $this->_em->getClassMetadata('Doctrine\Tests\Models\Quote\Address'), - )); - } catch(\Exception $e) { - } + parent::setUp(); $user = new User(); $user->name = "FabioBatSilva"; @@ -41,7 +34,7 @@ protected function setUp() $this->_em->persist($user); $this->_em->flush(); $this->_em->clear(); - + } public function testCreateRetrieveUpdateDelete() @@ -55,19 +48,19 @@ public function testCreateRetrieveUpdateDelete() $g2Id = $g2->id; // Retrieve - $user = $this->_em->find('Doctrine\Tests\Models\Quote\User', $u1Id); + $user = $this->_em->find(User::class, $u1Id); - $this->assertInstanceOf('Doctrine\Tests\Models\Quote\User', $user); + $this->assertInstanceOf(User::class, $user); $this->assertEquals('FabioBatSilva', $user->name); $this->assertEquals($u1Id, $user->id); - + $this->assertCount(2, $user->groups); $g1 = $user->getGroups()->get(0); $g2 = $user->getGroups()->get(1); - $this->assertInstanceOf('Doctrine\Tests\Models\Quote\Group', $g1); - $this->assertInstanceOf('Doctrine\Tests\Models\Quote\Group', $g2); + $this->assertInstanceOf(Group::class, $g1); + $this->assertInstanceOf(Group::class, $g2); $g1->name = 'Bar 11'; $g2->name = 'Foo 22'; @@ -77,36 +70,36 @@ public function testCreateRetrieveUpdateDelete() $this->_em->flush(); $this->_em->clear(); - $user = $this->_em->find('Doctrine\Tests\Models\Quote\User', $u1Id); + $user = $this->_em->find(User::class, $u1Id); - $this->assertInstanceOf('Doctrine\Tests\Models\Quote\User', $user); + $this->assertInstanceOf(User::class, $user); $this->assertEquals('FabioBatSilva', $user->name); $this->assertEquals($u1Id, $user->id); // Delete $this->_em->remove($user); - + $this->_em->flush(); $this->_em->clear(); - $this->assertNull($this->_em->find('Doctrine\Tests\Models\Quote\User', $u1Id)); - $this->assertNull($this->_em->find('Doctrine\Tests\Models\Quote\Group', $g1Id)); - $this->assertNull($this->_em->find('Doctrine\Tests\Models\Quote\Group', $g2Id)); + $this->assertNull($this->_em->find(User::class, $u1Id)); + $this->assertNull($this->_em->find(Group::class, $g1Id)); + $this->assertNull($this->_em->find(Group::class, $g2Id)); } public function testRemoveItem() { $user = $this->user; $u1Id = $user->id; - $user = $this->_em->find('Doctrine\Tests\Models\Quote\User', $u1Id); + $user = $this->_em->find(User::class, $u1Id); - $this->assertInstanceOf('Doctrine\Tests\Models\Quote\User', $user); + $this->assertInstanceOf(User::class, $user); $this->assertEquals('FabioBatSilva', $user->name); $this->assertEquals($u1Id, $user->id); $this->assertCount(2, $user->groups); - $this->assertInstanceOf('Doctrine\Tests\Models\Quote\Group', $user->getGroups()->get(0)); - $this->assertInstanceOf('Doctrine\Tests\Models\Quote\Group', $user->getGroups()->get(1)); + $this->assertInstanceOf(Group::class, $user->getGroups()->get(0)); + $this->assertInstanceOf(Group::class, $user->getGroups()->get(1)); $user->getGroups()->remove(0); @@ -115,9 +108,9 @@ public function testRemoveItem() $this->_em->flush(); $this->_em->clear(); - $user = $this->_em->find('Doctrine\Tests\Models\Quote\User', $u1Id); + $user = $this->_em->find(User::class, $u1Id); - $this->assertInstanceOf('Doctrine\Tests\Models\Quote\User', $user); + $this->assertInstanceOf(User::class, $user); $this->assertEquals('FabioBatSilva', $user->name); $this->assertEquals($u1Id, $user->id); @@ -128,15 +121,15 @@ public function testClearAll() { $user = $this->user; $u1Id = $user->id; - $user = $this->_em->find('Doctrine\Tests\Models\Quote\User', $u1Id); + $user = $this->_em->find(User::class, $u1Id); - $this->assertInstanceOf('Doctrine\Tests\Models\Quote\User', $user); + $this->assertInstanceOf(User::class, $user); $this->assertEquals('FabioBatSilva', $user->name); $this->assertEquals($u1Id, $user->id); $this->assertCount(2, $user->groups); - $this->assertInstanceOf('Doctrine\Tests\Models\Quote\Group', $user->getGroups()->get(0)); - $this->assertInstanceOf('Doctrine\Tests\Models\Quote\Group', $user->getGroups()->get(1)); + $this->assertInstanceOf(Group::class, $user->getGroups()->get(0)); + $this->assertInstanceOf(Group::class, $user->getGroups()->get(1)); $user->getGroups()->clear(); @@ -145,9 +138,9 @@ public function testClearAll() $this->_em->flush(); $this->_em->clear(); - $user = $this->_em->find('Doctrine\Tests\Models\Quote\User', $u1Id); + $user = $this->_em->find(User::class, $u1Id); - $this->assertInstanceOf('Doctrine\Tests\Models\Quote\User', $user); + $this->assertInstanceOf(User::class, $user); $this->assertEquals('FabioBatSilva', $user->name); $this->assertEquals($u1Id, $user->id); @@ -158,14 +151,14 @@ public function testCountExtraLazy() { $user = $this->user; $u1Id = $user->id; - $user = $this->_em->find('Doctrine\Tests\Models\Quote\User', $u1Id); + $user = $this->_em->find(User::class, $u1Id); - $this->assertInstanceOf('Doctrine\Tests\Models\Quote\User', $user); + $this->assertInstanceOf(User::class, $user); $this->assertEquals('FabioBatSilva', $user->name); $this->assertEquals($u1Id, $user->id); $this->assertCount(2, $user->groups); - $this->assertInstanceOf('Doctrine\Tests\Models\Quote\Group', $user->getGroups()->get(0)); - $this->assertInstanceOf('Doctrine\Tests\Models\Quote\Group', $user->getGroups()->get(1)); + $this->assertInstanceOf(Group::class, $user->getGroups()->get(0)); + $this->assertInstanceOf(Group::class, $user->getGroups()->get(1)); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1918Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1918Test.php index 64b3ad48dbc..4b0c7eb9151 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1918Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1918Test.php @@ -19,7 +19,7 @@ protected function setUp() public function testLastPageCorrect() { - $groups = array(); + $groups = []; for ($i = 0; $i < 3; $i++) { $group = new CmsGroup(); $group->name = "test"; diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1925Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1925Test.php index 4c50cf26285..ef7d6014bf6 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1925Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1925Test.php @@ -12,26 +12,36 @@ class DDC1925Test extends \Doctrine\Tests\OrmFunctionalTestCase { public function testIssue() { - $this->_schemaTool->createSchema(array( - $this->_em->getClassMetadata(__NAMESPACE__ . '\\DDC1925User'), - $this->_em->getClassMetadata(__NAMESPACE__ . '\\DDC1925Product'), - )); + $this->_schemaTool->createSchema( + [ + $this->_em->getClassMetadata(DDC1925User::class), + $this->_em->getClassMetadata(DDC1925Product::class), + ] + ); $user = new DDC1925User(); $user->setTitle("Test User"); - $this->_em->persist($user); $product = new DDC1925Product(); $product->setTitle("Test product"); + + $this->_em->persist($user); $this->_em->persist($product); $this->_em->flush(); $product->addBuyer($user); - $this->_em->getUnitOfWork()->computeChangeSets(); + $this->_em->getUnitOfWork() + ->computeChangeSets(); $this->_em->persist($product); $this->_em->flush(); + $this->_em->clear(); + + /** @var DDC1925Product $persistedProduct */ + $persistedProduct = $this->_em->find(DDC1925Product::class, $product->getId()); + + self::assertEquals($user, $persistedProduct->getBuyers()->first()); } } @@ -102,15 +112,7 @@ public function getTitle() } /** - * @param string $buyers - */ - public function setBuyers($buyers) - { - $this->buyers = $buyers; - } - - /** - * @return string + * @return ArrayCollection */ public function getBuyers() { diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC192Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC192Test.php index f01a2abacab..532e0edfeb4 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC192Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC192Test.php @@ -2,27 +2,43 @@ namespace Doctrine\Tests\ORM\Functional\Ticket; +use Doctrine\ORM\Mapping\ClassMetadata; use Doctrine\Tests\OrmFunctionalTestCase; +/** + * @group DDC-192 + */ class DDC192Test extends OrmFunctionalTestCase { public function testSchemaCreation() { - $this->_schemaTool->createSchema(array( - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC192User'), - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC192Phonenumber') - )); + $classes = [ + $this->_em->getClassMetadata(DDC192User::class), + $this->_em->getClassMetadata(DDC192Phonenumber::class), + ]; + + $this->_schemaTool->createSchema($classes); + + $tables = $this->_em->getConnection() + ->getSchemaManager() + ->listTableNames(); + + /** @var ClassMetadata $class */ + foreach ($classes as $class) { + self::assertContains($class->getTableName(), $tables); + } } } - /** - * @Entity @Table(name="ddc192_users") + * @Entity + * @Table(name="ddc192_users") */ class DDC192User { /** - * @Id @Column(name="id", type="integer") + * @Id + * @Column(name="id", type="integer") * @GeneratedValue(strategy="AUTO") */ public $id; @@ -35,12 +51,14 @@ class DDC192User /** - * @Entity @Table(name="ddc192_phonenumbers") + * @Entity + * @Table(name="ddc192_phonenumbers") */ class DDC192Phonenumber { /** - * @Id @Column(name="phone", type="string", length=40) + * @Id + * @Column(name="phone", type="string", length=40) */ protected $phone; @@ -52,14 +70,23 @@ class DDC192Phonenumber protected $User; - public function setPhone($value) { $this->phone = $value; } + public function setPhone($value) + { + $this->phone = $value; + } - public function getPhone() { return $this->phone; } + public function getPhone() + { + return $this->phone; + } public function setUser(User $user) { $this->User = $user; } - public function getUser() { return $this->User; } + public function getUser() + { + return $this->User; + } } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1995Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1995Test.php index 0bfd73960b2..8bb975a05b3 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1995Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1995Test.php @@ -15,7 +15,7 @@ public function setUp() $this->useModelSet('company'); parent::setUp(); } - + public function testIssue() { $person = new CompanyPerson; @@ -32,14 +32,14 @@ public function testIssue() $this->_em->clear(); $dql = 'SELECT u FROM Doctrine\Tests\Models\Company\CompanyPerson u WHERE u INSTANCE OF ?1'; - $class = $this->_em->getClassMetadata('Doctrine\Tests\Models\Company\CompanyEmployee'); + $class = $this->_em->getClassMetadata(CompanyEmployee::class); $result = $this->_em->createQuery($dql) ->setParameter(1, $class) ->getResult(); $this->assertCount(1, $result); - $this->assertInstanceOf('Doctrine\Tests\Models\Company\CompanyEmployee', $result[0]); + $this->assertInstanceOf(CompanyEmployee::class, $result[0]); } public function testQueryCache() @@ -58,8 +58,8 @@ public function testQueryCache() $this->_em->clear(); $dql = 'SELECT u FROM Doctrine\Tests\Models\Company\CompanyPerson u WHERE u INSTANCE OF :type'; - $class1 = $this->_em->getClassMetadata('Doctrine\Tests\Models\Company\CompanyEmployee'); - $class2 = $this->_em->getClassMetadata('Doctrine\Tests\Models\Company\CompanyPerson'); + $class1 = $this->_em->getClassMetadata(CompanyEmployee::class); + $class2 = $this->_em->getClassMetadata(CompanyPerson::class); $result1 = $this->_em->createQuery($dql) ->setParameter('type', $class1) @@ -72,10 +72,9 @@ public function testQueryCache() ->getResult(); $this->assertCount(1, $result1); - $this->assertCount(1, $result2); + $this->assertCount(2, $result2); - $this->assertInstanceOf('Doctrine\Tests\Models\Company\CompanyEmployee', $result1[0]); - $this->assertInstanceOf('Doctrine\Tests\Models\Company\CompanyPerson', $result2[0]); - $this->assertNotInstanceOf('Doctrine\Tests\Models\Company\CompanyEmployee', $result2[0]); + $this->assertInstanceOf(CompanyEmployee::class, $result1[0]); + $this->assertContainsOnlyInstancesOf(CompanyPerson::class, $result2); } -} \ No newline at end of file +} diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1998Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1998Test.php index 95e0a76f5b1..74ea2fd8889 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1998Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1998Test.php @@ -13,11 +13,13 @@ class DDC1998Test extends \Doctrine\Tests\OrmFunctionalTestCase { public function testSqlConversionAsIdentifier() { - Type::addType('ddc1998', __NAMESPACE__ . '\\DDC1998Type'); + Type::addType('ddc1998', DDC1998Type::class); - $this->_schemaTool->createSchema(array( - $this->_em->getClassMetadata(__NAMESPACE__ . '\\DDC1998Entity'), - )); + $this->_schemaTool->createSchema( + [ + $this->_em->getClassMetadata(DDC1998Entity::class), + ] + ); $entity = new DDC1998Entity(); $entity->id = new DDC1998Id("foo"); @@ -34,13 +36,13 @@ public function testSqlConversionAsIdentifier() $this->_em->clear(); - $found = $this->_em->find(__NAMESPACE__ . '\\DDC1998Entity', $entity->id); + $found = $this->_em->find(DDC1998Entity::class, $entity->id); $this->assertNull($found); - $found = $this->_em->find(__NAMESPACE__ . '\\DDC1998Entity', "foo"); + $found = $this->_em->find(DDC1998Entity::class, "foo"); $this->assertNull($found); - $this->assertEquals(0, count($this->_em->getRepository(__NAMESPACE__ . '\\DDC1998Entity')->findAll())); + $this->assertEquals(0, count($this->_em->getRepository(DDC1998Entity::class)->findAll())); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC199Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC199Test.php index 17a115d0f05..2fb3acd33bd 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC199Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC199Test.php @@ -9,11 +9,13 @@ class DDC199Test extends OrmFunctionalTestCase protected function setUp() { parent::setUp(); - $this->_schemaTool->createSchema(array( - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC199ParentClass'), - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC199ChildClass'), - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC199RelatedClass') - )); + $this->_schemaTool->createSchema( + [ + $this->_em->getClassMetadata(DDC199ParentClass::class), + $this->_em->getClassMetadata(DDC199ChildClass::class), + $this->_em->getClassMetadata(DDC199RelatedClass::class) + ] + ); } public function testPolymorphicLoading() @@ -40,11 +42,11 @@ public function testPolymorphicLoading() $result = $query->getResult(); $this->assertEquals(1, count($result)); - $this->assertInstanceOf('Doctrine\Tests\ORM\Functional\Ticket\DDC199ParentClass', $result[0]); + $this->assertInstanceOf(DDC199ParentClass::class, $result[0]); $this->assertTrue($result[0]->relatedEntities->isInitialized()); $this->assertEquals(2, $result[0]->relatedEntities->count()); - $this->assertInstanceOf('Doctrine\Tests\ORM\Functional\Ticket\DDC199RelatedClass', $result[0]->relatedEntities[0]); - $this->assertInstanceOf('Doctrine\Tests\ORM\Functional\Ticket\DDC199RelatedClass', $result[0]->relatedEntities[1]); + $this->assertInstanceOf(DDC199RelatedClass::class, $result[0]->relatedEntities[0]); + $this->assertInstanceOf(DDC199RelatedClass::class, $result[0]->relatedEntities[1]); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2012Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2012Test.php index 92510cb02c7..3882408081e 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2012Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2012Test.php @@ -15,20 +15,22 @@ protected function setUp() { parent::setUp(); - Type::addType(DDC2012TsVectorType::MYTYPE, __NAMESPACE__ . '\DDC2012TsVectorType'); + Type::addType(DDC2012TsVectorType::MYTYPE, DDC2012TsVectorType::class); - DDC2012TsVectorType::$calls = array(); + DDC2012TsVectorType::$calls = []; - $this->_schemaTool->createSchema(array( - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC2012Item'), - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC2012ItemPerson'), - )); + $this->_schemaTool->createSchema( + [ + $this->_em->getClassMetadata(DDC2012Item::class), + $this->_em->getClassMetadata(DDC2012ItemPerson::class), + ] + ); } public function testIssue() { $item = new DDC2012ItemPerson(); - $item->tsv = array('word1', 'word2', 'word3'); + $item->tsv = ['word1', 'word2', 'word3']; $this->_em->persist($item); $this->_em->flush(); @@ -44,11 +46,11 @@ public function testIssue() $this->assertCount(1, DDC2012TsVectorType::$calls['convertToDatabaseValue']); $this->assertCount(1, DDC2012TsVectorType::$calls['convertToPHPValue']); - $this->assertInstanceOf(__NAMESPACE__ . '\DDC2012Item', $item); - $this->assertEquals(array('word1', 'word2', 'word3'), $item->tsv); + $this->assertInstanceOf(DDC2012Item::class, $item); + $this->assertEquals(['word1', 'word2', 'word3'], $item->tsv); - $item->tsv = array('word1', 'word2'); + $item->tsv = ['word1', 'word2']; $this->_em->persist($item); $this->_em->flush(); @@ -60,8 +62,8 @@ public function testIssue() $this->assertCount(2, DDC2012TsVectorType::$calls['convertToDatabaseValue']); $this->assertCount(2, DDC2012TsVectorType::$calls['convertToPHPValue']); - $this->assertInstanceOf(__NAMESPACE__ . '\DDC2012Item', $item); - $this->assertEquals(array('word1', 'word2'), $item->tsv); + $this->assertInstanceOf(DDC2012Item::class, $item); + $this->assertEquals(['word1', 'word2'], $item->tsv); } } @@ -103,7 +105,7 @@ class DDC2012TsVectorType extends Type { const MYTYPE = 'tsvector'; - public static $calls = array(); + public static $calls = []; /** * {@inheritdoc} @@ -122,10 +124,10 @@ public function convertToDatabaseValue($value, AbstractPlatform $platform) $value = implode(" ", $value); } - self::$calls[__FUNCTION__][] = array( + self::$calls[__FUNCTION__][] = [ 'value' => $value, 'platform' => $platform, - ); + ]; return $value; } @@ -135,10 +137,10 @@ public function convertToDatabaseValue($value, AbstractPlatform $platform) */ public function convertToPHPValue($value, AbstractPlatform $platform) { - self::$calls[__FUNCTION__][] = array( + self::$calls[__FUNCTION__][] = [ 'value' => $value, 'platform' => $platform, - ); + ]; return explode(" ", strtolower($value)); } @@ -148,14 +150,14 @@ public function convertToPHPValue($value, AbstractPlatform $platform) */ public function convertToDatabaseValueSQL($sqlExpr, AbstractPlatform $platform) { - self::$calls[__FUNCTION__][] = array( + self::$calls[__FUNCTION__][] = [ 'sqlExpr' => $sqlExpr, 'platform' => $platform, - ); + ]; // changed to upper expression to keep the test compatible with other Databases //sprintf('to_tsvector(%s)', $sqlExpr); - + return $platform->getUpperExpression($sqlExpr); } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2074Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2074Test.php index f53857ab3e3..ed77ba13468 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2074Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2074Test.php @@ -20,10 +20,10 @@ public function setUp() public function testShouldNotScheduleDeletionOnClonedInstances() { - $class = $this->_em->getClassMetadata('Doctrine\Tests\Models\ECommerce\ECommerceProduct'); + $class = $this->_em->getClassMetadata(ECommerceProduct::class); $product = new ECommerceProduct(); $category = new ECommerceCategory(); - $collection = new PersistentCollection($this->_em, $class, new ArrayCollection(array($category))); + $collection = new PersistentCollection($this->_em, $class, new ArrayCollection([$category])); $collection->setOwner($product, $class->associationMappings['categories']); $uow = $this->_em->getUnitOfWork(); @@ -50,8 +50,8 @@ public function testSavingClonedPersistentCollection() $this->_em->flush(); $this->_em->clear(); - $product1 = $this->_em->find('Doctrine\Tests\Models\ECommerce\ECommerceProduct', $product->getId()); - $product2 = $this->_em->find('Doctrine\Tests\Models\ECommerce\ECommerceProduct', $newProduct->getId()); + $product1 = $this->_em->find(ECommerceProduct::class, $product->getId()); + $product2 = $this->_em->find(ECommerceProduct::class, $newProduct->getId()); $this->assertCount(1, $product1->getCategories()); $this->assertCount(1, $product2->getCategories()); diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2084Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2084Test.php index abd0fe2d82b..eadbc1caf9d 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2084Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2084Test.php @@ -12,10 +12,12 @@ public function setUp() parent::setUp(); try { - $this->_schemaTool->createSchema(array( + $this->_schemaTool->createSchema( + [ $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC2084\MyEntity1'), $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC2084\MyEntity2'), - )); + ] + ); } catch (\Exception $exc) { } } @@ -125,4 +127,4 @@ public function setValue($value) { $this->value = $value; } -} \ No newline at end of file +} diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2090Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2090Test.php index cd6db885712..174fee2b288 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2090Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2090Test.php @@ -18,7 +18,6 @@ public function setUp() public function testIssue() { - $className = 'Doctrine\Tests\Models\Company\CompanyEmployee'; $date1 = new \DateTime('2011-11-11 11:11:11'); $date2 = new \DateTime('2012-12-12 12:12:12'); $employee1 = new CompanyEmployee; @@ -40,37 +39,41 @@ public function testIssue() $this->_em->clear(); $this->_em->createQueryBuilder() - ->update($className, 'e') + ->update(CompanyEmployee::class, 'e') ->set('e.startDate', ':date') ->set('e.salary', ':salary') ->where('e = :e') - ->setParameters(array( + ->setParameters( + [ 'e' => $employee1, 'date' => $date1, 'salary' => 101, - )) + ] + ) ->getQuery() ->useQueryCache(true) ->execute(); $this->_em->createQueryBuilder() - ->update($className, 'e') + ->update(CompanyEmployee::class, 'e') ->set('e.startDate', ':date') ->set('e.salary', ':salary') ->where('e = :e') - ->setParameters(array( + ->setParameters( + [ 'e' => $employee2, 'date' => $date2, 'salary' => 102, - )) + ] + ) ->getQuery() ->useQueryCache(true) ->execute(); $this->_em->clear(); - $e1 = $this->_em->find($className, $employee1->getId()); - $e2 = $this->_em->find($className, $employee2->getId()); + $e1 = $this->_em->find(CompanyEmployee::class, $employee1->getId()); + $e2 = $this->_em->find(CompanyEmployee::class, $employee2->getId()); $this->assertEquals(101, $e1->getSalary()); $this->assertEquals(102, $e2->getSalary()); @@ -78,21 +81,21 @@ public function testIssue() $this->assertEquals($date2, $e2->getStartDate()); $this->_em->createQueryBuilder() - ->update($className, 'e') + ->update(CompanyEmployee::class, 'e') ->set('e.startDate', '?1') ->set('e.salary', '?2') ->where('e = ?0') - ->setParameters(array($employee1, $date1, 101)) + ->setParameters([$employee1, $date1, 101]) ->getQuery() ->useQueryCache(true) ->execute(); $this->_em->createQueryBuilder() - ->update($className, 'e') + ->update(CompanyEmployee::class, 'e') ->set('e.startDate', '?1') ->set('e.salary', '?2') ->where('e = ?0') - ->setParameters(array($employee2, $date2, 102)) + ->setParameters([$employee2, $date2, 102]) ->getQuery() ->useQueryCache(true) ->execute(); @@ -100,12 +103,12 @@ public function testIssue() $this->_em->clear(); - $e1 = $this->_em->find($className, $employee1->getId()); - $e2 = $this->_em->find($className, $employee2->getId()); + $e1 = $this->_em->find(CompanyEmployee::class, $employee1->getId()); + $e2 = $this->_em->find(CompanyEmployee::class, $employee2->getId()); $this->assertEquals(101, $e1->getSalary()); $this->assertEquals(102, $e2->getSalary()); $this->assertEquals($date1, $e1->getStartDate()); $this->assertEquals($date2, $e2->getStartDate()); } -} \ No newline at end of file +} diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2106Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2106Test.php index 925362b08c9..99b2ade0f0b 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2106Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2106Test.php @@ -12,9 +12,12 @@ class DDC2106Test extends \Doctrine\Tests\OrmFunctionalTestCase protected function setUp() { parent::setUp(); - $this->_schemaTool->createSchema(array( - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC2106Entity'), - )); + + $this->_schemaTool->createSchema( + [ + $this->_em->getClassMetadata(DDC2106Entity::class), + ] + ); } public function testDetachedEntityAsId() @@ -23,15 +26,16 @@ public function testDetachedEntityAsId() $entity = new DDC2106Entity(); $this->_em->persist($entity); $this->_em->flush(); - $this->_em->detach($entity); - $entity = $this->_em->getRepository(__NAMESPACE__ . '\DDC2106Entity')->findOneBy(array()); + $this->_em->clear(DDC2106Entity::class); + $entity = $this->_em->getRepository(DDC2106Entity::class)->findOneBy([]); // ... and a managed entity without id $entityWithoutId = new DDC2106Entity(); $this->_em->persist($entityWithoutId); $criteria = Criteria::create()->where(Criteria::expr()->eq('parent', $entityWithoutId)); - $entity->children->matching($criteria)->count(); + + self::assertCount(0, $entity->children->matching($criteria)); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC211Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC211Test.php index 728a393a0c2..9ac27f3cf94 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC211Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC211Test.php @@ -9,10 +9,12 @@ class DDC211Test extends OrmFunctionalTestCase protected function setUp() { parent::setUp(); - $this->_schemaTool->createSchema(array( - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC211User'), - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC211Group') - )); + $this->_schemaTool->createSchema( + [ + $this->_em->getClassMetadata(DDC211User::class), + $this->_em->getClassMetadata(DDC211Group::class) + ] + ); } public function testIssue() @@ -25,7 +27,7 @@ public function testIssue() $this->_em->persist($user); $this->_em->flush(); - $groupNames = array('group 1', 'group 2', 'group 3', 'group 4'); + $groupNames = ['group 1', 'group 2', 'group 3', 'group 4']; foreach ($groupNames as $name) { $group = new DDC211Group; diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2138Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2138Test.php index 97fdb3050bf..c6019f849c5 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2138Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2138Test.php @@ -14,23 +14,26 @@ class DDC2138Test extends OrmFunctionalTestCase public function testForeignKeyOnSTIWithMultipleMapping() { $em = $this->_em; + if (! $em->getConnection()->getDatabasePlatform()->supportsForeignKeyConstraints()) { + $this->markTestSkipped('Platform does not support foreign keys.'); + } $schemaTool = new SchemaTool($em); - $classes = array( - $em->getClassMetadata(__NAMESPACE__ . '\DDC2138User'), - $em->getClassMetadata(__NAMESPACE__ . '\DDC2138Structure'), - $em->getClassMetadata(__NAMESPACE__ . '\DDC2138UserFollowedObject'), - $em->getClassMetadata(__NAMESPACE__ . '\DDC2138UserFollowedStructure'), - $em->getClassMetadata(__NAMESPACE__ . '\DDC2138UserFollowedUser') - ); + $classes = [ + $em->getClassMetadata(DDC2138User::class), + $em->getClassMetadata(DDC2138Structure::class), + $em->getClassMetadata(DDC2138UserFollowedObject::class), + $em->getClassMetadata(DDC2138UserFollowedStructure::class), + $em->getClassMetadata(DDC2138UserFollowedUser::class) + ]; $schema = $schemaTool->getSchemaFromMetadata($classes); $this->assertTrue($schema->hasTable('users_followed_objects'), "Table users_followed_objects should exist."); /* @var $table \Doctrine\DBAL\Schema\Table */ $table = ($schema->getTable('users_followed_objects')); - $this->assertTrue($table->columnsAreIndexed(array('object_id'))); - $this->assertTrue($table->columnsAreIndexed(array('user_id'))); + $this->assertTrue($table->columnsAreIndexed(['object_id'])); + $this->assertTrue($table->columnsAreIndexed(['user_id'])); $foreignKeys = $table->getForeignKeys(); $this->assertCount(1, $foreignKeys, 'user_id column has to have FK, but not object_id'); diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2175Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2175Test.php index 178685b391f..d6b3c603b8f 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2175Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2175Test.php @@ -10,9 +10,11 @@ class DDC2175Test extends \Doctrine\Tests\OrmFunctionalTestCase protected function setUp() { parent::setUp(); - $this->_schemaTool->createSchema(array( - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC2175Entity'), - )); + $this->_schemaTool->createSchema( + [ + $this->_em->getClassMetadata(DDC2175Entity::class), + ] + ); } public function testIssue() diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2182Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2182Test.php index 031156dcc01..e610a67bcb2 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2182Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2182Test.php @@ -2,6 +2,9 @@ namespace Doctrine\Tests\ORM\Functional\Ticket; +use function method_exists; +use function sprintf; + class DDC2182Test extends \Doctrine\Tests\OrmFunctionalTestCase { public function testPassColumnOptionsToJoinColumns() @@ -10,15 +13,27 @@ public function testPassColumnOptionsToJoinColumns() $this->markTestSkipped("This test is useful for all databases, but designed only for mysql."); } - $sql = $this->_schemaTool->getCreateSchemaSql(array( - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC2182OptionParent'), - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC2182OptionChild'), - )); + $sql = $this->_schemaTool->getCreateSchemaSql( + [ + $this->_em->getClassMetadata(DDC2182OptionParent::class), + $this->_em->getClassMetadata(DDC2182OptionChild::class), + ] + ); + $collation = $this->getColumnCollationDeclarationSQL('utf8_unicode_ci'); - $this->assertEquals("CREATE TABLE DDC2182OptionParent (id INT UNSIGNED NOT NULL, PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB", $sql[0]); - $this->assertEquals("CREATE TABLE DDC2182OptionChild (id VARCHAR(255) NOT NULL, parent_id INT UNSIGNED DEFAULT NULL, INDEX IDX_B314D4AD727ACA70 (parent_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB", $sql[1]); + $this->assertEquals('CREATE TABLE DDC2182OptionParent (id INT UNSIGNED NOT NULL, PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 ' . $collation . ' ENGINE = InnoDB', $sql[0]); + $this->assertEquals('CREATE TABLE DDC2182OptionChild (id VARCHAR(255) NOT NULL, parent_id INT UNSIGNED DEFAULT NULL, INDEX IDX_B314D4AD727ACA70 (parent_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 ' . $collation . ' ENGINE = InnoDB', $sql[1]); $this->assertEquals("ALTER TABLE DDC2182OptionChild ADD CONSTRAINT FK_B314D4AD727ACA70 FOREIGN KEY (parent_id) REFERENCES DDC2182OptionParent (id)", $sql[2]); } + + private function getColumnCollationDeclarationSQL(string $collation) : string + { + if (method_exists($this->_em->getConnection()->getDatabasePlatform(), 'getColumnCollationDeclarationSQL')) { + return $this->_em->getConnection()->getDatabasePlatform()->getColumnCollationDeclarationSQL($collation); + } + + return sprintf('COLLATE %s', $collation); + } } /** diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2214Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2214Test.php index 060b6ba334e..87101fff1da 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2214Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2214Test.php @@ -17,10 +17,12 @@ protected function setUp() { parent::setUp(); - $this->_schemaTool->createSchema(array( - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC2214Foo'), - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC2214Bar'), - )); + $this->_schemaTool->createSchema( + [ + $this->_em->getClassMetadata(DDC2214Foo::class), + $this->_em->getClassMetadata(DDC2214Bar::class), + ] + ); } public function testIssue() @@ -36,7 +38,7 @@ public function testIssue() $this->_em->clear(); /* @var $foo \Doctrine\Tests\ORM\Functional\Ticket\DDC2214Foo */ - $foo = $this->_em->find(__NAMESPACE__ . '\\DDC2214Foo', $foo->id); + $foo = $this->_em->find(DDC2214Foo::class, $foo->id); $bar = $foo->bar; $logger = $this->_em->getConnection()->getConfiguration()->getSQLLogger(); @@ -44,7 +46,7 @@ public function testIssue() $related = $this ->_em ->createQuery('SELECT b FROM '.__NAMESPACE__ . '\DDC2214Bar b WHERE b.id IN(:ids)') - ->setParameter('ids', array($bar)) + ->setParameter('ids', [$bar]) ->getResult(); $query = end($logger->queries); diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2224Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2224Test.php index 781d644ff4e..3529fa35640 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2224Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2224Test.php @@ -14,7 +14,7 @@ class DDC2224Test extends \Doctrine\Tests\OrmFunctionalTestCase { public static function setUpBeforeClass() { - \Doctrine\DBAL\Types\Type::addType('DDC2224Type', __NAMESPACE__ . '\DDC2224Type'); + \Doctrine\DBAL\Types\Type::addType('DDC2224Type', DDC2224Type::class); } public function testIssue() diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2230Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2230Test.php index 8c2655d1be9..d68fd8a52e9 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2230Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2230Test.php @@ -4,23 +4,29 @@ use Doctrine\Common\NotifyPropertyChanged; use Doctrine\Common\PropertyChangedListener; +use Doctrine\Common\Proxy\Proxy; use Doctrine\ORM\Tools\ToolsException; use Doctrine\Tests\OrmFunctionalTestCase; +use Doctrine\Tests\VerifyDeprecations; /** * @group DDC-2230 */ class DDC2230Test extends OrmFunctionalTestCase { + use VerifyDeprecations; + protected function setUp() { parent::setUp(); try { - $this->_schemaTool->createSchema(array( - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC2230User'), - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC2230Address'), - )); + $this->_schemaTool->createSchema( + [ + $this->_em->getClassMetadata(DDC2230User::class), + $this->_em->getClassMetadata(DDC2230Address::class), + ] + ); } catch (ToolsException $e) {} } @@ -34,17 +40,18 @@ public function testNotifyTrackingNotCalledOnUninitializedProxies() $this->_em->flush(); $this->_em->clear(); - $user = $this->_em->find(__NAMESPACE__ . '\\DDC2230User', $insertedUser->id); + $user = $this->_em->find(DDC2230User::class, $insertedUser->id); $this->_em->clear(); $mergedUser = $this->_em->merge($user); - /* @var $address \Doctrine\Common\Proxy\Proxy */ + /* @var $address Proxy */ $address = $mergedUser->address; - $this->assertInstanceOf('Doctrine\\ORM\\Proxy\\Proxy', $address); + $this->assertInstanceOf(Proxy::class, $address); $this->assertFalse($address->__isInitialized()); + $this->assertHasDeprecationMessages(); } public function testNotifyTrackingCalledOnProxyInitialization() @@ -55,15 +62,16 @@ public function testNotifyTrackingCalledOnProxyInitialization() $this->_em->flush(); $this->_em->clear(); - $addressProxy = $this->_em->getReference(__NAMESPACE__ . '\\DDC2230Address', $insertedAddress->id); + $addressProxy = $this->_em->getReference(DDC2230Address::class, $insertedAddress->id); - /* @var $addressProxy \Doctrine\Common\Proxy\Proxy|\Doctrine\Tests\ORM\Functional\Ticket\DDC2230Address */ + /* @var $addressProxy Proxy|\Doctrine\Tests\ORM\Functional\Ticket\DDC2230Address */ $this->assertFalse($addressProxy->__isInitialized()); $this->assertNull($addressProxy->listener); $addressProxy->__load(); $this->assertSame($this->_em->getUnitOfWork(), $addressProxy->listener); + $this->assertNotHasDeprecationMessages(); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2231Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2231Test.php index d6ff17c5515..6bfd8d823d0 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2231Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2231Test.php @@ -5,6 +5,7 @@ use Doctrine\Common\Persistence\Mapping\ClassMetadata; use Doctrine\Common\Persistence\ObjectManager; use Doctrine\Common\Persistence\ObjectManagerAware; +use Doctrine\ORM\Proxy\Proxy; /** * @group DDC-2231 @@ -14,9 +15,11 @@ class DDC2231Test extends \Doctrine\Tests\OrmFunctionalTestCase protected function setUp() { parent::setUp(); - $this->_schemaTool->createSchema(array( - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC2231EntityY'), - )); + $this->_schemaTool->createSchema( + [ + $this->_em->getClassMetadata(DDC2231EntityY::class), + ] + ); } public function testInjectObjectManagerInProxyIfInitializedInUow() @@ -30,7 +33,7 @@ public function testInjectObjectManagerInProxyIfInitializedInUow() $y1ref = $this->_em->getReference(get_class($y1), $y1->id); - $this->assertInstanceOf('Doctrine\ORM\Proxy\Proxy', $y1ref); + $this->assertInstanceOf(Proxy::class, $y1ref); $this->assertFalse($y1ref->__isInitialized__); $id = $y1ref->doSomething(); diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2252Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2252Test.php index 491cf3bd6ad..e4b60196622 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2252Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2252Test.php @@ -12,18 +12,20 @@ class DDC2252Test extends \Doctrine\Tests\OrmFunctionalTestCase private $user; private $merchant; private $membership; - private $privileges = array(); + private $privileges = []; protected function setUp() { parent::setUp(); - $this->_schemaTool->createSchema(array( - $this->_em->getClassMetadata('Doctrine\Tests\ORM\Functional\Ticket\DDC2252User'), - $this->_em->getClassMetadata('Doctrine\Tests\ORM\Functional\Ticket\DDC2252Privilege'), - $this->_em->getClassMetadata('Doctrine\Tests\ORM\Functional\Ticket\DDC2252Membership'), - $this->_em->getClassMetadata('Doctrine\Tests\ORM\Functional\Ticket\DDC2252MerchantAccount'), - )); + $this->_schemaTool->createSchema( + [ + $this->_em->getClassMetadata(DDC2252User::class), + $this->_em->getClassMetadata(DDC2252Privilege::class), + $this->_em->getClassMetadata(DDC2252Membership::class), + $this->_em->getClassMetadata(DDC2252MerchantAccount::class), + ] + ); $this->loadFixtures(); } @@ -56,15 +58,14 @@ public function loadFixtures() public function testIssue() { - $identifier = array( + $identifier = [ 'merchantAccount' => $this->merchant->getAccountid(), 'userAccount' => $this->user->getUid(), - ); + ]; - $class = 'Doctrine\Tests\ORM\Functional\Ticket\DDC2252Membership'; - $membership = $this->_em->find($class, $identifier); + $membership = $this->_em->find(DDC2252Membership::class, $identifier); - $this->assertInstanceOf($class, $membership); + $this->assertInstanceOf(DDC2252Membership::class, $membership); $this->assertCount(3, $membership->getPrivileges()); $membership->getPrivileges()->remove(2); @@ -72,9 +73,9 @@ public function testIssue() $this->_em->flush(); $this->_em->clear(); - $membership = $this->_em->find($class, $identifier); + $membership = $this->_em->find(DDC2252Membership::class, $identifier); - $this->assertInstanceOf($class, $membership); + $this->assertInstanceOf(DDC2252Membership::class, $membership); $this->assertCount(2, $membership->getPrivileges()); $membership->getPrivileges()->clear(); @@ -82,9 +83,9 @@ public function testIssue() $this->_em->flush(); $this->_em->clear(); - $membership = $this->_em->find($class, $identifier); + $membership = $this->_em->find(DDC2252Membership::class, $identifier); - $this->assertInstanceOf($class, $membership); + $this->assertInstanceOf(DDC2252Membership::class, $membership); $this->assertCount(0, $membership->getPrivileges()); $membership->addPrivilege($privilege3 = new DDC2252Privilege); @@ -93,9 +94,9 @@ public function testIssue() $this->_em->flush(); $this->_em->clear(); - $membership = $this->_em->find($class, $identifier); + $membership = $this->_em->find(DDC2252Membership::class, $identifier); - $this->assertInstanceOf($class, $membership); + $this->assertInstanceOf(DDC2252Membership::class, $membership); $this->assertCount(1, $membership->getPrivileges()); } } @@ -226,4 +227,4 @@ public function getPrivileges() { return $this->privileges; } -} \ No newline at end of file +} diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2256Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2256Test.php index 42aeca43e3c..02281a5e3a0 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2256Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2256Test.php @@ -13,16 +13,19 @@ class DDC2256Test extends \Doctrine\Tests\OrmFunctionalTestCase protected function setUp() { parent::setUp(); - $this->_schemaTool->createSchema(array( - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC2256User'), - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC2256Group') - )); + + $this->_schemaTool->createSchema( + [ + $this->_em->getClassMetadata(DDC2256User::class), + $this->_em->getClassMetadata(DDC2256Group::class) + ] + ); } public function testIssue() { $config = $this->_em->getConfiguration(); - $config->addEntityNamespace('MyNamespace', 'Doctrine\Tests\ORM\Functional\Ticket'); + $config->addEntityNamespace('MyNamespace', __NAMESPACE__); $user = new DDC2256User(); $user->name = 'user'; @@ -48,14 +51,14 @@ public function testIssue() $rsm->addFieldResult('g', 'group_id', 'id'); $rsm->addFieldResult('g', 'group_name', 'name'); - $this->_em->createNativeQuery($sql, $rsm)->getResult(); + self::assertCount(1, $this->_em->createNativeQuery($sql, $rsm)->getResult()); // Test ResultSetMappingBuilder. $rsm = new ResultSetMappingBuilder($this->_em); $rsm->addRootEntityFromClassMetadata('MyNamespace:DDC2256User', 'u'); - $rsm->addJoinedEntityFromClassMetadata('MyNamespace:DDC2256Group', 'g', 'u', 'group', array('id' => 'group_id', 'name' => 'group_name')); + $rsm->addJoinedEntityFromClassMetadata('MyNamespace:DDC2256Group', 'g', 'u', 'group', ['id' => 'group_id', 'name' => 'group_name']); - $this->_em->createNativeQuery($sql, $rsm)->getResult(); + self::assertCount(1, $this->_em->createNativeQuery($sql, $rsm)->getResult()); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2306Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2306Test.php index ca3ee1a50cd..24807db029a 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2306Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2306Test.php @@ -3,6 +3,7 @@ namespace Doctrine\Tests\ORM\Functional\Ticket; use Doctrine\Common\Collections\ArrayCollection; +use Doctrine\ORM\Proxy\Proxy; /** * @group DDC-2306 @@ -16,12 +17,14 @@ protected function setUp() { parent::setUp(); - $this->_schemaTool->createSchema(array( - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC2306Zone'), - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC2306User'), - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC2306Address'), - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC2306UserAddress'), - )); + $this->_schemaTool->createSchema( + [ + $this->_em->getClassMetadata(DDC2306Zone::class), + $this->_em->getClassMetadata(DDC2306User::class), + $this->_em->getClassMetadata(DDC2306Address::class), + $this->_em->getClassMetadata(DDC2306UserAddress::class), + ] + ); } /** @@ -53,12 +56,12 @@ public function testIssue() $this->_em->clear(); /* @var $address DDC2306Address */ - $address = $this->_em->find(__NAMESPACE__ . '\\DDC2306Address', $address->id); - /* @var $user DDC2306User|\Doctrine\ORM\Proxy\Proxy */ + $address = $this->_em->find(DDC2306Address::class, $address->id); + /* @var $user DDC2306User|Proxy */ $user = $address->users->first()->user; - $this->assertInstanceOf('Doctrine\ORM\Proxy\Proxy', $user); - $this->assertInstanceOf(__NAMESPACE__ . '\\DDC2306User', $user); + $this->assertInstanceOf(Proxy::class, $user); + $this->assertInstanceOf(DDC2306User::class, $user); $userId = $user->id; @@ -148,4 +151,4 @@ public function __construct(DDC2306User $user, DDC2306Address $address) $user->addresses->add($this); $address->users->add($this); } -} \ No newline at end of file +} diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2346Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2346Test.php index 3d2781763e9..a1cac08eaf3 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2346Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2346Test.php @@ -22,11 +22,13 @@ protected function setUp() { parent::setUp(); - $this->_schemaTool->createSchema(array( - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC2346Foo'), - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC2346Bar'), - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC2346Baz'), - )); + $this->_schemaTool->createSchema( + [ + $this->_em->getClassMetadata(DDC2346Foo::class), + $this->_em->getClassMetadata(DDC2346Bar::class), + $this->_em->getClassMetadata(DDC2346Baz::class), + ] + ); $this->logger = new DebugStack(); } @@ -58,7 +60,7 @@ public function testIssue() $this->_em->getConnection()->getConfiguration()->setSQLLogger($this->logger); - $fetchedBazs = $this->_em->getRepository(__NAMESPACE__ . '\\DDC2346Baz')->findAll(); + $fetchedBazs = $this->_em->getRepository(DDC2346Baz::class)->findAll(); $this->assertCount(2, $fetchedBazs); $this->assertCount(2, $this->logger->queries, 'The total number of executed queries is 2, and not n+1'); @@ -106,4 +108,4 @@ class DDC2346Bar class DDC2346Baz extends DDC2346Bar { -} \ No newline at end of file +} diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2350Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2350Test.php index 145b1733079..1d3a4117ad0 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2350Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2350Test.php @@ -14,10 +14,12 @@ protected function setUp() { parent::setUp(); - $this->_schemaTool->createSchema(array( - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC2350User'), - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC2350Bug'), - )); + $this->_schemaTool->createSchema( + [ + $this->_em->getClassMetadata(DDC2350User::class), + $this->_em->getClassMetadata(DDC2350Bug::class), + ] + ); } public function testEagerCollectionsAreOnlyRetrievedOnce() @@ -36,7 +38,7 @@ public function testEagerCollectionsAreOnlyRetrievedOnce() $this->_em->clear(); $cnt = $this->getCurrentQueryCount(); - $user = $this->_em->find(__NAMESPACE__ . '\DDC2350User', $user->id); + $user = $this->_em->find(DDC2350User::class, $user->id); $this->assertEquals($cnt + 1, $this->getCurrentQueryCount()); diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2359Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2359Test.php index 12be3241a19..21a932ed36d 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2359Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2359Test.php @@ -8,11 +8,12 @@ use Doctrine\ORM\EntityManager; use Doctrine\ORM\Mapping\ClassMetadata; use Doctrine\ORM\Mapping\ClassMetadataFactory; +use PHPUnit\Framework\TestCase; /** * @group DDC-2359 */ -class DDC2359Test extends \PHPUnit_Framework_TestCase +class DDC2359Test extends TestCase { /** @@ -27,11 +28,11 @@ public function testIssue() /* @var $metadataFactory \Doctrine\ORM\Mapping\ClassMetadataFactory|\PHPUnit_Framework_MockObject_MockObject */ $metadataFactory = $this->getMockBuilder(ClassMetadataFactory::class) - ->setMethods(array('newClassMetadataInstance', 'wakeupReflection')) + ->setMethods(['newClassMetadataInstance', 'wakeupReflection']) ->getMock(); $configuration = $this->getMockBuilder(Configuration::class) - ->setMethods(array('getMetadataDriverImpl')) + ->setMethods(['getMetadataDriverImpl']) ->getMock(); $connection = $this->createMock(Connection::class); @@ -53,7 +54,7 @@ public function testIssue() $metadataFactory->setEntityManager($entityManager); - $this->assertSame($mockMetadata, $metadataFactory->getMetadataFor(__NAMESPACE__ . '\\DDC2359Foo')); + $this->assertSame($mockMetadata, $metadataFactory->getMetadataFor(DDC2359Foo::class)); } } @@ -62,4 +63,4 @@ class DDC2359Foo { /** @Id @Column(type="integer") @GeneratedValue */ public $id; -} \ No newline at end of file +} diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC237Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC237Test.php index 3ff5cd9b42d..eac219c7280 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC237Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC237Test.php @@ -2,16 +2,20 @@ namespace Doctrine\Tests\ORM\Functional\Ticket; +use Doctrine\ORM\Proxy\Proxy; + class DDC237Test extends \Doctrine\Tests\OrmFunctionalTestCase { protected function setUp() { parent::setUp(); - $this->_schemaTool->createSchema(array( - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC237EntityX'), - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC237EntityY'), - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC237EntityZ') - )); + $this->_schemaTool->createSchema( + [ + $this->_em->getClassMetadata(DDC237EntityX::class), + $this->_em->getClassMetadata(DDC237EntityY::class), + $this->_em->getClassMetadata(DDC237EntityZ::class) + ] + ); } public function testUninitializedProxyIsInitializedOnFetchJoin() @@ -35,7 +39,7 @@ public function testUninitializedProxyIsInitializedOnFetchJoin() $this->_em->clear(); $x2 = $this->_em->find(get_class($x), $x->id); // proxy injected for Y - $this->assertInstanceOf('Doctrine\ORM\Proxy\Proxy', $x2->y); + $this->assertInstanceOf(Proxy::class, $x2->y); $this->assertFalse($x2->y->__isInitialized__); // proxy for Y is in identity map @@ -43,7 +47,7 @@ public function testUninitializedProxyIsInitializedOnFetchJoin() $z2 = $this->_em->createQuery('select z,y from ' . get_class($z) . ' z join z.y y where z.id = ?1') ->setParameter(1, $z->id) ->getSingleResult(); - $this->assertInstanceOf('Doctrine\ORM\Proxy\Proxy', $z2->y); + $this->assertInstanceOf(Proxy::class, $z2->y); $this->assertTrue($z2->y->__isInitialized__); $this->assertEquals('Y', $z2->y->data); $this->assertEquals($y->id, $z2->y->id); @@ -54,7 +58,7 @@ public function testUninitializedProxyIsInitializedOnFetchJoin() $this->assertNotSame($x, $x2); $this->assertNotSame($z, $z2); $this->assertSame($z2->y, $x2->y); - $this->assertInstanceOf('Doctrine\ORM\Proxy\Proxy', $z2->y); + $this->assertInstanceOf(Proxy::class, $z2->y); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2387Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2387Test.php index f74d4e15cfe..de4e2058955 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2387Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2387Test.php @@ -14,15 +14,15 @@ public function testCompositeAssociationKeyDetection() { $product = new \Doctrine\DBAL\Schema\Table('ddc2387_product'); $product->addColumn('id', 'integer'); - $product->setPrimaryKey(array('id')); + $product->setPrimaryKey(['id']); $attributes = new \Doctrine\DBAL\Schema\Table('ddc2387_attributes'); $attributes->addColumn('product_id', 'integer'); $attributes->addColumn('attribute_name', 'string'); - $attributes->setPrimaryKey(array('product_id', 'attribute_name')); - $attributes->addForeignKeyConstraint('ddc2387_product', array('product_id'), array('product_id')); + $attributes->setPrimaryKey(['product_id', 'attribute_name']); + $attributes->addForeignKeyConstraint('ddc2387_product', ['product_id'], ['product_id']); - $metadata = $this->convertToClassMetadata(array($product, $attributes), array()); + $metadata = $this->convertToClassMetadata([$product, $attributes], []); $this->assertEquals(ClassMetadataInfo::GENERATOR_TYPE_NONE, $metadata['Ddc2387Attributes']->generatorType); $this->assertEquals(ClassMetadataInfo::GENERATOR_TYPE_AUTO, $metadata['Ddc2387Product']->generatorType); diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2409Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2409Test.php index c8b85f24fc3..aa44bbaee6b 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2409Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2409Test.php @@ -5,12 +5,15 @@ use Doctrine\ORM\UnitOfWork; use Doctrine\Tests\Models\CMS\CmsUser; use Doctrine\Tests\Models\CMS\CmsArticle; +use Doctrine\Tests\VerifyDeprecations; /** * @group DDC-2409 */ class DDC2409Test extends \Doctrine\Tests\OrmFunctionalTestCase { + use VerifyDeprecations; + public function setUp() { $this->useModelSet('cms'); @@ -21,7 +24,7 @@ public function testIssue() { $em = $this->_em; $uow = $em->getUnitOfWork(); - + $originalArticle = new CmsArticle(); $originalUser = new CmsUser(); @@ -39,7 +42,7 @@ public function testIssue() $em->flush(); $em->clear(); - $article = $em->find('Doctrine\Tests\Models\CMS\CmsArticle', $originalArticle->id); + $article = $em->find(CmsArticle::class, $originalArticle->id); $user = new CmsUser(); $user->name = 'Doctrine Bot 2.0'; @@ -53,8 +56,8 @@ public function testIssue() $this->assertEquals(UnitOfWork::STATE_MANAGED, $uow->getEntityState($article)); $this->assertEquals(UnitOfWork::STATE_NEW, $uow->getEntityState($user)); - $em->detach($user); - $em->detach($article); + $em->clear(CmsUser::class); + $em->clear(CmsArticle::class); $userMerged = $em->merge($user); $articleMerged = $em->merge($article); @@ -68,5 +71,6 @@ public function testIssue() $this->assertNotSame($article, $articleMerged); $this->assertNotSame($userMerged, $articleMerged->user); $this->assertSame($user, $articleMerged->user); + $this->assertHasDeprecationMessages(); } -} \ No newline at end of file +} diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2415Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2415Test.php index 0283e64577c..fb1f0ec273a 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2415Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2415Test.php @@ -16,22 +16,24 @@ protected function setUp() { parent::setUp(); - $this->_em->getConfiguration()->setMetadataDriverImpl(new StaticPHPDriver(array())); - - $this->_schemaTool->createSchema(array( - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC2415ParentEntity'), - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC2415ChildEntity'), - )); + $this->_em->getConfiguration()->setMetadataDriverImpl(new StaticPHPDriver([])); + + $this->_schemaTool->createSchema( + [ + $this->_em->getClassMetadata(DDC2415ParentEntity::class), + $this->_em->getClassMetadata(DDC2415ChildEntity::class), + ] + ); } public function testTicket() { - $parentMetadata = $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC2415ParentEntity'); - $childMetadata = $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC2415ChildEntity'); + $parentMetadata = $this->_em->getClassMetadata(DDC2415ParentEntity::class); + $childMetadata = $this->_em->getClassMetadata(DDC2415ChildEntity::class); $this->assertEquals($parentMetadata->generatorType, $childMetadata->generatorType); $this->assertEquals($parentMetadata->customGeneratorDefinition, $childMetadata->customGeneratorDefinition); - $this->assertEquals('Doctrine\Tests\ORM\Functional\Ticket\DDC2415Generator', $parentMetadata->customGeneratorDefinition['class']); + $this->assertEquals(DDC2415Generator::class, $parentMetadata->customGeneratorDefinition['class']); $e1 = new DDC2415ChildEntity("ChildEntity 1"); $e2 = new DDC2415ChildEntity("ChildEntity 2"); @@ -57,16 +59,16 @@ public function getId() public static function loadMetadata(ClassMetadataInfo $metadata) { - $metadata->mapField(array ( + $metadata->mapField( + [ 'id' => true, 'fieldName' => 'id', 'type' => 'string', - )); + ] + ); $metadata->setIdGeneratorType(ClassMetadataInfo::GENERATOR_TYPE_CUSTOM); - $metadata->setCustomGeneratorDefinition(array( - 'class' => 'Doctrine\Tests\ORM\Functional\Ticket\DDC2415Generator' - )); + $metadata->setCustomGeneratorDefinition(['class' => DDC2415Generator::class]); $metadata->isMappedSuperclass = true; } @@ -88,10 +90,12 @@ public function getName() public static function loadMetadata(ClassMetadataInfo $metadata) { - $metadata->mapField(array ( + $metadata->mapField( + [ 'fieldName' => 'name', 'type' => 'string', - )); + ] + ); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2494Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2494Test.php index b5a09f9223a..4aa30e95046 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2494Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2494Test.php @@ -15,14 +15,16 @@ protected function setUp() { parent::setUp(); - DDC2494TinyIntType::$calls = array(); + DDC2494TinyIntType::$calls = []; - Type::addType('ddc2494_tinyint', __NAMESPACE__ . '\DDC2494TinyIntType'); + Type::addType('ddc2494_tinyint', DDC2494TinyIntType::class); - $this->_schemaTool->createSchema(array( - $this->_em->getClassMetadata(DDC2494Currency::CLASSNAME), - $this->_em->getClassMetadata(DDC2494Campaign::CLASSNAME), - )); + $this->_schemaTool->createSchema( + [ + $this->_em->getClassMetadata(DDC2494Currency::class), + $this->_em->getClassMetadata(DDC2494Campaign::class), + ] + ); } public function testIssue() @@ -41,10 +43,10 @@ public function testIssue() $this->assertArrayHasKey('convertToDatabaseValue', DDC2494TinyIntType::$calls); $this->assertCount(3, DDC2494TinyIntType::$calls['convertToDatabaseValue']); - $item = $this->_em->find(DDC2494Campaign::CLASSNAME, $campaign->getId()); + $item = $this->_em->find(DDC2494Campaign::class, $campaign->getId()); - $this->assertInstanceOf(DDC2494Campaign::CLASSNAME, $item); - $this->assertInstanceOf(DDC2494Currency::CLASSNAME, $item->getCurrency()); + $this->assertInstanceOf(DDC2494Campaign::class, $item); + $this->assertInstanceOf(DDC2494Currency::class, $item->getCurrency()); $queryCount = $this->getCurrentQueryCount(); @@ -74,8 +76,6 @@ public function testIssue() */ class DDC2494Currency { - const CLASSNAME = __CLASS__; - /** * @Id * @Column(type="integer", type="ddc2494_tinyint") @@ -122,8 +122,6 @@ public function getCampaigns() */ class DDC2494Campaign { - const CLASSNAME = __CLASS__; - /** * @Id * @GeneratedValue @@ -160,7 +158,7 @@ public function getCurrency() class DDC2494TinyIntType extends Type { - public static $calls = array(); + public static $calls = []; /** * {@inheritdoc} @@ -177,11 +175,11 @@ public function convertToDatabaseValue($value, AbstractPlatform $platform) { $return = (string) $value; - self::$calls[__FUNCTION__][] = array( + self::$calls[__FUNCTION__][] = [ 'value' => $value, 'return' => $return, 'platform' => $platform, - ); + ]; return $return; } @@ -193,11 +191,11 @@ public function convertToPHPValue($value, AbstractPlatform $platform) { $return = (integer) $value; - self::$calls[__FUNCTION__][] = array( + self::$calls[__FUNCTION__][] = [ 'value' => $value, 'return' => $return, 'platform' => $platform, - ); + ]; return $return; } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2519Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2519Test.php index d6ea115b5ac..cc12d044dc0 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2519Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2519Test.php @@ -2,6 +2,7 @@ namespace Doctrine\Tests\ORM\Functional\Ticket; +use Doctrine\ORM\Proxy\Proxy; use Doctrine\Tests\Models\Legacy\LegacyUser; use Doctrine\Tests\Models\Legacy\LegacyUserReference; @@ -29,18 +30,18 @@ public function testIssue() $result = $this->_em->createQuery($dql)->getResult(); $this->assertCount(2, $result); - $this->assertInstanceOf('Doctrine\Tests\Models\Legacy\LegacyUserReference', $result[0]); - $this->assertInstanceOf('Doctrine\Tests\Models\Legacy\LegacyUserReference', $result[1]); - - $this->assertInstanceOf('Doctrine\Tests\Models\Legacy\LegacyUser', $result[0]->source()); - $this->assertInstanceOf('Doctrine\Tests\Models\Legacy\LegacyUser', $result[0]->target()); - $this->assertInstanceOf('Doctrine\Tests\Models\Legacy\LegacyUser', $result[1]->source()); - $this->assertInstanceOf('Doctrine\Tests\Models\Legacy\LegacyUser', $result[1]->target()); - - $this->assertInstanceOf('Doctrine\ORM\Proxy\Proxy', $result[0]->source()); - $this->assertInstanceOf('Doctrine\ORM\Proxy\Proxy', $result[0]->target()); - $this->assertInstanceOf('Doctrine\ORM\Proxy\Proxy', $result[1]->source()); - $this->assertInstanceOf('Doctrine\ORM\Proxy\Proxy', $result[1]->target()); + $this->assertInstanceOf(LegacyUserReference::class, $result[0]); + $this->assertInstanceOf(LegacyUserReference::class, $result[1]); + + $this->assertInstanceOf(LegacyUser::class, $result[0]->source()); + $this->assertInstanceOf(LegacyUser::class, $result[0]->target()); + $this->assertInstanceOf(LegacyUser::class, $result[1]->source()); + $this->assertInstanceOf(LegacyUser::class, $result[1]->target()); + + $this->assertInstanceOf(Proxy::class, $result[0]->source()); + $this->assertInstanceOf(Proxy::class, $result[0]->target()); + $this->assertInstanceOf(Proxy::class, $result[1]->source()); + $this->assertInstanceOf(Proxy::class, $result[1]->target()); $this->assertFalse($result[0]->target()->__isInitialized()); $this->assertFalse($result[0]->source()->__isInitialized()); diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2575Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2575Test.php index 2f6b406d3b6..e3652e55c04 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2575Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2575Test.php @@ -7,19 +7,21 @@ */ class DDC2575Test extends \Doctrine\Tests\OrmFunctionalTestCase { - private $rootsEntities = array(); - private $aEntities = array(); - private $bEntities = array(); + private $rootsEntities = []; + private $aEntities = []; + private $bEntities = []; protected function setUp() { parent::setUp(); - $this->_schemaTool->createSchema(array( - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC2575Root'), - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC2575A'), - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC2575B'), - )); + $this->_schemaTool->createSchema( + [ + $this->_em->getClassMetadata(DDC2575Root::class), + $this->_em->getClassMetadata(DDC2575A::class), + $this->_em->getClassMetadata(DDC2575B::class), + ] + ); $entityRoot1 = new DDC2575Root(1); $entityB1 = new DDC2575B(2); @@ -53,7 +55,7 @@ protected function setUp() public function testHydrationIssue() { - $repository = $this->_em->getRepository(__NAMESPACE__ . '\DDC2575Root'); + $repository = $this->_em->getRepository(DDC2575Root::class); $qb = $repository->createQueryBuilder('r') ->select('r, a, b') ->leftJoin('r.aRelation', 'a') @@ -61,7 +63,7 @@ public function testHydrationIssue() $query = $qb->getQuery(); $result = $query->getResult(); - + $this->assertCount(2, $result); $row = $result[0]; @@ -157,4 +159,4 @@ public function __construct($id, $value = 0) $this->id = $id; $this->sampleField = $value; } -} \ No newline at end of file +} diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2579Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2579Test.php index fe68ff564df..e7ba77759f4 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2579Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2579Test.php @@ -15,13 +15,15 @@ protected function setUp() { parent::setUp(); - Type::addType(DDC2579Type::NAME, DDC2579Type::CLASSNAME); - - $this->_schemaTool->createSchema(array( - $this->_em->getClassMetadata(DDC2579Entity::CLASSNAME), - $this->_em->getClassMetadata(DDC2579EntityAssoc::CLASSNAME), - $this->_em->getClassMetadata(DDC2579AssocAssoc::CLASSNAME), - )); + Type::addType(DDC2579Type::NAME, DDC2579Type::class); + + $this->_schemaTool->createSchema( + [ + $this->_em->getClassMetadata(DDC2579Entity::class), + $this->_em->getClassMetadata(DDC2579EntityAssoc::class), + $this->_em->getClassMetadata(DDC2579AssocAssoc::class), + ] + ); } public function testIssue() @@ -30,13 +32,13 @@ public function testIssue() $assoc = new DDC2579AssocAssoc($id); $assocAssoc = new DDC2579EntityAssoc($assoc); $entity = new DDC2579Entity($assocAssoc); - $repository = $this->_em->getRepository(DDC2579Entity::CLASSNAME); + $repository = $this->_em->getRepository(DDC2579Entity::class); $this->_em->persist($assoc); $this->_em->persist($assocAssoc); $this->_em->persist($entity); $this->_em->flush(); - + $entity->value++; $this->_em->persist($entity); @@ -45,10 +47,10 @@ public function testIssue() $id = $entity->id; $value = $entity->value; - $criteria = array('assoc' => $assoc, 'id' => $id); + $criteria = ['assoc' => $assoc, 'id' => $id]; $entity = $repository->findOneBy($criteria); - $this->assertInstanceOf(DDC2579Entity::CLASSNAME, $entity); + $this->assertInstanceOf(DDC2579Entity::class, $entity); $this->assertEquals($value, $entity->value); $this->_em->remove($entity); @@ -65,9 +67,6 @@ public function testIssue() */ class DDC2579Entity { - - const CLASSNAME = __CLASS__; - /** * @Id * @Column(type="ddc2579") @@ -100,8 +99,6 @@ public function __construct(DDC2579EntityAssoc $assoc, $value = 0) */ class DDC2579EntityAssoc { - const CLASSNAME = __CLASS__; - /** * @Id * @ManyToOne(targetEntity="DDC2579AssocAssoc") @@ -120,8 +117,6 @@ public function __construct(DDC2579AssocAssoc $assocAssoc) */ class DDC2579AssocAssoc { - const CLASSNAME = __CLASS__; - /** * @Id * @Column(type="ddc2579") @@ -138,7 +133,6 @@ public function __construct(DDC2579Id $id) class DDC2579Type extends StringType { const NAME = 'ddc2579'; - const CLASSNAME = __CLASS__; /** * {@inheritdoc} @@ -164,8 +158,6 @@ public function getName() class DDC2579Id { - const CLASSNAME = __CLASS__; - private $val; public function __construct($val) diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC258Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC258Test.php index d9dca3752c9..fb7ce673e3e 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC258Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC258Test.php @@ -9,12 +9,14 @@ class DDC258Test extends OrmFunctionalTestCase protected function setUp() { parent::setUp(); - $this->_schemaTool->createSchema(array( - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC258Super'), - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC258Class1'), - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC258Class2'), - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC258Class3'), - )); + $this->_schemaTool->createSchema( + [ + $this->_em->getClassMetadata(DDC258Super::class), + $this->_em->getClassMetadata(DDC258Class1::class), + $this->_em->getClassMetadata(DDC258Class2::class), + $this->_em->getClassMetadata(DDC258Class3::class), + ] + ); } /** @@ -43,14 +45,14 @@ public function testIssue() $this->_em->flush(); $this->_em->clear(); - $e2 = $this->_em->find('Doctrine\Tests\ORM\Functional\Ticket\DDC258Super', $c2->id); + $e2 = $this->_em->find(DDC258Super::class, $c2->id); - $this->assertInstanceOf('Doctrine\Tests\ORM\Functional\Ticket\DDC258Class2', $e2); + $this->assertInstanceOf(DDC258Class2::class, $e2); $this->assertEquals('Bar', $e2->title); $this->assertEquals('Bar', $e2->description); $this->assertEquals('Bar', $e2->text); - $all = $this->_em->getRepository(__NAMESPACE__.'\DDC258Super')->findAll(); + $all = $this->_em->getRepository(DDC258Super::class)->findAll(); foreach ($all as $obj) { if ($obj instanceof DDC258Class1) { diff --git a/tests/Doctrine/Tests/ORM/Performance/DDC2602Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2602Test.php similarity index 79% rename from tests/Doctrine/Tests/ORM/Performance/DDC2602Test.php rename to tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2602Test.php index 210f72c80cf..23b9f662f56 100644 --- a/tests/Doctrine/Tests/ORM/Performance/DDC2602Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2602Test.php @@ -1,63 +1,61 @@ _schemaTool->createSchema(array( - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC2602User'), - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC2602Biography'), - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC2602BiographyField'), - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC2602BiographyFieldChoice'), - )); + $this->_schemaTool->createSchema( + [ + $this->_em->getClassMetadata(DDC2602User::class), + $this->_em->getClassMetadata(DDC2602Biography::class), + $this->_em->getClassMetadata(DDC2602BiographyField::class), + $this->_em->getClassMetadata(DDC2602BiographyFieldChoice::class), + ] + ); $this->loadFixture(); } - protected function tearDown() + protected function tearDown() : void { parent::tearDown(); - $this->_schemaTool->dropSchema(array( - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC2602User'), - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC2602Biography'), - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC2602BiographyField'), - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC2602BiographyFieldChoice'), - )); + $this->_schemaTool->dropSchema( + [ + $this->_em->getClassMetadata(DDC2602User::class), + $this->_em->getClassMetadata(DDC2602Biography::class), + $this->_em->getClassMetadata(DDC2602BiographyField::class), + $this->_em->getClassMetadata(DDC2602BiographyFieldChoice::class), + ] + ); } - public function testIssue() + public function testPostLoadListenerShouldBeAbleToRunQueries() : void { $eventManager = $this->_em->getEventManager(); - $eventManager->addEventListener(array(Events::postLoad), new DDC2602PostLoadListener()); + $eventManager->addEventListener([Events::postLoad], new DDC2602PostLoadListener()); - // Set maximum seconds this can run - $this->setMaxRunningTime(1); + $result = $this->_em->createQuery('SELECT u, b FROM Doctrine\Tests\ORM\Functional\Ticket\DDC2602User u JOIN u.biography b') + ->getResult(); - $s = microtime(true); - - $query = $this->_em->createQuery('SELECT u, b FROM Doctrine\Tests\ORM\Performance\DDC2602User u JOIN u.biography b'); - $query->getResult(); - - $e = microtime(true); - - echo __FUNCTION__ . " - " . ($e - $s) . " seconds" . PHP_EOL; + self::assertCount(2, $result); + self::assertCount(2, $result[0]->biography->fieldList); + self::assertCount(1, $result[1]->biography->fieldList); } - private function loadFixture() + private function loadFixture() : void { $user1 = new DDC2602User(); $user2 = new DDC2602User(); @@ -128,7 +126,7 @@ private function loadFixture() class DDC2602PostLoadListener { - public function postLoad(LifecycleEventArgs $event) + public function postLoad(LifecycleEventArgs $event) : void { $entity = $event->getEntity(); @@ -139,7 +137,7 @@ public function postLoad(LifecycleEventArgs $event) $entityManager = $event->getEntityManager(); $query = $entityManager->createQuery(' SELECT f, fc - FROM Doctrine\Tests\ORM\Performance\DDC2602BiographyField f INDEX BY f.id + FROM Doctrine\Tests\ORM\Functional\Ticket\DDC2602BiographyField f INDEX BY f.id JOIN f.choiceList fc INDEX BY fc.id '); @@ -232,7 +230,7 @@ class DDC2602Biography /** * @var array */ - public $fieldList = array(); + public $fieldList = []; } /** diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2645Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2645Test.php index d6a77f7db37..e71de5b3f0a 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2645Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2645Test.php @@ -2,11 +2,15 @@ namespace Doctrine\Tests\ORM\Functional\Ticket; +use Doctrine\Tests\VerifyDeprecations; + /** * @group DDC-2645 */ class DDC2645Test extends \Doctrine\Tests\OrmFunctionalTestCase { + use VerifyDeprecations; + public function testIssue() { $bar = new DDC2645Bar; @@ -22,6 +26,7 @@ public function testIssue() $this->assertSame($foo, $foo3); $this->assertEquals('Bar', $foo->name); + $this->assertHasDeprecationMessages(); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2660Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2660Test.php index 2ec46ba29b4..46380f754b2 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2660Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2660Test.php @@ -5,7 +5,7 @@ use Doctrine\ORM\Query\ResultSetMappingBuilder; /** - * @group + * @group DDC-2660 */ class DDC2660Test extends \Doctrine\Tests\OrmFunctionalTestCase { @@ -17,11 +17,13 @@ protected function setUp() parent::setUp(); try { - $this->_schemaTool->createSchema(array( - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC2660Product'), - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC2660Customer'), - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC2660CustomerOrder') - )); + $this->_schemaTool->createSchema( + [ + $this->_em->getClassMetadata(DDC2660Product::class), + $this->_em->getClassMetadata(DDC2660Customer::class), + $this->_em->getClassMetadata(DDC2660CustomerOrder::class) + ] + ); } catch(\Exception $e) { return; } @@ -47,7 +49,7 @@ public function testIssueWithExtraColumn() $sql = "SELECT o.product_id, o.customer_id, o.name FROM ddc_2660_customer_order o"; $rsm = new ResultSetMappingBuilder($this->_getEntityManager()); - $rsm->addRootEntityFromClassMetadata(__NAMESPACE__ . '\DDC2660CustomerOrder', 'c'); + $rsm->addRootEntityFromClassMetadata(DDC2660CustomerOrder::class, 'c'); $query = $this->_em->createNativeQuery($sql, $rsm); $result = $query->getResult(); @@ -56,7 +58,7 @@ public function testIssueWithExtraColumn() foreach ($result as $order) { $this->assertNotNull($order); - $this->assertInstanceOf(__NAMESPACE__ . '\\DDC2660CustomerOrder', $order); + $this->assertInstanceOf(DDC2660CustomerOrder::class, $order); } } @@ -65,7 +67,7 @@ public function testIssueWithoutExtraColumn() $sql = "SELECT o.product_id, o.customer_id FROM ddc_2660_customer_order o"; $rsm = new ResultSetMappingBuilder($this->_getEntityManager()); - $rsm->addRootEntityFromClassMetadata(__NAMESPACE__ . '\DDC2660CustomerOrder', 'c'); + $rsm->addRootEntityFromClassMetadata(DDC2660CustomerOrder::class, 'c'); $query = $this->_em->createNativeQuery($sql, $rsm); $result = $query->getResult(); @@ -74,7 +76,7 @@ public function testIssueWithoutExtraColumn() foreach ($result as $order) { $this->assertNotNull($order); - $this->assertInstanceOf(__NAMESPACE__ . '\\DDC2660CustomerOrder', $order); + $this->assertInstanceOf(DDC2660CustomerOrder::class, $order); } } } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2692Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2692Test.php index 437f89ffbd4..1e9f05e4768 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2692Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2692Test.php @@ -18,9 +18,11 @@ protected function setUp() parent::setUp(); try { - $this->_schemaTool->createSchema(array( - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC2692Foo'), - )); + $this->_schemaTool->createSchema( + [ + $this->_em->getClassMetadata(DDC2692Foo::class), + ] + ); } catch(\Exception $e) { return; } @@ -30,7 +32,7 @@ protected function setUp() public function testIsListenerCalledOnlyOnceOnPreFlush() { $listener = $this->getMockBuilder(DDC2692Listener::class) - ->setMethods(array('preFlush')) + ->setMethods(['preFlush']) ->getMock(); $listener->expects($this->once())->method('preFlush'); @@ -56,7 +58,7 @@ class DDC2692Foo class DDC2692Listener implements EventSubscriber { public function getSubscribedEvents() { - return array(\Doctrine\ORM\Events::preFlush); + return [\Doctrine\ORM\Events::preFlush]; } public function preFlush(PreFlushEventArgs $args) { diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2759Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2759Test.php index 6198663e601..10d3e68ae91 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2759Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2759Test.php @@ -15,12 +15,14 @@ protected function setUp() parent::setUp(); try { - $this->_schemaTool->createSchema(array( - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC2759Qualification'), - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC2759Category'), - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC2759QualificationMetadata'), - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC2759MetadataCategory'), - )); + $this->_schemaTool->createSchema( + [ + $this->_em->getClassMetadata(DDC2759Qualification::class), + $this->_em->getClassMetadata(DDC2759Category::class), + $this->_em->getClassMetadata(DDC2759QualificationMetadata::class), + $this->_em->getClassMetadata(DDC2759MetadataCategory::class), + ] + ); } catch(\Exception $e) { return; } @@ -49,7 +51,7 @@ protected function setUp() public function testCorrectNumberOfAssociationsIsReturned() { - $repository = $this->_em->getRepository(__NAMESPACE__ . '\DDC2759Qualification'); + $repository = $this->_em->getRepository(DDC2759Qualification::class); $builder = $repository->createQueryBuilder('q') ->select('q, qm, qmc') diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2775Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2775Test.php index e98ff91a329..b84024f048d 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2775Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2775Test.php @@ -15,12 +15,14 @@ protected function setUp() { parent::setUp(); - $this->setUpEntitySchema(array( - 'Doctrine\Tests\ORM\Functional\Ticket\User', - 'Doctrine\Tests\ORM\Functional\Ticket\Role', - 'Doctrine\Tests\ORM\Functional\Ticket\AdminRole', - 'Doctrine\Tests\ORM\Functional\Ticket\Authorization', - )); + $this->setUpEntitySchema( + [ + User::class, + Role::class, + AdminRole::class, + Authorization::class, + ] + ); } /** @@ -28,9 +30,8 @@ protected function setUp() */ public function testIssueCascadeRemove() { - $user = new User(); - $role = new AdminRole(); + $user = new User(); $user->addRole($role); $authorization = new Authorization(); @@ -43,11 +44,13 @@ public function testIssueCascadeRemove() // Need to clear so that associations are lazy-loaded $this->_em->clear(); - $user = $this->_em->find('Doctrine\Tests\ORM\Functional\Ticket\User', $user->id); + $user = $this->_em->find(User::class, $user->id); $this->_em->remove($user); $this->_em->flush(); + self::assertEmpty($this->_em->getRepository(Authorization::class)->findAll()); + // With the bug, the second flush throws an error because the cascade remove didn't work correctly $this->_em->flush(); } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2780Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2780Test.php new file mode 100644 index 00000000000..5539dfbbe5c --- /dev/null +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2780Test.php @@ -0,0 +1,89 @@ +_schemaTool->createSchema( + [ + $this->_em->getClassMetadata(DDC2780User::class), + $this->_em->getClassMetadata(DDC2780Project::class) + ] + ); + } + + /** + * Verifies that IS [NOT] NULL can be used on join aliases + */ + public function testIssue() + { + $user = new DDC2780User; + $project = new DDC2780Project; + + $user->project = $project; + + $this->_em->persist($project); + $this->_em->persist($user); + $this->_em->flush(); + $this->_em->clear(); + + $result = $this->_em->createQueryBuilder() + ->select('user') + ->from(DDC2780User::class, 'user') + ->leftJoin('user.project', 'project') + ->where('project IS NOT NULL') + ->getQuery() + ->getOneOrNullResult(); + + $this->assertInstanceOf(DDC2780User::class, $result); + } +} + +/** + * @Entity + */ +class DDC2780User +{ + /** @Id @Column(type="integer") @GeneratedValue */ + public $id; + + /** + * @ManyToOne(targetEntity="DDC2780Project") + * + * @var DDC2780Project + */ + public $project; +} + +/** @Entity */ +class DDC2780Project +{ + /** @Id @Column(type="integer") @GeneratedValue */ + public $id; + + /** + * @OneToMany(targetEntity="DDC2780User", mappedBy="project") + * + * @var DDC2780User[] + */ + public $users; + + /** Constructor */ + public function __construct() + { + $this->users = new ArrayCollection(); + } +} + diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2790Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2790Test.php index ee2668931c0..0f3efab262c 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2790Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2790Test.php @@ -45,7 +45,7 @@ public function testIssue() // (and consequently also triggers preUpdate/postUpdate for the entity in question) $entity->name = 'Robin'; - $this->_em->flush($entity); + $this->_em->flush(); $qb = $this->_em->createQueryBuilder(); $qb->from(get_class($entity), 'c'); diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC279Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC279Test.php index 2f1be3d32c1..f09e2e68ccd 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC279Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC279Test.php @@ -7,12 +7,14 @@ class DDC279Test extends \Doctrine\Tests\OrmFunctionalTestCase protected function setUp() { parent::setUp(); - $this->_schemaTool->createSchema(array( - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC279EntityXAbstract'), - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC279EntityX'), - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC279EntityY'), - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC279EntityZ'), - )); + $this->_schemaTool->createSchema( + [ + $this->_em->getClassMetadata(DDC279EntityXAbstract::class), + $this->_em->getClassMetadata(DDC279EntityX::class), + $this->_em->getClassMetadata(DDC279EntityY::class), + $this->_em->getClassMetadata(DDC279EntityZ::class), + ] + ); } /** diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2825Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2825Test.php index 87c94cb8446..7aeba002a0a 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2825Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2825Test.php @@ -67,7 +67,7 @@ public function testClassSchemaMappingsValidity($className, $expectedSchemaName, public function testPersistenceOfEntityWithSchemaMapping($className) { try { - $this->_schemaTool->createSchema(array($this->_em->getClassMetadata($className))); + $this->_schemaTool->createSchema([$this->_em->getClassMetadata($className)]); } catch (ToolsException $e) { // table already exists } @@ -86,11 +86,11 @@ public function testPersistenceOfEntityWithSchemaMapping($className) */ public function getTestedClasses() { - return array( - array(ExplicitSchemaAndTable::CLASSNAME, 'explicit_schema', 'explicit_table'), - array(SchemaAndTableInTableName::CLASSNAME, 'implicit_schema', 'implicit_table'), - array(DDC2825ClassWithImplicitlyDefinedSchemaAndQuotedTableName::CLASSNAME, 'myschema', 'order'), - ); + return [ + [ExplicitSchemaAndTable::class, 'explicit_schema', 'explicit_table'], + [SchemaAndTableInTableName::class, 'implicit_schema', 'implicit_table'], + [DDC2825ClassWithImplicitlyDefinedSchemaAndQuotedTableName::class, 'myschema', 'order'], + ]; } } @@ -100,8 +100,6 @@ public function getTestedClasses() */ class DDC2825ClassWithImplicitlyDefinedSchemaAndQuotedTableName { - const CLASSNAME = __CLASS__; - /** * @Id @GeneratedValue * @Column(type="integer") diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2862Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2862Test.php index 28535a3d722..c4b2fb227bf 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2862Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2862Test.php @@ -16,10 +16,12 @@ public function setUp() parent::setUp(); try { - $this->_schemaTool->createSchema(array( - $this->_em->getClassMetadata(DDC2862User::CLASSNAME), - $this->_em->getClassMetadata(DDC2862Driver::CLASSNAME), - )); + $this->_schemaTool->createSchema( + [ + $this->_em->getClassMetadata(DDC2862User::class), + $this->_em->getClassMetadata(DDC2862Driver::class), + ] + ); } catch (ToolsException $exc) { } } @@ -34,30 +36,30 @@ public function testIssue() $this->_em->flush(); $this->_em->clear(); - $this->assertTrue($this->_em->getCache()->containsEntity(DDC2862User::CLASSNAME, array('id' => $user1->getId()))); - $this->assertTrue($this->_em->getCache()->containsEntity(DDC2862Driver::CLASSNAME, array('id' => $driver1->getId()))); + $this->assertTrue($this->_em->getCache()->containsEntity(DDC2862User::class, ['id' => $user1->getId()])); + $this->assertTrue($this->_em->getCache()->containsEntity(DDC2862Driver::class, ['id' => $driver1->getId()])); $queryCount = $this->getCurrentQueryCount(); - $driver2 = $this->_em->find(DDC2862Driver::CLASSNAME, $driver1->getId()); + $driver2 = $this->_em->find(DDC2862Driver::class, $driver1->getId()); $this->assertEquals($queryCount, $this->getCurrentQueryCount()); - $this->assertInstanceOf(DDC2862Driver::CLASSNAME, $driver2); - $this->assertInstanceOf(DDC2862User::CLASSNAME, $driver2->getUserProfile()); + $this->assertInstanceOf(DDC2862Driver::class, $driver2); + $this->assertInstanceOf(DDC2862User::class, $driver2->getUserProfile()); $driver2->setName('Franta'); $this->_em->flush(); $this->_em->clear(); - $this->assertTrue($this->_em->getCache()->containsEntity(DDC2862User::CLASSNAME, array('id' => $user1->getId()))); - $this->assertTrue($this->_em->getCache()->containsEntity(DDC2862Driver::CLASSNAME, array('id' => $driver1->getId()))); + $this->assertTrue($this->_em->getCache()->containsEntity(DDC2862User::class, ['id' => $user1->getId()])); + $this->assertTrue($this->_em->getCache()->containsEntity(DDC2862Driver::class, ['id' => $driver1->getId()])); $queryCount = $this->getCurrentQueryCount(); - $driver3 = $this->_em->find(DDC2862Driver::CLASSNAME, $driver1->getId()); + $driver3 = $this->_em->find(DDC2862Driver::class, $driver1->getId()); $this->assertEquals($queryCount, $this->getCurrentQueryCount()); - $this->assertInstanceOf(DDC2862Driver::CLASSNAME, $driver3); - $this->assertInstanceOf(DDC2862User::CLASSNAME, $driver3->getUserProfile()); + $this->assertInstanceOf(DDC2862Driver::class, $driver3); + $this->assertInstanceOf(DDC2862User::class, $driver3->getUserProfile()); $this->assertEquals('Franta', $driver3->getName()); $this->assertEquals('Foo', $driver3->getUserProfile()->getName()); } @@ -72,38 +74,38 @@ public function testIssueReopened() $this->_em->flush(); $this->_em->clear(); - $this->_em->getCache()->evictEntityRegion(DDC2862User::CLASSNAME); - $this->_em->getCache()->evictEntityRegion(DDC2862Driver::CLASSNAME); + $this->_em->getCache()->evictEntityRegion(DDC2862User::class); + $this->_em->getCache()->evictEntityRegion(DDC2862Driver::class); - $this->assertFalse($this->_em->getCache()->containsEntity(DDC2862User::CLASSNAME, array('id' => $user1->getId()))); - $this->assertFalse($this->_em->getCache()->containsEntity(DDC2862Driver::CLASSNAME, array('id' => $driver1->getId()))); + $this->assertFalse($this->_em->getCache()->containsEntity(DDC2862User::class, ['id' => $user1->getId()])); + $this->assertFalse($this->_em->getCache()->containsEntity(DDC2862Driver::class, ['id' => $driver1->getId()])); $queryCount = $this->getCurrentQueryCount(); - $driver2 = $this->_em->find(DDC2862Driver::CLASSNAME, $driver1->getId()); + $driver2 = $this->_em->find(DDC2862Driver::class, $driver1->getId()); - $this->assertInstanceOf(DDC2862Driver::CLASSNAME, $driver2); - $this->assertInstanceOf(DDC2862User::CLASSNAME, $driver2->getUserProfile()); + $this->assertInstanceOf(DDC2862Driver::class, $driver2); + $this->assertInstanceOf(DDC2862User::class, $driver2->getUserProfile()); $this->assertEquals($queryCount + 1, $this->getCurrentQueryCount()); $this->_em->clear(); - $this->assertFalse($this->_em->getCache()->containsEntity(DDC2862User::CLASSNAME, array('id' => $user1->getId()))); - $this->assertTrue($this->_em->getCache()->containsEntity(DDC2862Driver::CLASSNAME, array('id' => $driver1->getId()))); + $this->assertFalse($this->_em->getCache()->containsEntity(DDC2862User::class, ['id' => $user1->getId()])); + $this->assertTrue($this->_em->getCache()->containsEntity(DDC2862Driver::class, ['id' => $driver1->getId()])); $queryCount = $this->getCurrentQueryCount(); - $driver3 = $this->_em->find(DDC2862Driver::CLASSNAME, $driver1->getId()); + $driver3 = $this->_em->find(DDC2862Driver::class, $driver1->getId()); - $this->assertInstanceOf(DDC2862Driver::CLASSNAME, $driver3); - $this->assertInstanceOf(DDC2862User::CLASSNAME, $driver3->getUserProfile()); + $this->assertInstanceOf(DDC2862Driver::class, $driver3); + $this->assertInstanceOf(DDC2862User::class, $driver3->getUserProfile()); $this->assertEquals($queryCount, $this->getCurrentQueryCount()); $this->assertEquals('Foo', $driver3->getUserProfile()->getName()); $this->assertEquals($queryCount + 1, $this->getCurrentQueryCount()); $queryCount = $this->getCurrentQueryCount(); - $driver4 = $this->_em->find(DDC2862Driver::CLASSNAME, $driver1->getId()); + $driver4 = $this->_em->find(DDC2862Driver::class, $driver1->getId()); - $this->assertInstanceOf(DDC2862Driver::CLASSNAME, $driver4); - $this->assertInstanceOf(DDC2862User::CLASSNAME, $driver4->getUserProfile()); + $this->assertInstanceOf(DDC2862Driver::class, $driver4); + $this->assertInstanceOf(DDC2862User::class, $driver4->getUserProfile()); $this->assertEquals($queryCount, $this->getCurrentQueryCount()); $this->assertEquals('Foo', $driver4->getUserProfile()->getName()); $this->assertEquals($queryCount, $this->getCurrentQueryCount()); @@ -117,8 +119,6 @@ public function testIssueReopened() */ class DDC2862Driver { - const CLASSNAME = __CLASS__; - /** * @Id * @GeneratedValue @@ -194,8 +194,6 @@ public function getUserProfile() */ class DDC2862User { - const CLASSNAME = __CLASS__; - /** * @Id * @GeneratedValue diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2895Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2895Test.php index 5eece3f9bd8..397c7acd380 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2895Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2895Test.php @@ -13,9 +13,11 @@ public function setUp() { parent::setUp(); try { - $this->_schemaTool->createSchema(array( - $this->_em->getClassMetadata(__NAMESPACE__ . '\\DDC2895'), - )); + $this->_schemaTool->createSchema( + [ + $this->_em->getClassMetadata(DDC2895::class), + ] + ); } catch(\Exception $e) { } @@ -23,13 +25,13 @@ public function setUp() public function testPostLoadOneToManyInheritance() { - $cm = $this->_em->getClassMetadata(__NAMESPACE__ . '\\DDC2895'); + $cm = $this->_em->getClassMetadata(DDC2895::class); $this->assertEquals( - array( - "prePersist" => array("setLastModifiedPreUpdate"), - "preUpdate" => array("setLastModifiedPreUpdate"), - ), + [ + "prePersist" => ["setLastModifiedPreUpdate"], + "preUpdate" => ["setLastModifiedPreUpdate"], + ], $cm->lifecycleCallbacks ); @@ -109,4 +111,4 @@ public function getId() { return $this->id; } -} \ No newline at end of file +} diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2931Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2931Test.php index 8923f276454..927856a1c6e 100755 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2931Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2931Test.php @@ -14,9 +14,11 @@ public function setUp() parent::setUp(); try { - $this->_schemaTool->createSchema(array( - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC2931User'), - )); + $this->_schemaTool->createSchema( + [ + $this->_em->getClassMetadata(DDC2931User::class), + ] + ); } catch (\Exception $e) { // no action needed - schema seems to be already in place } @@ -38,7 +40,7 @@ public function testIssue() $this->_em->flush(); $this->_em->clear(); - $second = $this->_em->find('Doctrine\Tests\ORM\Functional\Ticket\DDC2931User', $second->id); + $second = $this->_em->find(DDC2931User::class, $second->id); $this->assertSame(2, $second->getRank()); } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2943Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2943Test.php index 7ae6ef5f31d..553bc98f528 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2943Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2943Test.php @@ -33,7 +33,7 @@ public function testIssue() { $this->loadFixtures(); - $region = $this->_em->getCache()->getEntityCacheRegion(Country::CLASSNAME); + $region = $this->_em->getCache()->getEntityCacheRegion(Country::class); $dql = 'SELECT c FROM Doctrine\Tests\Models\Cache\Country c'; $query = $this->_em->createQuery($dql) ->setCacheable(true) @@ -52,7 +52,7 @@ public function testIssueNonFetchJoin() { $this->loadFixtures(); - $region = $this->_em->getCache()->getEntityCacheRegion(Country::CLASSNAME); + $region = $this->_em->getCache()->getEntityCacheRegion(Country::class); $dql = 'SELECT c FROM Doctrine\Tests\Models\Cache\Country c'; $query = $this->_em->createQuery($dql) ->setCacheable(true) diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2984Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2984Test.php index 19439c1434c..e21ac82dc87 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2984Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2984Test.php @@ -15,18 +15,20 @@ class DDC2984Test extends \Doctrine\Tests\OrmFunctionalTestCase public function setUp() { parent::setUp(); - + if ( ! Type::hasType('ddc2984_domain_user_id')) { Type::addType( - 'ddc2984_domain_user_id', - __NAMESPACE__ . '\DDC2984UserIdCustomDbalType' + 'ddc2984_domain_user_id', + DDC2984UserIdCustomDbalType::class ); } try { - $this->_schemaTool->createSchema(array( - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC2984User'), - )); + $this->_schemaTool->createSchema( + [ + $this->_em->getClassMetadata(DDC2984User::class), + ] + ); } catch (\Exception $e) { // no action needed - schema seems to be already in place } @@ -36,10 +38,10 @@ public function testIssue() { $user = new DDC2984User(new DDC2984DomainUserId('unique_id_within_a_vo')); $user->applyName('Alex'); - + $this->_em->persist($user); - $this->_em->flush($user); - + $this->_em->flush(); + $repository = $this->_em->getRepository(__NAMESPACE__ . "\DDC2984User"); $sameUser = $repository->find(new DDC2984DomainUserId('unique_id_within_a_vo')); @@ -154,7 +156,7 @@ public function sameValueAs(DDC2984DomainUserId $other) { return $this->toString() === $other->toString(); } -} +} /** * Class DDC2984UserIdCustomDbalType @@ -196,4 +198,4 @@ public function convertToDatabaseValue($value, AbstractPlatform $platform) return $value->toString(); } -} \ No newline at end of file +} diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2996Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2996Test.php index 09d7415d2f9..4a2436330f0 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2996Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2996Test.php @@ -9,10 +9,12 @@ class DDC2996Test extends \Doctrine\Tests\OrmFunctionalTestCase { public function testIssue() { - $this->_schemaTool->createSchema(array( - $this->_em->getClassMetadata(__NAMESPACE__ . '\\DDC2996User'), - $this->_em->getClassMetadata(__NAMESPACE__ . '\\DDC2996UserPreference'), - )); + $this->_schemaTool->createSchema( + [ + $this->_em->getClassMetadata(DDC2996User::class), + $this->_em->getClassMetadata(DDC2996UserPreference::class), + ] + ); $pref = new DDC2996UserPreference(); $pref->user = new DDC2996User(); @@ -29,7 +31,7 @@ public function testIssue() $this->_em->clear(); - $pref = $this->_em->find(__NAMESPACE__ . '\\DDC2996UserPreference', $pref->id); + $pref = $this->_em->find(DDC2996UserPreference::class, $pref->id); $this->assertEquals(1, $pref->user->counter); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3033Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3033Test.php index e79551191d5..b25686dce10 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3033Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3033Test.php @@ -12,10 +12,12 @@ class DDC3033Test extends \Doctrine\Tests\OrmFunctionalTestCase { public function testIssue() { - $this->_schemaTool->createSchema(array( - $this->_em->getClassMetadata(__NAMESPACE__ . '\\DDC3033User'), - $this->_em->getClassMetadata(__NAMESPACE__ . '\\DDC3033Product'), - )); + $this->_schemaTool->createSchema( + [ + $this->_em->getClassMetadata(DDC3033User::class), + $this->_em->getClassMetadata(DDC3033Product::class), + ] + ); $user = new DDC3033User(); $user->name = "Test User"; @@ -38,12 +40,12 @@ public function testIssue() $this->_em->persist($product); $this->_em->flush(); - $expect = array( - 'title' => array( + $expect = [ + 'title' => [ 0 => 'Test product', 1 => 'Test Change title', - ), - ); + ], + ]; $this->assertEquals($expect, $product->changeSet); } @@ -55,7 +57,7 @@ public function testIssue() */ class DDC3033Product { - public $changeSet = array(); + public $changeSet = []; /** * @var int $id diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3042Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3042Test.php index fe84e11ffd3..940989bb713 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3042Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3042Test.php @@ -13,10 +13,12 @@ protected function setUp() { parent::setUp(); - $this->_schemaTool->createSchema(array( - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC3042Foo'), - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC3042Bar'), - )); + $this->_schemaTool->createSchema( + [ + $this->_em->getClassMetadata(DDC3042Foo::class), + $this->_em->getClassMetadata(DDC3042Bar::class), + ] + ); } public function testSQLGenerationDoesNotProvokeAliasCollisions() diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3068Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3068Test.php index d43e355635d..90a3f3ed80e 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3068Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3068Test.php @@ -8,7 +8,7 @@ /** * @group DDC-3068 - * + * * @author Giorgio Premi */ class DDC3068Test extends \Doctrine\Tests\OrmFunctionalTestCase @@ -40,19 +40,21 @@ protected function setUp() public function testFindUsingAnArrayOfObjectAsPrimaryKey() { - $ride1 = $this->_em->find('Doctrine\Tests\Models\Taxi\Ride', array( + $ride1 = $this->_em->find(Ride::class, [ 'driver' => $this->foo->getId(), - 'car' => $this->merc->getBrand()) + 'car' => $this->merc->getBrand() + ] ); - $this->assertInstanceOf('Doctrine\Tests\Models\Taxi\Ride', $ride1); + $this->assertInstanceOf(Ride::class, $ride1); - $ride2 = $this->_em->find('Doctrine\Tests\Models\Taxi\Ride', array( + $ride2 = $this->_em->find(Ride::class, [ 'driver' => $this->foo, 'car' => $this->merc - )); + ] + ); - $this->assertInstanceOf('Doctrine\Tests\Models\Taxi\Ride', $ride2); + $this->assertInstanceOf(Ride::class, $ride2); $this->assertSame($ride1, $ride2); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC309Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC309Test.php index 402c4374a41..15454b48269 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC309Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC309Test.php @@ -9,10 +9,12 @@ class DDC309Test extends OrmFunctionalTestCase protected function setUp() { parent::setUp(); - $this->_schemaTool->createSchema(array( - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC309Country'), - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC309User'), - )); + $this->_schemaTool->createSchema( + [ + $this->_em->getClassMetadata(DDC309Country::class), + $this->_em->getClassMetadata(DDC309User::class), + ] + ); } public function testTwoIterateHydrations() diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3103Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3103Test.php index bb9ccde1758..fe8329345ca 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3103Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3103Test.php @@ -14,10 +14,9 @@ class DDC3103Test extends \Doctrine\Tests\OrmFunctionalTestCase */ public function testIssue() { - $className = __NAMESPACE__ . '\\DDC3103ArticleId'; - $classMetadata = new ClassMetadata($className); + $classMetadata = new ClassMetadata(DDC3103ArticleId::class); - $this->createAnnotationDriver()->loadMetadataForClass($className, $classMetadata); + $this->createAnnotationDriver()->loadMetadataForClass(DDC3103ArticleId::class, $classMetadata); $this->assertTrue( $classMetadata->isEmbeddedClass, diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3123Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3123Test.php index 7f82e6c8969..515aa9febc7 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3123Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3123Test.php @@ -26,10 +26,10 @@ public function testIssue() $user->username = 'ocramius'; $this->_em->persist($user); - $uow->scheduleExtraUpdate($user, array('name' => 'changed name')); + $uow->scheduleExtraUpdate($user, ['name' => 'changed name']); $listener = $this->getMockBuilder(\stdClass::class) - ->setMethods(array(Events::postFlush)) + ->setMethods([Events::postFlush]) ->getMock(); $listener diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3170Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3170Test.php index 4924d39f9d4..45a49b7a6d0 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3170Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3170Test.php @@ -18,12 +18,12 @@ protected function setUp() parent::setUp(); $this->_schemaTool->createSchema( - array( - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC3170AbstractEntityJoined'), - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC3170ProductJoined'), - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC3170AbstractEntitySingleTable'), - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC3170ProductSingleTable'), - ) + [ + $this->_em->getClassMetadata(DDC3170AbstractEntityJoined::class), + $this->_em->getClassMetadata(DDC3170ProductJoined::class), + $this->_em->getClassMetadata(DDC3170AbstractEntitySingleTable::class), + $this->_em->getClassMetadata(DDC3170ProductSingleTable::class), + ] ); } @@ -38,36 +38,31 @@ protected function setUp() */ public function testIssue() { - // $this->_em->getConnection()->getConfiguration()->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger); - $productJoined = new DDC3170ProductJoined(); $productSingleTable = new DDC3170ProductSingleTable(); + $this->_em->persist($productJoined); $this->_em->persist($productSingleTable); $this->_em->flush(); $this->_em->clear(); - try { - $this->_em->createQueryBuilder() - ->select('p') - ->from(__NAMESPACE__ . '\\DDC3170ProductJoined', 'p') - ->getQuery() - ->getResult(AbstractQuery::HYDRATE_SIMPLEOBJECT); - } catch (HydrationException $e) // Thrown by SimpleObjectHydrator - { - $this->fail('Failed correct mapping of discriminator column when using simple object hydration and class table inheritance'); - } + $result = $this->_em->createQueryBuilder() + ->select('p') + ->from(DDC3170ProductJoined::class, 'p') + ->getQuery() + ->getResult(AbstractQuery::HYDRATE_SIMPLEOBJECT); + + self::assertCount(1, $result); + self::assertContainsOnly(DDC3170ProductJoined::class, $result); + + $result = $this->_em->createQueryBuilder() + ->select('p') + ->from(DDC3170ProductSingleTable::class, 'p') + ->getQuery() + ->getResult(AbstractQuery::HYDRATE_SIMPLEOBJECT); - try { - $this->_em->createQueryBuilder() - ->select('p') - ->from(__NAMESPACE__ . '\\DDC3170ProductSingleTable', 'p') - ->getQuery() - ->getResult(AbstractQuery::HYDRATE_SIMPLEOBJECT); - } catch (HydrationException $e) // Thrown by SimpleObjectHydrator - { - $this->fail('Failed correct mapping of discriminator column when using simple object hydration and single table inheritance'); - } + self::assertCount(1, $result); + self::assertContainsOnly(DDC3170ProductSingleTable::class, $result); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3192Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3192Test.php index da6a8de1d3f..1262bce4521 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3192Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3192Test.php @@ -23,12 +23,14 @@ protected function setUp() ); } - Type::addType('ddc3192_currency_code', __NAMESPACE__ . '\DDC3192CurrencyCode'); - - $this->_schemaTool->createSchema(array( - $this->_em->getClassMetadata(DDC3192Currency::CLASSNAME), - $this->_em->getClassMetadata(DDC3192Transaction::CLASSNAME), - )); + Type::addType('ddc3192_currency_code', DDC3192CurrencyCode::class); + + $this->_schemaTool->createSchema( + [ + $this->_em->getClassMetadata(DDC3192Currency::class), + $this->_em->getClassMetadata(DDC3192Transaction::class), + ] + ); } public function testIssue() @@ -45,7 +47,7 @@ public function testIssue() $this->_em->flush(); $this->_em->close(); - $resultByPersister = $this->_em->find(DDC3192Transaction::CLASSNAME, $transaction->id); + $resultByPersister = $this->_em->find(DDC3192Transaction::class, $transaction->id); // This works: DDC2494 makes persister set type mapping info to ResultSetMapping $this->assertEquals('BYR', $resultByPersister->currency->code); @@ -53,7 +55,7 @@ public function testIssue() $this->_em->close(); $query = $this->_em->createQuery(); - $query->setDQL('SELECT t FROM ' . DDC3192Transaction::CLASSNAME . ' t WHERE t.id = ?1'); + $query->setDQL('SELECT t FROM ' . DDC3192Transaction::class . ' t WHERE t.id = ?1'); $query->setParameter(1, $transaction->id); $resultByQuery = $query->getSingleResult(); @@ -70,8 +72,6 @@ public function testIssue() */ class DDC3192Currency { - const CLASSNAME = __CLASS__; - /** * @Id * @Column(type="ddc3192_currency_code") @@ -97,8 +97,6 @@ public function __construct($code) */ class DDC3192Transaction { - const CLASSNAME = __CLASS__; - /** * @Id * @GeneratedValue @@ -130,9 +128,9 @@ public function __construct($amount, DDC3192Currency $currency) class DDC3192CurrencyCode extends Type { - private static $map = array( + private static $map = [ 'BYR' => 974, - ); + ]; /** * {@inheritdoc} diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3223Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3223Test.php index 541221aa08e..0f98adca1fa 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3223Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3223Test.php @@ -15,12 +15,14 @@ protected function setUp() { parent::setUp(); - $this->setUpEntitySchema(array( - 'Doctrine\Tests\ORM\Functional\Ticket\Journalist', - 'Doctrine\Tests\ORM\Functional\Ticket\Participant', - 'Doctrine\Tests\ORM\Functional\Ticket\Status', - 'Doctrine\Tests\ORM\Functional\Ticket\ProfileStatus', - )); + $this->setUpEntitySchema( + [ + Journalist::class, + Participant::class, + Status::class, + ProfileStatus::class, + ] + ); } public function testIssueGetId() @@ -35,7 +37,7 @@ public function testIssueGetId() $this->_em->flush(); $this->_em->clear(); - $participant = $this->_em->find('Doctrine\Tests\ORM\Functional\Ticket\Participant', $participant->id); + $participant = $this->_em->find(Participant::class, $participant->id); $profileStatus = clone $participant->profileStatus; diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3300Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3300Test.php index b7905ca3de1..17de7d217e1 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3300Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3300Test.php @@ -14,22 +14,24 @@ public function testResolveTargetEntitiesChangesDiscriminatorMapValues() $resolveTargetEntity = new ResolveTargetEntityListener(); $resolveTargetEntity->addResolveTargetEntity( - DDC3300BossInterface::INTERFACENAME, - DDC3300Boss::CLASSNAME, - array() + DDC3300BossInterface::class, + DDC3300Boss::class, + [] ); $resolveTargetEntity->addResolveTargetEntity( - DDC3300EmployeeInterface::INTERFACENAME, - DDC3300Employee::CLASSNAME, - array() + DDC3300EmployeeInterface::class, + DDC3300Employee::class, + [] ); $this->_em->getEventManager()->addEventSubscriber($resolveTargetEntity); - $this->_schemaTool->createSchema(array( - $this->_em->getClassMetadata(DDC3300Person::CLASSNAME), - )); + $this->_schemaTool->createSchema( + [ + $this->_em->getClassMetadata(DDC3300Person::class), + ] + ); $boss = new DDC3300Boss(); $employee = new DDC3300Employee(); @@ -40,8 +42,8 @@ public function testResolveTargetEntitiesChangesDiscriminatorMapValues() $this->_em->flush(); $this->_em->clear(); - $this->assertEquals($boss, $this->_em->find(DDC3300BossInterface::INTERFACENAME, $boss->id)); - $this->assertEquals($employee, $this->_em->find(DDC3300EmployeeInterface::INTERFACENAME, $employee->id)); + $this->assertEquals($boss, $this->_em->find(DDC3300BossInterface::class, $boss->id)); + $this->assertEquals($employee, $this->_em->find(DDC3300EmployeeInterface::class, $employee->id)); } } @@ -56,30 +58,24 @@ public function testResolveTargetEntitiesChangesDiscriminatorMapValues() */ abstract class DDC3300Person { - const CLASSNAME = __CLASS__; - /** @Id @Column(type="integer") @GeneratedValue(strategy="AUTO") */ public $id; } interface DDC3300BossInterface { - const INTERFACENAME = __CLASS__; } /** @Entity */ class DDC3300Boss extends DDC3300Person implements DDC3300BossInterface { - const CLASSNAME = __CLASS__; } interface DDC3300EmployeeInterface { - const INTERFACENAME = __CLASS__; } /** @Entity */ class DDC3300Employee extends DDC3300Person implements DDC3300EmployeeInterface { - const CLASSNAME = __CLASS__; } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3330Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3330Test.php index a5ed2577026..a03c3172cfd 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3330Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3330Test.php @@ -16,10 +16,12 @@ protected function setUp() { parent::setUp(); - $this->setUpEntitySchema(array( - 'Doctrine\Tests\ORM\Functional\Ticket\DDC3330_Building', - 'Doctrine\Tests\ORM\Functional\Ticket\DDC3330_Hall', - )); + $this->setUpEntitySchema( + [ + DDC3330_Building::class, + DDC3330_Hall::class, + ] + ); } public function testIssueCollectionOrderWithPaginator() @@ -29,7 +31,7 @@ public function testIssueCollectionOrderWithPaginator() $this->createBuildingAndHalls(); $this->_em->clear(); - + $query = $this->_em->createQuery( 'SELECT b, h'. ' FROM Doctrine\Tests\ORM\Functional\Ticket\DDC3330_Building b'. @@ -37,32 +39,25 @@ public function testIssueCollectionOrderWithPaginator() ' ORDER BY b.id ASC, h.name DESC' ) ->setMaxResults(3); - + $paginator = new Paginator($query, true); - - /*foreach ($paginator as $building) { - echo 'BUILDING ID: '.$building->id."\n"; - foreach ($building->halls as $hall) { - echo ' - HALL: '.$hall->id.' - '.$hall->name."\n"; - } - }*/ - + $this->assertEquals(3, count(iterator_to_array($paginator)), 'Count is not correct for pagination'); } - + /** * Create a building and 10 halls */ private function createBuildingAndHalls() { $building = new DDC3330_Building(); - + for ($i = 0; $i < 10; $i++) { $hall = new DDC3330_Hall(); $hall->name = 'HALL-'.$i; $building->addHall($hall); } - + $this->_em->persist($building); $this->_em->flush(); } @@ -78,7 +73,7 @@ class DDC3330_Building * @GeneratedValue */ public $id; - + /** * @OneToMany(targetEntity="DDC3330_Hall", mappedBy="building", cascade={"persist"}) */ diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3346Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3346Test.php index ba286da24f2..3865767604e 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3346Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3346Test.php @@ -22,8 +22,8 @@ public function setUp() public function testFindOneWithEagerFetchWillNotHydrateLimitedCollection() { /* @var DDC3346Author $author */ - $author = $this->_em->getRepository(DDC3346Author::CLASSNAME)->findOneBy( - array('username' => 'bwoogy') + $author = $this->_em->getRepository(DDC3346Author::class)->findOneBy( + ['username' => 'bwoogy'] ); $this->assertCount(2, $author->articles); @@ -32,8 +32,8 @@ public function testFindOneWithEagerFetchWillNotHydrateLimitedCollection() public function testFindLimitedWithEagerFetchWillNotHydrateLimitedCollection() { /* @var DDC3346Author[] $authors */ - $authors = $this->_em->getRepository(DDC3346Author::CLASSNAME)->findBy( - array('username' => 'bwoogy'), + $authors = $this->_em->getRepository(DDC3346Author::class)->findBy( + ['username' => 'bwoogy'], null, 1 ); @@ -45,8 +45,8 @@ public function testFindLimitedWithEagerFetchWillNotHydrateLimitedCollection() public function testFindWithEagerFetchAndOffsetWillNotHydrateLimitedCollection() { /* @var DDC3346Author[] $authors */ - $authors = $this->_em->getRepository(DDC3346Author::CLASSNAME)->findBy( - array('username' => 'bwoogy'), + $authors = $this->_em->getRepository(DDC3346Author::class)->findBy( + ['username' => 'bwoogy'], null, null, 0 // using an explicitly defined offset diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC345Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC345Test.php index 255790d7cc3..20b4236c304 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC345Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC345Test.php @@ -8,11 +8,13 @@ protected function setUp() { parent::setUp(); //$this->_em->getConnection()->getConfiguration()->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger); - $this->_schemaTool->createSchema(array( - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC345User'), - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC345Group'), - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC345Membership'), - )); + $this->_schemaTool->createSchema( + [ + $this->_em->getClassMetadata(DDC345User::class), + $this->_em->getClassMetadata(DDC345Group::class), + $this->_em->getClassMetadata(DDC345Membership::class), + ] + ); } public function testTwoIterateHydrations() diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC353Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC353Test.php index 03d28bb2e99..dcb782bd4f8 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC353Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC353Test.php @@ -10,10 +10,12 @@ protected function setUp() { parent::setUp(); try { - $this->_schemaTool->createSchema(array( - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC353File'), - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC353Picture'), - )); + $this->_schemaTool->createSchema( + [ + $this->_em->getClassMetadata(DDC353File::class), + $this->_em->getClassMetadata(DDC353Picture::class), + ] + ); } catch(\Exception $ignored) {} } @@ -32,10 +34,10 @@ public function testWorkingCase() $fileId = $file->getFileId(); $this->assertTrue($fileId > 0); - $file = $em->getReference('Doctrine\Tests\ORM\Functional\Ticket\DDC353File', $fileId); + $file = $em->getReference(DDC353File::class, $fileId); $this->assertEquals(UnitOfWork::STATE_MANAGED, $em->getUnitOfWork()->getEntityState($file), "Reference Proxy should be marked MANAGED."); - $picture = $em->find('Doctrine\Tests\ORM\Functional\Ticket\DDC353Picture', $picture->getPictureId()); + $picture = $em->find(DDC353Picture::class, $picture->getPictureId()); $this->assertEquals(UnitOfWork::STATE_MANAGED, $em->getUnitOfWork()->getEntityState($picture->getFile()), "Lazy Proxy should be marked MANAGED."); $em->remove($picture); @@ -59,7 +61,7 @@ public function testFailingCase() $this->assertTrue($fileId > 0); - $picture = $em->find('Doctrine\Tests\ORM\Functional\Ticket\DDC353Picture', $pictureId); + $picture = $em->find(DDC353Picture::class, $pictureId); $this->assertEquals(UnitOfWork::STATE_MANAGED, $em->getUnitOfWork()->getEntityState($picture->getFile()), "Lazy Proxy should be marked MANAGED."); $em->remove($picture); diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3582Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3582Test.php index 4c07046f6fa..17b4bed85e4 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3582Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3582Test.php @@ -6,25 +6,23 @@ class DDC3582Test extends \Doctrine\Tests\OrmFunctionalTestCase { function testNestedEmbeddablesAreHydratedWithProperClass() { - $this->_schemaTool->createSchema([$this->_em->getClassMetadata(DDC3582Entity::CLASSNAME)]); + $this->_schemaTool->createSchema([$this->_em->getClassMetadata(DDC3582Entity::class)]); $this->_em->persist(new DDC3582Entity('foo')); $this->_em->flush(); $this->_em->clear(); /** @var DDC3582Entity $entity */ - $entity = $this->_em->find(DDC3582Entity::CLASSNAME, 'foo'); + $entity = $this->_em->find(DDC3582Entity::class, 'foo'); - $this->assertInstanceOf(DDC3582Embeddable1::CLASSNAME, $entity->embeddable1); - $this->assertInstanceOf(DDC3582Embeddable2::CLASSNAME, $entity->embeddable1->embeddable2); - $this->assertInstanceOf(DDC3582Embeddable3::CLASSNAME, $entity->embeddable1->embeddable2->embeddable3); + $this->assertInstanceOf(DDC3582Embeddable1::class, $entity->embeddable1); + $this->assertInstanceOf(DDC3582Embeddable2::class, $entity->embeddable1->embeddable2); + $this->assertInstanceOf(DDC3582Embeddable3::class, $entity->embeddable1->embeddable2->embeddable3); } } /** @Entity */ class DDC3582Entity { - const CLASSNAME = __CLASS__; - /** @Column @Id */ private $id; @@ -41,8 +39,6 @@ public function __construct($id) /** @Embeddable */ class DDC3582Embeddable1 { - const CLASSNAME = __CLASS__; - /** @Embedded(class="DDC3582Embeddable2") @var DDC3582Embeddable2 */ public $embeddable2; @@ -52,8 +48,6 @@ public function __construct() { $this->embeddable2 = new DDC3582Embeddable2(); } /** @Embeddable */ class DDC3582Embeddable2 { - const CLASSNAME = __CLASS__; - /** @Embedded(class="DDC3582Embeddable3") @var DDC3582Embeddable3 */ public $embeddable3; @@ -63,8 +57,6 @@ public function __construct() { $this->embeddable3 = new DDC3582Embeddable3(); } /** @Embeddable */ class DDC3582Embeddable3 { - const CLASSNAME = __CLASS__; - /** @Column */ public $embeddedValue = 'foo'; } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3597Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3597Test.php index e6f25b852e0..6d59fd6f70c 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3597Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3597Test.php @@ -13,11 +13,13 @@ class DDC3597Test extends \Doctrine\Tests\OrmFunctionalTestCase { protected function setUp() { parent::setUp(); - $this->_schemaTool->createSchema(array( - $this->_em->getClassMetadata(DDC3597Root::CLASSNAME), - $this->_em->getClassMetadata(DDC3597Media::CLASSNAME), - $this->_em->getClassMetadata(DDC3597Image::CLASSNAME) - )); + $this->_schemaTool->createSchema( + [ + $this->_em->getClassMetadata(DDC3597Root::class), + $this->_em->getClassMetadata(DDC3597Media::class), + $this->_em->getClassMetadata(DDC3597Image::class) + ] + ); } /** @@ -36,8 +38,8 @@ public function testSaveImageEntity() { $this->_em->clear(); //request entity - $imageEntity = $this->_em->find(DDC3597Image::CLASSNAME, $imageEntity->getId()); - $this->assertInstanceOf(DDC3597Image::CLASSNAME, $imageEntity); + $imageEntity = $this->_em->find(DDC3597Image::class, $imageEntity->getId()); + $this->assertInstanceOf(DDC3597Image::class, $imageEntity); //cleanup $this->_em->remove($imageEntity); @@ -45,7 +47,7 @@ public function testSaveImageEntity() { $this->_em->clear(); //check delete - $imageEntity = $this->_em->find(DDC3597Image::CLASSNAME, $imageEntity->getId()); + $imageEntity = $this->_em->find(DDC3597Image::class, $imageEntity->getId()); $this->assertNull($imageEntity); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3634Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3634Test.php index 679ab559c97..01f42bb930f 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3634Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3634Test.php @@ -16,7 +16,7 @@ class DDC3634Test extends OrmFunctionalTestCase { protected function setUp() { parent::setUp(); - $metadata = $this->_em->getClassMetadata(DDC3634Entity::CLASSNAME); + $metadata = $this->_em->getClassMetadata(DDC3634Entity::class); if ( ! $metadata->idGenerator->isPostInsertGenerator()) { $this->markTestSkipped('Need a post-insert ID generator in order to make this test work correctly'); @@ -25,8 +25,8 @@ protected function setUp() { try { $this->_schemaTool->createSchema([ $metadata, - $this->_em->getClassMetadata(DDC3634JTIBaseEntity::CLASSNAME), - $this->_em->getClassMetadata(DDC3634JTIChildEntity::CLASSNAME), + $this->_em->getClassMetadata(DDC3634JTIBaseEntity::class), + $this->_em->getClassMetadata(DDC3634JTIChildEntity::class), ]); } catch (ToolsException $e) { // schema already in place @@ -74,8 +74,6 @@ public function testSavesIntegerAutoGeneratedValueAsStringWithJoinedInheritance( /** @Entity */ class DDC3634Entity { - const CLASSNAME = __CLASS__; - /** @Id @Column(type="bigint") @GeneratedValue(strategy="AUTO") */ public $id; } @@ -90,8 +88,6 @@ class DDC3634Entity */ class DDC3634JTIBaseEntity { - const CLASSNAME = __CLASS__; - /** @Id @Column(type="bigint") @GeneratedValue(strategy="AUTO") */ public $id; } @@ -99,7 +95,6 @@ class DDC3634JTIBaseEntity /** @Entity */ class DDC3634JTIChildEntity extends DDC3634JTIBaseEntity { - const CLASSNAME = __CLASS__; } class DDC3634LastInsertIdMockingConnection extends Connection @@ -425,4 +420,4 @@ public function ping() { return $this->forwardCall(); } -} \ No newline at end of file +} diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3644Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3644Test.php index 46eeeab7447..968c44d721b 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3644Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3644Test.php @@ -16,12 +16,14 @@ protected function setUp() { parent::setUp(); - $this->setUpEntitySchema(array( - 'Doctrine\Tests\ORM\Functional\Ticket\DDC3644User', - 'Doctrine\Tests\ORM\Functional\Ticket\DDC3644Address', - 'Doctrine\Tests\ORM\Functional\Ticket\DDC3644Animal', - 'Doctrine\Tests\ORM\Functional\Ticket\DDC3644Pet', - )); + $this->setUpEntitySchema( + [ + DDC3644User::class, + DDC3644Address::class, + DDC3644Animal::class, + DDC3644Pet::class, + ] + ); } /** @@ -33,7 +35,7 @@ public function testIssueWithRegularEntity() $current = new DDC3644Address('Sao Paulo, SP, Brazil'); $previous = new DDC3644Address('Rio de Janeiro, RJ, Brazil'); $initial = new DDC3644Address('Sao Carlos, SP, Brazil'); - $addresses = new ArrayCollection(array($current, $previous, $initial)); + $addresses = new ArrayCollection([$current, $previous, $initial]); $user = new DDC3644User(); $user->name = 'Guilherme Blanco'; @@ -53,8 +55,8 @@ public function testIssueWithRegularEntity() // Replace entire collection (this should trigger OneToManyPersister::remove()) $current = new DDC3644Address('Toronto, ON, Canada'); - $addresses = new ArrayCollection(array($current)); - $user = $this->_em->find(__NAMESPACE__ . '\DDC3644User', $userId); + $addresses = new ArrayCollection([$current]); + $user = $this->_em->find(DDC3644User::class, $userId); $user->setAddresses($addresses); @@ -65,12 +67,12 @@ public function testIssueWithRegularEntity() $this->_em->clear(); // We should only have 1 item in the collection list now - $user = $this->_em->find(__NAMESPACE__ . '\DDC3644User', $userId); + $user = $this->_em->find(DDC3644User::class, $userId); $this->assertCount(1, $user->addresses); // We should only have 1 item in the addresses table too - $repository = $this->_em->getRepository(__NAMESPACE__ . '\DDC3644Address'); + $repository = $this->_em->getRepository(DDC3644Address::class); $addresses = $repository->findAll(); $this->assertCount(1, $addresses); @@ -84,7 +86,7 @@ public function testIssueWithJoinedEntity() // Define initial dataset $actual = new DDC3644Pet('Catharina'); $past = new DDC3644Pet('Nanny'); - $pets = new ArrayCollection(array($actual, $past)); + $pets = new ArrayCollection([$actual, $past]); $user = new DDC3644User(); $user->name = 'Guilherme Blanco'; @@ -103,8 +105,8 @@ public function testIssueWithJoinedEntity() // Replace entire collection (this should trigger OneToManyPersister::remove()) $actual = new DDC3644Pet('Valentina'); - $pets = new ArrayCollection(array($actual)); - $user = $this->_em->find(__NAMESPACE__ . '\DDC3644User', $userId); + $pets = new ArrayCollection([$actual]); + $user = $this->_em->find(DDC3644User::class, $userId); $user->setPets($pets); @@ -115,12 +117,12 @@ public function testIssueWithJoinedEntity() $this->_em->clear(); // We should only have 1 item in the collection list now - $user = $this->_em->find(__NAMESPACE__ . '\DDC3644User', $userId); + $user = $this->_em->find(DDC3644User::class, $userId); $this->assertCount(1, $user->pets); // We should only have 1 item in the pets table too - $repository = $this->_em->getRepository(__NAMESPACE__ . '\DDC3644Pet'); + $repository = $this->_em->getRepository(DDC3644Pet::class); $pets = $repository->findAll(); $this->assertCount(1, $pets); @@ -242,4 +244,4 @@ class DDC3644Pet extends DDC3644Animal * @JoinColumn(referencedColumnName="hash_id") */ public $owner; -} \ No newline at end of file +} diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3699Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3699Test.php index b33f9a4487e..8d3607112e2 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3699Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3699Test.php @@ -3,12 +3,15 @@ use Doctrine\Tests\Models\DDC3699\DDC3699RelationOne; use Doctrine\Tests\Models\DDC3699\DDC3699RelationMany; use Doctrine\Tests\Models\DDC3699\DDC3699Child; +use Doctrine\Tests\VerifyDeprecations; /** * @group DDC-3699 */ class DDC3597Test extends \Doctrine\Tests\OrmFunctionalTestCase { + use VerifyDeprecations; + protected function setUp() { $this->useModelSet('ddc3699'); @@ -16,6 +19,12 @@ protected function setUp() parent::setUp(); } + /** @after */ + public function ensureTestGeneratedDeprecationMessages() : void + { + $this->assertHasDeprecationMessages(); + } + /** * @group DDC-3699 */ @@ -42,12 +51,12 @@ public function testMergingParentClassFieldsDoesNotStopMergingScalarFieldsForToO // fixtures loaded /* @var $unManagedChild DDC3699Child */ - $unManagedChild = $this->_em->find(DDC3699Child::CLASSNAME, $id); + $unManagedChild = $this->_em->find(DDC3699Child::class, $id); $this->_em->detach($unManagedChild); // make it managed again - $this->_em->find(DDC3699Child::CLASSNAME, $id); + $this->_em->find(DDC3699Child::class, $id); $unManagedChild->childField = 'modifiedChildValue'; $unManagedChild->parentField = 'modifiedParentValue'; @@ -84,11 +93,11 @@ public function testMergingParentClassFieldsDoesNotStopMergingScalarFieldsForToM $this->_em->clear(); /* @var $unmanagedChild DDC3699Child */ - $unmanagedChild = $this->_em->find(DDC3699Child::CLASSNAME, $id); + $unmanagedChild = $this->_em->find(DDC3699Child::class, $id); $this->_em->detach($unmanagedChild); // make it managed again - $this->_em->find(DDC3699Child::CLASSNAME, $id); + $this->_em->find(DDC3699Child::class, $id); $unmanagedChild->childField = 'modifiedChildValue'; $unmanagedChild->parentField = 'modifiedParentValue'; @@ -99,4 +108,4 @@ public function testMergingParentClassFieldsDoesNotStopMergingScalarFieldsForToM $this->assertSame($mergedChild->childField, 'modifiedChildValue'); $this->assertSame($mergedChild->parentField, 'modifiedParentValue'); } -} \ No newline at end of file +} diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3711Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3711Test.php index 52c96154f22..dc633c7aa88 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3711Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3711Test.php @@ -1,16 +1,20 @@ - */ namespace Doctrine\Tests\ORM\Functional\Ticket; use Doctrine\ORM\Mapping\ClassMetadata; +use Doctrine\Tests\Models\DDC3711\DDC3711EntityA; use Doctrine\Tests\ORM\Mapping\YamlMappingDriverTest; +use Doctrine\Tests\VerifyDeprecations; +/** + * @author Marc Pantel + */ class DDC3711Test extends YamlMappingDriverTest { + use VerifyDeprecations; + public function testCompositeKeyForJoinTableInManyToManyCreation() { $yamlDriver = $this->_loadDriver(); @@ -20,11 +24,11 @@ public function testCompositeKeyForJoinTableInManyToManyCreation() $factory = new \Doctrine\ORM\Mapping\ClassMetadataFactory(); $factory->setEntityManager($em); - $entityA = new ClassMetadata('Doctrine\Tests\Models\DDC3711\DDC3711EntityA'); - $entityA = $factory->getMetadataFor('Doctrine\Tests\Models\DDC3711\DDC3711EntityA'); - - $this->assertEquals(array('link_a_id1' => "id1", 'link_a_id2' => "id2"), $entityA->associationMappings['entityB']['relationToSourceKeyColumns']); - $this->assertEquals(array('link_b_id1' => "id1", 'link_b_id2' => "id2"), $entityA->associationMappings['entityB']['relationToTargetKeyColumns']); + $entityA = new ClassMetadata(DDC3711EntityA::class); + $entityA = $factory->getMetadataFor(DDC3711EntityA::class); + $this->assertEquals(['link_a_id1' => "id1", 'link_a_id2' => "id2"], $entityA->associationMappings['entityB']['relationToSourceKeyColumns']); + $this->assertEquals(['link_b_id1' => "id1", 'link_b_id2' => "id2"], $entityA->associationMappings['entityB']['relationToTargetKeyColumns']); + $this->assertHasDeprecationMessages(); } -} \ No newline at end of file +} diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC371Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC371Test.php index 37e94c542bc..3fe5c4b80d3 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC371Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC371Test.php @@ -1,6 +1,7 @@ _em->getConnection()->getConfiguration()->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger); - $this->_schemaTool->createSchema(array( - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC371Parent'), - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC371Child') - )); + $this->_schemaTool->createSchema( + [ + $this->_em->getClassMetadata(DDC371Parent::class), + $this->_em->getClassMetadata(DDC371Child::class) + ] + ); } public function testIssue() @@ -42,7 +45,7 @@ public function testIssue() ->getResult(); $this->assertEquals(1, count($children)); - $this->assertNotInstanceOf('Doctrine\ORM\Proxy\Proxy', $children[0]->parent); + $this->assertNotInstanceOf(Proxy::class, $children[0]->parent); $this->assertFalse($children[0]->parent->children->isInitialized()); $this->assertEquals(0, $children[0]->parent->children->unwrap()->count()); } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3785Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3785Test.php index 4940c8abc8a..984cda551ba 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3785Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3785Test.php @@ -12,14 +12,16 @@ protected function setUp() { parent::setUp(); - Type::addType('ddc3785_asset_id', __NAMESPACE__ . '\\DDC3785_AssetIdType'); + Type::addType('ddc3785_asset_id', DDC3785_AssetIdType::class); try { - $this->_schemaTool->createSchema(array( - $this->_em->getClassMetadata(__NAMESPACE__ . '\\DDC3785_Asset'), - $this->_em->getClassMetadata(__NAMESPACE__ . '\\DDC3785_AssetId'), - $this->_em->getClassMetadata(__NAMESPACE__ . '\\DDC3785_Attribute') - )); + $this->_schemaTool->createSchema( + [ + $this->_em->getClassMetadata(DDC3785_Asset::class), + $this->_em->getClassMetadata(DDC3785_AssetId::class), + $this->_em->getClassMetadata(DDC3785_Attribute::class) + ] + ); } catch(\Exception $e) { } } @@ -29,18 +31,26 @@ protected function setUp() */ public function testOwningValueObjectIdIsCorrectlyTransformedWhenRemovingOrphanedChildEntities() { - $id = new DDC3785_AssetId("919609ba-57d9-4a13-be1d-d202521e858a"); - $attributes = array( - $attribute1 = new DDC3785_Attribute("foo1", "bar1"), - $attribute2 = new DDC3785_Attribute("foo2", "bar2") - ); + $id = new DDC3785_AssetId('919609ba-57d9-4a13-be1d-d202521e858a'); + + $attributes = [ + $attribute1 = new DDC3785_Attribute('foo1', 'bar1'), + $attribute2 = new DDC3785_Attribute('foo2', 'bar2') + ]; + $this->_em->persist($asset = new DDC3785_Asset($id, $attributes)); $this->_em->flush(); - $asset->getAttributes()->removeElement($attribute1); + $asset->getAttributes() + ->removeElement($attribute1); + + $idToBeRemoved = $attribute1->id; $this->_em->persist($asset); $this->_em->flush(); + + self::assertNull($this->_em->find(DDC3785_Attribute::class, $idToBeRemoved)); + self::assertNotNull($this->_em->find(DDC3785_Attribute::class, $attribute2->id)); } } @@ -64,14 +74,14 @@ class DDC3785_Asset **/ private $attributes; - public function __construct(DDC3785_AssetId $id, $attributes = array()) + public function __construct(DDC3785_AssetId $id, $attributes = []) { - $this->id = $id; - $this->attributes = new ArrayCollection(); + $this->id = $id; + $this->attributes = new ArrayCollection(); - foreach ($attributes as $attribute) { - $this->attributes->add($attribute); - } + foreach ($attributes as $attribute) { + $this->attributes->add($attribute); + } } public function getId() @@ -81,7 +91,7 @@ public function getId() public function getAttributes() { - return $this->attributes; + return $this->attributes; } } @@ -91,23 +101,23 @@ public function getAttributes() */ class DDC3785_Attribute { - /** + /** * @Id @Column(type="integer") * @GeneratedValue */ - private $id; + public $id; - /** @Column(type = "string") */ - private $name; + /** @Column(type = "string") */ + private $name; - /** @Column(type = "string") */ - private $value; + /** @Column(type = "string") */ + private $value; - public function __construct($name, $value) - { - $this->name = $name; - $this->value = $value; - } + public function __construct($name, $value) + { + $this->name = $name; + $this->value = $value; + } } /** @Embeddable */ @@ -118,12 +128,12 @@ class DDC3785_AssetId public function __construct($id) { - $this->id = $id; + $this->id = $id; } public function __toString() { - return $this->id; + return $this->id; } } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC381Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC381Test.php index eb3b77f5607..bbfd6974e21 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC381Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC381Test.php @@ -9,9 +9,11 @@ protected function setUp() parent::setUp(); try { - $this->_schemaTool->createSchema(array( - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC381Entity'), - )); + $this->_schemaTool->createSchema( + [ + $this->_em->getClassMetadata(DDC381Entity::class), + ] + ); } catch(\Exception $e) { } @@ -26,7 +28,7 @@ public function testCallUnserializedProxyMethods() $this->_em->clear(); $persistedId = $entity->getId(); - $entity = $this->_em->getReference('Doctrine\Tests\ORM\Functional\Ticket\DDC381Entity', $persistedId); + $entity = $this->_em->getReference(DDC381Entity::class, $persistedId); // explicitly load proxy (getId() does not trigger reload of proxy) $id = $entity->getOtherMethod(); diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3967Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3967Test.php index d5c3dd554ff..72a9cfe168a 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3967Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC3967Test.php @@ -12,7 +12,7 @@ protected function setUp() parent::setUp(); $this->loadFixturesCountries(); - $this->_em->getCache()->evictEntityRegion(Country::CLASSNAME); + $this->_em->getCache()->evictEntityRegion(Country::class); $this->_em->clear(); } @@ -22,12 +22,12 @@ public function testIdentifierCachedWithProperType() $id = $country->getId(); // First time, loaded from database - $this->_em->find(Country::CLASSNAME, "$id"); + $this->_em->find(Country::class, "$id"); $this->_em->clear(); // Second time, loaded from cache /** @var Country $country */ - $country = $this->_em->find(Country::CLASSNAME, "$id"); + $country = $this->_em->find(Country::class, "$id"); // Identifier type should be integer $this->assertSame($country->getId(), $id); diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC4003Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC4003Test.php index 1c286781a24..6764bc9bf75 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC4003Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC4003Test.php @@ -17,7 +17,7 @@ public function test_reads_through_repository_same_data_that_it_wrote_in_cache() // Get the id of the first bar $id = $this->attractions[0]->getId(); - $repository = $this->_em->getRepository(Bar::CLASSNAME); + $repository = $this->_em->getRepository(Bar::class); /** * This instance is fresh new, no QueryCache, so the full entity gets loaded from DB. diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC4024Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC4024Test.php new file mode 100644 index 00000000000..fa1208292bc --- /dev/null +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC4024Test.php @@ -0,0 +1,25 @@ +getMessage()); + } + + public function testADefaultMessageShouldBeUsedWhenNothingWasProvided() : void + { + $exception = new NonUniqueResultException(); + + self::assertSame(NonUniqueResultException::DEFAULT_MESSAGE, $exception->getMessage()); + } +} diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC422Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC422Test.php index 07f374b36d8..6ace5e74943 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC422Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC422Test.php @@ -2,17 +2,21 @@ namespace Doctrine\Tests\ORM\Functional\Ticket; +use Doctrine\ORM\PersistentCollection; + class DDC422Test extends \Doctrine\Tests\OrmFunctionalTestCase { protected function setUp() { parent::setUp(); //$this->_em->getConnection()->getConfiguration()->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger); - $this->_schemaTool->createSchema(array( - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC422Guest'), - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC422Customer'), - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC422Contact') - )); + $this->_schemaTool->createSchema( + [ + $this->_em->getClassMetadata(DDC422Guest::class), + $this->_em->getClassMetadata(DDC422Customer::class), + $this->_em->getClassMetadata(DDC422Contact::class) + ] + ); } /** @@ -27,7 +31,7 @@ public function testIssue() $customer = $this->_em->find(get_class($customer), $customer->id); - $this->assertInstanceOf('Doctrine\ORM\PersistentCollection', $customer->contacts); + $this->assertInstanceOf(PersistentCollection::class, $customer->contacts); $this->assertFalse($customer->contacts->isInitialized()); $contact = new DDC422Contact; $customer->contacts->add($contact); diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC425Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC425Test.php index d3d3e27ba9e..8d91119a200 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC425Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC425Test.php @@ -8,10 +8,11 @@ class DDC425Test extends \Doctrine\Tests\OrmFunctionalTestCase protected function setUp() { parent::setUp(); - $this->_schemaTool->createSchema(array( - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC425Entity'), - //$this->_em->getClassMetadata(__NAMESPACE__ . '\DDC425Other') - )); + $this->_schemaTool->createSchema( + [ + $this->_em->getClassMetadata(DDC425Entity::class), + ] + ); } /** diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC440Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC440Test.php index f4f944ad54a..30d2ca6b9cd 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC440Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC440Test.php @@ -9,10 +9,12 @@ protected function setUp() { parent::setUp(); try { - $this->_schemaTool->createSchema(array( - $this->_em->getClassMetadata('Doctrine\Tests\ORM\Functional\Ticket\DDC440Phone'), - $this->_em->getClassMetadata('Doctrine\Tests\ORM\Functional\Ticket\DDC440Client') - )); + $this->_schemaTool->createSchema( + [ + $this->_em->getClassMetadata(DDC440Phone::class), + $this->_em->getClassMetadata(DDC440Client::class) + ] + ); } catch (\Exception $e) { // Swallow all exceptions. We do not test the schema tool here. } @@ -56,7 +58,7 @@ public function testOriginalEntityDataEmptyWhenProxyLoadedFromTwoAssociations() $this->_em->clear(); $uw = $this->_em->getUnitOfWork(); - $client = $this->_em->find('Doctrine\Tests\ORM\Functional\Ticket\DDC440Client', $id); + $client = $this->_em->find(DDC440Client::class, $id); $clientPhones = $client->getPhones(); $p1 = $clientPhones[1]; @@ -65,13 +67,13 @@ public function testOriginalEntityDataEmptyWhenProxyLoadedFromTwoAssociations() // Test the first phone. The assertion actually failed because original entity data is not set properly. // This was because it is also set as MainPhone and that one is created as a proxy, not the // original object when the find on Client is called. However loading proxies did not work correctly. - $this->assertInstanceOf('Doctrine\Tests\ORM\Functional\Ticket\DDC440Phone', $p1); + $this->assertInstanceOf(DDC440Phone::class, $p1); $originalData = $uw->getOriginalEntityData($p1); $this->assertEquals($phone->getNumber(), $originalData['number']); //If you comment out previous test, this one should pass - $this->assertInstanceOf('Doctrine\Tests\ORM\Functional\Ticket\DDC440Phone', $p2); + $this->assertInstanceOf(DDC440Phone::class, $p2); $originalData = $uw->getOriginalEntityData($p2); $this->assertEquals($phone2->getNumber(), $originalData['number']); } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC444Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC444Test.php index 58ac8f20a97..41d7e1270ec 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC444Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC444Test.php @@ -8,14 +8,16 @@ public function setUp() { parent::setUp(); //$this->_em->getConnection()->getConfiguration()->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger); - $this->_schemaTool->createSchema(array( - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC444User'), - )); + $this->_schemaTool->createSchema( + [ + $this->_em->getClassMetadata(DDC444User::class), + ] + ); } public function testExplicitPolicy() { - $classname = __NAMESPACE__ . "\DDC444User"; + $classname = DDC444User::class; $u = new $classname; $u->name = "Initial value"; diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC448Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC448Test.php index 3688a80d82f..31e03e33732 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC448Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC448Test.php @@ -9,11 +9,13 @@ class DDC448Test extends OrmFunctionalTestCase protected function setUp() { parent::setUp(); - $this->_schemaTool->createSchema(array( - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC448MainTable'), - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC448ConnectedClass'), - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC448SubTable'), - )); + $this->_schemaTool->createSchema( + [ + $this->_em->getClassMetadata(DDC448MainTable::class), + $this->_em->getClassMetadata(DDC448ConnectedClass::class), + $this->_em->getClassMetadata(DDC448SubTable::class), + ] + ); } public function testIssue() diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC493Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC493Test.php index 1a8384f7da7..536a8b49b52 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC493Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC493Test.php @@ -7,11 +7,13 @@ class DDC493Test extends \Doctrine\Tests\OrmFunctionalTestCase protected function setUp() { parent::setUp(); - $this->_schemaTool->createSchema(array( - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC493Customer'), - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC493Distributor'), - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC493Contact') - )); + $this->_schemaTool->createSchema( + [ + $this->_em->getClassMetadata(DDC493Customer::class), + $this->_em->getClassMetadata(DDC493Distributor::class), + $this->_em->getClassMetadata(DDC493Contact::class) + ] + ); } public function testIssue() diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC501Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC501Test.php index 45c202ee5e9..14c8be412cb 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC501Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC501Test.php @@ -5,6 +5,7 @@ use Doctrine\Tests\Models\CMS\CmsUser; use Doctrine\Tests\Models\CMS\CmsGroup; use Doctrine\Tests\Models\CMS\CmsPhonenumber; +use Doctrine\Tests\VerifyDeprecations; /** * ----------------- !! NOTE !! -------------------- @@ -19,6 +20,8 @@ */ class DDC501Test extends OrmFunctionalTestCase { + use VerifyDeprecations; + protected function setUp() { $this->useModelSet('cms'); @@ -46,7 +49,7 @@ public function testMergeUnitializedManyToManyAndOneToManyCollections() // freeze and unfreeze $userClone = unserialize(serialize($userReloaded)); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsUser', $userClone); + $this->assertInstanceOf(CmsUser::class, $userClone); // detached user can't know about his phonenumbers $this->assertEquals(0, count($userClone->getPhonenumbers())); @@ -80,6 +83,7 @@ public function testMergeUnitializedManyToManyAndOneToManyCollections() // This works fine as long as cmUser::groups doesn't cascade "merge" // Otherwise group memberships are physically deleted now! $this->assertEquals(2, count($userClone->getGroups())); + $this->assertHasDeprecationMessages(); } protected function createAndPersistUser() @@ -89,13 +93,13 @@ protected function createAndPersistUser() $user->username = 'lukacho'; $user->status = 'developer'; - foreach(array(1111,2222,3333,4444) as $number) { + foreach([1111,2222,3333,4444] as $number) { $phone = new CmsPhonenumber; $phone->phonenumber = $number; $user->addPhonenumber($phone); } - foreach(array('Moshers', 'Headbangers') as $groupName) { + foreach(['Moshers', 'Headbangers'] as $groupName) { $group = new CmsGroup; $group->setName($groupName); $user->addGroup($group); diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC512Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC512Test.php index c6d792d3981..6f3c3cfb01b 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC512Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC512Test.php @@ -9,11 +9,13 @@ class DDC512Test extends OrmFunctionalTestCase protected function setUp() { parent::setUp(); - $this->_schemaTool->createSchema(array( - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC512Customer'), - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC512OfferItem'), - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC512Item'), - )); + $this->_schemaTool->createSchema( + [ + $this->_em->getClassMetadata(DDC512Customer::class), + $this->_em->getClassMetadata(DDC512OfferItem::class), + $this->_em->getClassMetadata(DDC512Item::class), + ] + ); } public function testIssue() @@ -33,14 +35,14 @@ public function testIssue() $result = $q->getResult(); $this->assertEquals(2, count($result)); - $this->assertInstanceOf(__NAMESPACE__ . '\DDC512Customer', $result[0]); - $this->assertInstanceOf(__NAMESPACE__ . '\DDC512Customer', $result[1]); + $this->assertInstanceOf(DDC512Customer::class, $result[0]); + $this->assertInstanceOf(DDC512Customer::class, $result[1]); if ($result[0]->id == $customer1->id) { - $this->assertInstanceOf(__NAMESPACE__ . '\DDC512OfferItem', $result[0]->item); + $this->assertInstanceOf(DDC512OfferItem::class, $result[0]->item); $this->assertEquals($item->id, $result[0]->item->id); $this->assertNull($result[1]->item); } else { - $this->assertInstanceOf(__NAMESPACE__ . '\DDC512OfferItem', $result[1]->item); + $this->assertInstanceOf(DDC512OfferItem::class, $result[1]->item); $this->assertNull($result[0]->item); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC513Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC513Test.php index 36bb29c74a3..800c442a398 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC513Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC513Test.php @@ -7,11 +7,13 @@ class DDC513Test extends \Doctrine\Tests\OrmFunctionalTestCase protected function setUp() { parent::setUp(); - $this->_schemaTool->createSchema(array( - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC513OfferItem'), - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC513Item'), - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC513Price'), - )); + $this->_schemaTool->createSchema( + [ + $this->_em->getClassMetadata(DDC513OfferItem::class), + $this->_em->getClassMetadata(DDC513Item::class), + $this->_em->getClassMetadata(DDC513Price::class), + ] + ); } public function testIssue() diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC518Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC518Test.php index 073bb335188..64749876b8c 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC518Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC518Test.php @@ -2,8 +2,12 @@ namespace Doctrine\Tests\ORM\Functional\Ticket; +use Doctrine\Tests\VerifyDeprecations; + class DDC518Test extends \Doctrine\Tests\OrmFunctionalTestCase { + use VerifyDeprecations; + public function setUp() { $this->useModelSet('cms'); @@ -31,5 +35,6 @@ public function testMergeWithRelatedNew() $managedArticle = $this->_em->merge($article); $this->assertSame($article->user, $managedArticle->user); + $this->assertHasDeprecationMessages(); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC522Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC522Test.php index f87216a55b0..dc6fa208179 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC522Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC522Test.php @@ -2,6 +2,8 @@ namespace Doctrine\Tests\ORM\Functional\Ticket; +use Doctrine\ORM\Proxy\Proxy; + /** * Tests that join columns (foreign keys) can be named the same as the association * fields they're used on without causing issues. @@ -11,14 +13,16 @@ class DDC522Test extends \Doctrine\Tests\OrmFunctionalTestCase protected function setUp() { parent::setUp(); + try { - $this->_schemaTool->createSchema(array( - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC522Customer'), - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC522Cart'), - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC522ForeignKeyTest') - )); + $this->_schemaTool->createSchema( + [ + $this->_em->getClassMetadata(DDC522Customer::class), + $this->_em->getClassMetadata(DDC522Cart::class), + $this->_em->getClassMetadata(DDC522ForeignKeyTest::class) + ] + ); } catch(\Exception $e) { - } } @@ -27,8 +31,6 @@ protected function setUp() */ public function testJoinColumnWithSameNameAsAssociationField() { - //$this->_em->getConnection()->getConfiguration()->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger); - $cust = new DDC522Customer; $cust->name = "name"; $cart = new DDC522Cart; @@ -41,12 +43,12 @@ public function testJoinColumnWithSameNameAsAssociationField() $this->_em->clear(); - $r = $this->_em->createQuery("select ca,c from ".get_class($cart)." ca join ca.customer c") - ->getResult(); + $r = $this->_em->createQuery('select ca,c from ' . DDC522Cart::class . ' ca join ca.customer c') + ->getResult(); - $this->assertInstanceOf(__NAMESPACE__ . '\DDC522Cart', $r[0]); - $this->assertInstanceOf(__NAMESPACE__ . '\DDC522Customer', $r[0]->customer); - $this->assertNotInstanceOf('Doctrine\ORM\Proxy\Proxy', $r[0]->customer); + $this->assertInstanceOf(DDC522Cart::class, $r[0]); + $this->assertInstanceOf(DDC522Customer::class, $r[0]->customer); + $this->assertNotInstanceOf(Proxy::class, $r[0]->customer); $this->assertEquals('name', $r[0]->customer->name); $fkt = new DDC522ForeignKeyTest(); @@ -58,7 +60,7 @@ public function testJoinColumnWithSameNameAsAssociationField() $fkt2 = $this->_em->find(get_class($fkt), $fkt->id); $this->assertEquals($fkt->cart->id, $fkt2->cartId); - $this->assertInstanceOf('Doctrine\ORM\Proxy\Proxy', $fkt2->cart); + $this->assertInstanceOf(Proxy::class, $fkt2->cart); $this->assertFalse($fkt2->cart->__isInitialized__); } @@ -69,33 +71,43 @@ public function testJoinColumnWithSameNameAsAssociationField() public function testJoinColumnWithNullSameNameAssociationField() { $fkCust = new DDC522ForeignKeyTest; - $fkCust->name = "name"; + $fkCust->name = 'name'; $fkCust->cart = null; $this->_em->persist($fkCust); $this->_em->flush(); $this->_em->clear(); - $newCust = $this->_em->find(get_class($fkCust), $fkCust->id); + $expected = clone $fkCust; + // removing dynamic field (which is not persisted) + unset($expected->name); + + self::assertEquals($expected, $this->_em->find(DDC522ForeignKeyTest::class, $fkCust->id)); } } /** @Entity */ -class DDC522Customer { +class DDC522Customer +{ /** @Id @Column(type="integer") @GeneratedValue */ public $id; + /** @Column */ public $name; + /** @OneToOne(targetEntity="DDC522Cart", mappedBy="customer") */ public $cart; } /** @Entity */ -class DDC522Cart { +class DDC522Cart +{ /** @Id @Column(type="integer") @GeneratedValue */ public $id; + /** @Column(type="integer") */ public $total; + /** * @OneToOne(targetEntity="DDC522Customer", inversedBy="cart") * @JoinColumn(name="customer", referencedColumnName="id") @@ -104,11 +116,14 @@ class DDC522Cart { } /** @Entity */ -class DDC522ForeignKeyTest { +class DDC522ForeignKeyTest +{ /** @Id @Column(type="integer") @GeneratedValue */ public $id; + /** @Column(type="integer", name="cart_id", nullable=true) */ public $cartId; + /** * @OneToOne(targetEntity="DDC522Cart") * @JoinColumn(name="cart_id", referencedColumnName="id") diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC531Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC531Test.php index 50f96968df8..33d88c6be1f 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC531Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC531Test.php @@ -2,15 +2,19 @@ namespace Doctrine\Tests\ORM\Functional\Ticket; +use Doctrine\ORM\Proxy\Proxy; + class DDC531Test extends \Doctrine\Tests\OrmFunctionalTestCase { protected function setUp() { parent::setUp(); - $this->_schemaTool->createSchema(array( - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC531Item'), - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC531SubItem'), - )); + $this->_schemaTool->createSchema( + [ + $this->_em->getClassMetadata(DDC531Item::class), + $this->_em->getClassMetadata(DDC531SubItem::class), + ] + ); } public function testIssue() @@ -24,12 +28,12 @@ public function testIssue() $this->_em->flush(); $this->_em->clear(); - $item3 = $this->_em->find(__NAMESPACE__ . '\DDC531Item', $item2->id); // Load child item first (id 2) + $item3 = $this->_em->find(DDC531Item::class, $item2->id); // Load child item first (id 2) // parent will already be loaded, cannot be lazy because it has mapped subclasses and we would not // know which proxy type to put in. - $this->assertInstanceOf(__NAMESPACE__ . '\DDC531Item', $item3->parent); - $this->assertNotInstanceOf('Doctrine\ORM\Proxy\Proxy', $item3->parent); - $item4 = $this->_em->find(__NAMESPACE__ . '\DDC531Item', $item1->id); // Load parent item (id 1) + $this->assertInstanceOf(DDC531Item::class, $item3->parent); + $this->assertNotInstanceOf(Proxy::class, $item3->parent); + $item4 = $this->_em->find(DDC531Item::class, $item1->id); // Load parent item (id 1) $this->assertNull($item4->parent); $this->assertNotNull($item4->getChildren()); $this->assertTrue($item4->getChildren()->contains($item3)); // lazy-loads children diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC5684Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC5684Test.php new file mode 100644 index 00000000000..e525ae1342b --- /dev/null +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC5684Test.php @@ -0,0 +1,111 @@ +_schemaTool->createSchema([$this->_em->getClassMetadata(DDC5684Object::class)]); + } + + protected function tearDown() + { + $this->_schemaTool->dropSchema([$this->_em->getClassMetadata(DDC5684Object::class)]); + + parent::tearDown(); + } + + public function testAutoIncrementIdWithCustomType() + { + $object = new DDC5684Object(); + $this->_em->persist($object); + $this->_em->flush(); + + $this->assertInstanceOf(DDC5684ObjectId::class, $object->id); + } + + public function testFetchObjectWithAutoIncrementedCustomType() + { + $object = new DDC5684Object(); + $this->_em->persist($object); + $this->_em->flush(); + $this->_em->clear(); + + $rawId = $object->id->value; + $object = $this->_em->find(DDC5684Object::class, new DDC5684ObjectId($rawId)); + + $this->assertInstanceOf(DDC5684ObjectId::class, $object->id); + $this->assertEquals($rawId, $object->id->value); + } +} + +class DDC5684ObjectIdType extends DBALTypes\IntegerType +{ + public function convertToPHPValue($value, AbstractPlatform $platform) + { + return new DDC5684ObjectId($value); + } + + public function convertToDatabaseValue($value, AbstractPlatform $platform) + { + return $value->value; + } + + public function getName() + { + return self::class; + } + + public function requiresSQLCommentHint(AbstractPlatform $platform) + { + return true; + } +} + +class DDC5684ObjectId +{ + public $value; + + public function __construct($value) + { + $this->value = $value; + } + + public function __toString() + { + return (string) $this->value; + } +} + +/** + * @Entity + * @Table(name="ticket_5684_objects") + */ +class DDC5684Object +{ + /** + * @Id + * @Column(type=Doctrine\Tests\ORM\Functional\Ticket\DDC5684ObjectIdType::class) + * @GeneratedValue(strategy="AUTO") + */ + public $id; +} diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC588Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC588Test.php index b5ace06b072..7361bc4f403 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC588Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC588Test.php @@ -7,9 +7,12 @@ class DDC588Test extends \Doctrine\Tests\OrmFunctionalTestCase protected function setUp() { parent::setUp(); - $this->_schemaTool->createSchema(array( - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC588Site'), - )); + + $this->_schemaTool->createSchema( + [ + $this->_em->getClassMetadata(DDC588Site::class), + ] + ); } public function testIssue() @@ -20,6 +23,8 @@ public function testIssue() $this->_em->flush(); // Following should not result in exception $this->_em->refresh($site); + + $this->addToAssertionCount(1); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC599Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC599Test.php index ed91bd59d6e..842ccdd1a73 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC599Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC599Test.php @@ -9,11 +9,13 @@ protected function setUp() parent::setUp(); //$this->_em->getConnection()->getConfiguration()->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger); try { - $this->_schemaTool->createSchema(array( - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC599Item'), - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC599Subitem'), - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC599Child'), - )); + $this->_schemaTool->createSchema( + [ + $this->_em->getClassMetadata(DDC599Item::class), + $this->_em->getClassMetadata(DDC599Subitem::class), + $this->_em->getClassMetadata(DDC599Child::class), + ] + ); } catch (\Exception $ignored) {} } @@ -29,7 +31,7 @@ public function testCascadeRemoveOnInheritanceHierarchy() $this->_em->flush(); $this->_em->clear(); - $item = $this->_em->find(__NAMESPACE__ . '\DDC599Item', $item->id); + $item = $this->_em->find(DDC599Item::class, $item->id); $this->_em->remove($item); $this->_em->flush(); // Should not fail @@ -62,7 +64,7 @@ public function testCascadeRemoveOnInheritanceHierarchy() public function testCascadeRemoveOnChildren() { - $class = $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC599Subitem'); + $class = $this->_em->getClassMetadata(DDC599Subitem::class); $this->assertArrayHasKey('children', $class->associationMappings); $this->assertTrue($class->associationMappings['children']['isCascadeRemove']); diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC618Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC618Test.php index 165a42b6d66..5e359863e91 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC618Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC618Test.php @@ -11,10 +11,12 @@ protected function setUp() { parent::setUp(); try { - $this->_schemaTool->createSchema(array( - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC618Author'), - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC618Book') - )); + $this->_schemaTool->createSchema( + [ + $this->_em->getClassMetadata(DDC618Author::class), + $this->_em->getClassMetadata(DDC618Book::class) + ] + ); // Create author 10/Joe with two books 22/JoeA and 20/JoeB $author = new DDC618Author(); @@ -44,8 +46,8 @@ public function testIndexByHydrateObject() $dql = 'SELECT A FROM Doctrine\Tests\ORM\Functional\Ticket\DDC618Author A INDEX BY A.name ORDER BY A.name ASC'; $result = $this->_em->createQuery($dql)->getResult(\Doctrine\ORM\Query::HYDRATE_OBJECT); - $joe = $this->_em->find('Doctrine\Tests\ORM\Functional\Ticket\DDC618Author', 10); - $alice = $this->_em->find('Doctrine\Tests\ORM\Functional\Ticket\DDC618Author', 11); + $joe = $this->_em->find(DDC618Author::class, 10); + $alice = $this->_em->find(DDC618Author::class, 11); $this->assertArrayHasKey('Joe', $result, "INDEX BY A.name should return an index by the name of 'Joe'."); $this->assertArrayHasKey('Alice', $result, "INDEX BY A.name should return an index by the name of 'Alice'."); @@ -56,8 +58,8 @@ public function testIndexByHydrateArray() $dql = 'SELECT A FROM Doctrine\Tests\ORM\Functional\Ticket\DDC618Author A INDEX BY A.name ORDER BY A.name ASC'; $result = $this->_em->createQuery($dql)->getResult(\Doctrine\ORM\Query::HYDRATE_ARRAY); - $joe = $this->_em->find('Doctrine\Tests\ORM\Functional\Ticket\DDC618Author', 10); - $alice = $this->_em->find('Doctrine\Tests\ORM\Functional\Ticket\DDC618Author', 11); + $joe = $this->_em->find(DDC618Author::class, 10); + $alice = $this->_em->find(DDC618Author::class, 11); $this->assertArrayHasKey('Joe', $result, "INDEX BY A.name should return an index by the name of 'Joe'."); $this->assertArrayHasKey('Alice', $result, "INDEX BY A.name should return an index by the name of 'Alice'."); @@ -96,8 +98,8 @@ public function testIndexByToOneJoinSilentlyIgnored() 'INNER JOIN B.author A INDEX BY A.name ORDER BY A.name ASC'; $result = $this->_em->createQuery($dql)->getResult(\Doctrine\ORM\Query::HYDRATE_OBJECT); - $this->assertInstanceOf('Doctrine\Tests\ORM\Functional\Ticket\DDC618Book', $result[0]); - $this->assertInstanceOf('Doctrine\Tests\ORM\Functional\Ticket\DDC618Author', $result[0]->author); + $this->assertInstanceOf(DDC618Book::class, $result[0]); + $this->assertInstanceOf(DDC618Author::class, $result[0]->author); $dql = 'SELECT B, A FROM Doctrine\Tests\ORM\Functional\Ticket\DDC618Book B '. 'INNER JOIN B.author A INDEX BY A.name ORDER BY A.name ASC'; diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC6303Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC6303Test.php new file mode 100644 index 00000000000..732808b5f09 --- /dev/null +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC6303Test.php @@ -0,0 +1,121 @@ +_schemaTool->createSchema([ + $this->_em->getClassMetadata(DDC6303BaseClass::class), + $this->_em->getClassMetadata(DDC6303ChildA::class), + $this->_em->getClassMetadata(DDC6303ChildB::class), + ]); + } catch (ToolsException $ignored) { + } + } + + public function testMixedTypeHydratedCorrectlyInJoinedInheritance() : void + { + // DDC6303ChildA and DDC6303ChildB have an inheritance from DDC6303BaseClass, + // but one has a string originalData and the second has an array, since the fields + // are mapped differently + $this->assertHydratedEntitiesSameToPersistedOnes([ + 'a' => new DDC6303ChildA('a', 'authorized'), + 'b' => new DDC6303ChildB('b', ['accepted', 'authorized']), + ]); + + } + + public function testEmptyValuesInJoinedInheritance() : void + { + $this->assertHydratedEntitiesSameToPersistedOnes([ + 'stringEmpty' => new DDC6303ChildA('stringEmpty', ''), + 'stringZero' => new DDC6303ChildA('stringZero', 0), + 'arrayEmpty' => new DDC6303ChildB('arrayEmpty', []), + ]); + } + + /** + * @param DDC6303BaseClass[] $persistedEntities indexed by identifier + * + * @throws \Doctrine\Common\Persistence\Mapping\MappingException + * @throws \Doctrine\ORM\ORMException + * @throws \Doctrine\ORM\OptimisticLockException + */ + private function assertHydratedEntitiesSameToPersistedOnes(array $persistedEntities) : void + { + array_walk($persistedEntities, [$this->_em, 'persist']); + $this->_em->flush(); + $this->_em->clear(); + + /* @var $entities DDC6303BaseClass[] */ + $entities = $this + ->_em + ->getRepository(DDC6303BaseClass::class) + ->createQueryBuilder('p') + ->where('p.id IN(:ids)') + ->setParameter('ids', array_keys($persistedEntities)) + ->getQuery()->getResult(); + + self::assertCount(count($persistedEntities), $entities); + + foreach ($entities as $entity) { + self::assertEquals($entity, $persistedEntities[$entity->id]); + } + } +} + +/** + * @Entity + * @Table + * @InheritanceType("JOINED") + * @DiscriminatorColumn(name="discr", type="string") + * @DiscriminatorMap({ + * DDC6303ChildB::class = DDC6303ChildB::class, + * DDC6303ChildA::class = DDC6303ChildA::class, + * }) + * + * Note: discriminator map order *IS IMPORTANT* for this test + */ +abstract class DDC6303BaseClass +{ + /** @Id @Column(type="string") @GeneratedValue(strategy="NONE") */ + public $id; +} + +/** @Entity @Table */ +class DDC6303ChildA extends DDC6303BaseClass +{ + /** @Column(type="string") */ + private $originalData; + + public function __construct(string $id, $originalData) + { + $this->id = $id; + $this->originalData = $originalData; + } +} + +/** @Entity @Table */ +class DDC6303ChildB extends DDC6303BaseClass +{ + /** @Column(type="simple_array", nullable=true) */ + private $originalData; + + public function __construct(string $id, array $originalData) + { + $this->id = $id; + $this->originalData = $originalData; + } +} diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC633Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC633Test.php index 0a538ee3e28..2ed53ed354f 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC633Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC633Test.php @@ -2,16 +2,20 @@ namespace Doctrine\Tests\ORM\Functional\Ticket; +use Doctrine\ORM\Proxy\Proxy; + class DDC633Test extends \Doctrine\Tests\OrmFunctionalTestCase { protected function setUp() { parent::setUp(); try { - $this->_schemaTool->createSchema(array( - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC633Patient'), - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC633Appointment'), - )); + $this->_schemaTool->createSchema( + [ + $this->_em->getClassMetadata(DDC633Patient::class), + $this->_em->getClassMetadata(DDC633Appointment::class), + ] + ); } catch(\Exception $e) { } @@ -34,10 +38,10 @@ public function testOneToOneEager() $this->_em->flush(); $this->_em->clear(); - $eagerAppointment = $this->_em->find(__NAMESPACE__ . '\DDC633Appointment', $app->id); + $eagerAppointment = $this->_em->find(DDC633Appointment::class, $app->id); // Eager loading of one to one leads to fetch-join - $this->assertNotInstanceOf('Doctrine\ORM\Proxy\Proxy', $eagerAppointment->patient); + $this->assertNotInstanceOf(Proxy::class, $eagerAppointment->patient); $this->assertTrue($this->_em->contains($eagerAppointment->patient)); } @@ -62,7 +66,7 @@ public function testDQLDeferredEagerLoad() $appointments = $this->_em->createQuery("SELECT a FROM " . __NAMESPACE__ . "\DDC633Appointment a")->getResult(); foreach ($appointments AS $eagerAppointment) { - $this->assertInstanceOf('Doctrine\ORM\Proxy\Proxy', $eagerAppointment->patient); + $this->assertInstanceOf(Proxy::class, $eagerAppointment->patient); $this->assertTrue($eagerAppointment->patient->__isInitialized__, "Proxy should already be initialized due to eager loading!"); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC6460Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC6460Test.php new file mode 100644 index 00000000000..9868c7d1c00 --- /dev/null +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC6460Test.php @@ -0,0 +1,111 @@ +setUpEntitySchema( + [ + DDC6460Entity::class, + DDC6460ParentEntity::class, + ] + ); + } catch (SchemaException $e) { + } + } + + /** + * @group DDC-6460 + */ + public function testInlineEmbeddable() + { + $isFieldMapped = $this->_em + ->getClassMetadata(DDC6460Entity::class) + ->hasField('embedded'); + + $this->assertTrue($isFieldMapped); + } + + /** + * @group DDC-6460 + */ + public function testInlineEmbeddableProxyInitialization() + { + $entity = new DDC6460Entity(); + $entity->id = 1; + $entity->embedded = new DDC6460Embeddable(); + $entity->embedded->field = 'test'; + $this->_em->persist($entity); + + $second = new DDC6460ParentEntity(); + $second->id = 1; + $second->lazyLoaded = $entity; + $this->_em->persist($second); + $this->_em->flush(); + + $this->_em->clear(); + + $secondEntityWithLazyParameter = $this->_em->getRepository(DDC6460ParentEntity::class)->findOneById(1); + + $this->assertInstanceOf(Proxy::class, $secondEntityWithLazyParameter->lazyLoaded); + $this->assertInstanceOf(DDC6460Entity::class, $secondEntityWithLazyParameter->lazyLoaded); + $this->assertFalse($secondEntityWithLazyParameter->lazyLoaded->__isInitialized()); + $this->assertEquals($secondEntityWithLazyParameter->lazyLoaded->embedded, $entity->embedded); + $this->assertTrue($secondEntityWithLazyParameter->lazyLoaded->__isInitialized()); + } +} + +/** + * @Embeddable() + */ +class DDC6460Embeddable +{ + /** @Column(type="string") */ + public $field; +} + +/** + * @Entity() + */ +class DDC6460Entity +{ + /** + * @Id + * @GeneratedValue(strategy = "NONE") + * @Column(type = "integer") + */ + public $id; + + /** @Embedded(class = "DDC6460Embeddable") */ + public $embedded; +} + +/** + * @Entity() + */ +class DDC6460ParentEntity +{ + /** + * @Id + * @GeneratedValue(strategy = "NONE") + * @Column(type = "integer") + */ + public $id; + + /** @ManyToOne(targetEntity = "DDC6460Entity", fetch="EXTRA_LAZY", cascade={"persist"}) */ + public $lazyLoaded; +} diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC656Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC656Test.php index eb368cd891d..1f94a3953a9 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC656Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC656Test.php @@ -8,9 +8,11 @@ protected function setUp() { parent::setUp(); try { - $this->_schemaTool->createSchema(array( - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC656Entity') - )); + $this->_schemaTool->createSchema( + [ + $this->_em->getClassMetadata(DDC656Entity::class) + ] + ); } catch(\Exception $e) { } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC657Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC657Test.php index f2fe56f7bf4..759464a5f0e 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC657Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC657Test.php @@ -9,8 +9,6 @@ */ class DDC657Test extends \Doctrine\Tests\OrmFunctionalTestCase { - const NS = 'Doctrine\Tests\Models\Generic'; - protected function setUp() { $this->useModelSet('generic'); @@ -21,10 +19,10 @@ protected function setUp() public function testEntitySingleResult() { - $query = $this->_em->createQuery('SELECT d FROM ' . self::NS . '\DateTimeModel d'); + $query = $this->_em->createQuery('SELECT d FROM ' . DateTimeModel::class . ' d'); $datetime = $query->setMaxResults(1)->getSingleResult(); - $this->assertInstanceOf('Doctrine\Tests\Models\Generic\DateTimeModel', $datetime); + $this->assertInstanceOf(DateTimeModel::class, $datetime); $this->assertInstanceOf('DateTime', $datetime->datetime); $this->assertInstanceOf('DateTime', $datetime->time); @@ -33,7 +31,7 @@ public function testEntitySingleResult() public function testScalarResult() { - $query = $this->_em->createQuery('SELECT d.id, d.time, d.date, d.datetime FROM ' . self::NS . '\DateTimeModel d ORDER BY d.date ASC'); + $query = $this->_em->createQuery('SELECT d.id, d.time, d.date, d.datetime FROM ' . DateTimeModel::class . ' d ORDER BY d.date ASC'); $result = $query->getScalarResult(); $this->assertCount(2,$result); @@ -49,7 +47,7 @@ public function testScalarResult() public function testaTicketEntityArrayResult() { - $query = $this->_em->createQuery('SELECT d FROM ' . self::NS . '\DateTimeModel d ORDER BY d.date ASC'); + $query = $this->_em->createQuery('SELECT d FROM ' . DateTimeModel::class . ' d ORDER BY d.date ASC'); $result = $query->getArrayResult(); $this->assertCount(2,$result); @@ -65,7 +63,7 @@ public function testaTicketEntityArrayResult() public function testTicketSingleResult() { - $query = $this->_em->createQuery('SELECT d.id, d.time, d.date, d.datetime FROM ' . self::NS . '\DateTimeModel d ORDER BY d.date ASC'); + $query = $this->_em->createQuery('SELECT d.id, d.time, d.date, d.datetime FROM ' . DateTimeModel::class . ' d ORDER BY d.date ASC'); $datetime = $query->setMaxResults(1)->getSingleResult(); $this->assertTrue(is_array($datetime)); @@ -77,7 +75,7 @@ public function testTicketSingleResult() public function testTicketResult() { - $query = $this->_em->createQuery('SELECT d.id, d.time, d.date, d.datetime FROM ' . self::NS . '\DateTimeModel d ORDER BY d.date ASC'); + $query = $this->_em->createQuery('SELECT d.id, d.time, d.date, d.datetime FROM ' . DateTimeModel::class . ' d ORDER BY d.date ASC'); $result = $query->getResult(); $this->assertCount(2,$result); diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC698Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC698Test.php index cf15770a811..f21d6de6936 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC698Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC698Test.php @@ -8,10 +8,12 @@ protected function setUp() { parent::setUp(); try { - $this->_schemaTool->createSchema(array( - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC698Role'), - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC698Privilege') - )); + $this->_schemaTool->createSchema( + [ + $this->_em->getClassMetadata(DDC698Role::class), + $this->_em->getClassMetadata(DDC698Privilege::class) + ] + ); } catch(\Exception $e) { } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC719Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC719Test.php index 428fe057afa..c6f1a2254cb 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC719Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC719Test.php @@ -8,9 +8,11 @@ protected function setUp() { parent::setUp(); //$this->_em->getConnection()->getConfiguration()->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger); - $this->_schemaTool->createSchema(array( - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC719Group'), - )); + $this->_schemaTool->createSchema( + [ + $this->_em->getClassMetadata(DDC719Group::class), + ] + ); } public function testIsEmptySqlGeneration() diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC729Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC729Test.php index 0dc89a3b36a..8cc9642100d 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC729Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC729Test.php @@ -2,23 +2,37 @@ namespace Doctrine\Tests\ORM\Functional\Ticket; +use Doctrine\Common\Collections\ArrayCollection; +use Doctrine\ORM\PersistentCollection; +use Doctrine\Tests\VerifyDeprecations; + class DDC729Test extends \Doctrine\Tests\OrmFunctionalTestCase { + use VerifyDeprecations; + public function setUp() { parent::setUp(); try { $schemaTool = new \Doctrine\ORM\Tools\SchemaTool($this->_em); - $schemaTool->createSchema(array( - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC729A'), - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC729B'), - )); + $schemaTool->createSchema( + [ + $this->_em->getClassMetadata(DDC729A::class), + $this->_em->getClassMetadata(DDC729B::class), + ] + ); } catch(\Exception $e) { } } + /** @after */ + public function ensureTestGeneratedDeprecationMessages() : void + { + $this->assertHasDeprecationMessages(); + } + public function testMergeManyToMany() { $a = new DDC729A(); @@ -34,11 +48,11 @@ public function testMergeManyToMany() $a = new DDC729A(); $a->id = $aId; - $this->assertInstanceOf('Doctrine\Common\Collections\ArrayCollection', $a->related); + $this->assertInstanceOf(ArrayCollection::class, $a->related); $a = $this->_em->merge($a); - $this->assertInstanceOf('Doctrine\ORM\PersistentCollection', $a->related); + $this->assertInstanceOf(PersistentCollection::class, $a->related); $this->assertFalse($a->related->isInitialized(), "Collection should not be marked initialized."); $this->assertFalse($a->related->isDirty(), "Collection should not be marked as dirty."); @@ -46,7 +60,7 @@ public function testMergeManyToMany() $this->_em->flush(); $this->_em->clear(); - $a = $this->_em->find(__NAMESPACE__ . '\DDC729A', $aId); + $a = $this->_em->find(DDC729A::class, $aId); $this->assertEquals(1, count($a->related)); } @@ -76,7 +90,7 @@ public function testUnidirectionalMergeManyToMany() $this->_em->flush(); $this->_em->clear(); - $a = $this->_em->find(__NAMESPACE__ . '\DDC729A', $aId); + $a = $this->_em->find(DDC729A::class, $aId); $this->assertEquals(2, count($a->related)); } @@ -108,7 +122,7 @@ public function testBidirectionalMergeManyToMany() $this->_em->flush(); $this->_em->clear(); - $a = $this->_em->find(__NAMESPACE__ . '\DDC729A', $aId); + $a = $this->_em->find(DDC729A::class, $aId); $this->assertEquals(2, count($a->related)); } @@ -140,7 +154,7 @@ public function testBidirectionalMultiMergeManyToMany() $this->_em->flush(); $this->_em->clear(); - $a = $this->_em->find(__NAMESPACE__ . '\DDC729A', $aId); + $a = $this->_em->find(DDC729A::class, $aId); $this->assertEquals(2, count($a->related)); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC735Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC735Test.php index 41f7b293b08..afae6973bf7 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC735Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC735Test.php @@ -10,10 +10,12 @@ protected function setUp() { parent::setUp(); try { - $this->_schemaTool->createSchema(array( - $this->_em->getClassMetadata(__NAMESPACE__ . '\\DDC735Product'), - $this->_em->getClassMetadata(__NAMESPACE__ . '\\DDC735Review') - )); + $this->_schemaTool->createSchema( + [ + $this->_em->getClassMetadata(DDC735Product::class), + $this->_em->getClassMetadata(DDC735Review::class) + ] + ); } catch(\Exception $e) { } @@ -47,7 +49,7 @@ public function testRemoveElement_AppliesOrphanRemoval() $this->assertEquals(0, count($product->getReviews()), 'count($reviews) should still be 0 after the refresh'); // Review should also not be available anymore - $this->assertNull($this->_em->find(__NAMESPACE__.'\DDC735Review', $reviewId)); + $this->assertNull($this->_em->find(DDC735Review::class, $reviewId)); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC736Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC736Test.php index a93c91c7e4b..932731bf6f5 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC736Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC736Test.php @@ -2,6 +2,7 @@ namespace Doctrine\Tests\ORM\Functional\Ticket; +use Doctrine\ORM\Proxy\Proxy; use Doctrine\Tests\Models\ECommerce\ECommerceCart; use Doctrine\Tests\Models\ECommerce\ECommerceCustomer; use Doctrine\ORM\Query; @@ -38,10 +39,10 @@ public function testReorderEntityFetchJoinForHydration() $cart2 = $result[0]; unset($result[0]); - $this->assertInstanceOf('Doctrine\Tests\Models\ECommerce\ECommerceCart', $cart2); - $this->assertNotInstanceOf('Doctrine\ORM\Proxy\Proxy', $cart2->getCustomer()); - $this->assertInstanceOf('Doctrine\Tests\Models\ECommerce\ECommerceCustomer', $cart2->getCustomer()); - $this->assertEquals(array('name' => 'roman', 'payment' => 'cash'), $result); + $this->assertInstanceOf(ECommerceCart::class, $cart2); + $this->assertNotInstanceOf(Proxy::class, $cart2->getCustomer()); + $this->assertInstanceOf(ECommerceCustomer::class, $cart2->getCustomer()); + $this->assertEquals(['name' => 'roman', 'payment' => 'cash'], $result); } /** @@ -65,12 +66,12 @@ public function testDqlTreeWalkerReordering() $dql = "select c, c.name, ca, ca.payment from Doctrine\Tests\Models\ECommerce\ECommerceCart ca join ca.customer c"; $result = $this->_em->createQuery($dql) - ->setHint(Query::HINT_CUSTOM_TREE_WALKERS, array('Doctrine\Tests\ORM\Functional\Ticket\DisableFetchJoinTreeWalker')) + ->setHint(Query::HINT_CUSTOM_TREE_WALKERS, [DisableFetchJoinTreeWalker::class]) ->getResult(); - /* @var $cart2 Doctrine\Tests\Models\ECommerce\ECommerceCart */ + /* @var $cart2 ECommerceCart */ $cart2 = $result[0][0]; - $this->assertInstanceOf('Doctrine\ORM\Proxy\Proxy', $cart2->getCustomer()); + $this->assertInstanceOf(Proxy::class, $cart2->getCustomer()); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC742Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC742Test.php index 46dddff6b25..8adcb08795e 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC742Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC742Test.php @@ -25,16 +25,18 @@ protected function setUp() $this->_em->getMetadataFactory()->setCacheDriver(new FilesystemCache($testDir)); try { - $this->_schemaTool->createSchema(array( - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC742User'), - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC742Comment') - )); + $this->_schemaTool->createSchema( + [ + $this->_em->getClassMetadata(DDC742User::class), + $this->_em->getClassMetadata(DDC742Comment::class) + ] + ); } catch(\Exception $e) { } // make sure classes will be deserialized from caches - $this->_em->getMetadataFactory()->setMetadataFor(__NAMESPACE__ . '\DDC742User', null); - $this->_em->getMetadataFactory()->setMetadataFor(__NAMESPACE__ . '\DDC742Comment', null); + $this->_em->getMetadataFactory()->setMetadataFor(DDC742User::class, null); + $this->_em->getMetadataFactory()->setMetadataFor(DDC742Comment::class, null); } public function testIssue() @@ -62,10 +64,11 @@ public function testIssue() $this->_em->flush(); $this->_em->clear(); - $user = $this->_em->find(get_class($user), $user->id); - $comment3 = $this->_em->find(get_class($comment3), $comment3->id); - $user->favoriteComments->add($comment3); + $user = $this->_em->find(DDC742User::class, $user->id); + $user->favoriteComments->add($this->_em->find(DDC742Comment::class, $comment3->id)); + $this->_em->flush(); + $this->addToAssertionCount(1); } } @@ -84,11 +87,13 @@ class DDC742User * @var int */ public $id; + /** * @Column(length=100, type="string") * @var string */ public $title; + /** * @ManyToMany(targetEntity="DDC742Comment", cascade={"persist"}, fetch="EAGER") * @JoinTable( @@ -97,7 +102,7 @@ class DDC742User * inverseJoinColumns={@JoinColumn(name="comment_id", referencedColumnName="id")} * ) * - * @var Doctrine\ORM\PersistentCollection + * @var \Doctrine\ORM\PersistentCollection */ public $favoriteComments; } @@ -117,6 +122,7 @@ class DDC742Comment * @var int */ public $id; + /** * @Column(length=100, type="string") * @var string diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC748Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC748Test.php index b71ae5cde8f..cfafc66dd64 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC748Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC748Test.php @@ -2,9 +2,10 @@ namespace Doctrine\Tests\ORM\Functional\Ticket; -use Doctrine\Tests\Models\CMS\CmsUser; -use Doctrine\Tests\Models\CMS\CmsArticle; +use Doctrine\Common\Collections\Collection; use Doctrine\Tests\Models\CMS\CmsAddress; +use Doctrine\Tests\Models\CMS\CmsArticle; +use Doctrine\Tests\Models\CMS\CmsUser; class DDC748Test extends \Doctrine\Tests\OrmFunctionalTestCase { @@ -30,10 +31,10 @@ public function testRefreshWithManyToOne() $this->_em->persist($article); $this->_em->flush(); - $this->assertInstanceOf('Doctrine\Common\Collections\Collection', $user->articles); + $this->assertInstanceOf(Collection::class, $user->articles); $this->_em->refresh($article); $this->assertTrue($article !== $user->articles, "The article should not be replaced on the inverse side of the relation."); - $this->assertInstanceOf('Doctrine\Common\Collections\Collection', $user->articles); + $this->assertInstanceOf(Collection::class, $user->articles); } public function testRefreshOneToOne() diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC758Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC758Test.php index 295542aab1c..e7a36310ed6 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC758Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC758Test.php @@ -5,9 +5,11 @@ use Doctrine\Common\Collections\ArrayCollection; use Doctrine\Tests\Models\CMS\CmsUser; use Doctrine\Tests\Models\CMS\CmsGroup; +use Doctrine\Tests\VerifyDeprecations; class DDC758Test extends \Doctrine\Tests\OrmFunctionalTestCase { + use VerifyDeprecations; public function setUp() { @@ -17,6 +19,12 @@ public function setUp() parent::setUp(); } + /** @after */ + public function ensureTestGeneratedDeprecationMessages() : void + { + $this->assertHasDeprecationMessages(); + } + /** * Helper method to set cascade to merge only */ @@ -38,8 +46,8 @@ private function setCascadeMergeFor($class) */ public function testManyToManyMergeAssociationAdds() { - $this->setCascadeMergeFor('Doctrine\Tests\Models\CMS\CmsUser'); - $this->setCascadeMergeFor('Doctrine\Tests\Models\CMS\CmsGroup'); + $this->setCascadeMergeFor(CmsUser::class); + $this->setCascadeMergeFor(CmsGroup::class); // Put entities in the database $cmsUser = new CmsUser(); @@ -91,8 +99,8 @@ public function testManyToManyMergeAssociationAdds() $this->_em->clear(); - $cmsUsers = $this->_em->getRepository('Doctrine\Tests\Models\CMS\CmsUser')->findAll(); - $cmsGroups = $this->_em->getRepository('Doctrine\Tests\Models\CMS\CmsGroup')->findAll(); + $cmsUsers = $this->_em->getRepository(CmsUser::class)->findAll(); + $cmsGroups = $this->_em->getRepository(CmsGroup::class)->findAll(); // Check the entities are in the database $this->assertEquals(1, sizeof($cmsUsers)); @@ -115,8 +123,8 @@ public function testManyToManyMergeAssociationAdds() */ public function testManyToManyMergeAssociationRemoves() { - $this->setCascadeMergeFor('Doctrine\Tests\Models\CMS\CmsUser'); - $this->setCascadeMergeFor('Doctrine\Tests\Models\CMS\CmsGroup'); + $this->setCascadeMergeFor(CmsUser::class); + $this->setCascadeMergeFor(CmsGroup::class); $cmsUser = new CmsUser(); $cmsUser->username = "dave"; @@ -167,8 +175,8 @@ public function testManyToManyMergeAssociationRemoves() $this->_em->clear(); - $cmsUsers = $this->_em->getRepository('Doctrine\Tests\Models\CMS\CmsUser')->findAll(); - $cmsGroups = $this->_em->getRepository('Doctrine\Tests\Models\CMS\CmsGroup')->findAll(); + $cmsUsers = $this->_em->getRepository(CmsUser::class)->findAll(); + $cmsGroups = $this->_em->getRepository(CmsGroup::class)->findAll(); // Check the entities are in the database $this->assertEquals(1, sizeof($cmsUsers)); diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC767Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC767Test.php index bcf72e4e98d..8420db13275 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC767Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC767Test.php @@ -48,7 +48,7 @@ public function testCollectionChangesInsideTransaction() $this->assertNotNull($pUser, "User not retrieved from database."); - $groups = array($group2->id, $group3->id); + $groups = [$group2->id, $group3->id]; try { $this->_em->beginTransaction(); diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC809Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC809Test.php index a88bbad81ed..4c6464a188b 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC809Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC809Test.php @@ -7,31 +7,33 @@ class DDC809Test extends \Doctrine\Tests\OrmFunctionalTestCase public function setUp() { parent::setUp(); - $this->_schemaTool->createSchema(array( - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC809Variant'), - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC809SpecificationValue') - )); + $this->_schemaTool->createSchema( + [ + $this->_em->getClassMetadata(DDC809Variant::class), + $this->_em->getClassMetadata(DDC809SpecificationValue::class) + ] + ); $conn = $this->_em->getConnection(); - $conn->insert('specification_value_test', array('specification_value_id' => 94589)); - $conn->insert('specification_value_test', array('specification_value_id' => 94593)); - $conn->insert('specification_value_test', array('specification_value_id' => 94606)); - $conn->insert('specification_value_test', array('specification_value_id' => 94607)); - $conn->insert('specification_value_test', array('specification_value_id' => 94609)); - $conn->insert('specification_value_test', array('specification_value_id' => 94711)); + $conn->insert('specification_value_test', ['specification_value_id' => 94589]); + $conn->insert('specification_value_test', ['specification_value_id' => 94593]); + $conn->insert('specification_value_test', ['specification_value_id' => 94606]); + $conn->insert('specification_value_test', ['specification_value_id' => 94607]); + $conn->insert('specification_value_test', ['specification_value_id' => 94609]); + $conn->insert('specification_value_test', ['specification_value_id' => 94711]); - $conn->insert('variant_test', array('variant_id' => 545208)); - $conn->insert('variant_test', array('variant_id' => 545209)); + $conn->insert('variant_test', ['variant_id' => 545208]); + $conn->insert('variant_test', ['variant_id' => 545209]); - $conn->insert('var_spec_value_test', array('variant_id' => 545208, 'specification_value_id' => 94606)); - $conn->insert('var_spec_value_test', array('variant_id' => 545208, 'specification_value_id' => 94607)); - $conn->insert('var_spec_value_test', array('variant_id' => 545208, 'specification_value_id' => 94609)); - $conn->insert('var_spec_value_test', array('variant_id' => 545208, 'specification_value_id' => 94711)); + $conn->insert('var_spec_value_test', ['variant_id' => 545208, 'specification_value_id' => 94606]); + $conn->insert('var_spec_value_test', ['variant_id' => 545208, 'specification_value_id' => 94607]); + $conn->insert('var_spec_value_test', ['variant_id' => 545208, 'specification_value_id' => 94609]); + $conn->insert('var_spec_value_test', ['variant_id' => 545208, 'specification_value_id' => 94711]); - $conn->insert('var_spec_value_test', array('variant_id' => 545209, 'specification_value_id' => 94589)); - $conn->insert('var_spec_value_test', array('variant_id' => 545209, 'specification_value_id' => 94593)); - $conn->insert('var_spec_value_test', array('variant_id' => 545209, 'specification_value_id' => 94606)); - $conn->insert('var_spec_value_test', array('variant_id' => 545209, 'specification_value_id' => 94607)); + $conn->insert('var_spec_value_test', ['variant_id' => 545209, 'specification_value_id' => 94589]); + $conn->insert('var_spec_value_test', ['variant_id' => 545209, 'specification_value_id' => 94593]); + $conn->insert('var_spec_value_test', ['variant_id' => 545209, 'specification_value_id' => 94606]); + $conn->insert('var_spec_value_test', ['variant_id' => 545209, 'specification_value_id' => 94607]); } /** @@ -41,7 +43,7 @@ public function testIssue() { $result = $this->_em->createQueryBuilder() ->select('Variant, SpecificationValue') - ->from('Doctrine\Tests\ORM\Functional\Ticket\DDC809Variant', 'Variant') + ->from(DDC809Variant::class, 'Variant') ->leftJoin('Variant.SpecificationValues', 'SpecificationValue') ->getQuery() ->getResult(); diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC832Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC832Test.php index 219aed48d8b..fdae13585fc 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC832Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC832Test.php @@ -7,20 +7,24 @@ class DDC832Test extends \Doctrine\Tests\OrmFunctionalTestCase public function setUp() { parent::setUp(); + $platform = $this->_em->getConnection()->getDatabasePlatform(); - if ($platform->getName() == "oracle") { + + if ($platform->getName() === 'oracle') { $this->markTestSkipped('Doesnt run on Oracle.'); } $this->_em->getConfiguration()->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger()); + try { - $this->_schemaTool->createSchema(array( - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC832JoinedIndex'), - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC832JoinedTreeIndex'), - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC832Like'), - )); + $this->_schemaTool->createSchema( + [ + $this->_em->getClassMetadata(DDC832JoinedIndex::class), + $this->_em->getClassMetadata(DDC832JoinedTreeIndex::class), + $this->_em->getClassMetadata(DDC832Like::class), + ] + ); } catch(\Exception $e) { - } } @@ -28,6 +32,7 @@ public function tearDown() { /* @var $sm \Doctrine\DBAL\Schema\AbstractSchemaManager */ $platform = $this->_em->getConnection()->getDatabasePlatform(); + $sm = $this->_em->getConnection()->getSchemaManager(); $sm->dropTable($platform->quoteIdentifier('TREE_INDEX')); $sm->dropTable($platform->quoteIdentifier('INDEX')); @@ -39,12 +44,15 @@ public function tearDown() */ public function testQuotedTableBasicUpdate() { - $like = new DDC832Like("test"); + $like = new DDC832Like('test'); $this->_em->persist($like); $this->_em->flush(); - $like->word = "test2"; + $like->word = 'test2'; $this->_em->flush(); + $this->_em->clear(); + + self::assertEquals($like, $this->_em->find(DDC832Like::class, $like->id)); } /** @@ -52,12 +60,17 @@ public function testQuotedTableBasicUpdate() */ public function testQuotedTableBasicRemove() { - $like = new DDC832Like("test"); + $like = new DDC832Like('test'); $this->_em->persist($like); $this->_em->flush(); + $idToBeRemoved = $like->id; + $this->_em->remove($like); $this->_em->flush(); + $this->_em->clear(); + + self::assertNull($this->_em->find(DDC832Like::class, $idToBeRemoved)); } /** @@ -65,12 +78,15 @@ public function testQuotedTableBasicRemove() */ public function testQuotedTableJoinedUpdate() { - $index = new DDC832JoinedIndex("test"); + $index = new DDC832JoinedIndex('test'); $this->_em->persist($index); $this->_em->flush(); - $index->name = "asdf"; + $index->name = 'asdf'; $this->_em->flush(); + $this->_em->clear(); + + self::assertEquals($index, $this->_em->find(DDC832JoinedIndex::class, $index->id)); } /** @@ -78,12 +94,17 @@ public function testQuotedTableJoinedUpdate() */ public function testQuotedTableJoinedRemove() { - $index = new DDC832JoinedIndex("test"); + $index = new DDC832JoinedIndex('test'); $this->_em->persist($index); $this->_em->flush(); + $idToBeRemoved = $index->id; + $this->_em->remove($index); $this->_em->flush(); + $this->_em->clear(); + + self::assertNull($this->_em->find(DDC832JoinedIndex::class, $idToBeRemoved)); } /** @@ -91,12 +112,15 @@ public function testQuotedTableJoinedRemove() */ public function testQuotedTableJoinedChildUpdate() { - $index = new DDC832JoinedTreeIndex("test", 1, 2); + $index = new DDC832JoinedTreeIndex('test', 1, 2); $this->_em->persist($index); $this->_em->flush(); - $index->name = "asdf"; + $index->name = 'asdf'; $this->_em->flush(); + $this->_em->clear(); + + self::assertEquals($index, $this->_em->find(DDC832JoinedTreeIndex::class, $index->id)); } /** @@ -104,12 +128,17 @@ public function testQuotedTableJoinedChildUpdate() */ public function testQuotedTableJoinedChildRemove() { - $index = new DDC832JoinedTreeIndex("test", 1, 2); + $index = new DDC832JoinedTreeIndex('test', 1, 2); $this->_em->persist($index); $this->_em->flush(); + $idToBeRemoved = $index->id; + $this->_em->remove($index); $this->_em->flush(); + $this->_em->clear(); + + self::assertNull($this->_em->find(DDC832JoinedTreeIndex::class, $idToBeRemoved)); } } @@ -176,6 +205,7 @@ class DDC832JoinedTreeIndex extends DDC832JoinedIndex { /** @Column(type="integer") */ public $lft; + /** @Column(type="integer") */ public $rgt; diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC837Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC837Test.php index ef4484ee73b..4721a6b18be 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC837Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC837Test.php @@ -7,13 +7,15 @@ class DDC837Test extends \Doctrine\Tests\OrmFunctionalTestCase protected function setUp() { parent::setUp(); - $this->_schemaTool->createSchema(array( - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC837Super'), - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC837Class1'), - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC837Class2'), - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC837Class3'), - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC837Aggregate'), - )); + $this->_schemaTool->createSchema( + [ + $this->_em->getClassMetadata(DDC837Super::class), + $this->_em->getClassMetadata(DDC837Class1::class), + $this->_em->getClassMetadata(DDC837Class2::class), + $this->_em->getClassMetadata(DDC837Class3::class), + $this->_em->getClassMetadata(DDC837Aggregate::class), + ] + ); } /** @@ -49,25 +51,25 @@ public function testIssue() $this->_em->clear(); // Test Class1 - $e1 = $this->_em->find('Doctrine\Tests\ORM\Functional\Ticket\DDC837Super', $c1->id); + $e1 = $this->_em->find(DDC837Super::class, $c1->id); - $this->assertInstanceOf('Doctrine\Tests\ORM\Functional\Ticket\DDC837Class1', $e1); + $this->assertInstanceOf(DDC837Class1::class, $e1); $this->assertEquals('Foo', $e1->title); $this->assertEquals('Foo', $e1->description); - $this->assertInstanceOf(__NAMESPACE__ . '\DDC837Aggregate', $e1->aggregate); + $this->assertInstanceOf(DDC837Aggregate::class, $e1->aggregate); $this->assertEquals('test1', $e1->aggregate->getSysname()); // Test Class 2 - $e2 = $this->_em->find('Doctrine\Tests\ORM\Functional\Ticket\DDC837Super', $c2->id); + $e2 = $this->_em->find(DDC837Super::class, $c2->id); - $this->assertInstanceOf('Doctrine\Tests\ORM\Functional\Ticket\DDC837Class2', $e2); + $this->assertInstanceOf(DDC837Class2::class, $e2); $this->assertEquals('Bar', $e2->title); $this->assertEquals('Bar', $e2->description); $this->assertEquals('Bar', $e2->text); - $this->assertInstanceOf(__NAMESPACE__ . '\DDC837Aggregate', $e2->aggregate); + $this->assertInstanceOf(DDC837Aggregate::class, $e2->aggregate); $this->assertEquals('test2', $e2->aggregate->getSysname()); - $all = $this->_em->getRepository(__NAMESPACE__.'\DDC837Super')->findAll(); + $all = $this->_em->getRepository(DDC837Super::class)->findAll(); foreach ($all as $obj) { if ($obj instanceof DDC837Class1) { diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC849Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC849Test.php index bab38f0be38..1844b316f37 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC849Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC849Test.php @@ -36,7 +36,7 @@ public function setUp() $this->_em->flush(); $this->_em->clear(); - $this->user = $this->_em->find('Doctrine\Tests\Models\CMS\CmsUser', $this->user->getId()); + $this->user = $this->_em->find(CmsUser::class, $this->user->getId()); } public function testRemoveContains() diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC881Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC881Test.php index 22e39f849a9..3df61f7165c 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC881Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC881Test.php @@ -2,6 +2,9 @@ namespace Doctrine\Tests\ORM\Functional\Ticket; +use Doctrine\ORM\PersistentCollection; +use Doctrine\ORM\Proxy\Proxy; + class DDC881Test extends \Doctrine\Tests\OrmFunctionalTestCase { @@ -10,11 +13,13 @@ protected function setUp() parent::setUp(); try { - $this->_schemaTool->createSchema(array( - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC881User'), - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC881Phonenumber'), - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC881Phonecall'), - )); + $this->_schemaTool->createSchema( + [ + $this->_em->getClassMetadata(DDC881User::class), + $this->_em->getClassMetadata(DDC881Phonenumber::class), + $this->_em->getClassMetadata(DDC881Phonecall::class), + ] + ); } catch (\Exception $e) { } @@ -75,18 +80,18 @@ public function testIssue() $this->_em->clear(); // fetch-join that foreign-key/primary-key entity association - $dql = "SELECT c, p FROM " . __NAMESPACE__ . "\DDC881PhoneCall c JOIN c.phonenumber p"; + $dql = "SELECT c, p FROM " . DDC881PhoneCall::class . " c JOIN c.phonenumber p"; $calls = $this->_em->createQuery($dql)->getResult(); $this->assertEquals(2, count($calls)); - $this->assertNotInstanceOf('Doctrine\ORM\Proxy\Proxy', $calls[0]->getPhoneNumber()); - $this->assertNotInstanceOf('Doctrine\ORM\Proxy\Proxy', $calls[1]->getPhoneNumber()); + $this->assertNotInstanceOf(Proxy::class, $calls[0]->getPhoneNumber()); + $this->assertNotInstanceOf(Proxy::class, $calls[1]->getPhoneNumber()); - $dql = "SELECT p, c FROM " . __NAMESPACE__ . "\DDC881PhoneNumber p JOIN p.calls c"; + $dql = "SELECT p, c FROM " . DDC881PhoneNumber::class . " p JOIN p.calls c"; $numbers = $this->_em->createQuery($dql)->getResult(); $this->assertEquals(2, count($numbers)); - $this->assertInstanceOf('Doctrine\ORM\PersistentCollection', $numbers[0]->getCalls()); + $this->assertInstanceOf(PersistentCollection::class, $numbers[0]->getCalls()); $this->assertTrue($numbers[0]->getCalls()->isInitialized()); } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC933Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC933Test.php index e4c9d132860..f6216a16237 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC933Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC933Test.php @@ -2,13 +2,17 @@ namespace Doctrine\Tests\ORM\Functional\Ticket; +use Doctrine\DBAL\LockMode; +use Doctrine\Tests\Models\Company\CompanyManager; use Doctrine\Tests\OrmFunctionalTestCase; +use Doctrine\Tests\TestUtil; class DDC933Test extends OrmFunctionalTestCase { public function setUp() { $this->useModelSet('company'); + parent::setUp(); } @@ -17,9 +21,11 @@ public function setUp() */ public function testLockCTIClass() { - //$this->_em->getConnection()->getConfiguration()->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger()); + if ($this->_em->getConnection()->getDatabasePlatform()->getName() === 'sqlite') { + self::markTestSkipped('It should not run on in-memory databases'); + } - $manager = new \Doctrine\Tests\Models\Company\CompanyManager(); + $manager = new CompanyManager(); $manager->setName('beberlei'); $manager->setSalary(1234); $manager->setTitle('Vice President of This Test'); @@ -29,7 +35,35 @@ public function testLockCTIClass() $this->_em->flush(); $this->_em->beginTransaction(); - $this->_em->lock($manager, \Doctrine\DBAL\LockMode::PESSIMISTIC_READ); + $this->_em->lock($manager, LockMode::PESSIMISTIC_READ); $this->_em->rollback(); + + // if lock hasn't been released we'd have an exception here + $this->assertManagerCanBeUpdatedOnAnotherConnection($manager->getId(), 'Master of This Test'); + } + + /** + * @param int $id + * @param string $newName + * + * @return void + * + * @throws \Doctrine\Common\Persistence\Mapping\MappingException + * @throws \Doctrine\ORM\ORMException + * @throws \Doctrine\ORM\OptimisticLockException + * @throws \Doctrine\ORM\TransactionRequiredException + */ + private function assertManagerCanBeUpdatedOnAnotherConnection(int $id, string $newName) + { + $em = $this->_getEntityManager(TestUtil::getConnection()); + + /** @var CompanyManager $manager */ + $manager = $em->find(CompanyManager::class, $id); + $manager->setName($newName); + + $em->flush(); + $em->clear(); + + self::assertSame($newName, $em->find(CompanyManager::class, $id)->getName()); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC949Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC949Test.php index a1634fe5d65..8c3162df364 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC949Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC949Test.php @@ -29,13 +29,13 @@ public function testBooleanThroughRepository() $this->_em->flush(); $this->_em->clear(); - $true = $this->_em->getRepository('Doctrine\Tests\Models\Generic\BooleanModel')->findOneBy(array('booleanField' => true)); - $false = $this->_em->getRepository('Doctrine\Tests\Models\Generic\BooleanModel')->findOneBy(array('booleanField' => false)); + $true = $this->_em->getRepository(BooleanModel::class)->findOneBy(['booleanField' => true]); + $false = $this->_em->getRepository(BooleanModel::class)->findOneBy(['booleanField' => false]); - $this->assertInstanceOf('Doctrine\Tests\Models\Generic\BooleanModel', $true, "True model not found"); + $this->assertInstanceOf(BooleanModel::class, $true, "True model not found"); $this->assertTrue($true->booleanField, "True Boolean Model should be true."); - $this->assertInstanceOf('Doctrine\Tests\Models\Generic\BooleanModel', $false, "False model not found"); + $this->assertInstanceOf(BooleanModel::class, $false, "False model not found"); $this->assertFalse($false->booleanField, "False Boolean Model should be false."); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC960Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC960Test.php index b1432ec8b72..730a70bce8c 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC960Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC960Test.php @@ -10,10 +10,12 @@ protected function setUp() { parent::setUp(); try { - $this->_schemaTool->createSchema(array( - $this->_em->getClassMetadata(__NAMESPACE__ . '\\DDC960Root'), - $this->_em->getClassMetadata(__NAMESPACE__ . '\\DDC960Child') - )); + $this->_schemaTool->createSchema( + [ + $this->_em->getClassMetadata(DDC960Root::class), + $this->_em->getClassMetadata(DDC960Child::class) + ] + ); } catch(\Exception $e) { } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC992Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC992Test.php index 25363b0b3e8..77780486bd4 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC992Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC992Test.php @@ -13,11 +13,13 @@ public function setUp() { parent::setUp(); try { - $this->_schemaTool->createSchema(array( - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC992Role'), - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC992Parent'), - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC992Child'), - )); + $this->_schemaTool->createSchema( + [ + $this->_em->getClassMetadata(DDC992Role::class), + $this->_em->getClassMetadata(DDC992Parent::class), + $this->_em->getClassMetadata(DDC992Child::class), + ] + ); } catch(\Exception $e) { } @@ -65,7 +67,7 @@ public function testOneToManyChild() $this->assertEquals(1, count($parent->childs)); $this->assertEquals(0, count($parent->childs[0]->childs())); - $child = $parentRepository->findOneBy(array("id" => $child->id)); + $child = $parentRepository->findOneBy(["id" => $child->id]); $this->assertSame($parent->childs[0], $child); $this->_em->clear(); diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/GH2947Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH2947Test.php new file mode 100644 index 00000000000..0b21b57f065 --- /dev/null +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH2947Test.php @@ -0,0 +1,95 @@ +resultCacheImpl = new ArrayCache(); + + parent::setUp(); + + $this->_schemaTool->createSchema([$this->_em->getClassMetadata(GH2947Car::class)]); + } + + public function testIssue() + { + $this->createData(); + $initialQueryCount = $this->getCurrentQueryCount(); + + $query = $this->createQuery(); + self::assertEquals('BMW', (string) $query->getSingleResult()); + self::assertEquals($initialQueryCount + 1, $this->getCurrentQueryCount()); + + $this->updateData(); + self::assertEquals('BMW', (string) $query->getSingleResult()); + self::assertEquals($initialQueryCount + 2, $this->getCurrentQueryCount()); + + $query->expireResultCache(true); + self::assertEquals('Dacia', (string) $query->getSingleResult()); + self::assertEquals($initialQueryCount + 3, $this->getCurrentQueryCount()); + + $query->expireResultCache(false); + self::assertEquals('Dacia', (string) $query->getSingleResult()); + self::assertEquals($initialQueryCount + 3, $this->getCurrentQueryCount()); + } + + private function createQuery() + { + return $this->_em->createQueryBuilder() + ->select('car') + ->from(GH2947Car::class, 'car') + ->getQuery() + ->useResultCache(true, 3600, 'foo-cache-id'); + } + + private function createData() + { + $this->_em->persist(new GH2947Car('BMW')); + $this->_em->flush(); + $this->_em->clear(); + } + + private function updateData() + { + $this->_em->createQueryBuilder() + ->update(GH2947Car::class, 'car') + ->set('car.brand', ':newBrand') + ->where('car.brand = :oldBrand') + ->setParameter('newBrand', 'Dacia') + ->setParameter('oldBrand', 'BMW') + ->getQuery() + ->execute(); + } +} + +/** + * @Entity + * @Table(name="GH2947_car") + */ +class GH2947Car +{ + /** + * @Id + * @Column(type="string", length=25) + * @GeneratedValue(strategy="NONE") + */ + public $brand; + + public function __construct(string $brand) + { + $this->brand = $brand; + } + + public function __toString(): string + { + return $this->brand; + } +} diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/GH5562Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH5562Test.php new file mode 100644 index 00000000000..824c4378add --- /dev/null +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH5562Test.php @@ -0,0 +1,128 @@ +enableSecondLevelCache(); + + parent::setUp(); + + $this->_schemaTool->createSchema( + [ + $this->_em->getClassMetadata(GH5562User::class), + $this->_em->getClassMetadata(GH5562Manager::class), + $this->_em->getClassMetadata(GH5562Merchant::class), + ] + ); + } + + /** + * @group 5562 + */ + public function testCacheShouldBeUpdatedWhenAssociationChanges() + { + $manager = new GH5562Manager(); + $merchant = new GH5562Merchant(); + + $manager->username = 'username'; + $manager->merchant = $merchant; + $merchant->manager = $manager; + + $merchant->name = 'Merchant'; + + $this->_em->persist($merchant); + $this->_em->persist($manager); + $this->_em->flush(); + $this->_em->clear(); + + $merchant = $this->_em->find(GH5562Merchant::class, $merchant->id); + + $merchant->name = mt_rand(); + $merchant->manager->username = 'usernameUPDATE'; + + $this->_em->flush(); + $this->_em->clear(); + + $merchant = $this->_em->find(GH5562Merchant::class, $merchant->id); + + self::assertEquals('usernameUPDATE', $merchant->manager->username); + } +} + +/** + * @Entity + * @Cache(usage="NONSTRICT_READ_WRITE") + */ +class GH5562Merchant +{ + /** + * @var integer + * + * @Id + * @Column(name="id", type="integer") + * @GeneratedValue(strategy="IDENTITY") + */ + public $id; + + /** + * @var GH5562Manager + * + * @OneToOne(targetEntity=GH5562Manager::class, mappedBy="merchant") + * @Cache(usage="NONSTRICT_READ_WRITE") + */ + public $manager; + + /** + * @var string + * + * @Column(name="name", type="string", length=255, nullable=false) + */ + public $name; +} + +/** + * @Entity + * @InheritanceType("SINGLE_TABLE") + * @DiscriminatorMap({"MANAGER" = GH5562Manager::class}) + */ +abstract class GH5562User +{ + /** + * @var integer + * + * @Id + * @Column(name="id", type="integer") + * @GeneratedValue(strategy="IDENTITY") + */ + public $id; +} + +/** + * @Entity + * @Cache(usage="NONSTRICT_READ_WRITE") + */ +class GH5562Manager extends GH5562User +{ + + /** + * @var string + * + * @Column + */ + public $username; + + /** + * @var GH5562Merchant + * + * @OneToOne(targetEntity=GH5562Merchant::class, inversedBy="manager") + */ + public $merchant; +} diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/GH5762Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH5762Test.php new file mode 100644 index 00000000000..b7a748ddc46 --- /dev/null +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH5762Test.php @@ -0,0 +1,190 @@ +_schemaTool->createSchema( + [ + $this->_em->getClassMetadata(GH5762Driver::class), + $this->_em->getClassMetadata(GH5762DriverRide::class), + $this->_em->getClassMetadata(GH5762Car::class), + ] + ); + } + + public function testIssue() + { + $result = $this->fetchData(); + + self::assertInstanceOf(GH5762Driver::class, $result); + self::assertInstanceOf(PersistentCollection::class, $result->driverRides); + self::assertInstanceOf(GH5762DriverRide::class, $result->driverRides->get(0)); + self::assertInstanceOf(GH5762Car::class, $result->driverRides->get(0)->car); + + $cars = []; + foreach ($result->driverRides as $ride) { + $cars[] = $ride->car->brand; + } + + self::assertEquals(count($cars), count(array_unique($cars))); + + self::assertContains('BMW', $cars); + self::assertContains('Crysler', $cars); + self::assertContains('Dodge', $cars); + self::assertContains('Mercedes', $cars); + self::assertContains('Volvo', $cars); + } + + private function fetchData() + { + $this->createData(); + + $qb = $this->_em->createQueryBuilder(); + $qb->select('d, dr, c') + ->from(GH5762Driver::class, 'd') + ->leftJoin('d.driverRides', 'dr') + ->leftJoin('dr.car', 'c') + ->where('d.id = 1'); + + return $qb->getQuery()->getSingleResult(); + } + + private function createData() + { + $car1 = new GH5762Car('BMW', '7 Series'); + $car2 = new GH5762Car('Crysler', '300'); + $car3 = new GH5762Car('Dodge', 'Dart'); + $car4 = new GH5762Car('Mercedes', 'C-Class'); + $car5 = new GH5762Car('Volvo', 'XC90'); + + $driver = new GH5762Driver(1, 'John Doe'); + + $ride1 = new GH5762DriverRide($driver, $car1); + $ride2 = new GH5762DriverRide($driver, $car2); + $ride3 = new GH5762DriverRide($driver, $car3); + $ride4 = new GH5762DriverRide($driver, $car4); + $ride5 = new GH5762DriverRide($driver, $car5); + + $this->_em->persist($car1); + $this->_em->persist($car2); + $this->_em->persist($car3); + $this->_em->persist($car4); + $this->_em->persist($car5); + + $this->_em->persist($driver); + + $this->_em->persist($ride1); + $this->_em->persist($ride2); + $this->_em->persist($ride3); + $this->_em->persist($ride4); + $this->_em->persist($ride5); + + $this->_em->flush(); + $this->_em->clear(); + } +} + +/** + * @Entity + * @Table(name="driver") + */ +class GH5762Driver +{ + /** + * @Id + * @Column(type="integer") + * @GeneratedValue(strategy="NONE") + */ + public $id; + + /** + * @Column(type="string", length=255); + */ + public $name; + + /** + * @OneToMany(targetEntity="GH5762DriverRide", mappedBy="driver") + */ + public $driverRides; + + public function __construct($id, $name) + { + $this->driverRides = new ArrayCollection(); + $this->id = $id; + $this->name = $name; + } +} + +/** + * @Entity + * @Table(name="driver_ride") + */ +class GH5762DriverRide +{ + /** + * @Id + * @ManyToOne(targetEntity="GH5762Driver", inversedBy="driverRides") + * @JoinColumn(name="driver_id", referencedColumnName="id") + */ + public $driver; + + /** + * @Id + * @ManyToOne(targetEntity="GH5762Car", inversedBy="carRides") + * @JoinColumn(name="car", referencedColumnName="brand") + */ + public $car; + + function __construct(GH5762Driver $driver, GH5762Car $car) + { + $this->driver = $driver; + $this->car = $car; + + $this->driver->driverRides->add($this); + $this->car->carRides->add($this); + } +} + +/** + * @Entity + * @Table(name="car") + */ +class GH5762Car +{ + + /** + * @Id + * @Column(type="string", length=25) + * @GeneratedValue(strategy="NONE") + */ + public $brand; + + /** + * @Column(type="string", length=255); + */ + public $model; + + /** + * @OneToMany(targetEntity="GH5762DriverRide", mappedBy="car") + */ + public $carRides; + + public function __construct($brand, $model) + { + $this->carRides = new ArrayCollection(); + $this->brand = $brand; + $this->model = $model; + } +} diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/GH5804Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH5804Test.php new file mode 100644 index 00000000000..77d4fbc878e --- /dev/null +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH5804Test.php @@ -0,0 +1,108 @@ +_schemaTool->createSchema( + [$this->_em->getClassMetadata(GH5804Article::class)] + ); + } + + public function testTextColumnSaveAndRetrieve2() + { + $firstArticle = new GH5804Article; + $firstArticle->text = 'Max'; + $this->_em->persist($firstArticle); + $this->_em->flush(); + + self::assertSame(1, $firstArticle->version); + + $firstArticle->text = 'Moritz'; + $this->_em->persist($firstArticle); + $this->_em->flush(); + + self::assertSame(2, $firstArticle->version); + } +} + +final class GH5804Generator extends AbstractIdGenerator +{ + /** + * {@inheritdoc} + */ + public function generate(EntityManager $em, $entity) + { + return 'test5804'; + } +} + +final class GH5804Type extends Type +{ + const NAME = 'GH5804Type'; + + public function getName() + { + return self::NAME; + } + + /** + * {@inheritdoc} + */ + public function getSQLDeclaration(array $fieldDeclaration, AbstractPlatform $platform) + { + return $platform->getVarcharTypeDeclarationSQL($fieldDeclaration); + } + + /** + * {@inheritdoc} + */ + public function convertToDatabaseValue($value, AbstractPlatform $platform) + { + if (empty($value)) { + return null; + } + + return 'testGh5804DbValue'; + } +} + +/** + * @Entity + */ +class GH5804Article +{ + /** + * @Id + * @Column(type="GH5804Type") + * @GeneratedValue(strategy="CUSTOM") + * @CustomIdGenerator(class=\Doctrine\Tests\ORM\Functional\Ticket\GH5804Generator::class) + */ + public $id; + + /** + * @Version + * @Column(type="integer") + */ + public $version; + + /** + * @Column(type="text") + */ + public $text; +} diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/GH5887Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH5887Test.php new file mode 100644 index 00000000000..f19dd5924b5 --- /dev/null +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH5887Test.php @@ -0,0 +1,234 @@ +_schemaTool->createSchema( + [ + $this->_em->getClassMetadata(GH5887Cart::class), + $this->_em->getClassMetadata(GH5887Customer::class), + ] + ); + } + + public function testLazyLoadsForeignEntitiesInOneToOneRelationWhileHavingCustomIdObject() + { + $customerId = new GH5887CustomIdObject(1); + $customer = new GH5887Customer(); + $customer->setId($customerId); + + $cartId = 2; + $cart = new GH5887Cart(); + $cart->setId($cartId); + $cart->setCustomer($customer); + + $this->_em->persist($customer); + $this->_em->persist($cart); + $this->_em->flush(); + + // Clearing cached entities + $this->_em->clear(); + + $customerRepository = $this->_em->getRepository(GH5887Customer::class); + /** @var GH5887Customer $customer */ + $customer = $customerRepository->createQueryBuilder('c') + ->where('c.id = :id') + ->setParameter('id', $customerId->getId()) + ->getQuery() + ->getOneOrNullResult(); + + $this->assertInstanceOf(GH5887Cart::class, $customer->getCart()); + } +} + +/** + * @Entity + */ +class GH5887Cart +{ + /** + * @var int + * + * @Id + * @Column(type="integer") + * @GeneratedValue(strategy="NONE") + */ + private $id; + + /** + * One Cart has One Customer. + * + * @var GH5887Customer + * + * @OneToOne(targetEntity="GH5887Customer", inversedBy="cart") + * @JoinColumn(name="customer_id", referencedColumnName="id") + */ + private $customer; + + /** + * @return int + */ + public function getId() + { + return $this->id; + } + + /** + * @param int $id + */ + public function setId($id) + { + $this->id = $id; + } + + /** + * @return GH5887Customer + */ + public function getCustomer() + { + return $this->customer; + } + + /** + * @param GH5887Customer $customer + */ + public function setCustomer(GH5887Customer $customer) + { + if ($this->customer !== $customer) { + $this->customer = $customer; + $customer->setCart($this); + } + } +} + +/** + * @Entity + */ +class GH5887Customer +{ + /** + * @var GH5887CustomIdObject + * + * @Id + * @Column(type="GH5887CustomIdObject") + * @GeneratedValue(strategy="NONE") + */ + private $id; + + /** + * One Customer has One Cart. + * + * @var GH5887Cart + * + * @OneToOne(targetEntity="GH5887Cart", mappedBy="customer") + */ + private $cart; + + /** + * @return GH5887CustomIdObject + */ + public function getId() + { + return $this->id; + } + + /** + * @param GH5887CustomIdObject $id + */ + public function setId(GH5887CustomIdObject $id) + { + $this->id = $id; + } + + /** + * @return GH5887Cart + */ + public function getCart(): GH5887Cart + { + return $this->cart; + } + + /** + * @param GH5887Cart $cart + */ + public function setCart(GH5887Cart $cart) + { + if ($this->cart !== $cart) { + $this->cart = $cart; + $cart->setCustomer($this); + } + } +} + +class GH5887CustomIdObject +{ + /** + * @var int + */ + private $id; + + /** + * @param int $id + */ + public function __construct($id) + { + $this->id = $id; + } + + /** + * @return int + */ + public function getId(): int + { + return $this->id; + } + + public function __toString() + { + return 'non existing id'; + } +} + +class GH5887CustomIdObjectType extends StringType +{ + const NAME = 'GH5887CustomIdObject'; + + /** + * {@inheritdoc} + */ + public function convertToDatabaseValue($value, AbstractPlatform $platform) + { + return $value->getId(); + } + + /** + * {@inheritdoc} + */ + public function convertToPHPValue($value, AbstractPlatform $platform) + { + return new GH5887CustomIdObject($value); + } + + /** + * {@inheritdoc} + */ + public function getName() + { + return self::NAME; + } +} diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/GH6029Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH6029Test.php new file mode 100644 index 00000000000..50696a51668 --- /dev/null +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH6029Test.php @@ -0,0 +1,137 @@ +setUpEntitySchema( + [ + GH6029User::class, + GH6029Group::class, + GH6029Group2::class, + GH6029Product::class, + GH6029Feature::class, + ] + ); + } + + /** + * Verifies that when wrong entity is persisted via relationship field, the error message does not correctly state + * the expected class name. + * + * @group 6029 + */ + public function testManyToManyAssociation() : void + { + $user = new GH6029User(); + $user->groups->add(new GH6029Group2()); + + $this->expectException(ORMInvalidArgumentException::class); + $this->expectExceptionMessage( + sprintf( + 'Expected value of type "%s" for association field "%s#$groups", got "%s" instead.', + GH6029Group::class, + GH6029User::class, + GH6029Group2::class + ) + ); + + $this->_em->persist($user); + $this->_em->flush(); + } + + /** + * Verifies that when wrong entity is persisted via relationship field, the error message does not correctly state + * the expected class name. + * + * @group 6029 + */ + public function testOneToManyAssociation() : void + { + $product = new GH6029Product(); + $product->features->add(new GH6029Group2()); + + $this->expectException(ORMInvalidArgumentException::class); + $this->expectExceptionMessage( + sprintf( + 'Expected value of type "%s" for association field "%s#$features", got "%s" instead.', + GH6029Feature::class, + GH6029Product::class, + GH6029Group2::class + ) + ); + + $this->_em->persist($product); + $this->_em->flush(); + } +} + +/** @Entity */ +class GH6029User +{ + /** @Id @Column(type="integer") @GeneratedValue */ + public $id; + + /** @ManyToMany(targetEntity=GH6029Group::class, cascade={"all"}) */ + public $groups; + + public function __construct() + { + $this->groups = new ArrayCollection(); + } +} + +/** @Entity */ +class GH6029Group +{ + /** @Id @Column(type="integer") @GeneratedValue */ + public $id; +} + +/** @Entity */ +class GH6029Group2 +{ + /** @Id @Column(type="integer") @GeneratedValue */ + public $id; +} + +/** @Entity */ +class GH6029Product +{ + /** @Id @Column(type="integer") @GeneratedValue */ + public $id; + + /** + * @OneToMany(targetEntity=GH6029Feature::class, mappedBy="product", cascade={"all"}) + */ + public $features; + + public function __construct() + { + $this->features = new ArrayCollection(); + } +} + +/** @Entity */ +class GH6029Feature +{ + /** @Id @Column(type="integer") @GeneratedValue */ + public $id; + + /** + * @ManyToOne(targetEntity=GH6029Product::class, inversedBy="features") + * @JoinColumn(name="product_id", referencedColumnName="id") + */ + public $product; +} diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/GH6141Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH6141Test.php new file mode 100644 index 00000000000..00ae936a4b1 --- /dev/null +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH6141Test.php @@ -0,0 +1,202 @@ +_schemaTool->createSchema( + [ + $this->_em->getClassMetadata(GH6141Person::class), + $this->_em->getClassMetadata(GH6141Boss::class), + $this->_em->getClassMetadata(GH6141Employee::class), + ] + ); + } + + /** + * The intent of this test is to ensure that the ORM is capable + * of using objects as discriminators (which makes things a bit + * more dynamic as you can see on the mapping of `GH6141Person`) + * + * @group 6141 + */ + public function testEnumDiscriminatorsShouldBeConvertedToString() + { + $boss = new GH6141Boss('John'); + $employee = new GH6141Employee('Bob'); + + $this->_em->persist($boss); + $this->_em->persist($employee); + $this->_em->flush(); + $this->_em->clear(); + + // Using DQL here to make sure that we'll use ObjectHydrator instead of SimpleObjectHydrator + $query = $this->_em->createQueryBuilder() + ->select('person') + ->from(GH6141Person::class, 'person') + ->where('person.name = :name') + ->setMaxResults(1) + ->getQuery(); + + $query->setParameter('name', 'John'); + self::assertEquals($boss, $query->getOneOrNullResult(AbstractQuery::HYDRATE_OBJECT)); + self::assertEquals( + GH6141People::get(GH6141People::BOSS), + $query->getOneOrNullResult(AbstractQuery::HYDRATE_ARRAY)['discr'] + ); + + $query->setParameter('name', 'Bob'); + self::assertEquals($employee, $query->getOneOrNullResult(AbstractQuery::HYDRATE_OBJECT)); + self::assertEquals( + GH6141People::get(GH6141People::EMPLOYEE), + $query->getOneOrNullResult(AbstractQuery::HYDRATE_ARRAY)['discr'] + ); + } +} + +class GH6141PeopleType extends StringType +{ + const NAME = 'gh6141people'; + + /** + * {@inheritdoc} + */ + public function convertToDatabaseValue($value, AbstractPlatform $platform) + { + if (!$value instanceof GH6141People) { + $value = GH6141People::get($value); + } + + return (string) $value; + } + + /** + * {@inheritdoc} + */ + public function convertToPhpValue($value, AbstractPlatform $platform) + { + return GH6141People::get($value); + } + + /** + * {@inheritdoc} + */ + public function getName() + { + return self::NAME; + } +} + +class GH6141People +{ + const BOSS = 'boss'; + const EMPLOYEE = 'employee'; + + /** + * @var string + */ + private $value; + + /** + * @param string $value + * + * @return GH6141People + * + * @throws \InvalidArgumentException + */ + public static function get($value) + { + if (!self::isValid($value)) { + throw new \InvalidArgumentException(); + } + + return new self($value); + } + + /** + * @param string $valid + * + * @return bool + */ + private static function isValid($valid) + { + return in_array($valid, [self::BOSS, self::EMPLOYEE]); + } + + /** + * @param string $value + */ + private function __construct($value) + { + $this->value = $value; + } + + /** + * @return string + */ + public function getValue() + { + return $this->value; + } + + /** + * @return string + */ + public function __toString() + { + return $this->value; + } +} + +/** + * @Entity + * @InheritanceType("JOINED") + * @DiscriminatorColumn(name="discr", type="gh6141people") + * @DiscriminatorMap({ + * Doctrine\Tests\ORM\Functional\Ticket\GH6141People::BOSS = GH6141Boss::class, + * Doctrine\Tests\ORM\Functional\Ticket\GH6141People::EMPLOYEE = GH6141Employee::class + * }) + */ +abstract class GH6141Person +{ + /** + * @Id + * @Column(type="integer") + * @GeneratedValue(strategy="AUTO") + */ + public $id; + + /** + * @Column(type="string") + */ + public $name; + + /** + * @param string $name + */ + public function __construct($name) + { + $this->name = $name; + } +} + +/** @Entity */ +class GH6141Boss extends GH6141Person +{ +} + +/** @Entity */ +class GH6141Employee extends GH6141Person +{ +} diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/GH6217Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH6217Test.php new file mode 100644 index 00000000000..d781d0c816d --- /dev/null +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH6217Test.php @@ -0,0 +1,78 @@ +enableSecondLevelCache(); + + parent::setUp(); + + $this->_schemaTool->createSchema([ + $this->_em->getClassMetadata(GH6217AssociatedEntity::class), + $this->_em->getClassMetadata(GH6217FetchedEntity::class), + ]); + } + + public function testLoadingOfSecondLevelCacheOnEagerAssociations() : void + { + $lazy = new GH6217AssociatedEntity(); + $eager = new GH6217AssociatedEntity(); + $fetched = new GH6217FetchedEntity($lazy, $eager); + + $this->_em->persist($eager); + $this->_em->persist($lazy); + $this->_em->persist($fetched); + $this->_em->flush(); + $this->_em->clear(); + + $repository = $this->_em->getRepository(GH6217FetchedEntity::class); + $filters = ['eager' => $eager->id]; + + self::assertCount(1, $repository->findBy($filters)); + $queryCount = $this->getCurrentQueryCount(); + + /* @var $found GH6217FetchedEntity[] */ + $found = $repository->findBy($filters); + + self::assertCount(1, $found); + self::assertInstanceOf(GH6217FetchedEntity::class, $found[0]); + self::assertSame($lazy->id, $found[0]->lazy->id); + self::assertSame($eager->id, $found[0]->eager->id); + self::assertEquals($queryCount, $this->getCurrentQueryCount(), 'No queries were executed in `findBy`'); + } +} + +/** @Entity @Cache(usage="NONSTRICT_READ_WRITE") */ +class GH6217AssociatedEntity +{ + /** @Id @Column(type="string") @GeneratedValue(strategy="NONE") */ + public $id; + + public function __construct() + { + $this->id = uniqid(self::class, true); + } +} + +/** @Entity @Cache(usage="NONSTRICT_READ_WRITE") */ +class GH6217FetchedEntity +{ + /** @Id @Cache("NONSTRICT_READ_WRITE") @ManyToOne(targetEntity=GH6217AssociatedEntity::class) */ + public $lazy; + + /** @Id @Cache("NONSTRICT_READ_WRITE") @ManyToOne(targetEntity=GH6217AssociatedEntity::class, fetch="EAGER") */ + public $eager; + + public function __construct(GH6217AssociatedEntity $lazy, GH6217AssociatedEntity $eager) + { + $this->lazy = $lazy; + $this->eager = $eager; + } +} diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/GH6362Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH6362Test.php new file mode 100644 index 00000000000..576fbd0eb86 --- /dev/null +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH6362Test.php @@ -0,0 +1,144 @@ +_schemaTool->createSchema( + [ + $this->_em->getClassMetadata(GH6362Start::class), + $this->_em->getClassMetadata(GH6362Base::class), + $this->_em->getClassMetadata(GH6362Child::class), + $this->_em->getClassMetadata(GH6362Join::class), + ] + ); + } + + /** + * @group 6362 + * + * SELECT a as base, b, c, d + * FROM Start a + * LEFT JOIN a.bases b + * LEFT JOIN Child c WITH b.id = c.id + * LEFT JOIN c.joins d + */ + public function testInheritanceJoinAlias() + { + $rsm = new ResultSetMapping; + $rsm->addEntityResult(GH6362Start::class, 'a', 'base'); + $rsm->addJoinedEntityResult(GH6362Base::class, 'b', 'a', 'bases'); + $rsm->addEntityResult(GH6362Child::class, 'c'); + $rsm->addJoinedEntityResult(GH6362Join::class, 'd', 'c', 'joins'); + + $rsm->addFieldResult('a', 'id_0', 'id'); + $rsm->addFieldResult('b', 'id_1', 'id'); + $rsm->addFieldResult('c', 'id_2', 'id'); + $rsm->addFieldResult('d', 'id_3', 'id'); + + $rsm->addMetaResult('a', 'bases_id_4', 'bases_id', false, 'integer'); + $rsm->addMetaResult('b', 'type_5', 'type'); + $rsm->addMetaResult('c', 'type_6', 'type'); + $rsm->addMetaResult('d', 'child_id_7', 'child_id', false, 'integer'); + + $rsm->setDiscriminatorColumn('b', 'type_5'); + $rsm->setDiscriminatorColumn('c', 'type_6'); + + $resultSet = [ + [ + 'id_0' => '1', + 'id_1' => '1', + 'id_2' => '1', + 'id_3' => '1', + 'bases_id_4' => '1', + 'type_5' => 'child', + 'type_6' => 'child', + 'child_id_7' => '1', + ], + ]; + + $stmt = new HydratorMockStatement($resultSet); + $hydrator = new \Doctrine\ORM\Internal\Hydration\ObjectHydrator($this->_em); + $result = $hydrator->hydrateAll($stmt, $rsm, [Query::HINT_FORCE_PARTIAL_LOAD => true]); + + $this->assertInstanceOf(GH6362Start::class, $result[0]['base']); + $this->assertInstanceOf(GH6362Child::class, $result[1][0]); + } +} + +/** + * @Entity + */ +class GH6362Start +{ + /** + * @Column(type="integer") + * @Id + * @GeneratedValue + */ + protected $id; + + /** + * @ManyToOne(targetEntity="GH6362Base", inversedBy="starts") + */ + private $bases; +} + +/** + * @InheritanceType("SINGLE_TABLE") + * @DiscriminatorColumn(name="type", type="string") + * @DiscriminatorMap({"child" = "GH6362Child"}) + * @Entity + */ +abstract class GH6362Base +{ + /** + * @Column(type="integer") + * @Id + * @GeneratedValue + */ + protected $id; + + /** + * @OneToMany(targetEntity="GH6362Start", mappedBy="bases") + */ + private $starts; +} + +/** + * @Entity + */ +class GH6362Child extends GH6362Base +{ + /** + * @OneToMany(targetEntity="GH6362Join", mappedBy="child") + */ + private $joins; +} + +/** + * @Entity + */ +class GH6362Join +{ + /** + * @Column(type="integer") + * @Id + * @GeneratedValue + */ + private $id; + + /** + * @ManyToOne(targetEntity="GH6362Child", inversedBy="joins") + */ + private $child; +} diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/GH6402Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH6402Test.php new file mode 100644 index 00000000000..d675da94ad3 --- /dev/null +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH6402Test.php @@ -0,0 +1,94 @@ +useModelSet('quote'); + + parent::setUp(); + } + + public function testFind() + { + $id = $this->createAddress(); + + $address = $this->_em->find(Address::class, $id); + self::assertNotNull($address->user); + } + + public function testQuery() + { + $id = $this->createAddress(); + + $addresses = $this->_em->createQuery('SELECT a FROM ' . Address::class . ' a WHERE a.id = :id') + ->setParameter('id', $id) + ->getResult(); + + self::assertCount(1, $addresses); + self::assertNotNull($addresses[0]->user); + } + + public function testFindWithSubClass() + { + $id = $this->createFullAddress(); + + $address = $this->_em->find(FullAddress::class, $id); + self::assertNotNull($address->user); + } + + public function testQueryWithSubClass() + { + $id = $this->createFullAddress(); + + $addresses = $this->_em->createQuery('SELECT a FROM ' . FullAddress::class . ' a WHERE a.id = :id') + ->setParameter('id', $id) + ->getResult(); + + self::assertCount(1, $addresses); + self::assertNotNull($addresses[0]->user); + } + + private function createAddress() + { + $address = new Address(); + $address->zip = 'bar'; + + $this->persistAddress($address); + + return $address->id; + } + + private function createFullAddress() + { + $address = new FullAddress(); + $address->zip = 'bar'; + $address->city = new City('London'); + + $this->persistAddress($address); + + return $address->id; + } + + private function persistAddress(Address $address) + { + $user = new User(); + $user->name = "foo"; + $user->setAddress($address); + + $this->_em->persist($user); + $this->_em->flush(); + $this->_em->clear(); + } +} diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/GH6464Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH6464Test.php new file mode 100644 index 00000000000..1d75cdf3dc2 --- /dev/null +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH6464Test.php @@ -0,0 +1,76 @@ +_schemaTool->createSchema([ + $this->_em->getClassMetadata(GH6464Post::class), + $this->_em->getClassMetadata(GH6464User::class), + $this->_em->getClassMetadata(GH6464Author::class), + ]); + } + + /** + * Verifies that SqlWalker generates valid SQL for an INNER JOIN to CTI table + * + * SqlWalker needs to generate nested INNER JOIN statements, otherwise there would be INNER JOIN + * statements without an ON clause, which are valid on e.g. MySQL but rejected by PostgreSQL. + */ + public function testIssue() : void + { + $query = $this->_em->createQueryBuilder() + ->select('p') + ->from(GH6464Post::class, 'p') + ->innerJoin(GH6464Author::class, 'a', 'WITH', 'p.authorId = a.id') + ->getQuery(); + + $this->assertNotRegExp( + '/INNER JOIN \w+ \w+ INNER JOIN/', + $query->getSQL(), + 'As of GH-6464, every INNER JOIN should have an ON clause, which is missing here' + ); + + // Query shouldn't yield a result, yet it shouldn't crash (anymore) + $this->assertEquals([], $query->getResult()); + } +} + +/** @Entity */ +class GH6464Post +{ + /** @Id @Column(type="integer") @GeneratedValue */ + public $id; + + /** @Column(type="integer") */ + public $authorId; +} + +/** + * @Entity + * @InheritanceType("JOINED") + * @DiscriminatorColumn(name="discr", type="string") + * @DiscriminatorMap({"author" = "GH6464Author"}) + */ +abstract class GH6464User +{ + /** @Id @Column(type="integer") @GeneratedValue */ + public $id; +} + +/** @Entity */ +class GH6464Author extends GH6464User +{ +} diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/GH6531Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH6531Test.php new file mode 100644 index 00000000000..1d819f2508f --- /dev/null +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH6531Test.php @@ -0,0 +1,190 @@ +setUpEntitySchema( + [ + GH6531User::class, + GH6531Address::class, + GH6531Article::class, + GH6531ArticleAttribute::class, + GH6531Order::class, + GH6531OrderItem::class, + GH6531Product::class, + ] + ); + } + + /** + * @group 6531 + */ + public function testSimpleDerivedIdentity() : void + { + $user = new GH6531User(); + $address = new GH6531Address(); + $address->user = $user; + + $this->_em->persist($user); + $this->_em->persist($address); + $this->_em->flush(); + + self::assertSame($user, $this->_em->find(GH6531User::class, $user->id)); + self::assertSame($address, $this->_em->find(GH6531Address::class, $user)); + } + + /** + * @group 6531 + */ + public function testDynamicAttributes() : void + { + $article = new GH6531Article(); + $article->addAttribute('name', 'value'); + + $this->_em->persist($article); + $this->_em->flush(); + + self::assertSame( + $article->attributes['name'], + $this->_em->find(GH6531ArticleAttribute::class, ['article' => $article, 'attribute' => 'name']) + ); + } + + /** + * @group 6531 + */ + public function testJoinTableWithMetadata() : void + { + $product = new GH6531Product(); + $this->_em->persist($product); + $this->_em->flush(); + + $order = new GH6531Order(); + $order->addItem($product, 2); + + $this->_em->persist($order); + $this->_em->flush(); + + self::assertSame( + $order->items->first(), + $this->_em->find(GH6531OrderItem::class, ['product' => $product, 'order' => $order]) + ); + } +} + +/** + * @Entity + */ +class GH6531User +{ + /** @Id @Column(type="integer") @GeneratedValue */ + public $id; +} + +/** + * @Entity + */ +class GH6531Address +{ + /** @Id @OneToOne(targetEntity=GH6531User::class) */ + public $user; +} + +/** + * @Entity + */ +class GH6531Article +{ + /** @Id @Column(type="integer") @GeneratedValue */ + public $id; + + /** @OneToMany(targetEntity=GH6531ArticleAttribute::class, mappedBy="article", cascade={"ALL"}, indexBy="attribute") */ + public $attributes; + + public function addAttribute(string $name, string $value) + { + $this->attributes[$name] = new GH6531ArticleAttribute($name, $value, $this); + } +} + +/** + * @Entity + */ +class GH6531ArticleAttribute +{ + /** @Id @ManyToOne(targetEntity=GH6531Article::class, inversedBy="attributes") */ + public $article; + + /** @Id @Column(type="string") */ + public $attribute; + + /** @Column(type="string") */ + public $value; + + public function __construct(string $name, string $value, GH6531Article $article) + { + $this->attribute = $name; + $this->value = $value; + $this->article = $article; + } +} + +/** + * @Entity + */ +class GH6531Order +{ + /** @Id @Column(type="integer") @GeneratedValue */ + public $id; + + /** @OneToMany(targetEntity=GH6531OrderItem::class, mappedBy="order", cascade={"ALL"}) */ + public $items; + + public function __construct() + { + $this->items = new ArrayCollection(); + } + + public function addItem(GH6531Product $product, int $amount) : void + { + $this->items->add(new GH6531OrderItem($this, $product, $amount)); + } +} + +/** + * @Entity + */ +class GH6531Product +{ + /** @Id @Column(type="integer") @GeneratedValue */ + public $id; +} + +/** + * @Entity + */ +class GH6531OrderItem +{ + /** @Id @ManyToOne(targetEntity=GH6531Order::class) */ + public $order; + + /** @Id @ManyToOne(targetEntity=GH6531Product::class) */ + public $product; + + /** @Column(type="integer") */ + public $amount = 1; + + public function __construct(GH6531Order $order, GH6531Product $product, int $amount = 1) + { + $this->order = $order; + $this->product = $product; + $this->amount = $amount; + } +} diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/GH6682Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH6682Test.php new file mode 100644 index 00000000000..a8fd76fa2d0 --- /dev/null +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH6682Test.php @@ -0,0 +1,29 @@ + 'test_sequence', + 'allocationSize' => '', + 'initialValue' => '', + ]; + + $classMetadataInfo = new ClassMetadataInfo('test_entity'); + $classMetadataInfo->setSequenceGeneratorDefinition($parsedDefinition); + + self::assertSame( + ['sequenceName' => 'test_sequence', 'allocationSize' => '1', 'initialValue' => '1'], + $classMetadataInfo->sequenceGeneratorDefinition + ); + } +} diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/GH6699Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH6699Test.php new file mode 100644 index 00000000000..c1e32fdef26 --- /dev/null +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH6699Test.php @@ -0,0 +1,56 @@ +useModelSet('cms'); + + parent::setUp(); + } + + public function testMixedParametersWithZeroNumber() : void + { + $query = $this->_em->createQueryBuilder() + ->select('u') + ->from(CmsUser::class, 'u') + ->andWhere('u.username = :username') + ->andWhere('u.id = ?0') + ->getQuery(); + + $query->setParameter('username', 'bar'); + $query->setParameter(0, 0); + + $query->execute(); + + self::assertCount(2, $query->getParameters()); + self::assertSame(0, $query->getParameter(0)->getValue()); + self::assertSame('bar', $query->getParameter('username')->getValue()); + } + + public function testMixedParametersWithZeroNumberOnQueryBuilder() : void + { + $query = $this->_em->createQueryBuilder() + ->select('u') + ->from(CmsUser::class, 'u') + ->andWhere('u.username = :username') + ->andWhere('u.id = ?0') + ->setParameter('username', 'bar') + ->setParameter(0, 0) + ->getQuery(); + + $query->execute(); + + self::assertCount(2, $query->getParameters()); + self::assertSame(0, $query->getParameter(0)->getValue()); + self::assertSame('bar', $query->getParameter('username')->getValue()); + } +} diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/GH6740Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH6740Test.php new file mode 100644 index 00000000000..3589fa2fb8a --- /dev/null +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH6740Test.php @@ -0,0 +1,108 @@ +useModelSet('ecommerce'); + + parent::setUp(); + + $product = new ECommerceProduct(); + $product->setName('First Product'); + + $firstCategory = new ECommerceCategory(); + $secondCategory = new ECommerceCategory(); + + $firstCategory->setName('Business'); + $secondCategory->setName('Home'); + + $product->addCategory($firstCategory); + $product->addCategory($secondCategory); + + $this->_em->persist($product); + $this->_em->flush(); + $this->_em->clear(); + + $this->productId = $product->getId(); + $this->firstCategoryId = $firstCategory->getId(); + $this->secondCategoryId = $secondCategory->getId(); + } + + /** + * @group 6740 + */ + public function testCollectionFilteringLteOperator() : void + { + $product = $this->_em->find(ECommerceProduct::class, $this->productId); + $criteria = Criteria::create()->where(Criteria::expr()->lte('id', $this->secondCategoryId)); + + self::assertCount(2, $product->getCategories()->matching($criteria)); + } + + /** + * @group 6740 + */ + public function testCollectionFilteringLtOperator() : void + { + $product = $this->_em->find(ECommerceProduct::class, $this->productId); + $criteria = Criteria::create()->where(Criteria::expr()->lt('id', $this->secondCategoryId)); + + self::assertCount(1, $product->getCategories()->matching($criteria)); + } + + /** + * @group 6740 + */ + public function testCollectionFilteringGteOperator() : void + { + $product = $this->_em->find(ECommerceProduct::class, $this->productId); + $criteria = Criteria::create()->where(Criteria::expr()->gte('id', $this->firstCategoryId)); + + self::assertCount(2, $product->getCategories()->matching($criteria)); + } + + /** + * @group 6740 + */ + public function testCollectionFilteringGtOperator() : void + { + $product = $this->_em->find(ECommerceProduct::class, $this->productId); + $criteria = Criteria::create()->where(Criteria::expr()->gt('id', $this->firstCategoryId)); + + self::assertCount(1, $product->getCategories()->matching($criteria)); + } + + /** + * @group 6740 + */ + public function testCollectionFilteringEqualsOperator() : void + { + $product = $this->_em->find(ECommerceProduct::class, $this->productId); + $criteria = Criteria::create()->where(Criteria::expr()->eq('id', $this->firstCategoryId)); + + self::assertCount(1, $product->getCategories()->matching($criteria)); + } +} diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/GH6937Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH6937Test.php new file mode 100644 index 00000000000..756111b9898 --- /dev/null +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH6937Test.php @@ -0,0 +1,119 @@ +setUpEntitySchema([GH6937Person::class, GH6937Employee::class, GH6937Manager::class]); + } + + public function testPhoneNumberIsPopulatedWithFind() : void + { + $manager = new GH6937Manager(); + $manager->name = 'Kevin'; + $manager->phoneNumber = '555-5555'; + $manager->department = 'Accounting'; + + $this->_em->persist($manager); + $this->_em->flush(); + $this->_em->clear(); + + $persistedManager = $this->_em->find(GH6937Person::class, $manager->id); + + self::assertSame('Kevin', $persistedManager->name); + self::assertSame('555-5555', $persistedManager->phoneNumber); + self::assertSame('Accounting', $persistedManager->department); + } + + public function testPhoneNumberIsPopulatedWithQueryBuilderUsingSimpleObjectHydrator() : void + { + $manager = new GH6937Manager(); + $manager->name = 'Kevin'; + $manager->phoneNumber = '555-5555'; + $manager->department = 'Accounting'; + + $this->_em->persist($manager); + $this->_em->flush(); + $this->_em->clear(); + + $persistedManager = $this->_em->getRepository(GH6937Person::class) + ->createQueryBuilder('e') + ->where('e.id = :id') + ->setParameter('id', $manager->id) + ->getQuery() + ->getOneOrNullResult(AbstractQuery::HYDRATE_SIMPLEOBJECT); + + self::assertSame('Kevin', $persistedManager->name); + self::assertSame('555-5555', $persistedManager->phoneNumber); + self::assertSame('Accounting', $persistedManager->department); + } + + public function testPhoneNumberIsPopulatedWithQueryBuilder() : void + { + $manager = new GH6937Manager(); + $manager->name = 'Kevin'; + $manager->phoneNumber = '555-5555'; + $manager->department = 'Accounting'; + + $this->_em->persist($manager); + $this->_em->flush(); + $this->_em->clear(); + + $persistedManager = $this->_em->getRepository(GH6937Person::class) + ->createQueryBuilder('e') + ->where('e.id = :id') + ->setParameter('id', $manager->id) + ->getQuery() + ->getOneOrNullResult(); + + self::assertSame('Kevin', $persistedManager->name); + self::assertSame('555-5555', $persistedManager->phoneNumber); + self::assertSame('Accounting', $persistedManager->department); + } +} + +/** + * @Entity + * @InheritanceType("JOINED") + * @DiscriminatorColumn(name="discr", type="string") + * @DiscriminatorMap({"employee"=GH6937Employee::class, "manager"=GH6937Manager::class}) + */ +abstract class GH6937Person +{ + /** @Id @Column(type="integer") @GeneratedValue */ + public $id; + + /** @Column(type="string") */ + public $name; +} + +/** + * @Entity + */ +abstract class GH6937Employee extends GH6937Person +{ + /** @Column(type="string") */ + public $phoneNumber; +} + +/** + * @Entity + */ +class GH6937Manager extends GH6937Employee +{ + /** @Column(type="string") */ + public $department; +} diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/GH7012Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH7012Test.php new file mode 100644 index 00000000000..38f57c57c6c --- /dev/null +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH7012Test.php @@ -0,0 +1,82 @@ +useModelSet('quote'); + + parent::setUp(); + + $this->setUpEntitySchema([GH7012UserData::class]); + } + + /** + * @group 7012 + */ + public function testUpdateEntityWithIdentifierAssociationWithQuotedJoinColumn() : void + { + $user = new QuotedUser(); + $user->name = 'John Doe'; + + $this->_em->persist($user); + $this->_em->flush(); + + $userData = new GH7012UserData($user, '123456789'); + + $this->_em->persist($userData); + $this->_em->flush(); + + $userData->name = '4321'; + $this->_em->flush(); + + $platform = $this->_em->getConnection()->getDatabasePlatform(); + $quotedTableName = $platform->quoteIdentifier('quote-user-data'); + $quotedColumn = $platform->quoteIdentifier('name'); + $quotedIdentifier = $platform->quoteIdentifier('user-id'); + + self::assertNotEquals('quote-user-data', $quotedTableName); + self::assertNotEquals('name', $quotedColumn); + self::assertNotEquals('user-id', $quotedIdentifier); + + $queries = $this->_sqlLoggerStack->queries; + + $this->assertSQLEquals( + sprintf('UPDATE %s SET %s = ? WHERE %s = ?', $quotedTableName, $quotedColumn, $quotedIdentifier), + $queries[$this->_sqlLoggerStack->currentQuery - 1]['sql'] + ); + } +} + + +/** + * @Entity + * @Table(name="`quote-user-data`") + */ +class GH7012UserData +{ + /** + * @Id + * @OneToOne(targetEntity=Doctrine\Tests\Models\Quote\User::class) + * @JoinColumn(name="`user-id`", referencedColumnName="`user-id`", onDelete="CASCADE") + */ + public $user; + + /** + * @Column(type="string", name="`name`") + */ + public $name; + + public function __construct(QuotedUser $user, string $name) + { + $this->user = $user; + $this->name = $name; + } +} diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/GH7062Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH7062Test.php new file mode 100644 index 00000000000..1d7a2d7cbd0 --- /dev/null +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH7062Test.php @@ -0,0 +1,212 @@ +setUpEntitySchema( + [ + GH7062Team::class, + GH7062Season::class, + GH7062Ranking::class, + GH7062RankingPosition::class + ] + ); + } + + /** + * @group 7062 + */ + public function testEntityWithAssociationKeyIdentityCanBeUpdated() : void + { + $this->createInitialRankingWithRelatedEntities(); + $this->modifyRanking(); + $this->verifyRanking(); + } + + private function createInitialRankingWithRelatedEntities() : void + { + $team = new GH7062Team(self::TEAM_ID); + $season = new GH7062Season(self::SEASON_ID); + + $season->ranking = new GH7062Ranking($season, [$team]); + + $this->_em->persist($team); + $this->_em->persist($season); + $this->_em->flush(); + $this->_em->clear(); + + foreach ($season->ranking->positions as $position) { + self::assertSame(0, $position->points); + } + } + + private function modifyRanking() : void + { + /** @var GH7062Ranking $ranking */ + $ranking = $this->_em->find(GH7062Ranking::class, self::SEASON_ID); + + foreach ($ranking->positions as $position) { + $position->points += 3; + } + + $this->_em->flush(); + $this->_em->clear(); + } + + private function verifyRanking() : void + { + /** @var GH7062Season $season */ + $season = $this->_em->find(GH7062Season::class, self::SEASON_ID); + self::assertInstanceOf(GH7062Season::class, $season); + + $ranking = $season->ranking; + self::assertInstanceOf(GH7062Ranking::class, $ranking); + + foreach ($ranking->positions as $position) { + self::assertSame(3, $position->points); + } + } +} + +/** + * Simple Entity whose identity is defined through another Entity (Season) + * + * @Entity + * @Table(name="soccer_rankings") + */ +class GH7062Ranking +{ + /** + * @Id + * @OneToOne(targetEntity=GH7062Season::class, inversedBy="ranking") + * @JoinColumn(name="season", referencedColumnName="id") + * + * @var GH7062Season + */ + public $season; + + /** + * @OneToMany(targetEntity=GH7062RankingPosition::class, mappedBy="ranking", cascade={"all"}) + * + * @var Collection|GH7062RankingPosition[] + */ + public $positions; + + /** + * @param GH7062Team[] $teams + */ + public function __construct(GH7062Season $season, array $teams) + { + $this->season = $season; + $this->positions = new ArrayCollection(); + + foreach ($teams as $team) { + $this->positions[] = new GH7062RankingPosition($this, $team); + } + } +} + +/** + * Entity which serves as a identity provider for other entities + * + * @Entity + * @Table(name="soccer_seasons") + */ +class GH7062Season +{ + /** + * @Id + * @Column(type="string") + * + * @var string + */ + public $id; + + /** + * @OneToOne(targetEntity=GH7062Ranking::class, mappedBy="season", cascade={"all"}) + * + * @var GH7062Ranking|null + */ + public $ranking; + + public function __construct(string $id) + { + $this->id = $id; + } +} + +/** + * Entity which serves as a identity provider for other entities + * + * @Entity + * @Table(name="soccer_teams") + */ +class GH7062Team +{ + /** + * @Id + * @Column(type="string") + * + * @var string + */ + public $id; + + public function __construct(string $id) + { + $this->id = $id; + } +} + +/** + * Entity whose identity is defined through two other entities + * + * @Entity + * @Table(name="soccer_ranking_positions") + */ +class GH7062RankingPosition +{ + /** + * @Id + * @ManyToOne(targetEntity=GH7062Ranking::class, inversedBy="positions") + * @JoinColumn(name="season", referencedColumnName="season") + * + * @var GH7062Ranking + */ + public $ranking; + + /** + * @Id + * @ManyToOne(targetEntity=GH7062Team::class) + * @JoinColumn(name="team_id", referencedColumnName="id") + * + * @var GH7062Team + */ + public $team; + + /** + * @Column(type="integer") + * + * @var int + */ + public $points; + + public function __construct(GH7062Ranking $ranking, GH7062Team $team) + { + $this->ranking = $ranking; + $this->team = $team; + $this->points = 0; + } +} diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/GH7067Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH7067Test.php new file mode 100644 index 00000000000..15dc5fa9caf --- /dev/null +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH7067Test.php @@ -0,0 +1,69 @@ +enableSecondLevelCache(); + parent::setUp(); + + $this->setUpEntitySchema([GH7067Entity::class]); + } + + /** + * @group 7067 + */ + public function testSLCWithVersion() : void + { + $entity = new GH7067Entity(); + $entity->lastUpdate = new \DateTime(); + + $this->_em->persist($entity); + $this->_em->flush(); + $this->_em->clear(); + + /** @var GH7067Entity $notCached */ + $notCached = $this->_em->find(GH7067Entity::class, $entity->id); + + self::assertNotNull($notCached->version, 'Version already cached by persister above, it must be not null'); + + $notCached->lastUpdate = new \DateTime('+1 seconds'); + + $this->_em->flush(); + $this->_em->clear(); + } +} + +/** + * @Entity() + * @Cache(usage="NONSTRICT_READ_WRITE") + */ +class GH7067Entity +{ + /** + * @Id + * @GeneratedValue + * @Column(type="integer") + * + * @var int + */ + public $id; + + /** + * @Column(type="datetime") + * + * @var \DateTime + */ + public $lastUpdate; + + /** + * @Column(type="datetime") + * @Version + * + * @var \DateTime + */ + public $version; +} diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/GH7068Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH7068Test.php new file mode 100644 index 00000000000..297d77e0364 --- /dev/null +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH7068Test.php @@ -0,0 +1,43 @@ +setUpEntitySchema( + [ + SomeEntity::class, + ] + ); + } + + public function testLockModeIsRespected() + { + $entity = new SomeEntity(); + $this->_em->persist($entity); + $this->_em->flush(); + $this->_em->clear(); + + $this->_em->find(SomeEntity::class, 1); + + $this->expectException(TransactionRequiredException::class); + $this->_em->find(SomeEntity::class, 1, LockMode::PESSIMISTIC_WRITE); + } +} + +/** @Entity */ +final class SomeEntity { + /** @Id @Column(type="integer") @GeneratedValue */ + public $id; +} diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/GH7079Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH7079Test.php new file mode 100644 index 00000000000..5df5dfcb06f --- /dev/null +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH7079Test.php @@ -0,0 +1,123 @@ +platform = $this->_em->getConnection()->getDatabasePlatform(); + $this->strategy = new DefaultQuoteStrategy(); + } + + public function testGetTableName() : void + { + $table = [ + 'name' => 'cms_user', + 'schema' => 'cms', + ]; + + $cm = $this->createClassMetadata(GH7079CmsUser::class); + $cm->setPrimaryTable($table); + + self::assertEquals($this->getTableFullName($table), $this->strategy->getTableName($cm, $this->platform)); + } + + public function testJoinTableName() : void + { + $table = [ + 'name' => 'cmsaddress_cmsuser', + 'schema' => 'cms', + ]; + + $cm = $this->createClassMetadata(GH7079CmsAddress::class); + $cm->mapManyToMany( + [ + 'fieldName' => 'user', + 'targetEntity' => 'DDC7079CmsUser', + 'inversedBy' => 'users', + 'joinTable' => $table, + ] + ); + + self::assertEquals( + $this->getTableFullName($table), + $this->strategy->getJoinTableName($cm->associationMappings['user'], $cm, $this->platform) + ); + } + + private function getTableFullName(array $table) : string + { + $join = '.'; + if (! $this->platform->supportsSchemas() && $this->platform->canEmulateSchemas()) { + $join = '__'; + } + + return $table['schema'] . $join . $table['name']; + } + + private function createClassMetadata(string $className) : ClassMetadata + { + $cm = new ClassMetadata($className); + $cm->initializeReflection(new RuntimeReflectionService()); + + return $cm; + } +} + +/** + * @Entity + * @Table(name="cms_users", schema="cms") + */ +class GH7079CmsUser +{ + /** + * @Id @Column(type="integer") + * @GeneratedValue + */ + public $id; + + /** @OneToOne(targetEntity=GH7079CmsAddress::class, mappedBy="user", cascade={"persist"}, orphanRemoval=true) */ + public $address; +} + +/** + * @Entity + * @Table(name="cms_addresses", schema="cms") + */ +class GH7079CmsAddress +{ + /** + * @Column(type="integer") + * @Id @GeneratedValue + */ + public $id; + + /** + * @OneToOne(targetEntity=GH7079CmsUser::class, inversedBy="address") + * @JoinColumn(referencedColumnName="id") + */ + public $user; +} diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/GH7259Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH7259Test.php new file mode 100644 index 00000000000..948259815c4 --- /dev/null +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH7259Test.php @@ -0,0 +1,165 @@ +setUpEntitySchema([GH7259Space::class, GH7259File::class, GH7259FileVersion::class, GH7259Feed::class]); + } + + /** + * @group 7259 + */ + public function testPersistFileBeforeVersion() : void + { + $space = new GH7259Space(); + + $this->_em->persist($space); + $this->_em->flush(); + + $feed = new GH7259Feed(); + $feed->space = $space; + + $file = new GH7259File(); + $file->space = $space; + $fileVersion = new GH7259FileVersion(); + $fileVersion->file = $file; + + $this->_em->persist($file); + $this->_em->persist($fileVersion); + $this->_em->persist($feed); + + $this->_em->flush(); + + self::assertNotNull($fileVersion->id); + } + + /** + * @group 7259 + */ + public function testPersistFileAfterVersion() : void + { + $space = new GH7259Space(); + + $this->_em->persist($space); + $this->_em->flush(); + $this->_em->clear(); + + $space = $this->_em->find(GH7259Space::class, $space->id); + + $feed = new GH7259Feed(); + $feed->space = $space; + + $file = new GH7259File(); + $file->space = $space; + $fileVersion = new GH7259FileVersion(); + $fileVersion->file = $file; + + $this->_em->persist($fileVersion); + $this->_em->persist($file); + $this->_em->persist($feed); + + $this->_em->flush(); + + self::assertNotNull($fileVersion->id); + } +} + +/** + * @Entity() + */ +class GH7259File +{ + /** + * @Id + * @GeneratedValue + * @Column(type="integer") + * + * @var int + */ + public $id; + + /** + * @ManyToOne(targetEntity=GH7259Space::class) + * @JoinColumn(nullable=false) + * + * @var GH7259Space|null + */ + public $space; +} + +/** + * @Entity() + */ +class GH7259FileVersion +{ + /** + * @Id + * @GeneratedValue + * @Column(type="integer") + * + * @var int + */ + public $id; + + /** + * @ManyToOne(targetEntity=GH7259File::class) + * @JoinColumn(nullable=false) + * + * @var GH7259File|null + */ + public $file; +} + +/** + * @Entity() + */ +class GH7259Space +{ + /** + * @Id + * @GeneratedValue + * @Column(type="integer") + * + * @var int + */ + public $id; + + /** + * @ManyToOne(targetEntity=GH7259File::class) + * @JoinColumn(nullable=true) + * + * @var GH7259File|null + */ + public $ruleFile; +} + +/** + * @Entity() + */ +class GH7259Feed +{ + /** + * @Id + * @GeneratedValue + * @Column(type="integer") + * + * @var int + */ + public $id; + + /** + * @ManyToOne(targetEntity=GH7259Space::class) + * @JoinColumn(nullable=false) + * + * @var GH7259Space|null + */ + public $space; +} diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/GH7286Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH7286Test.php new file mode 100644 index 00000000000..73d20148d9a --- /dev/null +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH7286Test.php @@ -0,0 +1,135 @@ +setUpEntitySchema( + [ + GH7286Entity::class, + ] + ); + + $this->_em->persist(new GH7286Entity('foo', 1)); + $this->_em->persist(new GH7286Entity('foo', 2)); + $this->_em->persist(new GH7286Entity('bar', 3)); + $this->_em->persist(new GH7286Entity(null, 4)); + $this->_em->flush(); + $this->_em->clear(); + } + + public function testAggregateExpressionInFunction() : void + { + $query = $this->_em->createQuery( + 'SELECT CONCAT(e.type, MIN(e.version)) pair' + . ' FROM ' . GH7286Entity::class . ' e' + . ' WHERE e.type IS NOT NULL' + . ' GROUP BY e.type' + . ' ORDER BY e.type' + ); + + self::assertSame( + [ + ['pair' => 'bar3'], + ['pair' => 'foo1'], + ], + $query->getArrayResult() + ); + } + + /** + * @group DDC-1091 + */ + public function testAggregateFunctionInCustomFunction() : void + { + $this->_em->getConfiguration()->addCustomStringFunction('CC', GH7286CustomConcat::class); + + $query = $this->_em->createQuery( + 'SELECT CC(e.type, MIN(e.version)) pair' + . ' FROM ' . GH7286Entity::class . ' e' + . ' WHERE e.type IS NOT NULL AND e.type != :type' + . ' GROUP BY e.type' + ); + $query->setParameter('type', 'bar'); + + self::assertSame( + ['pair' => 'foo1'], + $query->getSingleResult() + ); + } +} + +/** + * @Entity + */ +class GH7286Entity +{ + /** + * @Id + * @Column(type="integer") + * @GeneratedValue + * @var int + */ + public $id; + + /** + * @Column(nullable=true) + * @var string|null + */ + public $type; + + /** + * @Column(type="integer") + * @var int + */ + public $version; + + public function __construct(?string $type, int $version) + { + $this->type = $type; + $this->version = $version; + } +} + +class GH7286CustomConcat extends FunctionNode +{ + /** @var Node */ + private $first; + + /** @var Node */ + private $second; + + public function parse(Parser $parser) : void + { + $parser->match(Lexer::T_IDENTIFIER); + $parser->match(Lexer::T_OPEN_PARENTHESIS); + + $this->first = $parser->StringPrimary(); + $parser->match(Lexer::T_COMMA); + $this->second = $parser->StringPrimary(); + + $parser->match(Lexer::T_CLOSE_PARENTHESIS); + } + + public function getSql(SqlWalker $walker) : string + { + return $walker->getConnection()->getDatabasePlatform()->getConcatExpression( + $this->first->dispatch($walker), + $this->second->dispatch($walker) + ); + } +} diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/GH7366Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH7366Test.php new file mode 100644 index 00000000000..80f5cae723b --- /dev/null +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH7366Test.php @@ -0,0 +1,75 @@ +setUpEntitySchema( + [ + GH7366Entity::class, + ] + ); + + $this->_em->persist(new GH7366Entity('baz')); + $this->_em->flush(); + $this->_em->clear(); + } + + public function testOptimisticLockNoExceptionOnFind() : void + { + try { + $entity = $this->_em->find(GH7366Entity::class, 1, LockMode::OPTIMISTIC); + } catch (TransactionRequiredException $e) { + self::fail('EntityManager::find() threw TransactionRequiredException with LockMode::OPTIMISTIC'); + } + self::assertEquals('baz', $entity->getName()); + } +} + +/** + * @Entity + */ +class GH7366Entity +{ + /** + * @Id + * @Column(type="integer") + * @GeneratedValue + * @var int + */ + public $id; + + /** + * @Column(type="integer") + * @Version + */ + protected $lockVersion = 1; + + /** + * @Column(length=32) + * @var string + */ + protected $name; + + + public function __construct(string $name) + { + $this->name = $name; + } + + public function getName(): string + { + return $this->name; + } +} diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/GH7629Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH7629Test.php new file mode 100644 index 00000000000..a0c100acaaa --- /dev/null +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH7629Test.php @@ -0,0 +1,48 @@ +setUpEntitySchema([ + GH7629Entity::class, + ]); + + $this->_em->persist(new GH7629Entity()); + $this->_em->flush(); + $this->_em->clear(); + } + + public function testClearScheduledForSynchronizationWhenCommitEmpty(): void + { + $entity = $this->_em->find(GH7629Entity::class, 1); + + $this->_em->persist($entity); + $this->_em->flush(); + + self::assertFalse($this->_em->getUnitOfWork()->isScheduledForDirtyCheck($entity)); + } +} + +/** + * @Entity + * @ChangeTrackingPolicy("DEFERRED_EXPLICIT") + */ +class GH7629Entity +{ + /** + * @Id + * @Column(type="integer") + * @GeneratedValue + */ + public $id; +} diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/GH7684Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH7684Test.php new file mode 100644 index 00000000000..2d833036619 --- /dev/null +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH7684Test.php @@ -0,0 +1,38 @@ +_em->getConnection()->getDatabasePlatform()->supportsForeignKeyConstraints()) { + $this->markTestSkipped('Platform does not support foreign keys.'); + } + + $table1 = new Table('GH7684_identity_test_table'); + $table1->addColumn('id', 'integer'); + $table1->setPrimaryKey(['id']); + + $table2 = new Table('GH7684_identity_test_assoc_table'); + $table2->addColumn('id', 'integer'); + $table2->addColumn('gh7684_identity_test_id', 'integer'); + $table2->setPrimaryKey(['id']); + $table2->addForeignKeyConstraint('GH7684_identity_test', ['gh7684_identity_test_id'], ['id']); + + $metadatas = $this->convertToClassMetadata([$table1, $table2]); + $metadata = $metadatas['Gh7684IdentityTestAssocTable']; + + $this->assertArrayHasKey('gh7684IdentityTest', $metadata->associationMappings); + } +} diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/GH7735Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH7735Test.php new file mode 100644 index 00000000000..52a10dc6435 --- /dev/null +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH7735Test.php @@ -0,0 +1,172 @@ +enableSecondLevelCache(); + parent::setUp(); + + $this->_schemaTool->createSchema( + [ + $this->_em->getClassMetadata(GH7735Car::class), + $this->_em->getClassMetadata(GH7735Power::class), + $this->_em->getClassMetadata(GH7735Engine::class), + ] + ); + + $this->_em->persist(new GH7735Car(1, new GH7735Engine(1, 'turbo', new GH7735Power(1)))); + $this->_em->flush(); + $this->_em->clear(); + } + + /** + * @test + * @group GH7735 + */ + public function findByReturnsCachedEntity() : void + { + $this->_em->getCache()->evictEntityRegion(GH7735Power::class); + + $car = $this->_em->find(GH7735Car::class, 1); + assert($car instanceof GH7735Car); + + self::assertSame('turbo', $car->getEngine()->getModel()); + self::assertSame(1, $car->getEngine()->getPower()->getId()); + } +} + +/** + * @Entity @Cache(usage="READ_ONLY") + */ +class GH7735Car +{ + /** + * @Id + * @Column(type="integer") + * @var int + */ + private $id; + + /** + * @ManyToOne(targetEntity=GH7735Engine::class, cascade={"all"}) + * @JoinColumn(nullable=false) + * @Cache("READ_ONLY") + * @var GH7735Engine + */ + private $engine; + + public function __construct(int $id, GH7735Engine $engine) + { + $this->id = $id; + $this->engine = $engine; + } + + public function getId() : int + { + return $this->id; + } + + public function getEngine() : GH7735Engine + { + return $this->engine; + } +} + +/** + * @Entity + * @Cache(usage="READ_ONLY") + */ +class GH7735Engine +{ + /** + * @Id + * @Column(type="integer") + * @var int + */ + private $id; + + /** + * @OneToOne(targetEntity=GH7735Power::class, mappedBy="engine", cascade={"all"}) + * @Cache("READ_ONLY") + * @var GH7735Power + */ + private $power; + + /** + * @Column + * @var string + */ + private $model; + + public function __construct(int $id, string $model, GH7735Power $power) + { + $this->id = $id; + $this->model = $model; + $this->power = $power; + + $power->setEngine($this); + } + + public function getId() : int + { + return $this->id; + } + + public function getPower() : GH7735Power + { + return $this->power; + } + + public function getModel() : string + { + return $this->model; + } +} + +/** + * @Entity + * @Cache(usage="READ_ONLY") + */ +class GH7735Power +{ + /** + * @Id + * @Column(type="integer") + */ + private $id; + + /** + * @OneToOne(targetEntity=GH7735Engine::class, inversedBy="power") + * @Cache("READ_ONLY") + * @var GH7735Engine + */ + private $engine; + + public function __construct(int $id) + { + $this->id = $id; + } + + public function getId() : int + { + return $this->id; + } + + public function setEngine(GH7735Engine $engine) : void + { + $this->engine = $engine; + } + + public function getEngine() : GH7735Engine + { + return $this->engine; + } +} diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/GH7737Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH7737Test.php new file mode 100644 index 00000000000..8101488a980 --- /dev/null +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH7737Test.php @@ -0,0 +1,100 @@ +setUpEntitySchema([GH7737Group::class, GH7737Person::class]); + + $group1 = new GH7737Group(1, 'Test 1'); + $person = new GH7737Person(1); + $person->groups->add($group1); + + $this->_em->persist($person); + $this->_em->persist($group1); + $this->_em->persist(new GH7737Group(2, 'Test 2')); + $this->_em->flush(); + $this->_em->clear(); + } + + /** + * @test + */ + public function memberOfCriteriaShouldBeCompatibleWithQueryBuilder() : void + { + $query = $this->_em->createQueryBuilder() + ->select('person') + ->from(GH7737Person::class, 'person') + ->addCriteria(Criteria::create()->where(Criteria::expr()->memberOf(':group', 'person.groups'))) + ->getQuery(); + + $group1 = $this->_em->find(GH7737Group::class, 1); + $matching = $query->setParameter('group', $group1)->getOneOrNullResult(); + + self::assertInstanceOf(GH7737Person::class, $matching); + self::assertSame(1, $matching->id); + + $group2 = $this->_em->find(GH7737Group::class, 2); + $notMatching = $query->setParameter('group', $group2)->getOneOrNullResult(); + + self::assertNull($notMatching); + } +} + +/** + * @Entity + */ +class GH7737Group +{ + /** + * @Id + * @Column(type="integer") + */ + public $id; + + /** @Column */ + public $name; + + public function __construct(int $id, string $name) + { + $this->id = $id; + $this->name = $name; + } +} + +/** + * @Entity + */ +class GH7737Person +{ + /** + * @Id + * @Column(type="integer") + */ + public $id; + + /** + * @ManyToMany(targetEntity=GH7737Group::class) + * @JoinTable(inverseJoinColumns={@JoinColumn(name="group_id", referencedColumnName="id", unique=true)}) + */ + public $groups; + + public function __construct(int $id) + { + $this->id = $id; + $this->groups = new ArrayCollection(); + } +} diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/GH7761Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH7761Test.php new file mode 100644 index 00000000000..fcf3e3be7d2 --- /dev/null +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH7761Test.php @@ -0,0 +1,106 @@ +setUpEntitySchema([ + GH7761Entity::class, + GH7761ChildEntity::class, + ]); + + $parent = new GH7761Entity(); + $child = new GH7761ChildEntity(); + $parent->children->add($child); + + $this->_em->persist($parent); + $this->_em->persist($child); + $this->_em->flush(); + $this->_em->clear(); + } + + public function testCollectionClearDoesNotClearIfNotPersisted() : void + { + /** @var GH7761Entity $entity */ + $entity = $this->_em->find(GH7761Entity::class, 1); + $entity->children->clear(); + $this->_em->persist(new GH7761Entity()); + $this->_em->flush(); + + $this->_em->clear(); + + $entity = $this->_em->find(GH7761Entity::class, 1); + self::assertCount(1, $entity->children); + } + + /** + * @group GH-7862 + */ + public function testCollectionClearDoesClearIfPersisted() : void + { + /** @var GH7761Entity $entity */ + $entity = $this->_em->find(GH7761Entity::class, 1); + $entity->children->clear(); + $this->_em->persist($entity); + $this->_em->flush(); + + $this->_em->clear(); + + $entity = $this->_em->find(GH7761Entity::class, 1); + self::assertCount(0, $entity->children); + } +} + +/** + * @Entity + * @ChangeTrackingPolicy("DEFERRED_EXPLICIT") + */ +class GH7761Entity +{ + /** + * @Id + * @Column(type="integer") + * @GeneratedValue + */ + public $id; + + /** + * @ManyToMany(targetEntity="Doctrine\Tests\ORM\Functional\Ticket\GH7761ChildEntity", cascade={"all"}) + * @JoinTable(name="gh7761_to_child", + * joinColumns={@JoinColumn(name="entity_id")}, + * inverseJoinColumns={@JoinColumn(name="child_id")} + * ) + */ + public $children; + + public function __construct() + { + $this->children = new ArrayCollection(); + } +} + +/** + * @Entity + * @ChangeTrackingPolicy("DEFERRED_EXPLICIT") + */ +class GH7761ChildEntity +{ + /** + * @Id + * @Column(type="integer") + * @GeneratedValue + */ + public $id; +} diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/GH7767Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH7767Test.php new file mode 100644 index 00000000000..01f12f32159 --- /dev/null +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH7767Test.php @@ -0,0 +1,110 @@ +setUpEntitySchema([GH7767ParentEntity::class, GH7767ChildEntity::class]); + + $parent = new GH7767ParentEntity(); + $parent->addChild(200); + $parent->addChild(100); + $parent->addChild(300); + + $this->_em->persist($parent); + $this->_em->flush(); + $this->_em->clear(); + } + + public function testMatchingRespectsCollectionOrdering() : void + { + $parent = $this->_em->find(GH7767ParentEntity::class, 1); + assert($parent instanceof GH7767ParentEntity); + + $children = $parent->getChildren()->matching(Criteria::create()); + + self::assertEquals(100, $children[0]->position); + self::assertEquals(200, $children[1]->position); + self::assertEquals(300, $children[2]->position); + } + + public function testMatchingOverrulesCollectionOrdering() : void + { + $parent = $this->_em->find(GH7767ParentEntity::class, 1); + assert($parent instanceof GH7767ParentEntity); + + $children = $parent->getChildren()->matching(Criteria::create()->orderBy(['position' => 'DESC'])); + + self::assertEquals(300, $children[0]->position); + self::assertEquals(200, $children[1]->position); + self::assertEquals(100, $children[2]->position); + } +} + +/** + * @Entity + */ +class GH7767ParentEntity +{ + /** + * @Id + * @Column(type="integer") + * @GeneratedValue + */ + private $id; + + /** + * @OneToMany(targetEntity=GH7767ChildEntity::class, mappedBy="parent", fetch="EXTRA_LAZY", cascade={"persist"}) + * @OrderBy({"position" = "ASC"}) + */ + private $children; + + public function addChild(int $position) : void + { + $this->children[] = new GH7767ChildEntity($this, $position); + } + + public function getChildren() : PersistentCollection + { + return $this->children; + } +} + +/** + * @Entity + */ +class GH7767ChildEntity +{ + /** + * @Id + * @Column(type="integer") + * @GeneratedValue + */ + private $id; + + /** @Column(type="integer") */ + public $position; + + /** @ManyToOne(targetEntity=GH7767ParentEntity::class, inversedBy="children") */ + private $parent; + + public function __construct(GH7767ParentEntity $parent, int $position) + { + $this->parent = $parent; + $this->position = $position; + } +} diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/GH7820Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH7820Test.php new file mode 100644 index 00000000000..11110e5a73e --- /dev/null +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH7820Test.php @@ -0,0 +1,199 @@ +__toString()` + * is used implicitly by {@see \PDOStatement::bindValue()}, instead of being converted by the + * expected {@see \Doctrine\DBAL\Types\Type::convertToDatabaseValue()}. + * + * In order to reproduce this, you must have identifiers implementing + * `#__toString()` (to allow {@see \Doctrine\ORM\UnitOfWork} to hash them) and other accessors + * that are used by the custom DBAL type during DB/PHP conversions. + * + * If `#__toString()` and the DBAL type conversions are asymmetric, then the paginator will fail + * to find records. + * + * Tricky situation, but this very much affects `ramsey/uuid-doctrine` and anyone relying on (for + * example) the {@see \Ramsey\Uuid\Doctrine\UuidBinaryType} type. + */ +class GH7820Test extends OrmFunctionalTestCase +{ + private const SONG = [ + 'What is this song all about?', + 'Can\'t figure any lyrics out', + 'How do the words to it go?', + 'I wish you\'d tell me, I don\'t know', + 'Don\'t know, don\'t know, don\'t know, I don\'t know!', + 'Don\'t know, don\'t know, don\'t know...', + ]; + + protected function setUp() : void + { + parent::setUp(); + + if (! Type::hasType(GH7820LineTextType::class)) { + Type::addType(GH7820LineTextType::class, GH7820LineTextType::class); + } + + $this->setUpEntitySchema([GH7820Line::class]); + + $this->_em->createQuery('DELETE FROM ' . GH7820Line::class . ' l') + ->execute(); + + foreach (self::SONG as $index => $line) { + $this->_em->persist(new GH7820Line(GH7820LineText::fromText($line), $index)); + } + + $this->_em->flush(); + } + + public function testWillFindSongsInPaginator() : void + { + $query = $this->_em->getRepository(GH7820Line::class) + ->createQueryBuilder('l') + ->orderBy('l.lineNumber', Criteria::ASC); + + self::assertSame( + self::SONG, + array_map(static function (GH7820Line $line) : string { + return $line->toString(); + }, iterator_to_array(new Paginator($query))) + ); + } + + /** @group GH7837 */ + public function testWillFindSongsInPaginatorEvenWithCachedQueryParsing() : void + { + $cache = $this->_em->getConfiguration() + ->getQueryCacheImpl(); + + assert($cache instanceof ClearableCache); + + $cache->deleteAll(); + + $query = $this->_em->getRepository(GH7820Line::class) + ->createQueryBuilder('l') + ->orderBy('l.lineNumber', Criteria::ASC); + + self::assertSame( + self::SONG, + array_map(static function (GH7820Line $line) : string { + return $line->toString(); + }, iterator_to_array(new Paginator($query))), + 'Expected to return expected data before query cache is populated with DQL -> SQL translation. Were SQL parameters translated?' + ); + + $query = $this->_em->getRepository(GH7820Line::class) + ->createQueryBuilder('l') + ->orderBy('l.lineNumber', Criteria::ASC); + + self::assertSame( + self::SONG, + array_map(static function (GH7820Line $line) : string { + return $line->toString(); + }, iterator_to_array(new Paginator($query))), + 'Expected to return expected data even when DQL -> SQL translation is present in cache. Were SQL parameters translated again?' + ); + } +} + +/** @Entity */ +class GH7820Line +{ + /** + * @var GH7820LineText + * @Id() + * @Column(type="Doctrine\Tests\ORM\Functional\Ticket\GH7820LineTextType") + */ + private $text; + + /** + * @var int + * @Column(type="integer") + */ + private $lineNumber; + + public function __construct(GH7820LineText $text, int $index) + { + $this->text = $text; + $this->lineNumber = $index; + } + + public function toString() : string + { + return $this->text->getText(); + } +} + +final class GH7820LineText +{ + /** @var string */ + private $text; + + private function __construct(string $text) + { + $this->text = $text; + } + + public static function fromText(string $text) : self + { + return new self($text); + } + + public function getText() : string + { + return $this->text; + } + + public function __toString() : string + { + return 'Line: ' . $this->text; + } +} + +final class GH7820LineTextType extends StringType +{ + public function convertToPHPValue($value, AbstractPlatform $platform) + { + $text = parent::convertToPHPValue($value, $platform); + + if (! is_string($text)) { + return $text; + } + + return GH7820LineText::fromText($text); + } + + public function convertToDatabaseValue($value, AbstractPlatform $platform) + { + if (! $value instanceof GH7820LineText) { + return parent::convertToDatabaseValue($value, $platform); + } + + return parent::convertToDatabaseValue($value->getText(), $platform); + } + + /** {@inheritdoc} */ + public function getName() : string + { + return self::class; + } +} diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/GH7829Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH7829Test.php new file mode 100644 index 00000000000..08f91d2a8ea --- /dev/null +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH7829Test.php @@ -0,0 +1,63 @@ +useModelSet('cms'); + parent::setUp(); + + $article = new CmsArticle(); + + $article->topic = 'Skip Limit Subquery'; + $article->text = 'Skip Limit Subquery if not required.'; + + $this->_em->persist($article); + $this->_em->flush(); + $this->_em->clear(); + + $this->_em->getConnection()->getConfiguration()->setSQLLogger($this->logger = new DebugStack()); + } + + public function testPaginatorWithLimitSubquery() : void + { + $query = $this->_em->createQuery('SELECT a FROM Doctrine\Tests\Models\CMS\CmsArticle a'); + $query->setMaxResults(1); + + $paginator = new Paginator($query, true); + $paginator->setUseOutputWalkers(false); + + $paginator->count(); + $paginator->getIterator(); + + $this->assertCount(3, $this->logger->queries); + } + + public function testPaginatorWithLimitSubquerySkipped() : void + { + $query = $this->_em->createQuery('SELECT a FROM Doctrine\Tests\Models\CMS\CmsArticle a'); + + $paginator = new Paginator($query, true); + $paginator->setUseOutputWalkers(false); + + $paginator->count(); + $paginator->getIterator(); + + $this->assertCount(2, $this->logger->queries); + } +} diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/GH7836Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH7836Test.php new file mode 100644 index 00000000000..ab1ceeb7297 --- /dev/null +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH7836Test.php @@ -0,0 +1,135 @@ +setUpEntitySchema([GH7836ParentEntity::class, GH7836ChildEntity::class]); + + $parent = new GH7836ParentEntity(); + $parent->addChild(100, 'foo'); + $parent->addChild(100, 'bar'); + $parent->addChild(200, 'baz'); + + $this->_em->persist($parent); + $this->_em->flush(); + $this->_em->clear(); + } + + public function testMatchingRespectsCollectionOrdering() : void + { + $parent = $this->_em->find(GH7836ParentEntity::class, 1); + assert($parent instanceof GH7836ParentEntity); + + $children = $parent->getChildren()->matching(Criteria::create()); + + self::assertSame(100, $children[0]->position); + self::assertSame('bar', $children[0]->name); + self::assertSame(100, $children[1]->position); + self::assertSame('foo', $children[1]->name); + self::assertSame(200, $children[2]->position); + self::assertSame('baz', $children[2]->name); + } + + public function testMatchingOverrulesCollectionOrdering() : void + { + $parent = $this->_em->find(GH7836ParentEntity::class, 1); + assert($parent instanceof GH7836ParentEntity); + + $children = $parent->getChildren()->matching(Criteria::create()->orderBy(['position' => 'DESC', 'name' => 'ASC'])); + + self::assertSame(200, $children[0]->position); + self::assertSame('baz', $children[0]->name); + self::assertSame(100, $children[1]->position); + self::assertSame('bar', $children[1]->name); + self::assertSame(100, $children[2]->position); + self::assertSame('foo', $children[2]->name); + } + + public function testMatchingKeepsOrderOfCriteriaOrderingKeys() : void + { + $parent = $this->_em->find(GH7836ParentEntity::class, 1); + assert($parent instanceof GH7836ParentEntity); + + $children = $parent->getChildren()->matching(Criteria::create()->orderBy(['name' => 'ASC', 'position' => 'ASC'])); + + self::assertSame(100, $children[0]->position); + self::assertSame('bar', $children[0]->name); + self::assertSame(200, $children[1]->position); + self::assertSame('baz', $children[1]->name); + self::assertSame(100, $children[2]->position); + self::assertSame('foo', $children[2]->name); + } +} + +/** + * @Entity + */ +class GH7836ParentEntity +{ + /** + * @Id + * @Column(type="integer") + * @GeneratedValue + */ + private $id; + + /** + * @OneToMany(targetEntity=GH7836ChildEntity::class, mappedBy="parent", fetch="EXTRA_LAZY", cascade={"persist"}) + * @OrderBy({"position" = "ASC", "name" = "ASC"}) + */ + private $children; + + public function addChild(int $position, string $name) : void + { + $this->children[] = new GH7836ChildEntity($this, $position, $name); + } + + public function getChildren() : PersistentCollection + { + return $this->children; + } +} + +/** + * @Entity + */ +class GH7836ChildEntity +{ + /** + * @Id + * @Column(type="integer") + * @GeneratedValue + */ + private $id; + + /** @Column(type="integer") */ + public $position; + + /** @Column(type="string") */ + public $name; + + /** @ManyToOne(targetEntity=GH7836ParentEntity::class, inversedBy="children") */ + private $parent; + + public function __construct(GH7836ParentEntity $parent, int $position, string $name) + { + $this->parent = $parent; + $this->position = $position; + $this->name = $name; + } +} diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/GH7841Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH7841Test.php new file mode 100644 index 00000000000..4e6f46324ca --- /dev/null +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH7841Test.php @@ -0,0 +1,57 @@ +_em->getConnection()->getDatabasePlatform()->supportsForeignKeyConstraints()) { + $this->markTestSkipped('Test for platforms without foreign keys support'); + } + $class = $this->_em->getClassMetadata(GH7841Child::class); + $this->_schemaTool->updateSchema([$class], true); + $diff = $this->_schemaTool->getUpdateSchemaSql([$class], true); + + self::assertEmpty($diff); + + $this->_schemaTool->dropSchema([$class]); + } +} + +/** + * @Entity + */ +class GH7841Parent +{ + /** @Id @Column(type="integer") @GeneratedValue */ + public $id; + + /** @OneToMany(targetEntity=GH7841Child::class, mappedBy="parent") */ + public $children; + + public function __construct() + { + $this->children = new ArrayCollection(); + } +} + +/** + * @Entity + */ +class GH7841Child +{ + /** @Id @Column(type="integer") @GeneratedValue */ + public $id; + + /** @ManyToOne(targetEntity=GH7841Parent::class) */ + public $parent; +} diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/GH7869Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH7869Test.php new file mode 100644 index 00000000000..db16e38967e --- /dev/null +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/GH7869Test.php @@ -0,0 +1,67 @@ +getMockBuilder(EntityManagerDecorator::class) + ->setConstructorArgs([$decoratedEm]) + ->setMethods(['getClassMetadata']) + ->getMock(); + + $em->expects($this->exactly(2)) + ->method('getClassMetadata') + ->willReturnCallback([$decoratedEm, 'getClassMetadata']); + + $hints = [ + UnitOfWork::HINT_DEFEREAGERLOAD => true, + 'fetchMode' => [GH7869Appointment::class => ['patient' => ClassMetadata::FETCH_EAGER]], + ]; + + $uow = new UnitOfWork($em); + $uow->createEntity(GH7869Appointment::class, ['id' => 1, 'patient_id' => 1], $hints); + $uow->clear(); + $uow->triggerEagerLoads(); + } +} + +/** + * @Entity + */ +class GH7869Appointment +{ + /** @Id @Column(type="integer") @GeneratedValue */ + public $id; + + /** @OneToOne(targetEntity="GH7869Patient", inversedBy="appointment", fetch="EAGER") */ + public $patient; +} + +/** + * @Entity + */ +class GH7869Patient +{ + /** @Id @Column(type="integer") @GeneratedValue */ + public $id; + + /** @OneToOne(targetEntity="GH7869Appointment", mappedBy="patient") */ + public $appointment; +} diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/Issue5989Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/Issue5989Test.php new file mode 100644 index 00000000000..cf601b99aed --- /dev/null +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/Issue5989Test.php @@ -0,0 +1,51 @@ +useModelSet('issue5989'); + parent::setUp(); + } + + public function testSimpleArrayTypeHydratedCorrectlyInJoinedInheritance() + { + $manager = new Issue5989Manager(); + + $managerTags = ['tag1', 'tag2']; + $manager->tags = $managerTags; + $this->_em->persist($manager); + + $employee = new Issue5989Employee(); + + $employeeTags =['tag2', 'tag3']; + $employee->tags = $employeeTags; + $this->_em->persist($employee); + + $this->_em->flush(); + + $managerId = $manager->id; + $employeeId = $employee->id; + + // clear entity manager so that $repository->find actually fetches them and uses the hydrator + // instead of just returning the existing managed entities + $this->_em->clear(); + + $repository = $this->_em->getRepository(Issue5989Person::class); + + $manager = $repository->find($managerId); + $employee = $repository->find($employeeId); + + static::assertEquals($managerTags, $manager->tags); + static::assertEquals($employeeTags, $employee->tags); + } +} diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/Ticket2481Test.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/Ticket2481Test.php index 91521b5d5dd..ebedf0c869f 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/Ticket2481Test.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/Ticket2481Test.php @@ -9,9 +9,11 @@ protected function setUp() parent::setUp(); try { - $this->_schemaTool->createSchema(array( - $this->_em->getClassMetadata('Doctrine\Tests\ORM\Functional\Ticket\Ticket2481Product') - )); + $this->_schemaTool->createSchema( + [ + $this->_em->getClassMetadata(Ticket2481Product::class) + ] + ); } catch (\Exception $e) { // Swallow all exceptions. We do not test the schema tool here. } diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/Ticket4646InstanceOfAbstractTest.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/Ticket4646InstanceOfAbstractTest.php new file mode 100644 index 00000000000..5fa5cdc86ea --- /dev/null +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/Ticket4646InstanceOfAbstractTest.php @@ -0,0 +1,64 @@ +_schemaTool->createSchema([ + $this->_em->getClassMetadata(PersonTicket4646Abstract::class), + $this->_em->getClassMetadata(EmployeeTicket4646Abstract::class), + ]); + } + + public function testInstanceOf(): void + { + $this->_em->persist(new EmployeeTicket4646Abstract()); + $this->_em->flush(); + + $dql = 'SELECT p FROM Doctrine\Tests\ORM\Functional\Ticket\PersonTicket4646Abstract p + WHERE p INSTANCE OF Doctrine\Tests\ORM\Functional\Ticket\PersonTicket4646Abstract'; + $query = $this->_em->createQuery($dql); + $result = $query->getResult(); + + self::assertCount(1, $result); + self::assertContainsOnlyInstancesOf(PersonTicket4646Abstract::class, $result); + } +} + +/** + * @Entity() + * @Table(name="instance_of_abstract_test_person") + * @InheritanceType(value="JOINED") + * @DiscriminatorColumn(name="kind", type="string") + * @DiscriminatorMap(value={ + * "employee": EmployeeTicket4646Abstract::class + * }) + */ +abstract class PersonTicket4646Abstract +{ + /** + * @Id() + * @GeneratedValue() + * @Column(type="integer") + */ + private $id; + + public function getId(): ?int + { + return $this->id; + } +} + +/** + * @Entity() + * @Table(name="instance_of_abstract_test_employee") + */ +class EmployeeTicket4646Abstract extends PersonTicket4646Abstract +{ +} diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/Ticket4646InstanceOfMultiLevelTest.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/Ticket4646InstanceOfMultiLevelTest.php new file mode 100644 index 00000000000..2c111a9e613 --- /dev/null +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/Ticket4646InstanceOfMultiLevelTest.php @@ -0,0 +1,77 @@ +_schemaTool->createSchema([ + $this->_em->getClassMetadata(PersonTicket4646MultiLevel::class), + $this->_em->getClassMetadata(EmployeeTicket4646MultiLevel::class), + $this->_em->getClassMetadata(EngineerTicket4646MultiLevel::class), + ]); + } + + public function testInstanceOf(): void + { + $this->_em->persist(new PersonTicket4646MultiLevel()); + $this->_em->persist(new EmployeeTicket4646MultiLevel()); + $this->_em->persist(new EngineerTicket4646MultiLevel()); + $this->_em->flush(); + + $dql = 'SELECT p FROM Doctrine\Tests\ORM\Functional\Ticket\PersonTicket4646MultiLevel p + WHERE p INSTANCE OF Doctrine\Tests\ORM\Functional\Ticket\PersonTicket4646MultiLevel'; + $query = $this->_em->createQuery($dql); + $result = $query->getResult(); + + self::assertCount(3, $result); + self::assertContainsOnlyInstancesOf(PersonTicket4646MultiLevel::class, $result); + } +} + +/** + * @Entity() + * @Table(name="instance_of_multi_level_test_person") + * @InheritanceType(value="JOINED") + * @DiscriminatorColumn(name="kind", type="string") + * @DiscriminatorMap(value={ + * "person": "Doctrine\Tests\ORM\Functional\Ticket\PersonTicket4646MultiLevel", + * "employee": "Doctrine\Tests\ORM\Functional\Ticket\EmployeeTicket4646MultiLevel", + * "engineer": "Doctrine\Tests\ORM\Functional\Ticket\EngineerTicket4646MultiLevel", + * }) + */ +class PersonTicket4646MultiLevel +{ + /** + * @Id() + * @GeneratedValue() + * @Column(type="integer") + */ + private $id; + + public function getId(): ?int + { + return $this->id; + } +} + +/** + * @Entity() + * @Table(name="instance_of_multi_level_employee") + */ +class EmployeeTicket4646MultiLevel extends PersonTicket4646MultiLevel +{ +} + +/** + * @Entity() + * @Table(name="instance_of_multi_level_engineer") + */ +class EngineerTicket4646MultiLevel extends EmployeeTicket4646MultiLevel +{ +} diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/Ticket4646InstanceOfParametricTest.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/Ticket4646InstanceOfParametricTest.php new file mode 100644 index 00000000000..bf11c3a85d6 --- /dev/null +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/Ticket4646InstanceOfParametricTest.php @@ -0,0 +1,67 @@ +_schemaTool->createSchema([ + $this->_em->getClassMetadata(PersonTicket4646Parametric::class), + $this->_em->getClassMetadata(EmployeeTicket4646Parametric::class), + ]); + } + + public function testInstanceOf(): void + { + $this->_em->persist(new PersonTicket4646Parametric()); + $this->_em->persist(new EmployeeTicket4646Parametric()); + $this->_em->flush(); + $dql = 'SELECT p FROM Doctrine\Tests\ORM\Functional\Ticket\PersonTicket4646Parametric p + WHERE p INSTANCE OF :parameter'; + $query = $this->_em->createQuery($dql); + $query->setParameter( + 'parameter', + $this->_em->getClassMetadata(PersonTicket4646Parametric::class) + ); + $result = $query->getResult(); + self::assertCount(2, $result); + self::assertContainsOnlyInstancesOf(PersonTicket4646Parametric::class, $result); + } +} + +/** + * @Entity() + * @Table(name="instance_of_parametric_person") + * @InheritanceType(value="JOINED") + * @DiscriminatorColumn(name="kind", type="string") + * @DiscriminatorMap(value={ + * "person": "Doctrine\Tests\ORM\Functional\Ticket\PersonTicket4646Parametric", + * "employee": "Doctrine\Tests\ORM\Functional\Ticket\EmployeeTicket4646Parametric" + * }) + */ +class PersonTicket4646Parametric +{ + /** + * @Id() + * @GeneratedValue() + * @Column(type="integer") + */ + private $id; + + public function getId(): ?int + { + return $this->id; + } +} + +/** + * @Entity() + * @Table(name="instance_of_parametric_employee") + */ +class EmployeeTicket4646Parametric extends PersonTicket4646Parametric +{ +} diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/Ticket4646InstanceOfTest.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/Ticket4646InstanceOfTest.php new file mode 100644 index 00000000000..0ed97243c0e --- /dev/null +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/Ticket4646InstanceOfTest.php @@ -0,0 +1,66 @@ +_schemaTool->createSchema([ + $this->_em->getClassMetadata(PersonTicket4646::class), + $this->_em->getClassMetadata(EmployeeTicket4646::class), + ]); + } + + public function testInstanceOf(): void + { + $this->_em->persist(new PersonTicket4646()); + $this->_em->persist(new EmployeeTicket4646()); + $this->_em->flush(); + + $dql = 'SELECT p FROM Doctrine\Tests\ORM\Functional\Ticket\PersonTicket4646 p + WHERE p INSTANCE OF Doctrine\Tests\ORM\Functional\Ticket\PersonTicket4646'; + $query = $this->_em->createQuery($dql); + $result = $query->getResult(); + + self::assertCount(2, $result); + self::assertContainsOnlyInstancesOf(PersonTicket4646::class, $result); + } +} + +/** + * @Entity() + * @Table(name="instance_of_test_person") + * @InheritanceType(value="JOINED") + * @DiscriminatorColumn(name="kind", type="string") + * @DiscriminatorMap(value={ + * "person": "Doctrine\Tests\ORM\Functional\Ticket\PersonTicket4646", + * "employee": "Doctrine\Tests\ORM\Functional\Ticket\EmployeeTicket4646" + * }) + */ +class PersonTicket4646 +{ + /** + * @Id() + * @GeneratedValue() + * @Column(type="integer") + */ + private $id; + + public function getId(): ?int + { + return $this->id; + } +} + +/** + * @Entity() + * @Table(name="instance_of_test_employee") + */ +class EmployeeTicket4646 extends PersonTicket4646 +{ +} diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/Ticket4646InstanceOfWithMultipleParametersTest.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/Ticket4646InstanceOfWithMultipleParametersTest.php new file mode 100644 index 00000000000..c8c172ab694 --- /dev/null +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/Ticket4646InstanceOfWithMultipleParametersTest.php @@ -0,0 +1,88 @@ +_schemaTool->createSchema([ + $this->_em->getClassMetadata(PersonTicket4646Multiple::class), + $this->_em->getClassMetadata(EmployeeTicket4646Multiple::class), + $this->_em->getClassMetadata(ManagerTicket4646Multiple::class), + $this->_em->getClassMetadata(InternTicket4646Multiple::class), + ]); + } + + public function testInstanceOf(): void + { + $this->_em->persist(new PersonTicket4646Multiple()); + $this->_em->persist(new EmployeeTicket4646Multiple()); + $this->_em->persist(new ManagerTicket4646Multiple()); + $this->_em->persist(new InternTicket4646Multiple()); + $this->_em->flush(); + + $dql = 'SELECT p FROM Doctrine\Tests\ORM\Functional\Ticket\PersonTicket4646Multiple p + WHERE p INSTANCE OF (Doctrine\Tests\ORM\Functional\Ticket\EmployeeTicket4646Multiple, Doctrine\Tests\ORM\Functional\Ticket\InternTicket4646Multiple)'; + $query = $this->_em->createQuery($dql); + $result = $query->getResult(); + + self::assertCount(2, $result); + self::assertContainsOnlyInstancesOf(PersonTicket4646Multiple::class, $result); + } +} + +/** + * @Entity() + * @Table(name="instance_of_test_multiple_person") + * @InheritanceType(value="JOINED") + * @DiscriminatorColumn(name="kind", type="string") + * @DiscriminatorMap(value={ + * "person": "Doctrine\Tests\ORM\Functional\Ticket\PersonTicket4646Multiple", + * "employee": "Doctrine\Tests\ORM\Functional\Ticket\EmployeeTicket4646Multiple", + * "manager": "Doctrine\Tests\ORM\Functional\Ticket\ManagerTicket4646Multiple", + * "intern": "Doctrine\Tests\ORM\Functional\Ticket\InternTicket4646Multiple" + * }) + */ +class PersonTicket4646Multiple +{ + /** + * @Id() + * @GeneratedValue() + * @Column(type="integer") + */ + private $id; + + public function getId() + { + return $this->id; + } +} + +/** + * @Entity() + * @Table(name="instance_of_test_multiple_employee") + */ +class EmployeeTicket4646Multiple extends PersonTicket4646Multiple +{ +} + +/** + * @Entity() + * @Table(name="instance_of_test_multiple_manager") + */ +class ManagerTicket4646Multiple extends PersonTicket4646Multiple +{ +} + +/** + * @Entity() + * @Table(name="instance_of_test_multiple_intern") + */ +class InternTicket4646Multiple extends PersonTicket4646Multiple +{ +} diff --git a/tests/Doctrine/Tests/ORM/Functional/Ticket/Ticket69.php b/tests/Doctrine/Tests/ORM/Functional/Ticket/Ticket69.php index d9ac1cc6ab3..ccc8bce120c 100644 --- a/tests/Doctrine/Tests/ORM/Functional/Ticket/Ticket69.php +++ b/tests/Doctrine/Tests/ORM/Functional/Ticket/Ticket69.php @@ -2,8 +2,6 @@ namespace Doctrine\Tests\ORM\Functional\Ticket; -use Doctrine\ORM\Query; - /** * Functional tests for the Single Table Inheritance mapping strategy. * @@ -14,11 +12,13 @@ protected function setUp() { parent::setUp(); try { - $this->_schemaTool->createSchema(array( - $this->_em->getClassMetadata('Doctrine\Tests\ORM\Functional\Ticket\Lemma'), - $this->_em->getClassMetadata('Doctrine\Tests\ORM\Functional\Ticket\Relation'), - $this->_em->getClassMetadata('Doctrine\Tests\ORM\Functional\Ticket\RelationType') - )); + $this->_schemaTool->createSchema( + [ + $this->_em->getClassMetadata(Lemma::class), + $this->_em->getClassMetadata(Relation::class), + $this->_em->getClassMetadata(RelationType::class) + ] + ); } catch (\Exception $e) { // Swallow all exceptions. We do not test the schema tool here. } @@ -83,11 +83,11 @@ public function testIssue() $lemma = $res[0]; $this->assertEquals('foo', $lemma->getLemma()); - $this->assertInstanceOf('Doctrine\Tests\ORM\Functional\Ticket\Lemma', $lemma); + $this->assertInstanceOf(Lemma::class, $lemma); $relations = $lemma->getRelations(); foreach($relations as $relation) { - $this->assertInstanceOf('Doctrine\Tests\ORM\Functional\Ticket\Relation', $relation); + $this->assertInstanceOf(Relation::class, $relation); $this->assertTrue($relation->getType()->getType() != ''); } diff --git a/tests/Doctrine/Tests/ORM/Functional/TypeTest.php b/tests/Doctrine/Tests/ORM/Functional/TypeTest.php index c27e0dee638..9dd99777a04 100644 --- a/tests/Doctrine/Tests/ORM/Functional/TypeTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/TypeTest.php @@ -2,13 +2,12 @@ namespace Doctrine\Tests\ORM\Functional; +use Doctrine\DBAL\Types\Type as DBALType; +use Doctrine\ORM\Mapping\AssociationMapping; use Doctrine\Tests\Models\Generic\BooleanModel; use Doctrine\Tests\Models\Generic\DateTimeModel; use Doctrine\Tests\Models\Generic\DecimalModel; use Doctrine\Tests\Models\Generic\SerializationModel; - -use Doctrine\ORM\Mapping\AssociationMapping; -use Doctrine\DBAL\Types\Type as DBALType; use Doctrine\Tests\OrmFunctionalTestCase; class TypeTest extends OrmFunctionalTestCase @@ -16,6 +15,7 @@ class TypeTest extends OrmFunctionalTestCase protected function setUp() { $this->useModelSet('generic'); + parent::setUp(); } @@ -29,11 +29,11 @@ public function testDecimal() $this->_em->flush(); $this->_em->clear(); - $dql = "SELECT d FROM Doctrine\Tests\Models\Generic\DecimalModel d"; + $dql = 'SELECT d FROM ' . DecimalModel::class . ' d'; $decimal = $this->_em->createQuery($dql)->getSingleResult(); - $this->assertEquals(0.15, $decimal->decimal); - $this->assertEquals(0.1515, $decimal->highScale); + $this->assertSame('0.15', $decimal->decimal); + $this->assertSame('0.1515', $decimal->highScale); } /** @@ -49,7 +49,7 @@ public function testBoolean() $this->_em->flush(); $this->_em->clear(); - $dql = "SELECT b FROM Doctrine\Tests\Models\Generic\BooleanModel b WHERE b.booleanField = true"; + $dql = 'SELECT b FROM ' . BooleanModel::class . ' b WHERE b.booleanField = true'; $bool = $this->_em->createQuery($dql)->getSingleResult(); $this->assertTrue($bool->booleanField); @@ -59,7 +59,7 @@ public function testBoolean() $this->_em->flush(); $this->_em->clear(); - $dql = "SELECT b FROM Doctrine\Tests\Models\Generic\BooleanModel b WHERE b.booleanField = false"; + $dql = 'SELECT b FROM ' . BooleanModel::class . ' b WHERE b.booleanField = false'; $bool = $this->_em->createQuery($dql)->getSingleResult(); $this->assertFalse($bool->booleanField); @@ -75,10 +75,10 @@ public function testArray() $this->_em->flush(); $this->_em->clear(); - $dql = "SELECT s FROM Doctrine\Tests\Models\Generic\SerializationModel s"; + $dql = 'SELECT s FROM ' . SerializationModel::class . ' s'; $serialize = $this->_em->createQuery($dql)->getSingleResult(); - $this->assertEquals(array("foo" => "bar", "bar" => "baz"), $serialize->array); + $this->assertSame(["foo" => "bar", "bar" => "baz"], $serialize->array); } public function testObject() @@ -90,7 +90,7 @@ public function testObject() $this->_em->flush(); $this->_em->clear(); - $dql = "SELECT s FROM Doctrine\Tests\Models\Generic\SerializationModel s"; + $dql = 'SELECT s FROM ' . SerializationModel::class . ' s'; $serialize = $this->_em->createQuery($dql)->getSingleResult(); $this->assertInstanceOf('stdClass', $serialize->object); @@ -105,10 +105,10 @@ public function testDate() $this->_em->flush(); $this->_em->clear(); - $dateTimeDb = $this->_em->find('Doctrine\Tests\Models\Generic\DateTimeModel', $dateTime->id); + $dateTimeDb = $this->_em->find(DateTimeModel::class, $dateTime->id); - $this->assertInstanceOf('DateTime', $dateTimeDb->date); - $this->assertEquals('2009-10-01', $dateTimeDb->date->format('Y-m-d')); + $this->assertInstanceOf(\DateTime::class, $dateTimeDb->date); + $this->assertSame('2009-10-01', $dateTimeDb->date->format('Y-m-d')); } public function testDateTime() @@ -120,13 +120,15 @@ public function testDateTime() $this->_em->flush(); $this->_em->clear(); - $dateTimeDb = $this->_em->find('Doctrine\Tests\Models\Generic\DateTimeModel', $dateTime->id); + $dateTimeDb = $this->_em->find(DateTimeModel::class, $dateTime->id); + + $this->assertInstanceOf(\DateTime::class, $dateTimeDb->datetime); + $this->assertSame('2009-10-02 20:10:52', $dateTimeDb->datetime->format('Y-m-d H:i:s')); - $this->assertInstanceOf('DateTime', $dateTimeDb->datetime); - $this->assertEquals('2009-10-02 20:10:52', $dateTimeDb->datetime->format('Y-m-d H:i:s')); + $articles = $this->_em->getRepository(DateTimeModel::class) + ->findBy(['datetime' => new \DateTime()]); - $articles = $this->_em->getRepository( 'Doctrine\Tests\Models\Generic\DateTimeModel' )->findBy( array( 'datetime' => new \DateTime( "now" ) ) ); - $this->assertEquals( 0, count( $articles ) ); + $this->assertEmpty($articles); } public function testDqlQueryBindDateTimeInstance() @@ -143,6 +145,9 @@ public function testDqlQueryBindDateTimeInstance() $dateTimeDb = $this->_em->createQuery('SELECT d FROM Doctrine\Tests\Models\Generic\DateTimeModel d WHERE d.datetime = ?1') ->setParameter(1, $date, DBALType::DATETIME) ->getSingleResult(); + + $this->assertInstanceOf(\DateTime::class, $dateTimeDb->datetime); + $this->assertSame('2009-10-02 20:10:52', $dateTimeDb->datetime->format('Y-m-d H:i:s')); } public function testDqlQueryBuilderBindDateTimeInstance() @@ -158,10 +163,13 @@ public function testDqlQueryBuilderBindDateTimeInstance() $dateTimeDb = $this->_em->createQueryBuilder() ->select('d') - ->from('Doctrine\Tests\Models\Generic\DateTimeModel', 'd') + ->from(DateTimeModel::class, 'd') ->where('d.datetime = ?1') ->setParameter(1, $date, DBALType::DATETIME) ->getQuery()->getSingleResult(); + + $this->assertInstanceOf(\DateTime::class, $dateTimeDb->datetime); + $this->assertSame('2009-10-02 20:10:52', $dateTimeDb->datetime->format('Y-m-d H:i:s')); } public function testTime() @@ -173,9 +181,9 @@ public function testTime() $this->_em->flush(); $this->_em->clear(); - $dateTimeDb = $this->_em->find('Doctrine\Tests\Models\Generic\DateTimeModel', $dateTime->id); + $dateTimeDb = $this->_em->find(DateTimeModel::class, $dateTime->id); - $this->assertInstanceOf('DateTime', $dateTime->time); - $this->assertEquals('19:27:20', $dateTime->time->format('H:i:s')); + $this->assertInstanceOf(\DateTime::class, $dateTimeDb->time); + $this->assertSame('19:27:20', $dateTimeDb->time->format('H:i:s')); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/TypeValueSqlTest.php b/tests/Doctrine/Tests/ORM/Functional/TypeValueSqlTest.php index 8e305d1f13c..3af954cfd97 100644 --- a/tests/Doctrine/Tests/ORM/Functional/TypeValueSqlTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/TypeValueSqlTest.php @@ -2,26 +2,28 @@ namespace Doctrine\Tests\ORM\Functional; +use Doctrine\DBAL\Types\Type as DBALType; +use Doctrine\Tests\DbalTypes\NegativeToPositiveType; +use Doctrine\Tests\DbalTypes\UpperCaseStringType; use Doctrine\Tests\Models\CustomType\CustomTypeChild; use Doctrine\Tests\Models\CustomType\CustomTypeParent; use Doctrine\Tests\Models\CustomType\CustomTypeUpperCase; -use Doctrine\DBAL\Types\Type as DBALType; use Doctrine\Tests\OrmFunctionalTestCase; class TypeValueSqlTest extends OrmFunctionalTestCase { protected function setUp() { - if (DBALType::hasType('upper_case_string')) { - DBALType::overrideType('upper_case_string', '\Doctrine\Tests\DbalTypes\UpperCaseStringType'); + if (DBALType::hasType(UpperCaseStringType::NAME)) { + DBALType::overrideType(UpperCaseStringType::NAME, UpperCaseStringType::class); } else { - DBALType::addType('upper_case_string', '\Doctrine\Tests\DbalTypes\UpperCaseStringType'); + DBALType::addType(UpperCaseStringType::NAME, UpperCaseStringType::class); } - if (DBALType::hasType('negative_to_positive')) { - DBALType::overrideType('negative_to_positive', '\Doctrine\Tests\DbalTypes\NegativeToPositiveType'); + if (DBALType::hasType(NegativeToPositiveType::NAME)) { + DBALType::overrideType(NegativeToPositiveType::NAME, NegativeToPositiveType::class); } else { - DBALType::addType('negative_to_positive', '\Doctrine\Tests\DbalTypes\NegativeToPositiveType'); + DBALType::addType(NegativeToPositiveType::NAME, NegativeToPositiveType::class); } $this->useModelSet('customtype'); @@ -51,7 +53,7 @@ public function testUpperCaseStringType() */ public function testUpperCaseStringTypeWhenColumnNameIsDefined() { - + $entity = new CustomTypeUpperCase(); $entity->lowerCaseString = 'Some Value'; $entity->namedLowerCaseString = 'foo'; @@ -104,7 +106,7 @@ public function testTypeValueSqlWithAssociations() $this->_em->clear(); - $entity = $this->_em->find('Doctrine\Tests\Models\CustomType\CustomTypeParent', $parentId); + $entity = $this->_em->find(CustomTypeParent::class, $parentId); $this->assertTrue($entity->customInteger < 0, 'Fetched customInteger negative'); $this->assertEquals(1, $this->_em->getConnection()->fetchColumn("select customInteger from customtype_parents where id=".$entity->id.""), 'Database has stored customInteger positive'); @@ -131,7 +133,7 @@ public function testSelectDQL() $result = $query->getResult(); $this->assertEquals(1, count($result)); - $this->assertInstanceOf('Doctrine\Tests\Models\CustomType\CustomTypeParent', $result[0][0]); + $this->assertInstanceOf(CustomTypeParent::class, $result[0][0]); $this->assertEquals(-1, $result[0][0]->customInteger); $this->assertEquals(-1, $result[0]['customInteger']); diff --git a/tests/Doctrine/Tests/ORM/Functional/UUIDGeneratorTest.php b/tests/Doctrine/Tests/ORM/Functional/UUIDGeneratorTest.php index d5d559a4ff1..ff352ba1f11 100644 --- a/tests/Doctrine/Tests/ORM/Functional/UUIDGeneratorTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/UUIDGeneratorTest.php @@ -15,9 +15,11 @@ public function setUp() $this->markTestSkipped('Currently restricted to MySQL platform.'); } - $this->_schemaTool->createSchema(array( - $this->_em->getClassMetadata(__NAMESPACE__ . '\\UUIDEntity') - )); + $this->_schemaTool->createSchema( + [ + $this->_em->getClassMetadata(UUIDEntity::class) + ] + ); } public function testGenerateUUID() diff --git a/tests/Doctrine/Tests/ORM/Functional/UnitOfWorkLifecycleTest.php b/tests/Doctrine/Tests/ORM/Functional/UnitOfWorkLifecycleTest.php index 3e8285e8f89..8c4c500e728 100644 --- a/tests/Doctrine/Tests/ORM/Functional/UnitOfWorkLifecycleTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/UnitOfWorkLifecycleTest.php @@ -68,7 +68,7 @@ public function testAddToIdentityMapWithoutIdentity() $this->expectException(ORMInvalidArgumentException::class); $this->expectExceptionMessage("The given entity of type 'Doctrine\Tests\Models\CMS\CmsUser' (Doctrine\Tests\Models\CMS\CmsUser@"); - $this->_em->getUnitOfWork()->registerManaged($user, array(), array()); + $this->_em->getUnitOfWork()->registerManaged($user, [], []); } public function testMarkReadOnlyNonManaged() @@ -80,4 +80,4 @@ public function testMarkReadOnlyNonManaged() $this->_em->getUnitOfWork()->markReadOnly($user); } -} \ No newline at end of file +} diff --git a/tests/Doctrine/Tests/ORM/Functional/ValueConversionType/ManyToManyCompositeIdForeignKeyTest.php b/tests/Doctrine/Tests/ORM/Functional/ValueConversionType/ManyToManyCompositeIdForeignKeyTest.php index a6ad68d0a61..108ba743737 100644 --- a/tests/Doctrine/Tests/ORM/Functional/ValueConversionType/ManyToManyCompositeIdForeignKeyTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/ValueConversionType/ManyToManyCompositeIdForeignKeyTest.php @@ -2,6 +2,7 @@ namespace Doctrine\Tests\ORM\Functional\ValueConversionType; +use Doctrine\Tests\Models; use Doctrine\Tests\Models\ValueConversionType as Entity; use Doctrine\Tests\OrmFunctionalTestCase; @@ -75,23 +76,23 @@ public function testThatTheValueOfIdentifiersAreConvertedInTheDatabase() public function testThatEntitiesAreFetchedFromTheDatabase() { $auxiliary = $this->_em->find( - 'Doctrine\Tests\Models\ValueConversionType\AuxiliaryEntity', + Models\ValueConversionType\AuxiliaryEntity::class, 'abc' ); $inversed = $this->_em->find( - 'Doctrine\Tests\Models\ValueConversionType\InversedManyToManyCompositeIdForeignKeyEntity', - array('id1' => 'def', 'foreignEntity' => 'abc') + Models\ValueConversionType\InversedManyToManyCompositeIdForeignKeyEntity::class, + ['id1' => 'def', 'foreignEntity' => 'abc'] ); $owning = $this->_em->find( - 'Doctrine\Tests\Models\ValueConversionType\OwningManyToManyCompositeIdForeignKeyEntity', + Models\ValueConversionType\OwningManyToManyCompositeIdForeignKeyEntity::class, 'ghi' ); - $this->assertInstanceOf('Doctrine\Tests\Models\ValueConversionType\AuxiliaryEntity', $auxiliary); - $this->assertInstanceOf('Doctrine\Tests\Models\ValueConversionType\InversedManyToManyCompositeIdForeignKeyEntity', $inversed); - $this->assertInstanceOf('Doctrine\Tests\Models\ValueConversionType\OwningManyToManyCompositeIdForeignKeyEntity', $owning); + $this->assertInstanceOf(Models\ValueConversionType\AuxiliaryEntity::class, $auxiliary); + $this->assertInstanceOf(Models\ValueConversionType\InversedManyToManyCompositeIdForeignKeyEntity::class, $inversed); + $this->assertInstanceOf(Models\ValueConversionType\OwningManyToManyCompositeIdForeignKeyEntity::class, $owning); } /** @@ -100,17 +101,17 @@ public function testThatEntitiesAreFetchedFromTheDatabase() public function testThatTheValueOfIdentifiersAreConvertedBackAfterBeingFetchedFromTheDatabase() { $auxiliary = $this->_em->find( - 'Doctrine\Tests\Models\ValueConversionType\AuxiliaryEntity', + Models\ValueConversionType\AuxiliaryEntity::class, 'abc' ); $inversed = $this->_em->find( - 'Doctrine\Tests\Models\ValueConversionType\InversedManyToManyCompositeIdForeignKeyEntity', - array('id1' => 'def', 'foreignEntity' => 'abc') + Models\ValueConversionType\InversedManyToManyCompositeIdForeignKeyEntity::class, + ['id1' => 'def', 'foreignEntity' => 'abc'] ); $owning = $this->_em->find( - 'Doctrine\Tests\Models\ValueConversionType\OwningManyToManyCompositeIdForeignKeyEntity', + Models\ValueConversionType\OwningManyToManyCompositeIdForeignKeyEntity::class, 'ghi' ); @@ -126,16 +127,16 @@ public function testThatTheValueOfIdentifiersAreConvertedBackAfterBeingFetchedFr public function testThatInversedEntityIsFetchedFromTheDatabaseUsingAuxiliaryEntityAsId() { $auxiliary = $this->_em->find( - 'Doctrine\Tests\Models\ValueConversionType\AuxiliaryEntity', + Models\ValueConversionType\AuxiliaryEntity::class, 'abc' ); $inversed = $this->_em->find( - 'Doctrine\Tests\Models\ValueConversionType\InversedManyToManyCompositeIdForeignKeyEntity', - array('id1' => 'def', 'foreignEntity' => $auxiliary) + Models\ValueConversionType\InversedManyToManyCompositeIdForeignKeyEntity::class, + ['id1' => 'def', 'foreignEntity' => $auxiliary] ); - $this->assertInstanceOf('Doctrine\Tests\Models\ValueConversionType\InversedManyToManyCompositeIdForeignKeyEntity', $inversed); + $this->assertInstanceOf(Models\ValueConversionType\InversedManyToManyCompositeIdForeignKeyEntity::class, $inversed); } /** @@ -144,7 +145,7 @@ public function testThatInversedEntityIsFetchedFromTheDatabaseUsingAuxiliaryEnti public function testThatTheCollectionFromOwningToInversedIsLoaded() { $owning = $this->_em->find( - 'Doctrine\Tests\Models\ValueConversionType\OwningManyToManyCompositeIdForeignKeyEntity', + Models\ValueConversionType\OwningManyToManyCompositeIdForeignKeyEntity::class, 'ghi' ); @@ -157,8 +158,8 @@ public function testThatTheCollectionFromOwningToInversedIsLoaded() public function testThatTheCollectionFromInversedToOwningIsLoaded() { $inversed = $this->_em->find( - 'Doctrine\Tests\Models\ValueConversionType\InversedManyToManyCompositeIdForeignKeyEntity', - array('id1' => 'def', 'foreignEntity' => 'abc') + Models\ValueConversionType\InversedManyToManyCompositeIdForeignKeyEntity::class, + ['id1' => 'def', 'foreignEntity' => 'abc'] ); $this->assertCount(1, $inversed->associatedEntities); @@ -175,8 +176,8 @@ public function testThatTheJoinTableRowsAreRemovedWhenRemovingTheAssociation() // remove association $inversed = $this->_em->find( - 'Doctrine\Tests\Models\ValueConversionType\InversedManyToManyCompositeIdForeignKeyEntity', - array('id1' => 'def', 'foreignEntity' => 'abc') + Models\ValueConversionType\InversedManyToManyCompositeIdForeignKeyEntity::class, + ['id1' => 'def', 'foreignEntity' => 'abc'] ); foreach ($inversed->associatedEntities as $owning) { diff --git a/tests/Doctrine/Tests/ORM/Functional/ValueConversionType/ManyToManyCompositeIdTest.php b/tests/Doctrine/Tests/ORM/Functional/ValueConversionType/ManyToManyCompositeIdTest.php index 32779164807..4403f2bf959 100644 --- a/tests/Doctrine/Tests/ORM/Functional/ValueConversionType/ManyToManyCompositeIdTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/ValueConversionType/ManyToManyCompositeIdTest.php @@ -2,6 +2,7 @@ namespace Doctrine\Tests\ORM\Functional\ValueConversionType; +use Doctrine\Tests\Models; use Doctrine\Tests\Models\ValueConversionType as Entity; use Doctrine\Tests\OrmFunctionalTestCase; @@ -67,17 +68,17 @@ public function testThatTheValueOfIdentifiersAreConvertedInTheDatabase() public function testThatEntitiesAreFetchedFromTheDatabase() { $inversed = $this->_em->find( - 'Doctrine\Tests\Models\ValueConversionType\InversedManyToManyCompositeIdEntity', - array('id1' => 'abc', 'id2' => 'def') + Models\ValueConversionType\InversedManyToManyCompositeIdEntity::class, + ['id1' => 'abc', 'id2' => 'def'] ); $owning = $this->_em->find( - 'Doctrine\Tests\Models\ValueConversionType\OwningManyToManyCompositeIdEntity', + Models\ValueConversionType\OwningManyToManyCompositeIdEntity::class, 'ghi' ); - $this->assertInstanceOf('Doctrine\Tests\Models\ValueConversionType\InversedManyToManyCompositeIdEntity', $inversed); - $this->assertInstanceOf('Doctrine\Tests\Models\ValueConversionType\OwningManyToManyCompositeIdEntity', $owning); + $this->assertInstanceOf(Models\ValueConversionType\InversedManyToManyCompositeIdEntity::class, $inversed); + $this->assertInstanceOf(Models\ValueConversionType\OwningManyToManyCompositeIdEntity::class, $owning); } /** @@ -86,12 +87,12 @@ public function testThatEntitiesAreFetchedFromTheDatabase() public function testThatTheValueOfIdentifiersAreConvertedBackAfterBeingFetchedFromTheDatabase() { $inversed = $this->_em->find( - 'Doctrine\Tests\Models\ValueConversionType\InversedManyToManyCompositeIdEntity', - array('id1' => 'abc', 'id2' => 'def') + Models\ValueConversionType\InversedManyToManyCompositeIdEntity::class, + ['id1' => 'abc', 'id2' => 'def'] ); $owning = $this->_em->find( - 'Doctrine\Tests\Models\ValueConversionType\OwningManyToManyCompositeIdEntity', + Models\ValueConversionType\OwningManyToManyCompositeIdEntity::class, 'ghi' ); @@ -106,7 +107,7 @@ public function testThatTheValueOfIdentifiersAreConvertedBackAfterBeingFetchedFr public function testThatTheCollectionFromOwningToInversedIsLoaded() { $owning = $this->_em->find( - 'Doctrine\Tests\Models\ValueConversionType\OwningManyToManyCompositeIdEntity', + Models\ValueConversionType\OwningManyToManyCompositeIdEntity::class, 'ghi' ); @@ -119,8 +120,8 @@ public function testThatTheCollectionFromOwningToInversedIsLoaded() public function testThatTheCollectionFromInversedToOwningIsLoaded() { $inversed = $this->_em->find( - 'Doctrine\Tests\Models\ValueConversionType\InversedManyToManyCompositeIdEntity', - array('id1' => 'abc', 'id2' => 'def') + Models\ValueConversionType\InversedManyToManyCompositeIdEntity::class, + ['id1' => 'abc', 'id2' => 'def'] ); $this->assertCount(1, $inversed->associatedEntities); @@ -137,8 +138,8 @@ public function testThatTheJoinTableRowsAreRemovedWhenRemovingTheAssociation() // remove association $inversed = $this->_em->find( - 'Doctrine\Tests\Models\ValueConversionType\InversedManyToManyCompositeIdEntity', - array('id1' => 'abc', 'id2' => 'def') + Models\ValueConversionType\InversedManyToManyCompositeIdEntity::class, + ['id1' => 'abc', 'id2' => 'def'] ); foreach ($inversed->associatedEntities as $owning) { diff --git a/tests/Doctrine/Tests/ORM/Functional/ValueConversionType/ManyToManyExtraLazyTest.php b/tests/Doctrine/Tests/ORM/Functional/ValueConversionType/ManyToManyExtraLazyTest.php index a8ea389c9f9..af1d99de3f9 100644 --- a/tests/Doctrine/Tests/ORM/Functional/ValueConversionType/ManyToManyExtraLazyTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/ValueConversionType/ManyToManyExtraLazyTest.php @@ -2,6 +2,7 @@ namespace Doctrine\Tests\ORM\Functional\ValueConversionType; +use Doctrine\Tests\Models; use Doctrine\Tests\Models\ValueConversionType as Entity; use Doctrine\Tests\OrmFunctionalTestCase; @@ -64,7 +65,7 @@ public static function tearDownAfterClass() public function testThatTheExtraLazyCollectionFromOwningToInversedIsCounted() { $owning = $this->_em->find( - 'Doctrine\Tests\Models\ValueConversionType\OwningManyToManyExtraLazyEntity', + Models\ValueConversionType\OwningManyToManyExtraLazyEntity::class, 'ghi' ); @@ -74,7 +75,7 @@ public function testThatTheExtraLazyCollectionFromOwningToInversedIsCounted() public function testThatTheExtraLazyCollectionFromInversedToOwningIsCounted() { $inversed = $this->_em->find( - 'Doctrine\Tests\Models\ValueConversionType\InversedManyToManyExtraLazyEntity', + Models\ValueConversionType\InversedManyToManyExtraLazyEntity::class, 'abc' ); @@ -84,12 +85,12 @@ public function testThatTheExtraLazyCollectionFromInversedToOwningIsCounted() public function testThatTheExtraLazyCollectionFromOwningToInversedContainsAnEntity() { $owning = $this->_em->find( - 'Doctrine\Tests\Models\ValueConversionType\OwningManyToManyExtraLazyEntity', + Models\ValueConversionType\OwningManyToManyExtraLazyEntity::class, 'ghi' ); $inversed = $this->_em->find( - 'Doctrine\Tests\Models\ValueConversionType\InversedManyToManyExtraLazyEntity', + Models\ValueConversionType\InversedManyToManyExtraLazyEntity::class, 'abc' ); @@ -99,12 +100,12 @@ public function testThatTheExtraLazyCollectionFromOwningToInversedContainsAnEnti public function testThatTheExtraLazyCollectionFromInversedToOwningContainsAnEntity() { $inversed = $this->_em->find( - 'Doctrine\Tests\Models\ValueConversionType\InversedManyToManyExtraLazyEntity', + Models\ValueConversionType\InversedManyToManyExtraLazyEntity::class, 'abc' ); $owning = $this->_em->find( - 'Doctrine\Tests\Models\ValueConversionType\OwningManyToManyExtraLazyEntity', + Models\ValueConversionType\OwningManyToManyExtraLazyEntity::class, 'ghi' ); @@ -114,7 +115,7 @@ public function testThatTheExtraLazyCollectionFromInversedToOwningContainsAnEnti public function testThatTheExtraLazyCollectionFromOwningToInversedContainsAnIndexByKey() { $owning = $this->_em->find( - 'Doctrine\Tests\Models\ValueConversionType\OwningManyToManyExtraLazyEntity', + Models\ValueConversionType\OwningManyToManyExtraLazyEntity::class, 'ghi' ); @@ -124,7 +125,7 @@ public function testThatTheExtraLazyCollectionFromOwningToInversedContainsAnInde public function testThatTheExtraLazyCollectionFromInversedToOwningContainsAnIndexByKey() { $inversed = $this->_em->find( - 'Doctrine\Tests\Models\ValueConversionType\InversedManyToManyExtraLazyEntity', + Models\ValueConversionType\InversedManyToManyExtraLazyEntity::class, 'abc' ); @@ -134,7 +135,7 @@ public function testThatTheExtraLazyCollectionFromInversedToOwningContainsAnInde public function testThatASliceOfTheExtraLazyCollectionFromOwningToInversedIsLoaded() { $owning = $this->_em->find( - 'Doctrine\Tests\Models\ValueConversionType\OwningManyToManyExtraLazyEntity', + Models\ValueConversionType\OwningManyToManyExtraLazyEntity::class, 'ghi' ); @@ -144,7 +145,7 @@ public function testThatASliceOfTheExtraLazyCollectionFromOwningToInversedIsLoad public function testThatASliceOfTheExtraLazyCollectionFromInversedToOwningIsLoaded() { $inversed = $this->_em->find( - 'Doctrine\Tests\Models\ValueConversionType\InversedManyToManyExtraLazyEntity', + Models\ValueConversionType\InversedManyToManyExtraLazyEntity::class, 'abc' ); diff --git a/tests/Doctrine/Tests/ORM/Functional/ValueConversionType/ManyToManyTest.php b/tests/Doctrine/Tests/ORM/Functional/ValueConversionType/ManyToManyTest.php index 2c51d6cd215..4532ee9d5fc 100644 --- a/tests/Doctrine/Tests/ORM/Functional/ValueConversionType/ManyToManyTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/ValueConversionType/ManyToManyTest.php @@ -2,6 +2,7 @@ namespace Doctrine\Tests\ORM\Functional\ValueConversionType; +use Doctrine\Tests\Models; use Doctrine\Tests\Models\ValueConversionType as Entity; use Doctrine\Tests\OrmFunctionalTestCase; @@ -64,17 +65,17 @@ public function testThatTheValueOfIdentifiersAreConvertedInTheDatabase() public function testThatEntitiesAreFetchedFromTheDatabase() { $inversed = $this->_em->find( - 'Doctrine\Tests\Models\ValueConversionType\InversedManyToManyEntity', + Models\ValueConversionType\InversedManyToManyEntity::class, 'abc' ); $owning = $this->_em->find( - 'Doctrine\Tests\Models\ValueConversionType\OwningManyToManyEntity', + Models\ValueConversionType\OwningManyToManyEntity::class, 'def' ); - $this->assertInstanceOf('Doctrine\Tests\Models\ValueConversionType\InversedManyToManyEntity', $inversed); - $this->assertInstanceOf('Doctrine\Tests\Models\ValueConversionType\OwningManyToManyEntity', $owning); + $this->assertInstanceOf(Models\ValueConversionType\InversedManyToManyEntity::class, $inversed); + $this->assertInstanceOf(Models\ValueConversionType\OwningManyToManyEntity::class, $owning); } /** @@ -83,12 +84,12 @@ public function testThatEntitiesAreFetchedFromTheDatabase() public function testThatTheValueOfIdentifiersAreConvertedBackAfterBeingFetchedFromTheDatabase() { $inversed = $this->_em->find( - 'Doctrine\Tests\Models\ValueConversionType\InversedManyToManyEntity', + Models\ValueConversionType\InversedManyToManyEntity::class, 'abc' ); $owning = $this->_em->find( - 'Doctrine\Tests\Models\ValueConversionType\OwningManyToManyEntity', + Models\ValueConversionType\OwningManyToManyEntity::class, 'def' ); @@ -102,7 +103,7 @@ public function testThatTheValueOfIdentifiersAreConvertedBackAfterBeingFetchedFr public function testThatTheCollectionFromOwningToInversedIsLoaded() { $owning = $this->_em->find( - 'Doctrine\Tests\Models\ValueConversionType\OwningManyToManyEntity', + Models\ValueConversionType\OwningManyToManyEntity::class, 'def' ); @@ -115,7 +116,7 @@ public function testThatTheCollectionFromOwningToInversedIsLoaded() public function testThatTheCollectionFromInversedToOwningIsLoaded() { $inversed = $this->_em->find( - 'Doctrine\Tests\Models\ValueConversionType\InversedManyToManyEntity', + Models\ValueConversionType\InversedManyToManyEntity::class, 'abc' ); @@ -133,7 +134,7 @@ public function testThatTheJoinTableRowsAreRemovedWhenRemovingTheAssociation() // remove association $inversed = $this->_em->find( - 'Doctrine\Tests\Models\ValueConversionType\InversedManyToManyEntity', + Models\ValueConversionType\InversedManyToManyEntity::class, 'abc' ); diff --git a/tests/Doctrine/Tests/ORM/Functional/ValueConversionType/OneToManyCompositeIdForeignKeyTest.php b/tests/Doctrine/Tests/ORM/Functional/ValueConversionType/OneToManyCompositeIdForeignKeyTest.php index e899fbeb8d3..b76687bc4b3 100644 --- a/tests/Doctrine/Tests/ORM/Functional/ValueConversionType/OneToManyCompositeIdForeignKeyTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/ValueConversionType/OneToManyCompositeIdForeignKeyTest.php @@ -2,6 +2,7 @@ namespace Doctrine\Tests\ORM\Functional\ValueConversionType; +use Doctrine\Tests\Models; use Doctrine\Tests\Models\ValueConversionType as Entity; use Doctrine\Tests\OrmFunctionalTestCase; @@ -73,23 +74,23 @@ public function testThatTheValueOfIdentifiersAreConvertedInTheDatabase() public function testThatEntitiesAreFetchedFromTheDatabase() { $auxiliary = $this->_em->find( - 'Doctrine\Tests\Models\ValueConversionType\AuxiliaryEntity', + Models\ValueConversionType\AuxiliaryEntity::class, 'abc' ); $inversed = $this->_em->find( - 'Doctrine\Tests\Models\ValueConversionType\InversedOneToManyCompositeIdForeignKeyEntity', - array('id1' => 'def', 'foreignEntity' => 'abc') + Models\ValueConversionType\InversedOneToManyCompositeIdForeignKeyEntity::class, + ['id1' => 'def', 'foreignEntity' => 'abc'] ); $owning = $this->_em->find( - 'Doctrine\Tests\Models\ValueConversionType\OwningManyToOneCompositeIdForeignKeyEntity', + Models\ValueConversionType\OwningManyToOneCompositeIdForeignKeyEntity::class, 'ghi' ); - $this->assertInstanceOf('Doctrine\Tests\Models\ValueConversionType\AuxiliaryEntity', $auxiliary); - $this->assertInstanceOf('Doctrine\Tests\Models\ValueConversionType\InversedOneToManyCompositeIdForeignKeyEntity', $inversed); - $this->assertInstanceOf('Doctrine\Tests\Models\ValueConversionType\OwningManyToOneCompositeIdForeignKeyEntity', $owning); + $this->assertInstanceOf(Models\ValueConversionType\AuxiliaryEntity::class, $auxiliary); + $this->assertInstanceOf(Models\ValueConversionType\InversedOneToManyCompositeIdForeignKeyEntity::class, $inversed); + $this->assertInstanceOf(Models\ValueConversionType\OwningManyToOneCompositeIdForeignKeyEntity::class, $owning); } /** @@ -98,17 +99,17 @@ public function testThatEntitiesAreFetchedFromTheDatabase() public function testThatTheValueOfIdentifiersAreConvertedBackAfterBeingFetchedFromTheDatabase() { $auxiliary = $this->_em->find( - 'Doctrine\Tests\Models\ValueConversionType\AuxiliaryEntity', + Models\ValueConversionType\AuxiliaryEntity::class, 'abc' ); $inversed = $this->_em->find( - 'Doctrine\Tests\Models\ValueConversionType\InversedOneToManyCompositeIdForeignKeyEntity', - array('id1' => 'def', 'foreignEntity' => 'abc') + Models\ValueConversionType\InversedOneToManyCompositeIdForeignKeyEntity::class, + ['id1' => 'def', 'foreignEntity' => 'abc'] ); $owning = $this->_em->find( - 'Doctrine\Tests\Models\ValueConversionType\OwningManyToOneCompositeIdForeignKeyEntity', + Models\ValueConversionType\OwningManyToOneCompositeIdForeignKeyEntity::class, 'ghi' ); @@ -124,16 +125,16 @@ public function testThatTheValueOfIdentifiersAreConvertedBackAfterBeingFetchedFr public function testThatInversedEntityIsFetchedFromTheDatabaseUsingAuxiliaryEntityAsId() { $auxiliary = $this->_em->find( - 'Doctrine\Tests\Models\ValueConversionType\AuxiliaryEntity', + Models\ValueConversionType\AuxiliaryEntity::class, 'abc' ); $inversed = $this->_em->find( - 'Doctrine\Tests\Models\ValueConversionType\InversedOneToManyCompositeIdForeignKeyEntity', - array('id1' => 'def', 'foreignEntity' => $auxiliary) + Models\ValueConversionType\InversedOneToManyCompositeIdForeignKeyEntity::class, + ['id1' => 'def', 'foreignEntity' => $auxiliary] ); - $this->assertInstanceOf('Doctrine\Tests\Models\ValueConversionType\InversedOneToManyCompositeIdForeignKeyEntity', $inversed); + $this->assertInstanceOf(Models\ValueConversionType\InversedOneToManyCompositeIdForeignKeyEntity::class, $inversed); } /** @@ -142,7 +143,7 @@ public function testThatInversedEntityIsFetchedFromTheDatabaseUsingAuxiliaryEnti public function testThatTheProxyFromOwningToInversedIsLoaded() { $owning = $this->_em->find( - 'Doctrine\Tests\Models\ValueConversionType\OwningManyToOneCompositeIdForeignKeyEntity', + Models\ValueConversionType\OwningManyToOneCompositeIdForeignKeyEntity::class, 'ghi' ); @@ -159,8 +160,8 @@ public function testThatTheProxyFromOwningToInversedIsLoaded() public function testThatTheCollectionFromInversedToOwningIsLoaded() { $inversed = $this->_em->find( - 'Doctrine\Tests\Models\ValueConversionType\InversedOneToManyCompositeIdForeignKeyEntity', - array('id1' => 'def', 'foreignEntity' => 'abc') + Models\ValueConversionType\InversedOneToManyCompositeIdForeignKeyEntity::class, + ['id1' => 'def', 'foreignEntity' => 'abc'] ); $this->assertCount(1, $inversed->associatedEntities); diff --git a/tests/Doctrine/Tests/ORM/Functional/ValueConversionType/OneToManyCompositeIdTest.php b/tests/Doctrine/Tests/ORM/Functional/ValueConversionType/OneToManyCompositeIdTest.php index eabf26a8051..266a382e760 100644 --- a/tests/Doctrine/Tests/ORM/Functional/ValueConversionType/OneToManyCompositeIdTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/ValueConversionType/OneToManyCompositeIdTest.php @@ -2,6 +2,7 @@ namespace Doctrine\Tests\ORM\Functional\ValueConversionType; +use Doctrine\Tests\Models; use Doctrine\Tests\Models\ValueConversionType as Entity; use Doctrine\Tests\OrmFunctionalTestCase; @@ -65,17 +66,17 @@ public function testThatTheValueOfIdentifiersAreConvertedInTheDatabase() public function testThatEntitiesAreFetchedFromTheDatabase() { $inversed = $this->_em->find( - 'Doctrine\Tests\Models\ValueConversionType\InversedOneToManyCompositeIdEntity', - array('id1' => 'abc', 'id2' => 'def') + Models\ValueConversionType\InversedOneToManyCompositeIdEntity::class, + ['id1' => 'abc', 'id2' => 'def'] ); $owning = $this->_em->find( - 'Doctrine\Tests\Models\ValueConversionType\OwningManyToOneCompositeIdEntity', + Models\ValueConversionType\OwningManyToOneCompositeIdEntity::class, 'ghi' ); - $this->assertInstanceOf('Doctrine\Tests\Models\ValueConversionType\InversedOneToManyCompositeIdEntity', $inversed); - $this->assertInstanceOf('Doctrine\Tests\Models\ValueConversionType\OwningManyToOneCompositeIdEntity', $owning); + $this->assertInstanceOf(Models\ValueConversionType\InversedOneToManyCompositeIdEntity::class, $inversed); + $this->assertInstanceOf(Models\ValueConversionType\OwningManyToOneCompositeIdEntity::class, $owning); } /** @@ -84,12 +85,12 @@ public function testThatEntitiesAreFetchedFromTheDatabase() public function testThatTheValueOfIdentifiersAreConvertedBackAfterBeingFetchedFromTheDatabase() { $inversed = $this->_em->find( - 'Doctrine\Tests\Models\ValueConversionType\InversedOneToManyCompositeIdEntity', - array('id1' => 'abc', 'id2' => 'def') + Models\ValueConversionType\InversedOneToManyCompositeIdEntity::class, + ['id1' => 'abc', 'id2' => 'def'] ); $owning = $this->_em->find( - 'Doctrine\Tests\Models\ValueConversionType\OwningManyToOneCompositeIdEntity', + Models\ValueConversionType\OwningManyToOneCompositeIdEntity::class, 'ghi' ); @@ -104,7 +105,7 @@ public function testThatTheValueOfIdentifiersAreConvertedBackAfterBeingFetchedFr public function testThatTheProxyFromOwningToInversedIsLoaded() { $owning = $this->_em->find( - 'Doctrine\Tests\Models\ValueConversionType\OwningManyToOneCompositeIdEntity', + Models\ValueConversionType\OwningManyToOneCompositeIdEntity::class, 'ghi' ); @@ -119,8 +120,8 @@ public function testThatTheProxyFromOwningToInversedIsLoaded() public function testThatTheCollectionFromInversedToOwningIsLoaded() { $inversed = $this->_em->find( - 'Doctrine\Tests\Models\ValueConversionType\InversedOneToManyCompositeIdEntity', - array('id1' => 'abc', 'id2' => 'def') + Models\ValueConversionType\InversedOneToManyCompositeIdEntity::class, + ['id1' => 'abc', 'id2' => 'def'] ); $this->assertCount(1, $inversed->associatedEntities); diff --git a/tests/Doctrine/Tests/ORM/Functional/ValueConversionType/OneToManyExtraLazyTest.php b/tests/Doctrine/Tests/ORM/Functional/ValueConversionType/OneToManyExtraLazyTest.php index 75b5403fe55..9da341467a4 100644 --- a/tests/Doctrine/Tests/ORM/Functional/ValueConversionType/OneToManyExtraLazyTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/ValueConversionType/OneToManyExtraLazyTest.php @@ -2,6 +2,7 @@ namespace Doctrine\Tests\ORM\Functional\ValueConversionType; +use Doctrine\Tests\Models; use Doctrine\Tests\Models\ValueConversionType as Entity; use Doctrine\Tests\OrmFunctionalTestCase; @@ -61,7 +62,7 @@ public static function tearDownAfterClass() public function testThatExtraLazyCollectionIsCounted() { $inversed = $this->_em->find( - 'Doctrine\Tests\Models\ValueConversionType\InversedOneToManyExtraLazyEntity', + Models\ValueConversionType\InversedOneToManyExtraLazyEntity::class, 'abc' ); @@ -71,12 +72,12 @@ public function testThatExtraLazyCollectionIsCounted() public function testThatExtraLazyCollectionContainsAnEntity() { $inversed = $this->_em->find( - 'Doctrine\Tests\Models\ValueConversionType\InversedOneToManyExtraLazyEntity', + Models\ValueConversionType\InversedOneToManyExtraLazyEntity::class, 'abc' ); $owning = $this->_em->find( - 'Doctrine\Tests\Models\ValueConversionType\OwningManyToOneExtraLazyEntity', + Models\ValueConversionType\OwningManyToOneExtraLazyEntity::class, 'def' ); @@ -86,7 +87,7 @@ public function testThatExtraLazyCollectionContainsAnEntity() public function testThatExtraLazyCollectionContainsAnIndexbyKey() { $inversed = $this->_em->find( - 'Doctrine\Tests\Models\ValueConversionType\InversedOneToManyExtraLazyEntity', + Models\ValueConversionType\InversedOneToManyExtraLazyEntity::class, 'abc' ); @@ -96,7 +97,7 @@ public function testThatExtraLazyCollectionContainsAnIndexbyKey() public function testThatASliceOfTheExtraLazyCollectionIsLoaded() { $inversed = $this->_em->find( - 'Doctrine\Tests\Models\ValueConversionType\InversedOneToManyExtraLazyEntity', + Models\ValueConversionType\InversedOneToManyExtraLazyEntity::class, 'abc' ); diff --git a/tests/Doctrine/Tests/ORM/Functional/ValueConversionType/OneToManyTest.php b/tests/Doctrine/Tests/ORM/Functional/ValueConversionType/OneToManyTest.php index 137a5eaa963..6a10296a7f9 100644 --- a/tests/Doctrine/Tests/ORM/Functional/ValueConversionType/OneToManyTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/ValueConversionType/OneToManyTest.php @@ -2,6 +2,7 @@ namespace Doctrine\Tests\ORM\Functional\ValueConversionType; +use Doctrine\Tests\Models; use Doctrine\Tests\Models\ValueConversionType as Entity; use Doctrine\Tests\OrmFunctionalTestCase; @@ -62,17 +63,17 @@ public function testThatTheValueOfIdentifiersAreConvertedInTheDatabase() public function testThatEntitiesAreFetchedFromTheDatabase() { $inversed = $this->_em->find( - 'Doctrine\Tests\Models\ValueConversionType\InversedOneToManyEntity', + Models\ValueConversionType\InversedOneToManyEntity::class, 'abc' ); $owning = $this->_em->find( - 'Doctrine\Tests\Models\ValueConversionType\OwningManyToOneEntity', + Models\ValueConversionType\OwningManyToOneEntity::class, 'def' ); - $this->assertInstanceOf('Doctrine\Tests\Models\ValueConversionType\InversedOneToManyEntity', $inversed); - $this->assertInstanceOf('Doctrine\Tests\Models\ValueConversionType\OwningManyToOneEntity', $owning); + $this->assertInstanceOf(Models\ValueConversionType\InversedOneToManyEntity::class, $inversed); + $this->assertInstanceOf(Models\ValueConversionType\OwningManyToOneEntity::class, $owning); } /** @@ -81,12 +82,12 @@ public function testThatEntitiesAreFetchedFromTheDatabase() public function testThatTheValueOfIdentifiersAreConvertedBackAfterBeingFetchedFromTheDatabase() { $inversed = $this->_em->find( - 'Doctrine\Tests\Models\ValueConversionType\InversedOneToManyEntity', + Models\ValueConversionType\InversedOneToManyEntity::class, 'abc' ); $owning = $this->_em->find( - 'Doctrine\Tests\Models\ValueConversionType\OwningManyToOneEntity', + Models\ValueConversionType\OwningManyToOneEntity::class, 'def' ); @@ -100,7 +101,7 @@ public function testThatTheValueOfIdentifiersAreConvertedBackAfterBeingFetchedFr public function testThatTheProxyFromOwningToInversedIsLoaded() { $owning = $this->_em->find( - 'Doctrine\Tests\Models\ValueConversionType\OwningManyToOneEntity', + Models\ValueConversionType\OwningManyToOneEntity::class, 'def' ); @@ -115,7 +116,7 @@ public function testThatTheProxyFromOwningToInversedIsLoaded() public function testThatTheCollectionFromInversedToOwningIsLoaded() { $inversed = $this->_em->find( - 'Doctrine\Tests\Models\ValueConversionType\InversedOneToManyEntity', + Models\ValueConversionType\InversedOneToManyEntity::class, 'abc' ); diff --git a/tests/Doctrine/Tests/ORM/Functional/ValueConversionType/OneToOneCompositeIdForeignKeyTest.php b/tests/Doctrine/Tests/ORM/Functional/ValueConversionType/OneToOneCompositeIdForeignKeyTest.php index 762cad2ee32..206ca7e3258 100644 --- a/tests/Doctrine/Tests/ORM/Functional/ValueConversionType/OneToOneCompositeIdForeignKeyTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/ValueConversionType/OneToOneCompositeIdForeignKeyTest.php @@ -2,6 +2,7 @@ namespace Doctrine\Tests\ORM\Functional\ValueConversionType; +use Doctrine\Tests\Models; use Doctrine\Tests\Models\ValueConversionType as Entity; use Doctrine\Tests\OrmFunctionalTestCase; @@ -72,23 +73,23 @@ public function testThatTheValueOfIdentifiersAreConvertedInTheDatabase() public function testThatEntitiesAreFetchedFromTheDatabase() { $auxiliary = $this->_em->find( - 'Doctrine\Tests\Models\ValueConversionType\AuxiliaryEntity', + Models\ValueConversionType\AuxiliaryEntity::class, 'abc' ); $inversed = $this->_em->find( - 'Doctrine\Tests\Models\ValueConversionType\InversedOneToOneCompositeIdForeignKeyEntity', - array('id1' => 'def', 'foreignEntity' => 'abc') + Models\ValueConversionType\InversedOneToOneCompositeIdForeignKeyEntity::class, + ['id1' => 'def', 'foreignEntity' => 'abc'] ); $owning = $this->_em->find( - 'Doctrine\Tests\Models\ValueConversionType\OwningOneToOneCompositeIdForeignKeyEntity', + Models\ValueConversionType\OwningOneToOneCompositeIdForeignKeyEntity::class, 'ghi' ); - $this->assertInstanceOf('Doctrine\Tests\Models\ValueConversionType\AuxiliaryEntity', $auxiliary); - $this->assertInstanceOf('Doctrine\Tests\Models\ValueConversionType\InversedOneToOneCompositeIdForeignKeyEntity', $inversed); - $this->assertInstanceOf('Doctrine\Tests\Models\ValueConversionType\OwningOneToOneCompositeIdForeignKeyEntity', $owning); + $this->assertInstanceOf(Models\ValueConversionType\AuxiliaryEntity::class, $auxiliary); + $this->assertInstanceOf(Models\ValueConversionType\InversedOneToOneCompositeIdForeignKeyEntity::class, $inversed); + $this->assertInstanceOf(Models\ValueConversionType\OwningOneToOneCompositeIdForeignKeyEntity::class, $owning); } /** @@ -97,17 +98,17 @@ public function testThatEntitiesAreFetchedFromTheDatabase() public function testThatTheValueOfIdentifiersAreConvertedBackAfterBeingFetchedFromTheDatabase() { $auxiliary = $this->_em->find( - 'Doctrine\Tests\Models\ValueConversionType\AuxiliaryEntity', + Models\ValueConversionType\AuxiliaryEntity::class, 'abc' ); $inversed = $this->_em->find( - 'Doctrine\Tests\Models\ValueConversionType\InversedOneToOneCompositeIdForeignKeyEntity', - array('id1' => 'def', 'foreignEntity' => 'abc') + Models\ValueConversionType\InversedOneToOneCompositeIdForeignKeyEntity::class, + ['id1' => 'def', 'foreignEntity' => 'abc'] ); $owning = $this->_em->find( - 'Doctrine\Tests\Models\ValueConversionType\OwningOneToOneCompositeIdForeignKeyEntity', + Models\ValueConversionType\OwningOneToOneCompositeIdForeignKeyEntity::class, 'ghi' ); @@ -123,16 +124,16 @@ public function testThatTheValueOfIdentifiersAreConvertedBackAfterBeingFetchedFr public function testThatInversedEntityIsFetchedFromTheDatabaseUsingAuxiliaryEntityAsId() { $auxiliary = $this->_em->find( - 'Doctrine\Tests\Models\ValueConversionType\AuxiliaryEntity', + Models\ValueConversionType\AuxiliaryEntity::class, 'abc' ); $inversed = $this->_em->find( - 'Doctrine\Tests\Models\ValueConversionType\InversedOneToOneCompositeIdForeignKeyEntity', - array('id1' => 'def', 'foreignEntity' => $auxiliary) + Models\ValueConversionType\InversedOneToOneCompositeIdForeignKeyEntity::class, + ['id1' => 'def', 'foreignEntity' => $auxiliary] ); - $this->assertInstanceOf('Doctrine\Tests\Models\ValueConversionType\InversedOneToOneCompositeIdForeignKeyEntity', $inversed); + $this->assertInstanceOf(Models\ValueConversionType\InversedOneToOneCompositeIdForeignKeyEntity::class, $inversed); } /** @@ -141,7 +142,7 @@ public function testThatInversedEntityIsFetchedFromTheDatabaseUsingAuxiliaryEnti public function testThatTheProxyFromOwningToInversedIsLoaded() { $owning = $this->_em->find( - 'Doctrine\Tests\Models\ValueConversionType\OwningOneToOneCompositeIdForeignKeyEntity', + Models\ValueConversionType\OwningOneToOneCompositeIdForeignKeyEntity::class, 'ghi' ); @@ -156,10 +157,10 @@ public function testThatTheProxyFromOwningToInversedIsLoaded() public function testThatTheEntityFromInversedToOwningIsEagerLoaded() { $inversed = $this->_em->find( - 'Doctrine\Tests\Models\ValueConversionType\InversedOneToOneCompositeIdForeignKeyEntity', - array('id1' => 'def', 'foreignEntity' => 'abc') + Models\ValueConversionType\InversedOneToOneCompositeIdForeignKeyEntity::class, + ['id1' => 'def', 'foreignEntity' => 'abc'] ); - $this->assertInstanceOf('Doctrine\Tests\Models\ValueConversionType\OwningOneToOneCompositeIdForeignKeyEntity', $inversed->associatedEntity); + $this->assertInstanceOf(Models\ValueConversionType\OwningOneToOneCompositeIdForeignKeyEntity::class, $inversed->associatedEntity); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/ValueConversionType/OneToOneCompositeIdTest.php b/tests/Doctrine/Tests/ORM/Functional/ValueConversionType/OneToOneCompositeIdTest.php index a179ab61a59..428fe80c6c5 100644 --- a/tests/Doctrine/Tests/ORM/Functional/ValueConversionType/OneToOneCompositeIdTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/ValueConversionType/OneToOneCompositeIdTest.php @@ -2,6 +2,7 @@ namespace Doctrine\Tests\ORM\Functional\ValueConversionType; +use Doctrine\Tests\Models; use Doctrine\Tests\Models\ValueConversionType as Entity; use Doctrine\Tests\OrmFunctionalTestCase; @@ -64,17 +65,17 @@ public function testThatTheValueOfIdentifiersAreConvertedInTheDatabase() public function testThatEntitiesAreFetchedFromTheDatabase() { $inversed = $this->_em->find( - 'Doctrine\Tests\Models\ValueConversionType\InversedOneToOneCompositeIdEntity', - array('id1' => 'abc', 'id2' => 'def') + Models\ValueConversionType\InversedOneToOneCompositeIdEntity::class, + ['id1' => 'abc', 'id2' => 'def'] ); $owning = $this->_em->find( - 'Doctrine\Tests\Models\ValueConversionType\OwningOneToOneCompositeIdEntity', + Models\ValueConversionType\OwningOneToOneCompositeIdEntity::class, 'ghi' ); - $this->assertInstanceOf('Doctrine\Tests\Models\ValueConversionType\InversedOneToOneCompositeIdEntity', $inversed); - $this->assertInstanceOf('Doctrine\Tests\Models\ValueConversionType\OwningOneToOneCompositeIdEntity', $owning); + $this->assertInstanceOf(Models\ValueConversionType\InversedOneToOneCompositeIdEntity::class, $inversed); + $this->assertInstanceOf(Models\ValueConversionType\OwningOneToOneCompositeIdEntity::class, $owning); } /** @@ -83,12 +84,12 @@ public function testThatEntitiesAreFetchedFromTheDatabase() public function testThatTheValueOfIdentifiersAreConvertedBackAfterBeingFetchedFromTheDatabase() { $inversed = $this->_em->find( - 'Doctrine\Tests\Models\ValueConversionType\InversedOneToOneCompositeIdEntity', - array('id1' => 'abc', 'id2' => 'def') + Models\ValueConversionType\InversedOneToOneCompositeIdEntity::class, + ['id1' => 'abc', 'id2' => 'def'] ); $owning = $this->_em->find( - 'Doctrine\Tests\Models\ValueConversionType\OwningOneToOneCompositeIdEntity', + Models\ValueConversionType\OwningOneToOneCompositeIdEntity::class, 'ghi' ); @@ -103,7 +104,7 @@ public function testThatTheValueOfIdentifiersAreConvertedBackAfterBeingFetchedFr public function testThatTheProxyFromOwningToInversedIsLoaded() { $owning = $this->_em->find( - 'Doctrine\Tests\Models\ValueConversionType\OwningOneToOneCompositeIdEntity', + Models\ValueConversionType\OwningOneToOneCompositeIdEntity::class, 'ghi' ); @@ -118,10 +119,10 @@ public function testThatTheProxyFromOwningToInversedIsLoaded() public function testThatTheEntityFromInversedToOwningIsEagerLoaded() { $inversed = $this->_em->find( - 'Doctrine\Tests\Models\ValueConversionType\InversedOneToOneCompositeIdEntity', - array('id1' => 'abc', 'id2' => 'def') + Models\ValueConversionType\InversedOneToOneCompositeIdEntity::class, + ['id1' => 'abc', 'id2' => 'def'] ); - $this->assertInstanceOf('Doctrine\Tests\Models\ValueConversionType\OwningOneToOneCompositeIdEntity', $inversed->associatedEntity); + $this->assertInstanceOf(Models\ValueConversionType\OwningOneToOneCompositeIdEntity::class, $inversed->associatedEntity); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/ValueConversionType/OneToOneTest.php b/tests/Doctrine/Tests/ORM/Functional/ValueConversionType/OneToOneTest.php index 0de217e361c..8ca8eebe56d 100644 --- a/tests/Doctrine/Tests/ORM/Functional/ValueConversionType/OneToOneTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/ValueConversionType/OneToOneTest.php @@ -2,6 +2,7 @@ namespace Doctrine\Tests\ORM\Functional\ValueConversionType; +use Doctrine\Tests\Models; use Doctrine\Tests\Models\ValueConversionType as Entity; use Doctrine\Tests\OrmFunctionalTestCase; @@ -62,17 +63,17 @@ public function testThatTheValueOfIdentifiersAreConvertedInTheDatabase() public function testThatEntitiesAreFetchedFromTheDatabase() { $inversed = $this->_em->find( - 'Doctrine\Tests\Models\ValueConversionType\InversedOneToOneEntity', + Models\ValueConversionType\InversedOneToOneEntity::class, 'abc' ); $owning = $this->_em->find( - 'Doctrine\Tests\Models\ValueConversionType\OwningOneToOneEntity', + Models\ValueConversionType\OwningOneToOneEntity::class, 'def' ); - $this->assertInstanceOf('Doctrine\Tests\Models\ValueConversionType\InversedOneToOneEntity', $inversed); - $this->assertInstanceOf('Doctrine\Tests\Models\ValueConversionType\OwningOneToOneEntity', $owning); + $this->assertInstanceOf(Models\ValueConversionType\InversedOneToOneEntity::class, $inversed); + $this->assertInstanceOf(Models\ValueConversionType\OwningOneToOneEntity::class, $owning); } /** @@ -81,12 +82,12 @@ public function testThatEntitiesAreFetchedFromTheDatabase() public function testThatTheValueOfIdentifiersAreConvertedBackAfterBeingFetchedFromTheDatabase() { $inversed = $this->_em->find( - 'Doctrine\Tests\Models\ValueConversionType\InversedOneToOneEntity', + Models\ValueConversionType\InversedOneToOneEntity::class, 'abc' ); $owning = $this->_em->find( - 'Doctrine\Tests\Models\ValueConversionType\OwningOneToOneEntity', + Models\ValueConversionType\OwningOneToOneEntity::class, 'def' ); @@ -100,7 +101,7 @@ public function testThatTheValueOfIdentifiersAreConvertedBackAfterBeingFetchedFr public function testThatTheProxyFromOwningToInversedIsLoaded() { $owning = $this->_em->find( - 'Doctrine\Tests\Models\ValueConversionType\OwningOneToOneEntity', + Models\ValueConversionType\OwningOneToOneEntity::class, 'def' ); @@ -115,10 +116,10 @@ public function testThatTheProxyFromOwningToInversedIsLoaded() public function testThatTheEntityFromInversedToOwningIsEagerLoaded() { $inversed = $this->_em->find( - 'Doctrine\Tests\Models\ValueConversionType\InversedOneToOneEntity', + Models\ValueConversionType\InversedOneToOneEntity::class, 'abc' ); - $this->assertInstanceOf('Doctrine\Tests\Models\ValueConversionType\OwningOneToOneEntity', $inversed->associatedEntity); + $this->assertInstanceOf(Models\ValueConversionType\OwningOneToOneEntity::class, $inversed->associatedEntity); } } diff --git a/tests/Doctrine/Tests/ORM/Functional/ValueObjectsTest.php b/tests/Doctrine/Tests/ORM/Functional/ValueObjectsTest.php index 47e98d25cfb..7a483ebc783 100644 --- a/tests/Doctrine/Tests/ORM/Functional/ValueObjectsTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/ValueObjectsTest.php @@ -1,7 +1,9 @@ _schemaTool->createSchema(array( - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC93Person'), - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC93Address'), - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC93Vehicle'), - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC93Car'), - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC3027Animal'), - $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC3027Dog'), - )); + $this->_schemaTool->createSchema( + [ + $this->_em->getClassMetadata(DDC93Person::class), + $this->_em->getClassMetadata(DDC93Address::class), + $this->_em->getClassMetadata(DDC93Vehicle::class), + $this->_em->getClassMetadata(DDC93Car::class), + $this->_em->getClassMetadata(DDC3027Animal::class), + $this->_em->getClassMetadata(DDC3027Dog::class), + ] + ); } catch(\Exception $e) { } } public function testMetadataHasReflectionEmbeddablesAccessible() { - $classMetadata = $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC93Person'); + $classMetadata = $this->_em->getClassMetadata(DDC93Person::class); - $this->assertInstanceOf('Doctrine\Common\Reflection\RuntimePublicReflectionProperty', $classMetadata->getReflectionProperty('address')); - $this->assertInstanceOf('Doctrine\ORM\Mapping\ReflectionEmbeddedProperty', $classMetadata->getReflectionProperty('address.street')); + $this->assertInstanceOf(RuntimePublicReflectionProperty::class, $classMetadata->getReflectionProperty('address')); + $this->assertInstanceOf(ReflectionEmbeddedProperty::class, $classMetadata->getReflectionProperty('address.street')); } public function testCRUD() @@ -52,13 +56,13 @@ public function testCRUD() $this->_em->clear(); // 2. check loading value objects works - $person = $this->_em->find(DDC93Person::CLASSNAME, $person->id); + $person = $this->_em->find(DDC93Person::class, $person->id); - $this->assertInstanceOf(DDC93Address::CLASSNAME, $person->address); + $this->assertInstanceOf(DDC93Address::class, $person->address); $this->assertEquals('United States of Tara Street', $person->address->street); $this->assertEquals('12345', $person->address->zip); $this->assertEquals('funkytown', $person->address->city); - $this->assertInstanceOf(DDC93Country::CLASSNAME, $person->address->country); + $this->assertInstanceOf(DDC93Country::class, $person->address->country); $this->assertEquals('Germany', $person->address->country->name); // 3. check changing value objects works @@ -70,7 +74,7 @@ public function testCRUD() $this->_em->clear(); - $person = $this->_em->find(DDC93Person::CLASSNAME, $person->id); + $person = $this->_em->find(DDC93Person::class, $person->id); $this->assertEquals('Street', $person->address->street); $this->assertEquals('54321', $person->address->zip); @@ -82,7 +86,7 @@ public function testCRUD() $this->_em->remove($person); $this->_em->flush(); - $this->assertNull($this->_em->find(DDC93Person::CLASSNAME, $personId)); + $this->assertNull($this->_em->find(DDC93Person::class, $personId)); } public function testLoadDql() @@ -107,11 +111,11 @@ public function testLoadDql() $this->assertCount(3, $persons); foreach ($persons as $person) { - $this->assertInstanceOf(DDC93Address::CLASSNAME, $person->address); + $this->assertInstanceOf(DDC93Address::class, $person->address); $this->assertEquals('Tree', $person->address->street); $this->assertEquals('12345', $person->address->zip); $this->assertEquals('funkytown', $person->address->city); - $this->assertInstanceOf(DDC93Country::CLASSNAME, $person->address->country); + $this->assertInstanceOf(DDC93Country::class, $person->address->country); $this->assertEquals('United States of America', $person->address->country->name); } @@ -137,7 +141,7 @@ public function testDqlOnEmbeddedObjectsField() $person = new DDC93Person('Johannes', new DDC93Address('Moo', '12345', 'Karlsruhe', new DDC93Country('Germany'))); $this->_em->persist($person); - $this->_em->flush($person); + $this->_em->flush(); // SELECT $selectDql = "SELECT p FROM " . __NAMESPACE__ ."\\DDC93Person p WHERE p.address.city = :city AND p.address.country.name = :country"; @@ -173,37 +177,37 @@ public function testDqlOnEmbeddedObjectsField() ->execute(); $this->_em->clear(); - $this->assertNull($this->_em->find(__NAMESPACE__.'\\DDC93Person', $person->id)); + $this->assertNull($this->_em->find(DDC93Person::class, $person->id)); } - + public function testPartialDqlOnEmbeddedObjectsField() { $person = new DDC93Person('Karl', new DDC93Address('Foo', '12345', 'Gosport', new DDC93Country('England'))); $this->_em->persist($person); - $this->_em->flush($person); + $this->_em->flush(); $this->_em->clear(); - + // Prove that the entity was persisted correctly. $dql = "SELECT p FROM " . __NAMESPACE__ ."\\DDC93Person p WHERE p.name = :name"; - + $person = $this->_em->createQuery($dql) ->setParameter('name', 'Karl') ->getSingleResult(); - + $this->assertEquals('Gosport', $person->address->city); $this->assertEquals('Foo', $person->address->street); $this->assertEquals('12345', $person->address->zip); $this->assertEquals('England', $person->address->country->name); - + // Clear the EM and prove that the embeddable can be the subject of a partial query. $this->_em->clear(); - + $dql = "SELECT PARTIAL p.{id,address.city} FROM " . __NAMESPACE__ ."\\DDC93Person p WHERE p.name = :name"; - + $person = $this->_em->createQuery($dql) ->setParameter('name', 'Karl') ->getSingleResult(); - + // Selected field must be equal, all other fields must be null. $this->assertEquals('Gosport', $person->address->city); $this->assertNull($person->address->street); @@ -213,13 +217,13 @@ public function testPartialDqlOnEmbeddedObjectsField() // Clear the EM and prove that the embeddable can be the subject of a partial query regardless of attributes positions. $this->_em->clear(); - + $dql = "SELECT PARTIAL p.{address.city, id} FROM " . __NAMESPACE__ ."\\DDC93Person p WHERE p.name = :name"; - + $person = $this->_em->createQuery($dql) ->setParameter('name', 'Karl') ->getSingleResult(); - + // Selected field must be equal, all other fields must be null. $this->assertEquals('Gosport', $person->address->city); $this->assertNull($person->address->street); @@ -236,7 +240,7 @@ public function testDqlWithNonExistentEmbeddableField() $this->_em->createQuery("SELECT p FROM " . __NAMESPACE__ . "\\DDC93Person p WHERE p.address.asdfasdf IS NULL") ->execute(); } - + public function testPartialDqlWithNonExistentEmbeddableField() { $this->expectException(QueryException::class); @@ -250,15 +254,15 @@ public function testEmbeddableWithInheritance() { $car = new DDC93Car(new DDC93Address('Foo', '12345', 'Asdf')); $this->_em->persist($car); - $this->_em->flush($car); + $this->_em->flush(); - $reloadedCar = $this->_em->find(__NAMESPACE__.'\\DDC93Car', $car->id); + $reloadedCar = $this->_em->find(DDC93Car::class, $car->id); $this->assertEquals($car, $reloadedCar); } public function testInlineEmbeddableWithPrefix() { - $metadata = $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC3028PersonWithPrefix'); + $metadata = $this->_em->getClassMetadata(DDC3028PersonWithPrefix::class); $this->assertEquals('foobar_id', $metadata->getColumnName('id.id')); $this->assertEquals('bloo_foo_id', $metadata->getColumnName('nested.nestedWithPrefix.id')); @@ -268,7 +272,7 @@ public function testInlineEmbeddableWithPrefix() public function testInlineEmbeddableEmptyPrefix() { - $metadata = $this->_em->getClassMetadata(__NAMESPACE__ . '\DDC3028PersonEmptyPrefix'); + $metadata = $this->_em->getClassMetadata(DDC3028PersonEmptyPrefix::class); $this->assertEquals('id_id', $metadata->getColumnName('id.id')); $this->assertEquals('nested_foo_id', $metadata->getColumnName('nested.nestedWithPrefix.id')); @@ -281,7 +285,7 @@ public function testInlineEmbeddablePrefixFalse() $expectedColumnName = 'id'; $actualColumnName = $this->_em - ->getClassMetadata(__NAMESPACE__ . '\DDC3028PersonPrefixFalse') + ->getClassMetadata(DDC3028PersonPrefixFalse::class) ->getColumnName('id.id'); $this->assertEquals($expectedColumnName, $actualColumnName); @@ -290,7 +294,7 @@ public function testInlineEmbeddablePrefixFalse() public function testInlineEmbeddableInMappedSuperClass() { $isFieldMapped = $this->_em - ->getClassMetadata(__NAMESPACE__ . '\DDC3027Dog') + ->getClassMetadata(DDC3027Dog::class) ->hasField('address.street'); $this->assertTrue($isFieldMapped); @@ -310,17 +314,19 @@ public function testThrowsExceptionOnInfiniteEmbeddableNesting($embeddableClassN ) ); - $this->_schemaTool->createSchema(array( + $this->_schemaTool->createSchema( + [ $this->_em->getClassMetadata(__NAMESPACE__ . '\\' . $embeddableClassName), - )); + ] + ); } public function getInfiniteEmbeddableNestingData() { - return array( - array('DDCInfiniteNestingEmbeddable', 'DDCInfiniteNestingEmbeddable'), - array('DDCNestingEmbeddable1', 'DDCNestingEmbeddable4'), - ); + return [ + ['DDCInfiniteNestingEmbeddable', 'DDCInfiniteNestingEmbeddable'], + ['DDCNestingEmbeddable1', 'DDCNestingEmbeddable4'], + ]; } } @@ -330,8 +336,6 @@ public function getInfiniteEmbeddableNestingData() */ class DDC93Person { - const CLASSNAME = __CLASS__; - /** @Id @GeneratedValue @Column(type="integer") */ public $id; @@ -401,8 +405,6 @@ class DDC93Car extends DDC93Vehicle */ class DDC93Country { - const CLASSNAME = __CLASS__; - /** * @Column(type="string", nullable=true) */ @@ -419,8 +421,6 @@ public function __construct($name = null) */ class DDC93Address { - const CLASSNAME = __CLASS__; - /** * @Column(type="string") */ @@ -458,8 +458,6 @@ class DDC93Customer /** @Embeddable */ class DDC93ContactInfo { - const CLASSNAME = __CLASS__; - /** * @Column(type="string") */ @@ -473,8 +471,6 @@ class DDC93ContactInfo */ class DDC3028PersonWithPrefix { - const CLASSNAME = __CLASS__; - /** @Embedded(class="DDC3028Id", columnPrefix = "foobar_") */ public $id; @@ -493,8 +489,6 @@ public function __construct(DDC3028Id $id = null, DDC3028NestedEmbeddable $neste */ class DDC3028PersonEmptyPrefix { - const CLASSNAME = __CLASS__; - /** @Embedded(class="DDC3028Id", columnPrefix = "") */ public $id; @@ -513,8 +507,6 @@ public function __construct(DDC3028Id $id = null, DDC3028NestedEmbeddable $neste */ class DDC3028PersonPrefixFalse { - const CLASSNAME = __CLASS__; - /** @Embedded(class="DDC3028Id", columnPrefix = false) */ public $id; @@ -529,8 +521,6 @@ public function __construct(DDC3028Id $id = null) */ class DDC3028Id { - const CLASSNAME = __CLASS__; - /** * @Id @Column(type="string") */ @@ -547,8 +537,6 @@ public function __construct($id = null) */ class DDC3028NestedEmbeddable { - const CLASSNAME = __CLASS__; - /** @Embedded(class="DDC3028Id", columnPrefix = "foo_") */ public $nestedWithPrefix; diff --git a/tests/Doctrine/Tests/ORM/Functional/VersionedOneToOneTest.php b/tests/Doctrine/Tests/ORM/Functional/VersionedOneToOneTest.php index f354be60088..f8062f9954e 100644 --- a/tests/Doctrine/Tests/ORM/Functional/VersionedOneToOneTest.php +++ b/tests/Doctrine/Tests/ORM/Functional/VersionedOneToOneTest.php @@ -22,10 +22,10 @@ protected function setUp() try { $this->_schemaTool->createSchema( - array( - $this->_em->getClassMetadata('Doctrine\Tests\Models\VersionedOneToOne\FirstRelatedEntity'), - $this->_em->getClassMetadata('Doctrine\Tests\Models\VersionedOneToOne\SecondRelatedEntity') - ) + [ + $this->_em->getClassMetadata(FirstRelatedEntity::class), + $this->_em->getClassMetadata(SecondRelatedEntity::class) + ] ); } catch (ORMException $e) { } @@ -50,11 +50,11 @@ public function testSetVersionOnCreate() $this->_em->persist($firstRelatedEntity); $this->_em->flush(); - $firstEntity = $this->_em->getRepository('Doctrine\Tests\Models\VersionedOneToOne\FirstRelatedEntity') - ->findOneBy(array('name' => 'Fred')); + $firstEntity = $this->_em->getRepository(FirstRelatedEntity::class) + ->findOneBy(['name' => 'Fred']); - $secondEntity = $this->_em->getRepository('Doctrine\Tests\Models\VersionedOneToOne\SecondRelatedEntity') - ->findOneBy(array('name' => 'Bob')); + $secondEntity = $this->_em->getRepository(SecondRelatedEntity::class) + ->findOneBy(['name' => 'Bob']); $this->assertSame($firstRelatedEntity, $firstEntity); $this->assertSame($secondRelatedEntity, $secondEntity); diff --git a/tests/Doctrine/Tests/ORM/Functional/xml/Doctrine.Tests.Models.OrnementalOrphanRemoval.Person.dcm.xml b/tests/Doctrine/Tests/ORM/Functional/xml/Doctrine.Tests.Models.OrnementalOrphanRemoval.Person.dcm.xml new file mode 100644 index 00000000000..ff0f103c4cd --- /dev/null +++ b/tests/Doctrine/Tests/ORM/Functional/xml/Doctrine.Tests.Models.OrnementalOrphanRemoval.Person.dcm.xml @@ -0,0 +1,12 @@ + + + + + + + + diff --git a/tests/Doctrine/Tests/ORM/Functional/xml/Doctrine.Tests.Models.OrnementalOrphanRemoval.PhoneNumber.dcm.xml b/tests/Doctrine/Tests/ORM/Functional/xml/Doctrine.Tests.Models.OrnementalOrphanRemoval.PhoneNumber.dcm.xml new file mode 100644 index 00000000000..f56c918b420 --- /dev/null +++ b/tests/Doctrine/Tests/ORM/Functional/xml/Doctrine.Tests.Models.OrnementalOrphanRemoval.PhoneNumber.dcm.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + diff --git a/tests/Doctrine/Tests/ORM/Hydration/AbstractHydratorTest.php b/tests/Doctrine/Tests/ORM/Hydration/AbstractHydratorTest.php new file mode 100644 index 00000000000..40a3d03233e --- /dev/null +++ b/tests/Doctrine/Tests/ORM/Hydration/AbstractHydratorTest.php @@ -0,0 +1,112 @@ +createMock(Connection::class); + $mockEntityManagerInterface = $this->createMock(EntityManagerInterface::class); + $this->mockEventManager = $this->createMock(EventManager::class); + $this->mockStatement = $this->createMock(Statement::class); + $this->mockResultMapping = $this->getMockBuilder(ResultSetMapping::class); + + $mockEntityManagerInterface + ->expects(self::any()) + ->method('getEventManager') + ->willReturn($this->mockEventManager); + $mockEntityManagerInterface + ->expects(self::any()) + ->method('getConnection') + ->willReturn($mockConnection); + $this->mockStatement + ->expects(self::any()) + ->method('fetch') + ->willReturn(false); + + $this->hydrator = $this + ->getMockBuilder(AbstractHydrator::class) + ->setConstructorArgs([$mockEntityManagerInterface]) + ->setMethods(['hydrateAllData']) + ->getMock(); + } + + /** + * @group DDC-3146 + * @group #1515 + * + * Verify that the number of added events to the event listener from the abstract hydrator class is equal to the + * number of removed events + */ + public function testOnClearEventListenerIsDetachedOnCleanup() : void + { + $this + ->mockEventManager + ->expects(self::at(0)) + ->method('addEventListener') + ->with([Events::onClear], $this->hydrator); + + $this + ->mockEventManager + ->expects(self::at(1)) + ->method('removeEventListener') + ->with([Events::onClear], $this->hydrator); + + iterator_to_array($this->hydrator->iterate($this->mockStatement, $this->mockResultMapping)); + } + + /** + * @group #6623 + */ + public function testHydrateAllRegistersAndClearsAllAttachedListeners() : void + { + $this + ->mockEventManager + ->expects(self::at(0)) + ->method('addEventListener') + ->with([Events::onClear], $this->hydrator); + + $this + ->mockEventManager + ->expects(self::at(1)) + ->method('removeEventListener') + ->with([Events::onClear], $this->hydrator); + + $this->hydrator->hydrateAll($this->mockStatement, $this->mockResultMapping); + } +} diff --git a/tests/Doctrine/Tests/ORM/Hydration/ArrayHydratorTest.php b/tests/Doctrine/Tests/ORM/Hydration/ArrayHydratorTest.php index 0942a6051e0..6c0b30ef655 100644 --- a/tests/Doctrine/Tests/ORM/Hydration/ArrayHydratorTest.php +++ b/tests/Doctrine/Tests/ORM/Hydration/ArrayHydratorTest.php @@ -2,19 +2,25 @@ namespace Doctrine\Tests\ORM\Hydration; -use Doctrine\Tests\Mocks\HydratorMockStatement; use Doctrine\ORM\Query\ResultSetMapping; +use Doctrine\Tests\Mocks\HydratorMockStatement; +use Doctrine\Tests\Models\CMS\CmsArticle; +use Doctrine\Tests\Models\CMS\CmsComment; +use Doctrine\Tests\Models\CMS\CmsPhonenumber; +use Doctrine\Tests\Models\CMS\CmsUser; +use Doctrine\Tests\Models\Forum\ForumBoard; +use Doctrine\Tests\Models\Forum\ForumCategory; class ArrayHydratorTest extends HydrationTestCase { public function provideDataForUserEntityResult() { - return array( - array(0), - array('user'), - array('scalars'), - array('newObjects'), - ); + return [ + [0], + ['user'], + ['scalars'], + ['newObjects'], + ]; } /** @@ -25,21 +31,21 @@ public function testSimpleEntityQuery() { $rsm = new ResultSetMapping; - $rsm->addEntityResult('Doctrine\Tests\Models\CMS\CmsUser', 'u'); + $rsm->addEntityResult(CmsUser::class, 'u'); $rsm->addFieldResult('u', 'u__id', 'id'); $rsm->addFieldResult('u', 'u__name', 'name'); // Faked result set - $resultSet = array( - array( + $resultSet = [ + [ 'u__id' => '1', 'u__name' => 'romanb' - ), - array( + ], + [ 'u__id' => '2', 'u__name' => 'jwage' - ) - ); + ] + ]; $stmt = new HydratorMockStatement($resultSet); $hydrator = new \Doctrine\ORM\Internal\Hydration\ArrayHydrator($this->_em); @@ -66,24 +72,24 @@ public function testSimpleEntityWithScalarQuery($userEntityKey) $alias = $userEntityKey ?: 'u'; $rsm = new ResultSetMapping; - $rsm->addEntityResult('Doctrine\Tests\Models\CMS\CmsUser', $alias); + $rsm->addEntityResult(CmsUser::class, $alias); $rsm->addFieldResult($alias, 's__id', 'id'); $rsm->addFieldResult($alias, 's__name', 'name'); $rsm->addScalarResult('sclr0', 'nameUpper', 'string'); // Faked result set - $resultSet = array( - array( + $resultSet = [ + [ 's__id' => '1', 's__name' => 'romanb', 'sclr0' => 'ROMANB', - ), - array( + ], + [ 's__id' => '2', 's__name' => 'jwage', 'sclr0' => 'JWAGE', - ) - ); + ] + ]; $stmt = new HydratorMockStatement($resultSet); $hydrator = new \Doctrine\ORM\Internal\Hydration\ArrayHydrator($this->_em); @@ -117,21 +123,21 @@ public function testSimpleEntityQueryWithAliasedUserEntity() { $rsm = new ResultSetMapping; - $rsm->addEntityResult('Doctrine\Tests\Models\CMS\CmsUser', 'u', 'user'); + $rsm->addEntityResult(CmsUser::class, 'u', 'user'); $rsm->addFieldResult('u', 'u__id', 'id'); $rsm->addFieldResult('u', 'u__name', 'name'); // Faked result set - $resultSet = array( - array( + $resultSet = [ + [ 'u__id' => '1', 'u__name' => 'romanb' - ), - array( + ], + [ 'u__id' => '2', 'u__name' => 'jwage' - ) - ); + ] + ]; $stmt = new HydratorMockStatement($resultSet); $hydrator = new \Doctrine\ORM\Internal\Hydration\ArrayHydrator($this->_em); @@ -157,28 +163,28 @@ public function testSimpleMultipleRootEntityQuery() { $rsm = new ResultSetMapping; - $rsm->addEntityResult('Doctrine\Tests\Models\CMS\CmsUser', 'u'); - $rsm->addEntityResult('Doctrine\Tests\Models\CMS\CmsArticle', 'a'); + $rsm->addEntityResult(CmsUser::class, 'u'); + $rsm->addEntityResult(CmsArticle::class, 'a'); $rsm->addFieldResult('u', 'u__id', 'id'); $rsm->addFieldResult('u', 'u__name', 'name'); $rsm->addFieldResult('a', 'a__id', 'id'); $rsm->addFieldResult('a', 'a__topic', 'topic'); // Faked result set - $resultSet = array( - array( + $resultSet = [ + [ 'u__id' => '1', 'u__name' => 'romanb', 'a__id' => '1', 'a__topic' => 'Cool things.' - ), - array( + ], + [ 'u__id' => '2', 'u__name' => 'jwage', 'a__id' => '2', 'a__topic' => 'Cool things II.' - ) - ); + ] + ]; $stmt = new HydratorMockStatement($resultSet); $hydrator = new \Doctrine\ORM\Internal\Hydration\ArrayHydrator($this->_em); @@ -207,28 +213,28 @@ public function testSimpleMultipleRootEntityQueryWithAliasedUserEntity() { $rsm = new ResultSetMapping; - $rsm->addEntityResult('Doctrine\Tests\Models\CMS\CmsUser', 'u', 'user'); - $rsm->addEntityResult('Doctrine\Tests\Models\CMS\CmsArticle', 'a'); + $rsm->addEntityResult(CmsUser::class, 'u', 'user'); + $rsm->addEntityResult(CmsArticle::class, 'a'); $rsm->addFieldResult('u', 'u__id', 'id'); $rsm->addFieldResult('u', 'u__name', 'name'); $rsm->addFieldResult('a', 'a__id', 'id'); $rsm->addFieldResult('a', 'a__topic', 'topic'); // Faked result set - $resultSet = array( - array( + $resultSet = [ + [ 'u__id' => '1', 'u__name' => 'romanb', 'a__id' => '1', 'a__topic' => 'Cool things.' - ), - array( + ], + [ 'u__id' => '2', 'u__name' => 'jwage', 'a__id' => '2', 'a__topic' => 'Cool things II.' - ) - ); + ] + ]; $stmt = new HydratorMockStatement($resultSet); $hydrator = new \Doctrine\ORM\Internal\Hydration\ArrayHydrator($this->_em); @@ -261,28 +267,28 @@ public function testSimpleMultipleRootEntityQueryWithAliasedArticleEntity() { $rsm = new ResultSetMapping; - $rsm->addEntityResult('Doctrine\Tests\Models\CMS\CmsUser', 'u'); - $rsm->addEntityResult('Doctrine\Tests\Models\CMS\CmsArticle', 'a', 'article'); + $rsm->addEntityResult(CmsUser::class, 'u'); + $rsm->addEntityResult(CmsArticle::class, 'a', 'article'); $rsm->addFieldResult('u', 'u__id', 'id'); $rsm->addFieldResult('u', 'u__name', 'name'); $rsm->addFieldResult('a', 'a__id', 'id'); $rsm->addFieldResult('a', 'a__topic', 'topic'); // Faked result set - $resultSet = array( - array( + $resultSet = [ + [ 'u__id' => '1', 'u__name' => 'romanb', 'a__id' => '1', 'a__topic' => 'Cool things.' - ), - array( + ], + [ 'u__id' => '2', 'u__name' => 'jwage', 'a__id' => '2', 'a__topic' => 'Cool things II.' - ) - ); + ] + ]; $stmt = new HydratorMockStatement($resultSet); $hydrator = new \Doctrine\ORM\Internal\Hydration\ArrayHydrator($this->_em); @@ -315,28 +321,28 @@ public function testSimpleMultipleRootEntityQueryWithAliasedEntities() { $rsm = new ResultSetMapping; - $rsm->addEntityResult('Doctrine\Tests\Models\CMS\CmsUser', 'u', 'user'); - $rsm->addEntityResult('Doctrine\Tests\Models\CMS\CmsArticle', 'a', 'article'); + $rsm->addEntityResult(CmsUser::class, 'u', 'user'); + $rsm->addEntityResult(CmsArticle::class, 'a', 'article'); $rsm->addFieldResult('u', 'u__id', 'id'); $rsm->addFieldResult('u', 'u__name', 'name'); $rsm->addFieldResult('a', 'a__id', 'id'); $rsm->addFieldResult('a', 'a__topic', 'topic'); // Faked result set - $resultSet = array( - array( + $resultSet = [ + [ 'u__id' => '1', 'u__name' => 'romanb', 'a__id' => '1', 'a__topic' => 'Cool things.' - ), - array( + ], + [ 'u__id' => '2', 'u__name' => 'jwage', 'a__id' => '2', 'a__topic' => 'Cool things II.' - ) - ); + ] + ]; $stmt = new HydratorMockStatement($resultSet); $hydrator = new \Doctrine\ORM\Internal\Hydration\ArrayHydrator($this->_em); @@ -373,25 +379,25 @@ public function testMixedQueryNormalJoin($userEntityKey) { $rsm = new ResultSetMapping; - $rsm->addEntityResult('Doctrine\Tests\Models\CMS\CmsUser', 'u', $userEntityKey ?: null); + $rsm->addEntityResult(CmsUser::class, 'u', $userEntityKey ?: null); $rsm->addFieldResult('u', 'u__id', 'id'); $rsm->addFieldResult('u', 'u__status', 'status'); $rsm->addScalarResult('sclr0', 'numPhones', 'integer'); // Faked result set - $resultSet = array( + $resultSet = [ //row1 - array( + [ 'u__id' => '1', 'u__status' => 'developer', 'sclr0' => '2', - ), - array( + ], + [ 'u__id' => '2', 'u__status' => 'developer', 'sclr0' => '1', - ) - ); + ] + ]; $stmt = new HydratorMockStatement($resultSet); $hydrator = new \Doctrine\ORM\Internal\Hydration\ArrayHydrator($this->_em); @@ -422,9 +428,9 @@ public function testMixedQueryFetchJoin($userEntityKey) { $rsm = new ResultSetMapping; - $rsm->addEntityResult('Doctrine\Tests\Models\CMS\CmsUser', 'u', $userEntityKey ?: null); + $rsm->addEntityResult(CmsUser::class, 'u', $userEntityKey ?: null); $rsm->addJoinedEntityResult( - 'Doctrine\Tests\Models\CMS\CmsPhonenumber', + CmsPhonenumber::class, 'p', 'u', 'phonenumbers' @@ -435,27 +441,27 @@ public function testMixedQueryFetchJoin($userEntityKey) $rsm->addFieldResult('p', 'p__phonenumber', 'phonenumber'); // Faked result set - $resultSet = array( + $resultSet = [ //row1 - array( + [ 'u__id' => '1', 'u__status' => 'developer', 'sclr0' => 'ROMANB', 'p__phonenumber' => '42', - ), - array( + ], + [ 'u__id' => '1', 'u__status' => 'developer', 'sclr0' => 'ROMANB', 'p__phonenumber' => '43', - ), - array( + ], + [ 'u__id' => '2', 'u__status' => 'developer', 'sclr0' => 'JWAGE', 'p__phonenumber' => '91' - ) - ); + ] + ]; $stmt = new HydratorMockStatement($resultSet); $hydrator = new \Doctrine\ORM\Internal\Hydration\ArrayHydrator($this->_em); @@ -493,9 +499,9 @@ public function testMixedQueryFetchJoinCustomIndex($userEntityKey) { $rsm = new ResultSetMapping; - $rsm->addEntityResult('Doctrine\Tests\Models\CMS\CmsUser', 'u', $userEntityKey ?: null); + $rsm->addEntityResult(CmsUser::class, 'u', $userEntityKey ?: null); $rsm->addJoinedEntityResult( - 'Doctrine\Tests\Models\CMS\CmsPhonenumber', + CmsPhonenumber::class, 'p', 'u', 'phonenumbers' @@ -508,27 +514,27 @@ public function testMixedQueryFetchJoinCustomIndex($userEntityKey) $rsm->addIndexBy('p', 'phonenumber'); // Faked result set - $resultSet = array( + $resultSet = [ //row1 - array( + [ 'u__id' => '1', 'u__status' => 'developer', 'sclr0' => 'ROMANB', 'p__phonenumber' => '42', - ), - array( + ], + [ 'u__id' => '1', 'u__status' => 'developer', 'sclr0' => 'ROMANB', 'p__phonenumber' => '43', - ), - array( + ], + [ 'u__id' => '2', 'u__status' => 'developer', 'sclr0' => 'JWAGE', 'p__phonenumber' => '91' - ) - ); + ] + ]; $stmt = new HydratorMockStatement($resultSet); @@ -572,15 +578,15 @@ public function testMixedQueryMultipleFetchJoin() { $rsm = new ResultSetMapping; - $rsm->addEntityResult('Doctrine\Tests\Models\CMS\CmsUser', 'u'); + $rsm->addEntityResult(CmsUser::class, 'u'); $rsm->addJoinedEntityResult( - 'Doctrine\Tests\Models\CMS\CmsPhonenumber', + CmsPhonenumber::class, 'p', 'u', 'phonenumbers' ); $rsm->addJoinedEntityResult( - 'Doctrine\Tests\Models\CMS\CmsArticle', + CmsArticle::class, 'a', 'u', 'articles' @@ -593,57 +599,57 @@ public function testMixedQueryMultipleFetchJoin() $rsm->addFieldResult('a', 'a__topic', 'topic'); // Faked result set - $resultSet = array( + $resultSet = [ //row1 - array( + [ 'u__id' => '1', 'u__status' => 'developer', 'sclr0' => 'ROMANB', 'p__phonenumber' => '42', 'a__id' => '1', 'a__topic' => 'Getting things done!' - ), - array( + ], + [ 'u__id' => '1', 'u__status' => 'developer', 'sclr0' => 'ROMANB', 'p__phonenumber' => '43', 'a__id' => '1', 'a__topic' => 'Getting things done!' - ), - array( + ], + [ 'u__id' => '1', 'u__status' => 'developer', 'sclr0' => 'ROMANB', 'p__phonenumber' => '42', 'a__id' => '2', 'a__topic' => 'ZendCon' - ), - array( + ], + [ 'u__id' => '1', 'u__status' => 'developer', 'sclr0' => 'ROMANB', 'p__phonenumber' => '43', 'a__id' => '2', 'a__topic' => 'ZendCon' - ), - array( + ], + [ 'u__id' => '2', 'u__status' => 'developer', 'sclr0' => 'JWAGE', 'p__phonenumber' => '91', 'a__id' => '3', 'a__topic' => 'LINQ' - ), - array( + ], + [ 'u__id' => '2', 'u__status' => 'developer', 'sclr0' => 'JWAGE', 'p__phonenumber' => '91', 'a__id' => '4', 'a__topic' => 'PHP7' - ), - ); + ], + ]; $stmt = new HydratorMockStatement($resultSet); $hydrator = new \Doctrine\ORM\Internal\Hydration\ArrayHydrator($this->_em); @@ -691,21 +697,21 @@ public function testMixedQueryMultipleDeepMixedFetchJoin() { $rsm = new ResultSetMapping; - $rsm->addEntityResult('Doctrine\Tests\Models\CMS\CmsUser', 'u'); + $rsm->addEntityResult(CmsUser::class, 'u'); $rsm->addJoinedEntityResult( - 'Doctrine\Tests\Models\CMS\CmsPhonenumber', + CmsPhonenumber::class, 'p', 'u', 'phonenumbers' ); $rsm->addJoinedEntityResult( - 'Doctrine\Tests\Models\CMS\CmsArticle', + CmsArticle::class, 'a', 'u', 'articles' ); $rsm->addJoinedEntityResult( - 'Doctrine\Tests\Models\CMS\CmsComment', + CmsComment::class, 'c', 'a', 'comments' @@ -720,9 +726,9 @@ public function testMixedQueryMultipleDeepMixedFetchJoin() $rsm->addFieldResult('c', 'c__topic', 'topic'); // Faked result set - $resultSet = array( + $resultSet = [ //row1 - array( + [ 'u__id' => '1', 'u__status' => 'developer', 'sclr0' => 'ROMANB', @@ -731,8 +737,8 @@ public function testMixedQueryMultipleDeepMixedFetchJoin() 'a__topic' => 'Getting things done!', 'c__id' => '1', 'c__topic' => 'First!' - ), - array( + ], + [ 'u__id' => '1', 'u__status' => 'developer', 'sclr0' => 'ROMANB', @@ -741,8 +747,8 @@ public function testMixedQueryMultipleDeepMixedFetchJoin() 'a__topic' => 'Getting things done!', 'c__id' => '1', 'c__topic' => 'First!' - ), - array( + ], + [ 'u__id' => '1', 'u__status' => 'developer', 'sclr0' => 'ROMANB', @@ -751,8 +757,8 @@ public function testMixedQueryMultipleDeepMixedFetchJoin() 'a__topic' => 'ZendCon', 'c__id' => null, 'c__topic' => null - ), - array( + ], + [ 'u__id' => '1', 'u__status' => 'developer', 'sclr0' => 'ROMANB', @@ -761,8 +767,8 @@ public function testMixedQueryMultipleDeepMixedFetchJoin() 'a__topic' => 'ZendCon', 'c__id' => null, 'c__topic' => null - ), - array( + ], + [ 'u__id' => '2', 'u__status' => 'developer', 'sclr0' => 'JWAGE', @@ -771,8 +777,8 @@ public function testMixedQueryMultipleDeepMixedFetchJoin() 'a__topic' => 'LINQ', 'c__id' => null, 'c__topic' => null - ), - array( + ], + [ 'u__id' => '2', 'u__status' => 'developer', 'sclr0' => 'JWAGE', @@ -781,8 +787,8 @@ public function testMixedQueryMultipleDeepMixedFetchJoin() 'a__topic' => 'PHP7', 'c__id' => null, 'c__topic' => null - ), - ); + ], + ]; $stmt = new HydratorMockStatement($resultSet); $hydrator = new \Doctrine\ORM\Internal\Hydration\ArrayHydrator($this->_em); @@ -848,9 +854,9 @@ public function testEntityQueryCustomResultSetOrder() { $rsm = new ResultSetMapping; - $rsm->addEntityResult('Doctrine\Tests\Models\Forum\ForumCategory', 'c'); + $rsm->addEntityResult(ForumCategory::class, 'c'); $rsm->addJoinedEntityResult( - 'Doctrine\Tests\Models\Forum\ForumBoard', + ForumBoard::class, 'b', 'c', 'boards' @@ -863,40 +869,40 @@ public function testEntityQueryCustomResultSetOrder() $rsm->addFieldResult('b', 'b__position', 'position'); // Faked result set - $resultSet = array( - array( + $resultSet = [ + [ 'c__id' => '1', 'c__position' => '0', 'c__name' => 'First', 'b__id' => '1', 'b__position' => '0', //'b__category_id' => '1' - ), - array( + ], + [ 'c__id' => '2', 'c__position' => '0', 'c__name' => 'Second', 'b__id' => '2', 'b__position' => '0', //'b__category_id' => '2' - ), - array( + ], + [ 'c__id' => '1', 'c__position' => '0', 'c__name' => 'First', 'b__id' => '3', 'b__position' => '1', //'b__category_id' => '1' - ), - array( + ], + [ 'c__id' => '1', 'c__position' => '0', 'c__name' => 'First', 'b__id' => '4', 'b__position' => '2', //'b__category_id' => '1' - ) - ); + ] + ]; $stmt = new HydratorMockStatement($resultSet); $hydrator = new \Doctrine\ORM\Internal\Hydration\ArrayHydrator($this->_em); @@ -924,7 +930,7 @@ public function testChainedJoinWithScalars($entityKey) { $rsm = new ResultSetMapping; - $rsm->addEntityResult('Doctrine\Tests\Models\CMS\CmsUser', 'u', $entityKey ?: null); + $rsm->addEntityResult(CmsUser::class, 'u', $entityKey ?: null); $rsm->addFieldResult('u', 'u__id', 'id'); $rsm->addFieldResult('u', 'u__status', 'status'); $rsm->addScalarResult('a__id', 'id', 'integer'); @@ -933,33 +939,33 @@ public function testChainedJoinWithScalars($entityKey) $rsm->addScalarResult('c__topic', 'ctopic', 'string'); // Faked result set - $resultSet = array( + $resultSet = [ //row1 - array( + [ 'u__id' => '1', 'u__status' => 'developer', 'a__id' => '1', 'a__topic' => 'The First', 'c__id' => '1', 'c__topic' => 'First Comment' - ), - array( + ], + [ 'u__id' => '1', 'u__status' => 'developer', 'a__id' => '1', 'a__topic' => 'The First', 'c__id' => '2', 'c__topic' => 'Second Comment' - ), - array( + ], + [ 'u__id' => '1', 'u__status' => 'developer', 'a__id' => '42', 'a__topic' => 'The Answer', 'c__id' => null, 'c__topic' => null - ), - ); + ], + ]; $stmt = new HydratorMockStatement($resultSet); $hydrator = new \Doctrine\ORM\Internal\Hydration\ArrayHydrator($this->_em); @@ -994,21 +1000,21 @@ public function testResultIteration() { $rsm = new ResultSetMapping; - $rsm->addEntityResult('Doctrine\Tests\Models\CMS\CmsUser', 'u'); + $rsm->addEntityResult(CmsUser::class, 'u'); $rsm->addFieldResult('u', 'u__id', 'id'); $rsm->addFieldResult('u', 'u__name', 'name'); // Faked result set - $resultSet = array( - array( + $resultSet = [ + [ 'u__id' => '1', 'u__name' => 'romanb' - ), - array( + ], + [ 'u__id' => '2', 'u__name' => 'jwage' - ) - ); + ] + ]; $stmt = new HydratorMockStatement($resultSet); $hydrator = new \Doctrine\ORM\Internal\Hydration\ArrayHydrator($this->_em); @@ -1039,21 +1045,21 @@ public function testResultIterationWithAliasedUserEntity() { $rsm = new ResultSetMapping; - $rsm->addEntityResult('Doctrine\Tests\Models\CMS\CmsUser', 'u', 'user'); + $rsm->addEntityResult(CmsUser::class, 'u', 'user'); $rsm->addFieldResult('u', 'u__id', 'id'); $rsm->addFieldResult('u', 'u__name', 'name'); // Faked result set - $resultSet = array( - array( + $resultSet = [ + [ 'u__id' => '1', 'u__name' => 'romanb' - ), - array( + ], + [ 'u__id' => '2', 'u__name' => 'jwage' - ) - ); + ] + ]; $stmt = new HydratorMockStatement($resultSet); $hydrator = new \Doctrine\ORM\Internal\Hydration\ArrayHydrator($this->_em); @@ -1087,18 +1093,18 @@ public function testSkipUnknownColumns() { $rsm = new ResultSetMapping; - $rsm->addEntityResult('Doctrine\Tests\Models\CMS\CmsUser', 'u'); + $rsm->addEntityResult(CmsUser::class, 'u'); $rsm->addFieldResult('u', 'u__id', 'id'); $rsm->addFieldResult('u', 'u__name', 'name'); // Faked result set - $resultSet = array( - array( + $resultSet = [ + [ 'u__id' => '1', 'u__name' => 'romanb', 'foo' => 'bar', // unknown! - ), - ); + ], + ]; $stmt = new HydratorMockStatement($resultSet); $hydrator = new \Doctrine\ORM\Internal\Hydration\ArrayHydrator($this->_em); @@ -1121,35 +1127,35 @@ public function testMissingIdForRootEntity($userEntityKey) { $rsm = new ResultSetMapping; - $rsm->addEntityResult('Doctrine\Tests\Models\CMS\CmsUser', 'u', $userEntityKey ?: null); + $rsm->addEntityResult(CmsUser::class, 'u', $userEntityKey ?: null); $rsm->addFieldResult('u', 'u__id', 'id'); $rsm->addFieldResult('u', 'u__status', 'status'); $rsm->addScalarResult('sclr0', 'nameUpper', 'string'); // Faked result set - $resultSet = array( + $resultSet = [ //row1 - array( + [ 'u__id' => '1', 'u__status' => 'developer', 'sclr0' => 'ROMANB', - ), - array( + ], + [ 'u__id' => null, 'u__status' => null, 'sclr0' => 'ROMANB', - ), - array( + ], + [ 'u__id' => '2', 'u__status' => 'developer', 'sclr0' => 'JWAGE', - ), - array( + ], + [ 'u__id' => null, 'u__status' => null, 'sclr0' => 'JWAGE', - ), - ); + ], + ]; $stmt = new HydratorMockStatement($resultSet); $hydrator = new \Doctrine\ORM\Internal\Hydration\ArrayHydrator($this->_em); @@ -1162,9 +1168,9 @@ public function testMissingIdForRootEntity($userEntityKey) $this->assertEquals('JWAGE', $result[2]['nameUpper']); $this->assertEquals('JWAGE', $result[3]['nameUpper']); - $this->assertEquals(array('id' => 1, 'status' => 'developer'), $result[0][$userEntityKey]); + $this->assertEquals(['id' => 1, 'status' => 'developer'], $result[0][$userEntityKey]); $this->assertNull($result[1][$userEntityKey]); - $this->assertEquals(array('id' => 2, 'status' => 'developer'), $result[2][$userEntityKey]); + $this->assertEquals(['id' => 2, 'status' => 'developer'], $result[2][$userEntityKey]); $this->assertNull($result[3][$userEntityKey]); } @@ -1180,26 +1186,26 @@ public function testIndexByAndMixedResult($userEntityKey) { $rsm = new ResultSetMapping; - $rsm->addEntityResult('Doctrine\Tests\Models\CMS\CmsUser', 'u', $userEntityKey ?: null); + $rsm->addEntityResult(CmsUser::class, 'u', $userEntityKey ?: null); $rsm->addFieldResult('u', 'u__id', 'id'); $rsm->addFieldResult('u', 'u__status', 'status'); $rsm->addScalarResult('sclr0', 'nameUpper', 'string'); $rsm->addIndexBy('u', 'id'); // Faked result set - $resultSet = array( + $resultSet = [ //row1 - array( + [ 'u__id' => '1', 'u__status' => 'developer', 'sclr0' => 'ROMANB', - ), - array( + ], + [ 'u__id' => '2', 'u__status' => 'developer', 'sclr0' => 'JWAGE', - ), - ); + ], + ]; $stmt = new HydratorMockStatement($resultSet); $hydrator = new \Doctrine\ORM\Internal\Hydration\ArrayHydrator($this->_em); diff --git a/tests/Doctrine/Tests/ORM/Hydration/CustomHydratorTest.php b/tests/Doctrine/Tests/ORM/Hydration/CustomHydratorTest.php index 1135e988d5d..7342b942f4f 100644 --- a/tests/Doctrine/Tests/ORM/Hydration/CustomHydratorTest.php +++ b/tests/Doctrine/Tests/ORM/Hydration/CustomHydratorTest.php @@ -2,7 +2,8 @@ namespace Doctrine\Tests\ORM\Hydration; -use PDO, Doctrine\ORM\Internal\Hydration\AbstractHydrator; +use Doctrine\ORM\Internal\Hydration\AbstractHydrator; +use PDO; class CustomHydratorTest extends HydrationTestCase { @@ -10,10 +11,10 @@ public function testCustomHydrator() { $em = $this->_getTestEntityManager(); $config = $em->getConfiguration(); - $config->addCustomHydrationMode('CustomHydrator', 'Doctrine\Tests\ORM\Hydration\CustomHydrator'); + $config->addCustomHydrationMode('CustomHydrator', CustomHydrator::class); $hydrator = $em->newHydrator('CustomHydrator'); - $this->assertInstanceOf('Doctrine\Tests\ORM\Hydration\CustomHydrator', $hydrator); + $this->assertInstanceOf(CustomHydrator::class, $hydrator); $this->assertNull($config->getCustomHydrationMode('does not exist')); } } diff --git a/tests/Doctrine/Tests/ORM/Hydration/ObjectHydratorTest.php b/tests/Doctrine/Tests/ORM/Hydration/ObjectHydratorTest.php index 22cf3b5985e..c7d82a0dc7a 100644 --- a/tests/Doctrine/Tests/ORM/Hydration/ObjectHydratorTest.php +++ b/tests/Doctrine/Tests/ORM/Hydration/ObjectHydratorTest.php @@ -2,11 +2,25 @@ namespace Doctrine\Tests\ORM\Hydration; -use Doctrine\ORM\Proxy\ProxyFactory; -use Doctrine\Tests\Mocks\HydratorMockStatement; -use Doctrine\ORM\Query\ResultSetMapping; use Doctrine\ORM\Mapping\ClassMetadata; +use Doctrine\ORM\PersistentCollection; +use Doctrine\ORM\Proxy\ProxyFactory; use Doctrine\ORM\Query; +use Doctrine\ORM\Query\ResultSetMapping; +use Doctrine\Tests\Mocks\HydratorMockStatement; +use Doctrine\Tests\Models\CMS\CmsAddress; +use Doctrine\Tests\Models\CMS\CmsArticle; +use Doctrine\Tests\Models\CMS\CmsComment; +use Doctrine\Tests\Models\CMS\CmsGroup; +use Doctrine\Tests\Models\CMS\CmsPhonenumber; +use Doctrine\Tests\Models\CMS\CmsUser; +use Doctrine\Tests\Models\Company\CompanyEmployee; +use Doctrine\Tests\Models\Company\CompanyFixContract; +use Doctrine\Tests\Models\Company\CompanyPerson; +use Doctrine\Tests\Models\ECommerce\ECommerceProduct; +use Doctrine\Tests\Models\ECommerce\ECommerceShipping; +use Doctrine\Tests\Models\Forum\ForumBoard; +use Doctrine\Tests\Models\Forum\ForumCategory; use Doctrine\Tests\Models\Hydration\EntityWithArrayDefaultArrayValueM2M; use Doctrine\Tests\Models\Hydration\SimpleEntity; @@ -14,28 +28,28 @@ class ObjectHydratorTest extends HydrationTestCase { public function provideDataForUserEntityResult() { - return array( - array(0), - array('user'), - ); + return [ + [0], + ['user'], + ]; } public function provideDataForMultipleRootEntityResult() { - return array( - array(0, 0), - array('user', 0), - array(0, 'article'), - array('user', 'article'), - ); + return [ + [0, 0], + ['user', 0], + [0, 'article'], + ['user', 'article'], + ]; } public function provideDataForProductEntityResult() { - return array( - array(0), - array('product'), - ); + return [ + [0], + ['product'], + ]; } /** @@ -45,30 +59,30 @@ public function provideDataForProductEntityResult() public function testSimpleEntityQuery() { $rsm = new ResultSetMapping; - $rsm->addEntityResult('Doctrine\Tests\Models\CMS\CmsUser', 'u'); + $rsm->addEntityResult(CmsUser::class, 'u'); $rsm->addFieldResult('u', 'u__id', 'id'); $rsm->addFieldResult('u', 'u__name', 'name'); // Faked result set - $resultSet = array( - array( + $resultSet = [ + [ 'u__id' => '1', 'u__name' => 'romanb' - ), - array( + ], + [ 'u__id' => '2', 'u__name' => 'jwage' - ) - ); + ] + ]; $stmt = new HydratorMockStatement($resultSet); $hydrator = new \Doctrine\ORM\Internal\Hydration\ObjectHydrator($this->_em); - $result = $hydrator->hydrateAll($stmt, $rsm, array(Query::HINT_FORCE_PARTIAL_LOAD => true)); + $result = $hydrator->hydrateAll($stmt, $rsm, [Query::HINT_FORCE_PARTIAL_LOAD => true]); $this->assertEquals(2, count($result)); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsUser', $result[0]); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsUser', $result[1]); + $this->assertInstanceOf(CmsUser::class, $result[0]); + $this->assertInstanceOf(CmsUser::class, $result[1]); $this->assertEquals(1, $result[0]->id); $this->assertEquals('romanb', $result[0]->name); @@ -84,33 +98,33 @@ public function testSimpleEntityQuery() public function testSimpleEntityQueryWithAliasedUserEntity() { $rsm = new ResultSetMapping; - $rsm->addEntityResult('Doctrine\Tests\Models\CMS\CmsUser', 'u', 'user'); + $rsm->addEntityResult(CmsUser::class, 'u', 'user'); $rsm->addFieldResult('u', 'u__id', 'id'); $rsm->addFieldResult('u', 'u__name', 'name'); // Faked result set - $resultSet = array( - array( + $resultSet = [ + [ 'u__id' => '1', 'u__name' => 'romanb' - ), - array( + ], + [ 'u__id' => '2', 'u__name' => 'jwage' - ) - ); + ] + ]; $stmt = new HydratorMockStatement($resultSet); $hydrator = new \Doctrine\ORM\Internal\Hydration\ObjectHydrator($this->_em); - $result = $hydrator->hydrateAll($stmt, $rsm, array(Query::HINT_FORCE_PARTIAL_LOAD => true)); + $result = $hydrator->hydrateAll($stmt, $rsm, [Query::HINT_FORCE_PARTIAL_LOAD => true]); $this->assertEquals(2, count($result)); $this->assertArrayHasKey('user', $result[0]); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsUser', $result[0]['user']); + $this->assertInstanceOf(CmsUser::class, $result[0]['user']); $this->assertArrayHasKey('user', $result[1]); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsUser', $result[1]['user']); + $this->assertInstanceOf(CmsUser::class, $result[1]['user']); $this->assertEquals(1, $result[0]['user']->id); $this->assertEquals('romanb', $result[0]['user']->name); @@ -126,39 +140,39 @@ public function testSimpleEntityQueryWithAliasedUserEntity() public function testSimpleMultipleRootEntityQuery() { $rsm = new ResultSetMapping; - $rsm->addEntityResult('Doctrine\Tests\Models\CMS\CmsUser', 'u'); - $rsm->addEntityResult('Doctrine\Tests\Models\CMS\CmsArticle', 'a'); + $rsm->addEntityResult(CmsUser::class, 'u'); + $rsm->addEntityResult(CmsArticle::class, 'a'); $rsm->addFieldResult('u', 'u__id', 'id'); $rsm->addFieldResult('u', 'u__name', 'name'); $rsm->addFieldResult('a', 'a__id', 'id'); $rsm->addFieldResult('a', 'a__topic', 'topic'); // Faked result set - $resultSet = array( - array( + $resultSet = [ + [ 'u__id' => '1', 'u__name' => 'romanb', 'a__id' => '1', 'a__topic' => 'Cool things.' - ), - array( + ], + [ 'u__id' => '2', 'u__name' => 'jwage', 'a__id' => '2', 'a__topic' => 'Cool things II.' - ) - ); + ] + ]; $stmt = new HydratorMockStatement($resultSet); $hydrator = new \Doctrine\ORM\Internal\Hydration\ObjectHydrator($this->_em); - $result = $hydrator->hydrateAll($stmt, $rsm, array(Query::HINT_FORCE_PARTIAL_LOAD => true)); + $result = $hydrator->hydrateAll($stmt, $rsm, [Query::HINT_FORCE_PARTIAL_LOAD => true]); $this->assertEquals(4, count($result)); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsUser', $result[0]); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsArticle', $result[1]); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsUser', $result[2]); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsArticle', $result[3]); + $this->assertInstanceOf(CmsUser::class, $result[0]); + $this->assertInstanceOf(CmsArticle::class, $result[1]); + $this->assertInstanceOf(CmsUser::class, $result[2]); + $this->assertInstanceOf(CmsArticle::class, $result[3]); $this->assertEquals(1, $result[0]->id); $this->assertEquals('romanb', $result[0]->name); @@ -180,56 +194,56 @@ public function testSimpleMultipleRootEntityQuery() public function testSimpleMultipleRootEntityQueryWithAliasedUserEntity() { $rsm = new ResultSetMapping; - $rsm->addEntityResult('Doctrine\Tests\Models\CMS\CmsUser', 'u', 'user'); - $rsm->addEntityResult('Doctrine\Tests\Models\CMS\CmsArticle', 'a'); + $rsm->addEntityResult(CmsUser::class, 'u', 'user'); + $rsm->addEntityResult(CmsArticle::class, 'a'); $rsm->addFieldResult('u', 'u__id', 'id'); $rsm->addFieldResult('u', 'u__name', 'name'); $rsm->addFieldResult('a', 'a__id', 'id'); $rsm->addFieldResult('a', 'a__topic', 'topic'); // Faked result set - $resultSet = array( - array( + $resultSet = [ + [ 'u__id' => '1', 'u__name' => 'romanb', 'a__id' => '1', 'a__topic' => 'Cool things.' - ), - array( + ], + [ 'u__id' => '2', 'u__name' => 'jwage', 'a__id' => '2', 'a__topic' => 'Cool things II.' - ) - ); + ] + ]; $stmt = new HydratorMockStatement($resultSet); $hydrator = new \Doctrine\ORM\Internal\Hydration\ObjectHydrator($this->_em); - $result = $hydrator->hydrateAll($stmt, $rsm, array(Query::HINT_FORCE_PARTIAL_LOAD => true)); + $result = $hydrator->hydrateAll($stmt, $rsm, [Query::HINT_FORCE_PARTIAL_LOAD => true]); $this->assertEquals(4, count($result)); $this->assertArrayHasKey('user', $result[0]); $this->assertArrayNotHasKey(0, $result[0]); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsUser', $result[0]['user']); + $this->assertInstanceOf(CmsUser::class, $result[0]['user']); $this->assertEquals(1, $result[0]['user']->id); $this->assertEquals('romanb', $result[0]['user']->name); $this->assertArrayHasKey(0, $result[1]); $this->assertArrayNotHasKey('user', $result[1]); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsArticle', $result[1][0]); + $this->assertInstanceOf(CmsArticle::class, $result[1][0]); $this->assertEquals(1, $result[1][0]->id); $this->assertEquals('Cool things.', $result[1][0]->topic); $this->assertArrayHasKey('user', $result[2]); $this->assertArrayNotHasKey(0, $result[2]); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsUser', $result[2]['user']); + $this->assertInstanceOf(CmsUser::class, $result[2]['user']); $this->assertEquals(2, $result[2]['user']->id); $this->assertEquals('jwage', $result[2]['user']->name); $this->assertArrayHasKey(0, $result[3]); $this->assertArrayNotHasKey('user', $result[3]); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsArticle', $result[3][0]); + $this->assertInstanceOf(CmsArticle::class, $result[3][0]); $this->assertEquals(2, $result[3][0]->id); $this->assertEquals('Cool things II.', $result[3][0]->topic); } @@ -241,56 +255,56 @@ public function testSimpleMultipleRootEntityQueryWithAliasedUserEntity() public function testSimpleMultipleRootEntityQueryWithAliasedArticleEntity() { $rsm = new ResultSetMapping; - $rsm->addEntityResult('Doctrine\Tests\Models\CMS\CmsUser', 'u'); - $rsm->addEntityResult('Doctrine\Tests\Models\CMS\CmsArticle', 'a', 'article'); + $rsm->addEntityResult(CmsUser::class, 'u'); + $rsm->addEntityResult(CmsArticle::class, 'a', 'article'); $rsm->addFieldResult('u', 'u__id', 'id'); $rsm->addFieldResult('u', 'u__name', 'name'); $rsm->addFieldResult('a', 'a__id', 'id'); $rsm->addFieldResult('a', 'a__topic', 'topic'); // Faked result set - $resultSet = array( - array( + $resultSet = [ + [ 'u__id' => '1', 'u__name' => 'romanb', 'a__id' => '1', 'a__topic' => 'Cool things.' - ), - array( + ], + [ 'u__id' => '2', 'u__name' => 'jwage', 'a__id' => '2', 'a__topic' => 'Cool things II.' - ) - ); + ] + ]; $stmt = new HydratorMockStatement($resultSet); $hydrator = new \Doctrine\ORM\Internal\Hydration\ObjectHydrator($this->_em); - $result = $hydrator->hydrateAll($stmt, $rsm, array(Query::HINT_FORCE_PARTIAL_LOAD => true)); + $result = $hydrator->hydrateAll($stmt, $rsm, [Query::HINT_FORCE_PARTIAL_LOAD => true]); $this->assertEquals(4, count($result)); $this->assertArrayHasKey(0, $result[0]); $this->assertArrayNotHasKey('article', $result[0]); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsUser', $result[0][0]); + $this->assertInstanceOf(CmsUser::class, $result[0][0]); $this->assertEquals(1, $result[0][0]->id); $this->assertEquals('romanb', $result[0][0]->name); $this->assertArrayHasKey('article', $result[1]); $this->assertArrayNotHasKey(0, $result[1]); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsArticle', $result[1]['article']); + $this->assertInstanceOf(CmsArticle::class, $result[1]['article']); $this->assertEquals(1, $result[1]['article']->id); $this->assertEquals('Cool things.', $result[1]['article']->topic); $this->assertArrayHasKey(0, $result[2]); $this->assertArrayNotHasKey('article', $result[2]); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsUser', $result[2][0]); + $this->assertInstanceOf(CmsUser::class, $result[2][0]); $this->assertEquals(2, $result[2][0]->id); $this->assertEquals('jwage', $result[2][0]->name); $this->assertArrayHasKey('article', $result[3]); $this->assertArrayNotHasKey(0, $result[3]); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsArticle', $result[3]['article']); + $this->assertInstanceOf(CmsArticle::class, $result[3]['article']); $this->assertEquals(2, $result[3]['article']->id); $this->assertEquals('Cool things II.', $result[3]['article']->topic); } @@ -302,56 +316,56 @@ public function testSimpleMultipleRootEntityQueryWithAliasedArticleEntity() public function testSimpleMultipleRootEntityQueryWithAliasedEntities() { $rsm = new ResultSetMapping; - $rsm->addEntityResult('Doctrine\Tests\Models\CMS\CmsUser', 'u', 'user'); - $rsm->addEntityResult('Doctrine\Tests\Models\CMS\CmsArticle', 'a', 'article'); + $rsm->addEntityResult(CmsUser::class, 'u', 'user'); + $rsm->addEntityResult(CmsArticle::class, 'a', 'article'); $rsm->addFieldResult('u', 'u__id', 'id'); $rsm->addFieldResult('u', 'u__name', 'name'); $rsm->addFieldResult('a', 'a__id', 'id'); $rsm->addFieldResult('a', 'a__topic', 'topic'); // Faked result set - $resultSet = array( - array( + $resultSet = [ + [ 'u__id' => '1', 'u__name' => 'romanb', 'a__id' => '1', 'a__topic' => 'Cool things.' - ), - array( + ], + [ 'u__id' => '2', 'u__name' => 'jwage', 'a__id' => '2', 'a__topic' => 'Cool things II.' - ) - ); + ] + ]; $stmt = new HydratorMockStatement($resultSet); $hydrator = new \Doctrine\ORM\Internal\Hydration\ObjectHydrator($this->_em); - $result = $hydrator->hydrateAll($stmt, $rsm, array(Query::HINT_FORCE_PARTIAL_LOAD => true)); + $result = $hydrator->hydrateAll($stmt, $rsm, [Query::HINT_FORCE_PARTIAL_LOAD => true]); $this->assertEquals(4, count($result)); $this->assertArrayHasKey('user', $result[0]); $this->assertArrayNotHasKey('article', $result[0]); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsUser', $result[0]['user']); + $this->assertInstanceOf(CmsUser::class, $result[0]['user']); $this->assertEquals(1, $result[0]['user']->id); $this->assertEquals('romanb', $result[0]['user']->name); $this->assertArrayHasKey('article', $result[1]); $this->assertArrayNotHasKey('user', $result[1]); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsArticle', $result[1]['article']); + $this->assertInstanceOf(CmsArticle::class, $result[1]['article']); $this->assertEquals(1, $result[1]['article']->id); $this->assertEquals('Cool things.', $result[1]['article']->topic); $this->assertArrayHasKey('user', $result[2]); $this->assertArrayNotHasKey('article', $result[2]); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsUser', $result[2]['user']); + $this->assertInstanceOf(CmsUser::class, $result[2]['user']); $this->assertEquals(2, $result[2]['user']->id); $this->assertEquals('jwage', $result[2]['user']->name); $this->assertArrayHasKey('article', $result[3]); $this->assertArrayNotHasKey('user', $result[3]); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsArticle', $result[3]['article']); + $this->assertInstanceOf(CmsArticle::class, $result[3]['article']); $this->assertEquals(2, $result[3]['article']->id); $this->assertEquals('Cool things II.', $result[3]['article']->topic); } @@ -367,29 +381,29 @@ public function testSimpleMultipleRootEntityQueryWithAliasedEntities() public function testMixedQueryNormalJoin($userEntityKey) { $rsm = new ResultSetMapping; - $rsm->addEntityResult('Doctrine\Tests\Models\CMS\CmsUser', 'u', $userEntityKey ?: null); + $rsm->addEntityResult(CmsUser::class, 'u', $userEntityKey ?: null); $rsm->addFieldResult('u', 'u__id', 'id'); $rsm->addFieldResult('u', 'u__status', 'status'); $rsm->addScalarResult('sclr0', 'numPhones', 'integer'); // Faked result set - $resultSet = array( + $resultSet = [ //row1 - array( + [ 'u__id' => '1', 'u__status' => 'developer', 'sclr0' => '2', - ), - array( + ], + [ 'u__id' => '2', 'u__status' => 'developer', 'sclr0' => '1', - ) - ); + ] + ]; $stmt = new HydratorMockStatement($resultSet); $hydrator = new \Doctrine\ORM\Internal\Hydration\ObjectHydrator($this->_em); - $result = $hydrator->hydrateAll($stmt, $rsm, array(Query::HINT_FORCE_PARTIAL_LOAD => true)); + $result = $hydrator->hydrateAll($stmt, $rsm, [Query::HINT_FORCE_PARTIAL_LOAD => true]); $this->assertEquals(2, count($result)); @@ -399,11 +413,11 @@ public function testMixedQueryNormalJoin($userEntityKey) // first user => 2 phonenumbers $this->assertEquals(2, $result[0]['numPhones']); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsUser', $result[0][$userEntityKey]); + $this->assertInstanceOf(CmsUser::class, $result[0][$userEntityKey]); // second user => 1 phonenumber $this->assertEquals(1, $result[1]['numPhones']); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsUser', $result[1][$userEntityKey]); + $this->assertInstanceOf(CmsUser::class, $result[1][$userEntityKey]); } /** @@ -416,9 +430,9 @@ public function testMixedQueryNormalJoin($userEntityKey) public function testMixedQueryFetchJoin($userEntityKey) { $rsm = new ResultSetMapping; - $rsm->addEntityResult('Doctrine\Tests\Models\CMS\CmsUser', 'u', $userEntityKey ?: null); + $rsm->addEntityResult(CmsUser::class, 'u', $userEntityKey ?: null); $rsm->addJoinedEntityResult( - 'Doctrine\Tests\Models\CMS\CmsPhonenumber', + CmsPhonenumber::class, 'p', 'u', 'phonenumbers' @@ -429,31 +443,31 @@ public function testMixedQueryFetchJoin($userEntityKey) $rsm->addScalarResult('sclr0', 'nameUpper', 'string'); // Faked result set - $resultSet = array( + $resultSet = [ //row1 - array( + [ 'u__id' => '1', 'u__status' => 'developer', 'p__phonenumber' => '42', 'sclr0' => 'ROMANB', - ), - array( + ], + [ 'u__id' => '1', 'u__status' => 'developer', 'p__phonenumber' => '43', 'sclr0' => 'ROMANB', - ), - array( + ], + [ 'u__id' => '2', 'u__status' => 'developer', 'p__phonenumber' => '91', 'sclr0' => 'JWAGE', - ) - ); + ] + ]; $stmt = new HydratorMockStatement($resultSet); $hydrator = new \Doctrine\ORM\Internal\Hydration\ObjectHydrator($this->_em); - $result = $hydrator->hydrateAll($stmt, $rsm, array(Query::HINT_FORCE_PARTIAL_LOAD => true)); + $result = $hydrator->hydrateAll($stmt, $rsm, [Query::HINT_FORCE_PARTIAL_LOAD => true]); $this->assertEquals(2, count($result)); @@ -461,13 +475,13 @@ public function testMixedQueryFetchJoin($userEntityKey) $this->assertInternalType('array', $result[0]); $this->assertInternalType('array', $result[1]); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsUser', $result[0][$userEntityKey]); - $this->assertInstanceOf('Doctrine\ORM\PersistentCollection', $result[0][$userEntityKey]->phonenumbers); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsPhonenumber', $result[0][$userEntityKey]->phonenumbers[0]); + $this->assertInstanceOf(CmsUser::class, $result[0][$userEntityKey]); + $this->assertInstanceOf(PersistentCollection::class, $result[0][$userEntityKey]->phonenumbers); + $this->assertInstanceOf(CmsPhonenumber::class, $result[0][$userEntityKey]->phonenumbers[0]); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsUser', $result[1][$userEntityKey]); - $this->assertInstanceOf('Doctrine\ORM\PersistentCollection', $result[1][$userEntityKey]->phonenumbers); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsPhonenumber', $result[0][$userEntityKey]->phonenumbers[1]); + $this->assertInstanceOf(CmsUser::class, $result[1][$userEntityKey]); + $this->assertInstanceOf(PersistentCollection::class, $result[1][$userEntityKey]->phonenumbers); + $this->assertInstanceOf(CmsPhonenumber::class, $result[0][$userEntityKey]->phonenumbers[1]); // first user => 2 phonenumbers $this->assertEquals(2, count($result[0][$userEntityKey]->phonenumbers)); @@ -494,9 +508,9 @@ public function testMixedQueryFetchJoin($userEntityKey) public function testMixedQueryFetchJoinCustomIndex($userEntityKey) { $rsm = new ResultSetMapping; - $rsm->addEntityResult('Doctrine\Tests\Models\CMS\CmsUser', 'u', $userEntityKey ?: null); + $rsm->addEntityResult(CmsUser::class, 'u', $userEntityKey ?: null); $rsm->addJoinedEntityResult( - 'Doctrine\Tests\Models\CMS\CmsPhonenumber', + CmsPhonenumber::class, 'p', 'u', 'phonenumbers' @@ -509,32 +523,32 @@ public function testMixedQueryFetchJoinCustomIndex($userEntityKey) $rsm->addIndexBy('p', 'phonenumber'); // Faked result set - $resultSet = array( + $resultSet = [ //row1 - array( + [ 'u__id' => '1', 'u__status' => 'developer', 'sclr0' => 'ROMANB', 'p__phonenumber' => '42', - ), - array( + ], + [ 'u__id' => '1', 'u__status' => 'developer', 'sclr0' => 'ROMANB', 'p__phonenumber' => '43', - ), - array( + ], + [ 'u__id' => '2', 'u__status' => 'developer', 'sclr0' => 'JWAGE', 'p__phonenumber' => '91' - ) - ); + ] + ]; $stmt = new HydratorMockStatement($resultSet); $hydrator = new \Doctrine\ORM\Internal\Hydration\ObjectHydrator($this->_em); - $result = $hydrator->hydrateAll($stmt, $rsm, array(Query::HINT_FORCE_PARTIAL_LOAD => true)); + $result = $hydrator->hydrateAll($stmt, $rsm, [Query::HINT_FORCE_PARTIAL_LOAD => true]); $this->assertEquals(2, count($result)); @@ -546,9 +560,9 @@ public function testMixedQueryFetchJoinCustomIndex($userEntityKey) $this->assertEquals('ROMANB', $result[1]['nameUpper']); $this->assertEquals('JWAGE', $result[2]['nameUpper']); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsUser', $result[1][$userEntityKey]); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsUser', $result[2][$userEntityKey]); - $this->assertInstanceOf('Doctrine\ORM\PersistentCollection', $result[1][$userEntityKey]->phonenumbers); + $this->assertInstanceOf(CmsUser::class, $result[1][$userEntityKey]); + $this->assertInstanceOf(CmsUser::class, $result[2][$userEntityKey]); + $this->assertInstanceOf(PersistentCollection::class, $result[1][$userEntityKey]->phonenumbers); // first user => 2 phonenumbers. notice the custom indexing by user id $this->assertEquals(2, count($result[1][$userEntityKey]->phonenumbers)); @@ -573,15 +587,15 @@ public function testMixedQueryFetchJoinCustomIndex($userEntityKey) public function testMixedQueryMultipleFetchJoin($userEntityKey) { $rsm = new ResultSetMapping; - $rsm->addEntityResult('Doctrine\Tests\Models\CMS\CmsUser', 'u', $userEntityKey ?: null); + $rsm->addEntityResult(CmsUser::class, 'u', $userEntityKey ?: null); $rsm->addJoinedEntityResult( - 'Doctrine\Tests\Models\CMS\CmsPhonenumber', + CmsPhonenumber::class, 'p', 'u', 'phonenumbers' ); $rsm->addJoinedEntityResult( - 'Doctrine\Tests\Models\CMS\CmsArticle', + CmsArticle::class, 'a', 'u', 'articles' @@ -594,61 +608,61 @@ public function testMixedQueryMultipleFetchJoin($userEntityKey) $rsm->addFieldResult('a', 'a__topic', 'topic'); // Faked result set - $resultSet = array( + $resultSet = [ //row1 - array( + [ 'u__id' => '1', 'u__status' => 'developer', 'sclr0' => 'ROMANB', 'p__phonenumber' => '42', 'a__id' => '1', 'a__topic' => 'Getting things done!' - ), - array( + ], + [ 'u__id' => '1', 'u__status' => 'developer', 'sclr0' => 'ROMANB', 'p__phonenumber' => '43', 'a__id' => '1', 'a__topic' => 'Getting things done!' - ), - array( + ], + [ 'u__id' => '1', 'u__status' => 'developer', 'sclr0' => 'ROMANB', 'p__phonenumber' => '42', 'a__id' => '2', 'a__topic' => 'ZendCon' - ), - array( + ], + [ 'u__id' => '1', 'u__status' => 'developer', 'sclr0' => 'ROMANB', 'p__phonenumber' => '43', 'a__id' => '2', 'a__topic' => 'ZendCon' - ), - array( + ], + [ 'u__id' => '2', 'u__status' => 'developer', 'sclr0' => 'JWAGE', 'p__phonenumber' => '91', 'a__id' => '3', 'a__topic' => 'LINQ' - ), - array( + ], + [ 'u__id' => '2', 'u__status' => 'developer', 'sclr0' => 'JWAGE', 'p__phonenumber' => '91', 'a__id' => '4', 'a__topic' => 'PHP7' - ), - ); + ], + ]; $stmt = new HydratorMockStatement($resultSet); $hydrator = new \Doctrine\ORM\Internal\Hydration\ObjectHydrator($this->_em); - $result = $hydrator->hydrateAll($stmt, $rsm, array(Query::HINT_FORCE_PARTIAL_LOAD => true)); + $result = $hydrator->hydrateAll($stmt, $rsm, [Query::HINT_FORCE_PARTIAL_LOAD => true]); $this->assertEquals(2, count($result)); @@ -656,19 +670,19 @@ public function testMixedQueryMultipleFetchJoin($userEntityKey) $this->assertTrue(is_array($result[0])); $this->assertTrue(is_array($result[1])); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsUser', $result[0][$userEntityKey]); - $this->assertInstanceOf('Doctrine\ORM\PersistentCollection', $result[0][$userEntityKey]->phonenumbers); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsPhonenumber', $result[0][$userEntityKey]->phonenumbers[0]); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsPhonenumber', $result[0][$userEntityKey]->phonenumbers[1]); - $this->assertInstanceOf('Doctrine\ORM\PersistentCollection', $result[0][$userEntityKey]->articles); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsArticle', $result[0][$userEntityKey]->articles[0]); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsArticle', $result[0][$userEntityKey]->articles[1]); - - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsUser', $result[1][$userEntityKey]); - $this->assertInstanceOf('Doctrine\ORM\PersistentCollection', $result[1][$userEntityKey]->phonenumbers); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsPhonenumber', $result[1][$userEntityKey]->phonenumbers[0]); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsArticle', $result[1][$userEntityKey]->articles[0]); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsArticle', $result[1][$userEntityKey]->articles[1]); + $this->assertInstanceOf(CmsUser::class, $result[0][$userEntityKey]); + $this->assertInstanceOf(PersistentCollection::class, $result[0][$userEntityKey]->phonenumbers); + $this->assertInstanceOf(CmsPhonenumber::class, $result[0][$userEntityKey]->phonenumbers[0]); + $this->assertInstanceOf(CmsPhonenumber::class, $result[0][$userEntityKey]->phonenumbers[1]); + $this->assertInstanceOf(PersistentCollection::class, $result[0][$userEntityKey]->articles); + $this->assertInstanceOf(CmsArticle::class, $result[0][$userEntityKey]->articles[0]); + $this->assertInstanceOf(CmsArticle::class, $result[0][$userEntityKey]->articles[1]); + + $this->assertInstanceOf(CmsUser::class, $result[1][$userEntityKey]); + $this->assertInstanceOf(PersistentCollection::class, $result[1][$userEntityKey]->phonenumbers); + $this->assertInstanceOf(CmsPhonenumber::class, $result[1][$userEntityKey]->phonenumbers[0]); + $this->assertInstanceOf(CmsArticle::class, $result[1][$userEntityKey]->articles[0]); + $this->assertInstanceOf(CmsArticle::class, $result[1][$userEntityKey]->articles[1]); } /** @@ -683,21 +697,21 @@ public function testMixedQueryMultipleFetchJoin($userEntityKey) public function testMixedQueryMultipleDeepMixedFetchJoin($userEntityKey) { $rsm = new ResultSetMapping; - $rsm->addEntityResult('Doctrine\Tests\Models\CMS\CmsUser', 'u', $userEntityKey ?: null); + $rsm->addEntityResult(CmsUser::class, 'u', $userEntityKey ?: null); $rsm->addJoinedEntityResult( - 'Doctrine\Tests\Models\CMS\CmsPhonenumber', + CmsPhonenumber::class, 'p', 'u', 'phonenumbers' ); $rsm->addJoinedEntityResult( - 'Doctrine\Tests\Models\CMS\CmsArticle', + CmsArticle::class, 'a', 'u', 'articles' ); $rsm->addJoinedEntityResult( - 'Doctrine\Tests\Models\CMS\CmsComment', + CmsComment::class, 'c', 'a', 'comments' @@ -712,9 +726,9 @@ public function testMixedQueryMultipleDeepMixedFetchJoin($userEntityKey) $rsm->addFieldResult('c', 'c__topic', 'topic'); // Faked result set - $resultSet = array( + $resultSet = [ //row1 - array( + [ 'u__id' => '1', 'u__status' => 'developer', 'sclr0' => 'ROMANB', @@ -723,8 +737,8 @@ public function testMixedQueryMultipleDeepMixedFetchJoin($userEntityKey) 'a__topic' => 'Getting things done!', 'c__id' => '1', 'c__topic' => 'First!' - ), - array( + ], + [ 'u__id' => '1', 'u__status' => 'developer', 'sclr0' => 'ROMANB', @@ -733,8 +747,8 @@ public function testMixedQueryMultipleDeepMixedFetchJoin($userEntityKey) 'a__topic' => 'Getting things done!', 'c__id' => '1', 'c__topic' => 'First!' - ), - array( + ], + [ 'u__id' => '1', 'u__status' => 'developer', 'sclr0' => 'ROMANB', @@ -743,8 +757,8 @@ public function testMixedQueryMultipleDeepMixedFetchJoin($userEntityKey) 'a__topic' => 'ZendCon', 'c__id' => null, 'c__topic' => null - ), - array( + ], + [ 'u__id' => '1', 'u__status' => 'developer', 'sclr0' => 'ROMANB', @@ -753,8 +767,8 @@ public function testMixedQueryMultipleDeepMixedFetchJoin($userEntityKey) 'a__topic' => 'ZendCon', 'c__id' => null, 'c__topic' => null - ), - array( + ], + [ 'u__id' => '2', 'u__status' => 'developer', 'sclr0' => 'JWAGE', @@ -763,8 +777,8 @@ public function testMixedQueryMultipleDeepMixedFetchJoin($userEntityKey) 'a__topic' => 'LINQ', 'c__id' => null, 'c__topic' => null - ), - array( + ], + [ 'u__id' => '2', 'u__status' => 'developer', 'sclr0' => 'JWAGE', @@ -773,12 +787,12 @@ public function testMixedQueryMultipleDeepMixedFetchJoin($userEntityKey) 'a__topic' => 'PHP7', 'c__id' => null, 'c__topic' => null - ), - ); + ], + ]; $stmt = new HydratorMockStatement($resultSet); $hydrator = new \Doctrine\ORM\Internal\Hydration\ObjectHydrator($this->_em); - $result = $hydrator->hydrateAll($stmt, $rsm, array(Query::HINT_FORCE_PARTIAL_LOAD => true)); + $result = $hydrator->hydrateAll($stmt, $rsm, [Query::HINT_FORCE_PARTIAL_LOAD => true]); $this->assertEquals(2, count($result)); @@ -786,36 +800,36 @@ public function testMixedQueryMultipleDeepMixedFetchJoin($userEntityKey) $this->assertTrue(is_array($result[0])); $this->assertTrue(is_array($result[1])); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsUser', $result[0][$userEntityKey]); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsUser', $result[1][$userEntityKey]); + $this->assertInstanceOf(CmsUser::class, $result[0][$userEntityKey]); + $this->assertInstanceOf(CmsUser::class, $result[1][$userEntityKey]); // phonenumbers - $this->assertInstanceOf('Doctrine\ORM\PersistentCollection', $result[0][$userEntityKey]->phonenumbers); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsPhonenumber', $result[0][$userEntityKey]->phonenumbers[0]); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsPhonenumber', $result[0][$userEntityKey]->phonenumbers[1]); + $this->assertInstanceOf(PersistentCollection::class, $result[0][$userEntityKey]->phonenumbers); + $this->assertInstanceOf(CmsPhonenumber::class, $result[0][$userEntityKey]->phonenumbers[0]); + $this->assertInstanceOf(CmsPhonenumber::class, $result[0][$userEntityKey]->phonenumbers[1]); - $this->assertInstanceOf('Doctrine\ORM\PersistentCollection', $result[1][$userEntityKey]->phonenumbers); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsPhonenumber', $result[1][$userEntityKey]->phonenumbers[0]); + $this->assertInstanceOf(PersistentCollection::class, $result[1][$userEntityKey]->phonenumbers); + $this->assertInstanceOf(CmsPhonenumber::class, $result[1][$userEntityKey]->phonenumbers[0]); // articles - $this->assertInstanceOf('Doctrine\ORM\PersistentCollection', $result[0][$userEntityKey]->articles); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsArticle', $result[0][$userEntityKey]->articles[0]); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsArticle', $result[0][$userEntityKey]->articles[1]); + $this->assertInstanceOf(PersistentCollection::class, $result[0][$userEntityKey]->articles); + $this->assertInstanceOf(CmsArticle::class, $result[0][$userEntityKey]->articles[0]); + $this->assertInstanceOf(CmsArticle::class, $result[0][$userEntityKey]->articles[1]); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsArticle', $result[1][$userEntityKey]->articles[0]); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsArticle', $result[1][$userEntityKey]->articles[1]); + $this->assertInstanceOf(CmsArticle::class, $result[1][$userEntityKey]->articles[0]); + $this->assertInstanceOf(CmsArticle::class, $result[1][$userEntityKey]->articles[1]); // article comments - $this->assertInstanceOf('Doctrine\ORM\PersistentCollection', $result[0][$userEntityKey]->articles[0]->comments); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsComment', $result[0][$userEntityKey]->articles[0]->comments[0]); + $this->assertInstanceOf(PersistentCollection::class, $result[0][$userEntityKey]->articles[0]->comments); + $this->assertInstanceOf(CmsComment::class, $result[0][$userEntityKey]->articles[0]->comments[0]); // empty comment collections - $this->assertInstanceOf('Doctrine\ORM\PersistentCollection', $result[0][$userEntityKey]->articles[1]->comments); + $this->assertInstanceOf(PersistentCollection::class, $result[0][$userEntityKey]->articles[1]->comments); $this->assertEquals(0, count($result[0][$userEntityKey]->articles[1]->comments)); - $this->assertInstanceOf('Doctrine\ORM\PersistentCollection', $result[1][$userEntityKey]->articles[0]->comments); + $this->assertInstanceOf(PersistentCollection::class, $result[1][$userEntityKey]->articles[0]->comments); $this->assertEquals(0, count($result[1][$userEntityKey]->articles[0]->comments)); - $this->assertInstanceOf('Doctrine\ORM\PersistentCollection', $result[1][$userEntityKey]->articles[1]->comments); + $this->assertInstanceOf(PersistentCollection::class, $result[1][$userEntityKey]->articles[1]->comments); $this->assertEquals(0, count($result[1][$userEntityKey]->articles[1]->comments)); } @@ -840,9 +854,9 @@ public function testMixedQueryMultipleDeepMixedFetchJoin($userEntityKey) public function testEntityQueryCustomResultSetOrder() { $rsm = new ResultSetMapping; - $rsm->addEntityResult('Doctrine\Tests\Models\Forum\ForumCategory', 'c'); + $rsm->addEntityResult(ForumCategory::class, 'c'); $rsm->addJoinedEntityResult( - 'Doctrine\Tests\Models\Forum\ForumBoard', + ForumBoard::class, 'b', 'c', 'boards' @@ -854,49 +868,49 @@ public function testEntityQueryCustomResultSetOrder() $rsm->addFieldResult('b', 'b__position', 'position'); // Faked result set - $resultSet = array( - array( + $resultSet = [ + [ 'c__id' => '1', 'c__position' => '0', 'c__name' => 'First', 'b__id' => '1', 'b__position' => '0', //'b__category_id' => '1' - ), - array( + ], + [ 'c__id' => '2', 'c__position' => '0', 'c__name' => 'Second', 'b__id' => '2', 'b__position' => '0', //'b__category_id' => '2' - ), - array( + ], + [ 'c__id' => '1', 'c__position' => '0', 'c__name' => 'First', 'b__id' => '3', 'b__position' => '1', //'b__category_id' => '1' - ), - array( + ], + [ 'c__id' => '1', 'c__position' => '0', 'c__name' => 'First', 'b__id' => '4', 'b__position' => '2', //'b__category_id' => '1' - ) - ); + ] + ]; $stmt = new HydratorMockStatement($resultSet); $hydrator = new \Doctrine\ORM\Internal\Hydration\ObjectHydrator($this->_em); - $result = $hydrator->hydrateAll($stmt, $rsm, array(Query::HINT_FORCE_PARTIAL_LOAD => true)); + $result = $hydrator->hydrateAll($stmt, $rsm, [Query::HINT_FORCE_PARTIAL_LOAD => true]); $this->assertEquals(2, count($result)); - $this->assertInstanceOf('Doctrine\Tests\Models\Forum\ForumCategory', $result[0]); - $this->assertInstanceOf('Doctrine\Tests\Models\Forum\ForumCategory', $result[1]); + $this->assertInstanceOf(ForumCategory::class, $result[0]); + $this->assertInstanceOf(ForumCategory::class, $result[1]); $this->assertTrue($result[0] !== $result[1]); @@ -919,25 +933,25 @@ public function testEntityQueryCustomResultSetOrder() public function testSkipUnknownColumns() { $rsm = new ResultSetMapping; - $rsm->addEntityResult('Doctrine\Tests\Models\CMS\CmsUser', 'u'); + $rsm->addEntityResult(CmsUser::class, 'u'); $rsm->addFieldResult('u', 'u__id', 'id'); $rsm->addFieldResult('u', 'u__name', 'name'); // Faked result set - $resultSet = array( - array( + $resultSet = [ + [ 'u__id' => '1', 'u__name' => 'romanb', 'foo' => 'bar', // unknown! - ), - ); + ], + ]; $stmt = new HydratorMockStatement($resultSet); $hydrator = new \Doctrine\ORM\Internal\Hydration\ObjectHydrator($this->_em); - $result = $hydrator->hydrateAll($stmt, $rsm, array(Query::HINT_FORCE_PARTIAL_LOAD => true)); + $result = $hydrator->hydrateAll($stmt, $rsm, [Query::HINT_FORCE_PARTIAL_LOAD => true]); $this->assertEquals(1, count($result)); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsUser', $result[0]); + $this->assertInstanceOf(CmsUser::class, $result[0]); } /** @@ -949,25 +963,25 @@ public function testSkipUnknownColumns() public function testScalarQueryWithoutResultVariables($userEntityKey) { $rsm = new ResultSetMapping; - $rsm->addEntityResult('Doctrine\Tests\Models\CMS\CmsUser', 'u', $userEntityKey ?: null); + $rsm->addEntityResult(CmsUser::class, 'u', $userEntityKey ?: null); $rsm->addScalarResult('sclr0', 'id', 'integer'); $rsm->addScalarResult('sclr1', 'name', 'string'); // Faked result set - $resultSet = array( - array( + $resultSet = [ + [ 'sclr0' => '1', 'sclr1' => 'romanb' - ), - array( + ], + [ 'sclr0' => '2', 'sclr1' => 'jwage' - ) - ); + ] + ]; $stmt = new HydratorMockStatement($resultSet); $hydrator = new \Doctrine\ORM\Internal\Hydration\ObjectHydrator($this->_em); - $result = $hydrator->hydrateAll($stmt, $rsm, array(Query::HINT_FORCE_PARTIAL_LOAD => true)); + $result = $hydrator->hydrateAll($stmt, $rsm, [Query::HINT_FORCE_PARTIAL_LOAD => true]); $this->assertEquals(2, count($result)); @@ -988,37 +1002,37 @@ public function testScalarQueryWithoutResultVariables($userEntityKey) public function testCreatesProxyForLazyLoadingWithForeignKeys() { $rsm = new ResultSetMapping; - $rsm->addEntityResult('Doctrine\Tests\Models\ECommerce\ECommerceProduct', 'p'); + $rsm->addEntityResult(ECommerceProduct::class, 'p'); $rsm->addFieldResult('p', 'p__id', 'id'); $rsm->addFieldResult('p', 'p__name', 'name'); $rsm->addMetaResult('p', 'p__shipping_id', 'shipping_id', false, 'integer'); // Faked result set - $resultSet = array( - array( + $resultSet = [ + [ 'p__id' => '1', 'p__name' => 'Doctrine Book', 'p__shipping_id' => 42 - ) - ); + ] + ]; $proxyInstance = new \Doctrine\Tests\Models\ECommerce\ECommerceShipping(); // mocking the proxy factory $proxyFactory = $this->getMockBuilder(ProxyFactory::class) - ->setMethods(array('getProxy')) + ->setMethods(['getProxy']) ->disableOriginalConstructor() ->getMock(); $proxyFactory->expects($this->once()) ->method('getProxy') - ->with($this->equalTo('Doctrine\Tests\Models\ECommerce\ECommerceShipping'), array('id' => 42)) + ->with($this->equalTo(ECommerceShipping::class), ['id' => 42]) ->will($this->returnValue($proxyInstance)); $this->_em->setProxyFactory($proxyFactory); // configuring lazy loading - $metadata = $this->_em->getClassMetadata('Doctrine\Tests\Models\ECommerce\ECommerceProduct'); + $metadata = $this->_em->getClassMetadata(ECommerceProduct::class); $metadata->associationMappings['shipping']['fetch'] = ClassMetadata::FETCH_LAZY; $stmt = new HydratorMockStatement($resultSet); @@ -1027,7 +1041,7 @@ public function testCreatesProxyForLazyLoadingWithForeignKeys() $this->assertEquals(1, count($result)); - $this->assertInstanceOf('Doctrine\Tests\Models\ECommerce\ECommerceProduct', $result[0]); + $this->assertInstanceOf(ECommerceProduct::class, $result[0]); } /** @@ -1037,37 +1051,37 @@ public function testCreatesProxyForLazyLoadingWithForeignKeys() public function testCreatesProxyForLazyLoadingWithForeignKeysWithAliasedProductEntity() { $rsm = new ResultSetMapping; - $rsm->addEntityResult('Doctrine\Tests\Models\ECommerce\ECommerceProduct', 'p', 'product'); + $rsm->addEntityResult(ECommerceProduct::class, 'p', 'product'); $rsm->addFieldResult('p', 'p__id', 'id'); $rsm->addFieldResult('p', 'p__name', 'name'); $rsm->addMetaResult('p', 'p__shipping_id', 'shipping_id', false, 'integer'); // Faked result set - $resultSet = array( - array( + $resultSet = [ + [ 'p__id' => '1', 'p__name' => 'Doctrine Book', 'p__shipping_id' => 42 - ) - ); + ] + ]; $proxyInstance = new \Doctrine\Tests\Models\ECommerce\ECommerceShipping(); // mocking the proxy factory $proxyFactory = $this->getMockBuilder(ProxyFactory::class) - ->setMethods(array('getProxy')) + ->setMethods(['getProxy']) ->disableOriginalConstructor() ->getMock(); $proxyFactory->expects($this->once()) ->method('getProxy') - ->with($this->equalTo('Doctrine\Tests\Models\ECommerce\ECommerceShipping'), array('id' => 42)) + ->with($this->equalTo(ECommerceShipping::class), ['id' => 42]) ->will($this->returnValue($proxyInstance)); $this->_em->setProxyFactory($proxyFactory); // configuring lazy loading - $metadata = $this->_em->getClassMetadata('Doctrine\Tests\Models\ECommerce\ECommerceProduct'); + $metadata = $this->_em->getClassMetadata(ECommerceProduct::class); $metadata->associationMappings['shipping']['fetch'] = ClassMetadata::FETCH_LAZY; $stmt = new HydratorMockStatement($resultSet); @@ -1077,7 +1091,7 @@ public function testCreatesProxyForLazyLoadingWithForeignKeysWithAliasedProductE $this->assertEquals(1, count($result)); $this->assertInternalType('array', $result[0]); - $this->assertInstanceOf('Doctrine\Tests\Models\ECommerce\ECommerceProduct', $result[0]['product']); + $this->assertInstanceOf(ECommerceProduct::class, $result[0]['product']); } /** @@ -1089,15 +1103,15 @@ public function testCreatesProxyForLazyLoadingWithForeignKeysWithAliasedProductE public function testChainedJoinWithEmptyCollections() { $rsm = new ResultSetMapping; - $rsm->addEntityResult('Doctrine\Tests\Models\CMS\CmsUser', 'u'); + $rsm->addEntityResult(CmsUser::class, 'u'); $rsm->addJoinedEntityResult( - 'Doctrine\Tests\Models\CMS\CmsArticle', + CmsArticle::class, 'a', 'u', 'articles' ); $rsm->addJoinedEntityResult( - 'Doctrine\Tests\Models\CMS\CmsComment', + CmsComment::class, 'c', 'a', 'comments' @@ -1110,34 +1124,34 @@ public function testChainedJoinWithEmptyCollections() $rsm->addFieldResult('c', 'c__topic', 'topic'); // Faked result set - $resultSet = array( + $resultSet = [ //row1 - array( + [ 'u__id' => '1', 'u__status' => 'developer', 'a__id' => null, 'a__topic' => null, 'c__id' => null, 'c__topic' => null - ), - array( + ], + [ 'u__id' => '2', 'u__status' => 'developer', 'a__id' => null, 'a__topic' => null, 'c__id' => null, 'c__topic' => null - ), - ); + ], + ]; $stmt = new HydratorMockStatement($resultSet); $hydrator = new \Doctrine\ORM\Internal\Hydration\ObjectHydrator($this->_em); - $result = $hydrator->hydrateAll($stmt, $rsm, array(Query::HINT_FORCE_PARTIAL_LOAD => true)); + $result = $hydrator->hydrateAll($stmt, $rsm, [Query::HINT_FORCE_PARTIAL_LOAD => true]); $this->assertEquals(2, count($result)); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsUser', $result[0]); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsUser', $result[1]); + $this->assertInstanceOf(CmsUser::class, $result[0]); + $this->assertInstanceOf(CmsUser::class, $result[1]); $this->assertEquals(0, $result[0]->articles->count()); $this->assertEquals(0, $result[1]->articles->count()); @@ -1152,15 +1166,15 @@ public function testChainedJoinWithEmptyCollections() public function testChainedJoinWithEmptyCollectionsWithAliasedUserEntity() { $rsm = new ResultSetMapping; - $rsm->addEntityResult('Doctrine\Tests\Models\CMS\CmsUser', 'u', 'user'); + $rsm->addEntityResult(CmsUser::class, 'u', 'user'); $rsm->addJoinedEntityResult( - 'Doctrine\Tests\Models\CMS\CmsArticle', + CmsArticle::class, 'a', 'u', 'articles' ); $rsm->addJoinedEntityResult( - 'Doctrine\Tests\Models\CMS\CmsComment', + CmsComment::class, 'c', 'a', 'comments' @@ -1173,106 +1187,42 @@ public function testChainedJoinWithEmptyCollectionsWithAliasedUserEntity() $rsm->addFieldResult('c', 'c__topic', 'topic'); // Faked result set - $resultSet = array( + $resultSet = [ //row1 - array( + [ 'u__id' => '1', 'u__status' => 'developer', 'a__id' => null, 'a__topic' => null, 'c__id' => null, 'c__topic' => null - ), - array( + ], + [ 'u__id' => '2', 'u__status' => 'developer', 'a__id' => null, 'a__topic' => null, 'c__id' => null, 'c__topic' => null - ), - ); + ], + ]; $stmt = new HydratorMockStatement($resultSet); $hydrator = new \Doctrine\ORM\Internal\Hydration\ObjectHydrator($this->_em); - $result = $hydrator->hydrateAll($stmt, $rsm, array(Query::HINT_FORCE_PARTIAL_LOAD => true)); + $result = $hydrator->hydrateAll($stmt, $rsm, [Query::HINT_FORCE_PARTIAL_LOAD => true]); $this->assertEquals(2, count($result)); $this->assertInternalType('array', $result[0]); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsUser', $result[0]['user']); + $this->assertInstanceOf(CmsUser::class, $result[0]['user']); $this->assertInternalType('array', $result[1]); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsUser', $result[1]['user']); + $this->assertInstanceOf(CmsUser::class, $result[1]['user']); $this->assertEquals(0, $result[0]['user']->articles->count()); $this->assertEquals(0, $result[1]['user']->articles->count()); } - /** - * SELECT PARTIAL u.{id,status}, a.id, a.topic, c.id as cid, c.topic as ctopic - * FROM CmsUser u - * LEFT JOIN u.articles a - * LEFT JOIN a.comments c - * - * @group bubu - * @dataProvider provideDataForUserEntityResult - */ - /*public function testChainedJoinWithScalars($userEntityKey) - { - $rsm = new ResultSetMapping; - $rsm->addEntityResult('Doctrine\Tests\Models\CMS\CmsUser', 'u', $userEntityKey ?: null); - $rsm->addFieldResult('u', 'u__id', 'id'); - $rsm->addFieldResult('u', 'u__status', 'status'); - $rsm->addScalarResult('a__id', 'id'); - $rsm->addScalarResult('a__topic', 'topic'); - $rsm->addScalarResult('c__id', 'cid'); - $rsm->addScalarResult('c__topic', 'ctopic'); - - // Faked result set - $resultSet = array( - //row1 - array( - 'u__id' => '1', - 'u__status' => 'developer', - 'a__id' => '1', - 'a__topic' => 'The First', - 'c__id' => '1', - 'c__topic' => 'First Comment' - ), - array( - 'u__id' => '1', - 'u__status' => 'developer', - 'a__id' => '1', - 'a__topic' => 'The First', - 'c__id' => '2', - 'c__topic' => 'Second Comment' - ), - array( - 'u__id' => '1', - 'u__status' => 'developer', - 'a__id' => '42', - 'a__topic' => 'The Answer', - 'c__id' => null, - 'c__topic' => null - ), - ); - - $stmt = new HydratorMockStatement($resultSet); - $hydrator = new \Doctrine\ORM\Internal\Hydration\ObjectHydrator($this->_em); - $result = $hydrator->hydrateAll($stmt, $rsm, array(Query::HINT_FORCE_PARTIAL_LOAD => true)); - - \Doctrine\Common\Util\Debug::dump($result, 3); - - $this->assertEquals(1, count($result)); - - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsUser', $result[0][$userEntityKey]); // User object - $this->assertEquals(42, $result[0]['id']); - $this->assertEquals('The First', $result[0]['topic']); - $this->assertEquals(1, $result[0]['cid']); - $this->assertEquals('First Comment', $result[0]['ctopic']); - }*/ - /** * SELECT PARTIAL u.{id, name} * FROM Doctrine\Tests\Models\CMS\CmsUser u @@ -1280,30 +1230,30 @@ public function testChainedJoinWithEmptyCollectionsWithAliasedUserEntity() public function testResultIteration() { $rsm = new ResultSetMapping; - $rsm->addEntityResult('Doctrine\Tests\Models\CMS\CmsUser', 'u'); + $rsm->addEntityResult(CmsUser::class, 'u'); $rsm->addFieldResult('u', 'u__id', 'id'); $rsm->addFieldResult('u', 'u__name', 'name'); // Faked result set - $resultSet = array( - array( + $resultSet = [ + [ 'u__id' => '1', 'u__name' => 'romanb' - ), - array( + ], + [ 'u__id' => '2', 'u__name' => 'jwage' - ) - ); + ] + ]; $stmt = new HydratorMockStatement($resultSet); $hydrator = new \Doctrine\ORM\Internal\Hydration\ObjectHydrator($this->_em); - $iterableResult = $hydrator->iterate($stmt, $rsm, array(Query::HINT_FORCE_PARTIAL_LOAD => true)); + $iterableResult = $hydrator->iterate($stmt, $rsm, [Query::HINT_FORCE_PARTIAL_LOAD => true]); $rowNum = 0; while (($row = $iterableResult->next()) !== false) { $this->assertEquals(1, count($row)); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsUser', $row[0]); + $this->assertInstanceOf(CmsUser::class, $row[0]); if ($rowNum == 0) { $this->assertEquals(1, $row[0]->id); @@ -1324,32 +1274,32 @@ public function testResultIteration() public function testResultIterationWithAliasedUserEntity() { $rsm = new ResultSetMapping; - $rsm->addEntityResult('Doctrine\Tests\Models\CMS\CmsUser', 'u', 'user'); + $rsm->addEntityResult(CmsUser::class, 'u', 'user'); $rsm->addFieldResult('u', 'u__id', 'id'); $rsm->addFieldResult('u', 'u__name', 'name'); // Faked result set - $resultSet = array( - array( + $resultSet = [ + [ 'u__id' => '1', 'u__name' => 'romanb' - ), - array( + ], + [ 'u__id' => '2', 'u__name' => 'jwage' - ) - ); + ] + ]; $stmt = new HydratorMockStatement($resultSet); $hydrator = new \Doctrine\ORM\Internal\Hydration\ObjectHydrator($this->_em); - $iterableResult = $hydrator->iterate($stmt, $rsm, array(Query::HINT_FORCE_PARTIAL_LOAD => true)); + $iterableResult = $hydrator->iterate($stmt, $rsm, [Query::HINT_FORCE_PARTIAL_LOAD => true]); $rowNum = 0; while (($row = $iterableResult->next()) !== false) { $this->assertEquals(1, count($row)); $this->assertArrayHasKey(0, $row); $this->assertArrayHasKey('user', $row[0]); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsUser', $row[0]['user']); + $this->assertInstanceOf(CmsUser::class, $row[0]['user']); if ($rowNum == 0) { $this->assertEquals(1, $row[0]['user']->id); @@ -1374,110 +1324,110 @@ public function testResultIterationWithAliasedUserEntity() public function testManyToManyHydration() { $rsm = new ResultSetMapping; - $rsm->addEntityResult('Doctrine\Tests\Models\CMS\CmsUser', 'u'); + $rsm->addEntityResult(CmsUser::class, 'u'); $rsm->addFieldResult('u', 'u__id', 'id'); $rsm->addFieldResult('u', 'u__name', 'name'); - $rsm->addJoinedEntityResult('Doctrine\Tests\Models\CMS\CmsGroup', 'g', 'u', 'groups'); + $rsm->addJoinedEntityResult(CmsGroup::class, 'g', 'u', 'groups'); $rsm->addFieldResult('g', 'g__id', 'id'); $rsm->addFieldResult('g', 'g__name', 'name'); - $rsm->addJoinedEntityResult('Doctrine\Tests\Models\CMS\CmsPhonenumber', 'p', 'u', 'phonenumbers'); + $rsm->addJoinedEntityResult(CmsPhonenumber::class, 'p', 'u', 'phonenumbers'); $rsm->addFieldResult('p', 'p__phonenumber', 'phonenumber'); // Faked result set - $resultSet = array( - array( + $resultSet = [ + [ 'u__id' => '1', 'u__name' => 'romanb', 'g__id' => '3', 'g__name' => 'TestGroupB', 'p__phonenumber' => 1111, - ), - array( + ], + [ 'u__id' => '1', 'u__name' => 'romanb', 'g__id' => '5', 'g__name' => 'TestGroupD', 'p__phonenumber' => 1111, - ), - array( + ], + [ 'u__id' => '1', 'u__name' => 'romanb', 'g__id' => '3', 'g__name' => 'TestGroupB', 'p__phonenumber' => 2222, - ), - array( + ], + [ 'u__id' => '1', 'u__name' => 'romanb', 'g__id' => '5', 'g__name' => 'TestGroupD', 'p__phonenumber' => 2222, - ), - array( + ], + [ 'u__id' => '2', 'u__name' => 'jwage', 'g__id' => '2', 'g__name' => 'TestGroupA', 'p__phonenumber' => 3333, - ), - array( + ], + [ 'u__id' => '2', 'u__name' => 'jwage', 'g__id' => '3', 'g__name' => 'TestGroupB', 'p__phonenumber' => 3333, - ), - array( + ], + [ 'u__id' => '2', 'u__name' => 'jwage', 'g__id' => '4', 'g__name' => 'TestGroupC', 'p__phonenumber' => 3333, - ), - array( + ], + [ 'u__id' => '2', 'u__name' => 'jwage', 'g__id' => '5', 'g__name' => 'TestGroupD', 'p__phonenumber' => 3333, - ), - array( + ], + [ 'u__id' => '2', 'u__name' => 'jwage', 'g__id' => '2', 'g__name' => 'TestGroupA', 'p__phonenumber' => 4444, - ), - array( + ], + [ 'u__id' => '2', 'u__name' => 'jwage', 'g__id' => '3', 'g__name' => 'TestGroupB', 'p__phonenumber' => 4444, - ), - array( + ], + [ 'u__id' => '2', 'u__name' => 'jwage', 'g__id' => '4', 'g__name' => 'TestGroupC', 'p__phonenumber' => 4444, - ), - array( + ], + [ 'u__id' => '2', 'u__name' => 'jwage', 'g__id' => '5', 'g__name' => 'TestGroupD', 'p__phonenumber' => 4444, - ), - ); + ], + ]; $stmt = new HydratorMockStatement($resultSet); $hydrator = new \Doctrine\ORM\Internal\Hydration\ObjectHydrator($this->_em); - $result = $hydrator->hydrateAll($stmt, $rsm, array(Query::HINT_FORCE_PARTIAL_LOAD => true)); + $result = $hydrator->hydrateAll($stmt, $rsm, [Query::HINT_FORCE_PARTIAL_LOAD => true]); $this->assertEquals(2, count($result)); - $this->assertContainsOnly('Doctrine\Tests\Models\CMS\CmsUser', $result); + $this->assertContainsOnly(CmsUser::class, $result); $this->assertEquals(2, count($result[0]->groups)); $this->assertEquals(2, count($result[0]->phonenumbers)); @@ -1497,113 +1447,113 @@ public function testManyToManyHydration() public function testManyToManyHydrationWithAliasedUserEntity() { $rsm = new ResultSetMapping; - $rsm->addEntityResult('Doctrine\Tests\Models\CMS\CmsUser', 'u', 'user'); + $rsm->addEntityResult(CmsUser::class, 'u', 'user'); $rsm->addFieldResult('u', 'u__id', 'id'); $rsm->addFieldResult('u', 'u__name', 'name'); - $rsm->addJoinedEntityResult('Doctrine\Tests\Models\CMS\CmsGroup', 'g', 'u', 'groups'); + $rsm->addJoinedEntityResult(CmsGroup::class, 'g', 'u', 'groups'); $rsm->addFieldResult('g', 'g__id', 'id'); $rsm->addFieldResult('g', 'g__name', 'name'); - $rsm->addJoinedEntityResult('Doctrine\Tests\Models\CMS\CmsPhonenumber', 'p', 'u', 'phonenumbers'); + $rsm->addJoinedEntityResult(CmsPhonenumber::class, 'p', 'u', 'phonenumbers'); $rsm->addFieldResult('p', 'p__phonenumber', 'phonenumber'); // Faked result set - $resultSet = array( - array( + $resultSet = [ + [ 'u__id' => '1', 'u__name' => 'romanb', 'g__id' => '3', 'g__name' => 'TestGroupB', 'p__phonenumber' => 1111, - ), - array( + ], + [ 'u__id' => '1', 'u__name' => 'romanb', 'g__id' => '5', 'g__name' => 'TestGroupD', 'p__phonenumber' => 1111, - ), - array( + ], + [ 'u__id' => '1', 'u__name' => 'romanb', 'g__id' => '3', 'g__name' => 'TestGroupB', 'p__phonenumber' => 2222, - ), - array( + ], + [ 'u__id' => '1', 'u__name' => 'romanb', 'g__id' => '5', 'g__name' => 'TestGroupD', 'p__phonenumber' => 2222, - ), - array( + ], + [ 'u__id' => '2', 'u__name' => 'jwage', 'g__id' => '2', 'g__name' => 'TestGroupA', 'p__phonenumber' => 3333, - ), - array( + ], + [ 'u__id' => '2', 'u__name' => 'jwage', 'g__id' => '3', 'g__name' => 'TestGroupB', 'p__phonenumber' => 3333, - ), - array( + ], + [ 'u__id' => '2', 'u__name' => 'jwage', 'g__id' => '4', 'g__name' => 'TestGroupC', 'p__phonenumber' => 3333, - ), - array( + ], + [ 'u__id' => '2', 'u__name' => 'jwage', 'g__id' => '5', 'g__name' => 'TestGroupD', 'p__phonenumber' => 3333, - ), - array( + ], + [ 'u__id' => '2', 'u__name' => 'jwage', 'g__id' => '2', 'g__name' => 'TestGroupA', 'p__phonenumber' => 4444, - ), - array( + ], + [ 'u__id' => '2', 'u__name' => 'jwage', 'g__id' => '3', 'g__name' => 'TestGroupB', 'p__phonenumber' => 4444, - ), - array( + ], + [ 'u__id' => '2', 'u__name' => 'jwage', 'g__id' => '4', 'g__name' => 'TestGroupC', 'p__phonenumber' => 4444, - ), - array( + ], + [ 'u__id' => '2', 'u__name' => 'jwage', 'g__id' => '5', 'g__name' => 'TestGroupD', 'p__phonenumber' => 4444, - ), - ); + ], + ]; $stmt = new HydratorMockStatement($resultSet); $hydrator = new \Doctrine\ORM\Internal\Hydration\ObjectHydrator($this->_em); - $result = $hydrator->hydrateAll($stmt, $rsm, array(Query::HINT_FORCE_PARTIAL_LOAD => true)); + $result = $hydrator->hydrateAll($stmt, $rsm, [Query::HINT_FORCE_PARTIAL_LOAD => true]); $this->assertEquals(2, count($result)); $this->assertInternalType('array', $result[0]); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsUser', $result[0]['user']); + $this->assertInstanceOf(CmsUser::class, $result[0]['user']); $this->assertInternalType('array', $result[1]); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsUser', $result[1]['user']); + $this->assertInstanceOf(CmsUser::class, $result[1]['user']); $this->assertEquals(2, count($result[0]['user']->groups)); $this->assertEquals(2, count($result[0]['user']->phonenumbers)); @@ -1622,39 +1572,39 @@ public function testManyToManyHydrationWithAliasedUserEntity() public function testMissingIdForRootEntity($userEntityKey) { $rsm = new ResultSetMapping; - $rsm->addEntityResult('Doctrine\Tests\Models\CMS\CmsUser', 'u', $userEntityKey ?: null); + $rsm->addEntityResult(CmsUser::class, 'u', $userEntityKey ?: null); $rsm->addFieldResult('u', 'u__id', 'id'); $rsm->addFieldResult('u', 'u__status', 'status'); $rsm->addScalarResult('sclr0', 'nameUpper', 'string'); // Faked result set - $resultSet = array( + $resultSet = [ //row1 - array( + [ 'u__id' => '1', 'u__status' => 'developer', 'sclr0' => 'ROMANB', - ), - array( + ], + [ 'u__id' => null, 'u__status' => null, 'sclr0' => 'ROMANB', - ), - array( + ], + [ 'u__id' => '2', 'u__status' => 'developer', 'sclr0' => 'JWAGE', - ), - array( + ], + [ 'u__id' => null, 'u__status' => null, 'sclr0' => 'JWAGE', - ), - ); + ], + ]; $stmt = new HydratorMockStatement($resultSet); $hydrator = new \Doctrine\ORM\Internal\Hydration\ObjectHydrator($this->_em); - $result = $hydrator->hydrateAll($stmt, $rsm, array(Query::HINT_FORCE_PARTIAL_LOAD => true)); + $result = $hydrator->hydrateAll($stmt, $rsm, [Query::HINT_FORCE_PARTIAL_LOAD => true]); $this->assertEquals(4, count($result), "Should hydrate four results."); @@ -1663,10 +1613,10 @@ public function testMissingIdForRootEntity($userEntityKey) $this->assertEquals('JWAGE', $result[2]['nameUpper']); $this->assertEquals('JWAGE', $result[3]['nameUpper']); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsUser', $result[0][$userEntityKey]); + $this->assertInstanceOf(CmsUser::class, $result[0][$userEntityKey]); $this->assertNull($result[1][$userEntityKey]); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsUser', $result[2][$userEntityKey]); + $this->assertInstanceOf(CmsUser::class, $result[2][$userEntityKey]); $this->assertNull($result[3][$userEntityKey]); } @@ -1681,9 +1631,9 @@ public function testMissingIdForRootEntity($userEntityKey) public function testMissingIdForCollectionValuedChildEntity($userEntityKey) { $rsm = new ResultSetMapping; - $rsm->addEntityResult('Doctrine\Tests\Models\CMS\CmsUser', 'u', $userEntityKey ?: null); + $rsm->addEntityResult(CmsUser::class, 'u', $userEntityKey ?: null); $rsm->addJoinedEntityResult( - 'Doctrine\Tests\Models\CMS\CmsPhonenumber', + CmsPhonenumber::class, 'p', 'u', 'phonenumbers' @@ -1694,37 +1644,37 @@ public function testMissingIdForCollectionValuedChildEntity($userEntityKey) $rsm->addFieldResult('p', 'p__phonenumber', 'phonenumber'); // Faked result set - $resultSet = array( + $resultSet = [ //row1 - array( + [ 'u__id' => '1', 'u__status' => 'developer', 'sclr0' => 'ROMANB', 'p__phonenumber' => '42', - ), - array( + ], + [ 'u__id' => '1', 'u__status' => 'developer', 'sclr0' => 'ROMANB', 'p__phonenumber' => null - ), - array( + ], + [ 'u__id' => '2', 'u__status' => 'developer', 'sclr0' => 'JWAGE', 'p__phonenumber' => '91' - ), - array( + ], + [ 'u__id' => '2', 'u__status' => 'developer', 'sclr0' => 'JWAGE', 'p__phonenumber' => null - ) - ); + ] + ]; $stmt = new HydratorMockStatement($resultSet); $hydrator = new \Doctrine\ORM\Internal\Hydration\ObjectHydrator($this->_em); - $result = $hydrator->hydrateAll($stmt, $rsm, array(Query::HINT_FORCE_PARTIAL_LOAD => true)); + $result = $hydrator->hydrateAll($stmt, $rsm, [Query::HINT_FORCE_PARTIAL_LOAD => true]); $this->assertEquals(2, count($result)); @@ -1743,9 +1693,9 @@ public function testMissingIdForCollectionValuedChildEntity($userEntityKey) public function testMissingIdForSingleValuedChildEntity($userEntityKey) { $rsm = new ResultSetMapping; - $rsm->addEntityResult('Doctrine\Tests\Models\CMS\CmsUser', 'u', $userEntityKey ?: null); + $rsm->addEntityResult(CmsUser::class, 'u', $userEntityKey ?: null); $rsm->addJoinedEntityResult( - 'Doctrine\Tests\Models\CMS\CmsAddress', + CmsAddress::class, 'a', 'u', 'address' @@ -1758,31 +1708,31 @@ public function testMissingIdForSingleValuedChildEntity($userEntityKey) $rsm->addMetaResult('a', 'user_id', 'user_id', false, 'string'); // Faked result set - $resultSet = array( + $resultSet = [ //row1 - array( + [ 'u__id' => '1', 'u__status' => 'developer', 'sclr0' => 'ROMANB', 'a__id' => 1, 'a__city' => 'Berlin', - ), - array( + ], + [ 'u__id' => '2', 'u__status' => 'developer', 'sclr0' => 'BENJAMIN', 'a__id' => null, 'a__city' => null, - ), - ); + ], + ]; $stmt = new HydratorMockStatement($resultSet); $hydrator = new \Doctrine\ORM\Internal\Hydration\ObjectHydrator($this->_em); - $result = $hydrator->hydrateAll($stmt, $rsm, array(Query::HINT_FORCE_PARTIAL_LOAD => true)); + $result = $hydrator->hydrateAll($stmt, $rsm, [Query::HINT_FORCE_PARTIAL_LOAD => true]); $this->assertEquals(2, count($result)); - $this->assertInstanceOf('Doctrine\Tests\Models\CMS\CmsAddress', $result[0][$userEntityKey]->address); + $this->assertInstanceOf(CmsAddress::class, $result[0][$userEntityKey]->address); $this->assertNull($result[1][$userEntityKey]->address); } @@ -1797,30 +1747,30 @@ public function testMissingIdForSingleValuedChildEntity($userEntityKey) public function testIndexByAndMixedResult($userEntityKey) { $rsm = new ResultSetMapping; - $rsm->addEntityResult('Doctrine\Tests\Models\CMS\CmsUser', 'u', $userEntityKey ?: null); + $rsm->addEntityResult(CmsUser::class, 'u', $userEntityKey ?: null); $rsm->addFieldResult('u', 'u__id', 'id'); $rsm->addFieldResult('u', 'u__status', 'status'); $rsm->addScalarResult('sclr0', 'nameUpper', 'string'); $rsm->addIndexBy('u', 'id'); // Faked result set - $resultSet = array( + $resultSet = [ //row1 - array( + [ 'u__id' => '1', 'u__status' => 'developer', 'sclr0' => 'ROMANB', - ), - array( + ], + [ 'u__id' => '2', 'u__status' => 'developer', 'sclr0' => 'JWAGE', - ), - ); + ], + ]; $stmt = new HydratorMockStatement($resultSet); $hydrator = new \Doctrine\ORM\Internal\Hydration\ObjectHydrator($this->_em); - $result = $hydrator->hydrateAll($stmt, $rsm, array(Query::HINT_FORCE_PARTIAL_LOAD => true)); + $result = $hydrator->hydrateAll($stmt, $rsm, [Query::HINT_FORCE_PARTIAL_LOAD => true]); $this->assertEquals(2, count($result)); @@ -1841,30 +1791,30 @@ public function testIndexByAndMixedResult($userEntityKey) public function testIndexByScalarsOnly($userEntityKey) { $rsm = new ResultSetMapping; - $rsm->addEntityResult('Doctrine\Tests\Models\CMS\CmsUser', 'u', $userEntityKey ?: null); + $rsm->addEntityResult(CmsUser::class, 'u', $userEntityKey ?: null); $rsm->addScalarResult('sclr0', 'nameUpper', 'string'); $rsm->addIndexByScalar('sclr0'); // Faked result set - $resultSet = array( + $resultSet = [ //row1 - array( + [ 'sclr0' => 'ROMANB', - ), - array( + ], + [ 'sclr0' => 'JWAGE', - ), - ); + ], + ]; $stmt = new HydratorMockStatement($resultSet); $hydrator = new \Doctrine\ORM\Internal\Hydration\ObjectHydrator($this->_em); - $result = $hydrator->hydrateAll($stmt, $rsm, array(Query::HINT_FORCE_PARTIAL_LOAD => true)); + $result = $hydrator->hydrateAll($stmt, $rsm, [Query::HINT_FORCE_PARTIAL_LOAD => true]); $this->assertEquals( - array( - 'ROMANB' => array('nameUpper' => 'ROMANB'), - 'JWAGE' => array('nameUpper' => 'JWAGE') - ), + [ + 'ROMANB' => ['nameUpper' => 'ROMANB'], + 'JWAGE' => ['nameUpper' => 'JWAGE'] + ], $result ); } @@ -1880,17 +1830,17 @@ public function testMissingMetaMappingException() { $rsm = new ResultSetMapping; - $rsm->addEntityResult('Doctrine\Tests\Models\Company\CompanyFixContract', 'c'); - $rsm->addJoinedEntityResult('Doctrine\Tests\Models\Company\CompanyEmployee', 'e', 'c', 'salesPerson'); + $rsm->addEntityResult(CompanyFixContract::class, 'c'); + $rsm->addJoinedEntityResult(CompanyEmployee::class, 'e', 'c', 'salesPerson'); $rsm->addFieldResult('c', 'c__id', 'id'); $rsm->setDiscriminatorColumn('c', 'c_discr'); - $resultSet = array( - array( + $resultSet = [ + [ 'c__id' => '1', 'c_discr' => 'fix', - ), - ); + ], + ]; $stmt = new HydratorMockStatement($resultSet); $hydrator = new \Doctrine\ORM\Internal\Hydration\ObjectHydrator($this->_em); @@ -1907,8 +1857,8 @@ public function testMissingDiscriminatorColumnException() { $rsm = new ResultSetMapping; - $rsm->addEntityResult('Doctrine\Tests\Models\Company\CompanyFixContract', 'c'); - $rsm->addJoinedEntityResult('Doctrine\Tests\Models\Company\CompanyEmployee', 'e', 'c', 'salesPerson'); + $rsm->addEntityResult(CompanyFixContract::class, 'c'); + $rsm->addJoinedEntityResult(CompanyEmployee::class, 'e', 'c', 'salesPerson'); $rsm->addFieldResult('c', 'c__id', 'id'); $rsm->addMetaResult('c', 'c_discr', 'discr', false, 'string'); $rsm->setDiscriminatorColumn('c', 'c_discr'); @@ -1917,14 +1867,14 @@ public function testMissingDiscriminatorColumnException() $rsm->addMetaResult('e ', 'e_discr', 'discr', false, 'string'); $rsm->setDiscriminatorColumn('e', 'e_discr'); - $resultSet = array( - array( + $resultSet = [ + [ 'c__id' => '1', 'c_discr' => 'fix', 'e__id' => '1', 'e__name' => 'Fabio B. Silva' - ), - ); + ], + ]; $stmt = new HydratorMockStatement($resultSet); $hydrator = new \Doctrine\ORM\Internal\Hydration\ObjectHydrator($this->_em); @@ -1941,19 +1891,19 @@ public function testInvalidDiscriminatorValueException() { $rsm = new ResultSetMapping; - $rsm->addEntityResult('Doctrine\Tests\Models\Company\CompanyPerson', 'p'); + $rsm->addEntityResult(CompanyPerson::class, 'p'); $rsm->addFieldResult('p', 'p__id', 'id'); $rsm->addFieldResult('p', 'p__name', 'name'); $rsm->addMetaResult('p', 'discr', 'discr', false, 'string'); $rsm->setDiscriminatorColumn('p', 'discr'); - $resultSet = array( - array( + $resultSet = [ + [ 'p__id' => '1', 'p__name' => 'Fabio B. Silva', 'discr' => 'subworker' - ), - ); + ], + ]; $stmt = new HydratorMockStatement($resultSet); $hydrator = new \Doctrine\ORM\Internal\Hydration\ObjectHydrator($this->_em); @@ -1964,26 +1914,26 @@ public function testFetchJoinCollectionValuedAssociationWithDefaultArrayValue() { $rsm = new ResultSetMapping; - $rsm->addEntityResult(EntityWithArrayDefaultArrayValueM2M::CLASSNAME, 'e1', null); - $rsm->addJoinedEntityResult(SimpleEntity::CLASSNAME, 'e2', 'e1', 'collection'); + $rsm->addEntityResult(EntityWithArrayDefaultArrayValueM2M::class, 'e1', null); + $rsm->addJoinedEntityResult(SimpleEntity::class, 'e2', 'e1', 'collection'); $rsm->addFieldResult('e1', 'a1__id', 'id'); $rsm->addFieldResult('e2', 'e2__id', 'id'); - $resultSet = array( - array( + $resultSet = [ + [ 'a1__id' => '1', 'e2__id' => '1', - ) - ); + ] + ]; $stmt = new HydratorMockStatement($resultSet); $hydrator = new \Doctrine\ORM\Internal\Hydration\ObjectHydrator($this->_em); $result = $hydrator->hydrateAll($stmt, $rsm); $this->assertCount(1, $result); - $this->assertInstanceOf(EntityWithArrayDefaultArrayValueM2M::CLASSNAME, $result[0]); - $this->assertInstanceOf('Doctrine\ORM\PersistentCollection', $result[0]->collection); + $this->assertInstanceOf(EntityWithArrayDefaultArrayValueM2M::class, $result[0]); + $this->assertInstanceOf(PersistentCollection::class, $result[0]->collection); $this->assertCount(1, $result[0]->collection); - $this->assertInstanceOf(SimpleEntity::CLASSNAME, $result[0]->collection[0]); + $this->assertInstanceOf(SimpleEntity::class, $result[0]->collection[0]); } } diff --git a/tests/Doctrine/Tests/ORM/Hydration/ResultSetMappingTest.php b/tests/Doctrine/Tests/ORM/Hydration/ResultSetMappingTest.php index 2ce9ae78930..3ec87b237de 100644 --- a/tests/Doctrine/Tests/ORM/Hydration/ResultSetMappingTest.php +++ b/tests/Doctrine/Tests/ORM/Hydration/ResultSetMappingTest.php @@ -2,8 +2,13 @@ namespace Doctrine\Tests\ORM\Hydration; -use Doctrine\ORM\Query\ResultSetMapping; use Doctrine\ORM\Mapping\ClassMetadata; +use Doctrine\ORM\Query\ResultSetMapping; +use Doctrine\Tests\Models\CMS\CmsEmail; +use Doctrine\Tests\Models\CMS\CmsPhonenumber; +use Doctrine\Tests\Models\CMS\CmsUser; +use Doctrine\Tests\Models\Legacy\LegacyUser; +use Doctrine\Tests\Models\Legacy\LegacyUserReference; /** * Description of ResultSetMappingTest @@ -34,7 +39,7 @@ protected function setUp() { public function testBasicResultSetMapping() { $this->_rsm->addEntityResult( - 'Doctrine\Tests\Models\CMS\CmsUser', + CmsUser::class, 'u' ); $this->_rsm->addFieldResult('u', 'id', 'id'); @@ -47,9 +52,9 @@ public function testBasicResultSetMapping() $this->assertFalse($this->_rsm->isScalarResult('username')); $this->assertFalse($this->_rsm->isScalarResult('name')); - $this->assertTrue($this->_rsm->getClassName('u') == 'Doctrine\Tests\Models\CMS\CmsUser'); + $this->assertTrue($this->_rsm->getClassName('u') == CmsUser::class); $class = $this->_rsm->getDeclaringClass('id'); - $this->assertTrue($class == 'Doctrine\Tests\Models\CMS\CmsUser'); + $this->assertTrue($class == CmsUser::class); $this->assertEquals('u', $this->_rsm->getEntityAlias('id')); $this->assertEquals('u', $this->_rsm->getEntityAlias('status')); @@ -71,8 +76,8 @@ public function testFluentInterface() { $rms = $this->_rsm; - $this->_rsm->addEntityResult('Doctrine\Tests\Models\CMS\CmsUser','u'); - $this->_rsm->addJoinedEntityResult('Doctrine\Tests\Models\CMS\CmsPhonenumber','p','u','phonenumbers'); + $this->_rsm->addEntityResult(CmsUser::class,'u'); + $this->_rsm->addJoinedEntityResult(CmsPhonenumber::class,'p','u','phonenumbers'); $this->_rsm->addFieldResult('u', 'id', 'id'); $this->_rsm->addFieldResult('u', 'name', 'name'); $this->_rsm->setDiscriminatorColumn('name', 'name'); @@ -96,64 +101,71 @@ public function testFluentInterface() */ public function testAddNamedNativeQueryResultSetMapping() { - $cm = new ClassMetadata('Doctrine\Tests\Models\CMS\CmsUser'); + $cm = new ClassMetadata(CmsUser::class); $cm->initializeReflection(new \Doctrine\Common\Persistence\Mapping\RuntimeReflectionService); - $cm->mapOneToOne(array( + $cm->mapOneToOne( + [ 'fieldName' => 'email', - 'targetEntity' => 'Doctrine\Tests\Models\CMS\CmsEmail', - 'cascade' => array('persist'), + 'targetEntity' => CmsEmail::class, + 'cascade' => ['persist'], 'inversedBy' => 'user', 'orphanRemoval' => false, - 'joinColumns' => array(array( + 'joinColumns' => [ + [ 'nullable' => true, 'referencedColumnName' => 'id', - ) - ) - )); + ] + ] + ] + ); - $cm->addNamedNativeQuery(array( + $cm->addNamedNativeQuery( + [ 'name' => 'find-all', 'query' => 'SELECT u.id AS user_id, e.id AS email_id, u.name, e.email, u.id + e.id AS scalarColumn FROM cms_users u INNER JOIN cms_emails e ON e.id = u.email_id', 'resultSetMapping' => 'find-all', - )); + ] + ); - $cm->addSqlResultSetMapping(array( + $cm->addSqlResultSetMapping( + [ 'name' => 'find-all', - 'entities' => array( - array( + 'entities' => [ + [ 'entityClass' => '__CLASS__', - 'fields' => array( - array( + 'fields' => [ + [ 'name' => 'id', 'column'=> 'user_id' - ), - array( + ], + [ 'name' => 'name', 'column'=> 'name' - ) - ) - ), - array( + ] + ] + ], + [ 'entityClass' => 'CmsEmail', - 'fields' => array( - array( + 'fields' => [ + [ 'name' => 'id', 'column'=> 'email_id' - ), - array( + ], + [ 'name' => 'email', 'column'=> 'email' - ) - ) - ) - ), - 'columns' => array( - array( + ] + ] + ] + ], + 'columns' => [ + [ 'name' => 'scalarColumn' - ) - ) - )); + ] + ] + ] + ); $queryMapping = $cm->getNamedNativeQuery('find-all'); @@ -164,16 +176,16 @@ public function testAddNamedNativeQueryResultSetMapping() $this->assertEquals('c0', $rsm->getEntityAlias('user_id')); $this->assertEquals('c0', $rsm->getEntityAlias('name')); - $this->assertEquals('Doctrine\Tests\Models\CMS\CmsUser', $rsm->getClassName('c0')); - $this->assertEquals('Doctrine\Tests\Models\CMS\CmsUser', $rsm->getDeclaringClass('name')); - $this->assertEquals('Doctrine\Tests\Models\CMS\CmsUser', $rsm->getDeclaringClass('user_id')); + $this->assertEquals(CmsUser::class, $rsm->getClassName('c0')); + $this->assertEquals(CmsUser::class, $rsm->getDeclaringClass('name')); + $this->assertEquals(CmsUser::class, $rsm->getDeclaringClass('user_id')); $this->assertEquals('c1', $rsm->getEntityAlias('email_id')); $this->assertEquals('c1', $rsm->getEntityAlias('email')); - $this->assertEquals('Doctrine\Tests\Models\CMS\CmsEmail', $rsm->getClassName('c1')); - $this->assertEquals('Doctrine\Tests\Models\CMS\CmsEmail', $rsm->getDeclaringClass('email')); - $this->assertEquals('Doctrine\Tests\Models\CMS\CmsEmail', $rsm->getDeclaringClass('email_id')); + $this->assertEquals(CmsEmail::class, $rsm->getClassName('c1')); + $this->assertEquals(CmsEmail::class, $rsm->getDeclaringClass('email')); + $this->assertEquals(CmsEmail::class, $rsm->getDeclaringClass('email_id')); } /** @@ -181,28 +193,32 @@ public function testAddNamedNativeQueryResultSetMapping() */ public function testAddNamedNativeQueryResultSetMappingWithoutFields() { - $cm = new ClassMetadata('Doctrine\Tests\Models\CMS\CmsUser'); + $cm = new ClassMetadata(CmsUser::class); $cm->initializeReflection(new \Doctrine\Common\Persistence\Mapping\RuntimeReflectionService); - $cm->addNamedNativeQuery(array( + $cm->addNamedNativeQuery( + [ 'name' => 'find-all', 'query' => 'SELECT u.id AS user_id, e.id AS email_id, u.name, e.email, u.id + e.id AS scalarColumn FROM cms_users u INNER JOIN cms_emails e ON e.id = u.email_id', 'resultSetMapping' => 'find-all', - )); + ] + ); - $cm->addSqlResultSetMapping(array( + $cm->addSqlResultSetMapping( + [ 'name' => 'find-all', - 'entities' => array( - array( + 'entities' => [ + [ 'entityClass' => '__CLASS__', - ) - ), - 'columns' => array( - array( + ] + ], + 'columns' => [ + [ 'name' => 'scalarColumn' - ) - ) - )); + ] + ] + ] + ); $queryMapping = $cm->getNamedNativeQuery('find-all'); $rsm = new \Doctrine\ORM\Query\ResultSetMappingBuilder($this->_em); @@ -214,11 +230,11 @@ public function testAddNamedNativeQueryResultSetMappingWithoutFields() $this->assertEquals('c0', $rsm->getEntityAlias('name')); $this->assertEquals('c0', $rsm->getEntityAlias('status')); $this->assertEquals('c0', $rsm->getEntityAlias('username')); - $this->assertEquals('Doctrine\Tests\Models\CMS\CmsUser', $rsm->getClassName('c0')); - $this->assertEquals('Doctrine\Tests\Models\CMS\CmsUser', $rsm->getDeclaringClass('id')); - $this->assertEquals('Doctrine\Tests\Models\CMS\CmsUser', $rsm->getDeclaringClass('name')); - $this->assertEquals('Doctrine\Tests\Models\CMS\CmsUser', $rsm->getDeclaringClass('status')); - $this->assertEquals('Doctrine\Tests\Models\CMS\CmsUser', $rsm->getDeclaringClass('username')); + $this->assertEquals(CmsUser::class, $rsm->getClassName('c0')); + $this->assertEquals(CmsUser::class, $rsm->getDeclaringClass('id')); + $this->assertEquals(CmsUser::class, $rsm->getDeclaringClass('name')); + $this->assertEquals(CmsUser::class, $rsm->getDeclaringClass('status')); + $this->assertEquals(CmsUser::class, $rsm->getDeclaringClass('username')); } /** @@ -226,15 +242,17 @@ public function testAddNamedNativeQueryResultSetMappingWithoutFields() */ public function testAddNamedNativeQueryResultClass() { - $cm = new ClassMetadata('Doctrine\Tests\Models\CMS\CmsUser'); + $cm = new ClassMetadata(CmsUser::class); $cm->initializeReflection(new \Doctrine\Common\Persistence\Mapping\RuntimeReflectionService); - $cm->addNamedNativeQuery(array( + $cm->addNamedNativeQuery( + [ 'name' => 'find-all', 'resultClass' => '__CLASS__', 'query' => 'SELECT * FROM cms_users', - )); + ] + ); $queryMapping = $cm->getNamedNativeQuery('find-all'); $rsm = new \Doctrine\ORM\Query\ResultSetMappingBuilder($this->_em); @@ -245,19 +263,20 @@ public function testAddNamedNativeQueryResultClass() $this->assertEquals('c0', $rsm->getEntityAlias('name')); $this->assertEquals('c0', $rsm->getEntityAlias('status')); $this->assertEquals('c0', $rsm->getEntityAlias('username')); - $this->assertEquals('Doctrine\Tests\Models\CMS\CmsUser', $rsm->getClassName('c0')); - $this->assertEquals('Doctrine\Tests\Models\CMS\CmsUser', $rsm->getDeclaringClass('id')); - $this->assertEquals('Doctrine\Tests\Models\CMS\CmsUser', $rsm->getDeclaringClass('name')); - $this->assertEquals('Doctrine\Tests\Models\CMS\CmsUser', $rsm->getDeclaringClass('status')); - $this->assertEquals('Doctrine\Tests\Models\CMS\CmsUser', $rsm->getDeclaringClass('username')); + $this->assertEquals(CmsUser::class, $rsm->getClassName('c0')); + $this->assertEquals(CmsUser::class, $rsm->getDeclaringClass('id')); + $this->assertEquals(CmsUser::class, $rsm->getDeclaringClass('name')); + $this->assertEquals(CmsUser::class, $rsm->getDeclaringClass('status')); + $this->assertEquals(CmsUser::class, $rsm->getDeclaringClass('username')); } + /** * @group DDC-117 */ public function testIndexByMetadataColumn() { - $this->_rsm->addEntityResult('Doctrine\Tests\Models\Legacy\LegacyUser', 'u'); - $this->_rsm->addJoinedEntityResult('Doctrine\Tests\Models\LegacyUserReference', 'lu', 'u', '_references'); + $this->_rsm->addEntityResult(LegacyUser::class, 'u'); + $this->_rsm->addJoinedEntityResult(LegacyUserReference::class, 'lu', 'u', '_references'); $this->_rsm->addMetaResult('lu', '_source', '_source', true, 'integer'); $this->_rsm->addMetaResult('lu', '_target', '_target', true, 'integer'); $this->_rsm->addIndexBy('lu', '_source'); diff --git a/tests/Doctrine/Tests/ORM/Hydration/ScalarHydratorTest.php b/tests/Doctrine/Tests/ORM/Hydration/ScalarHydratorTest.php index 5c5f55f4057..919486cc8ec 100644 --- a/tests/Doctrine/Tests/ORM/Hydration/ScalarHydratorTest.php +++ b/tests/Doctrine/Tests/ORM/Hydration/ScalarHydratorTest.php @@ -2,8 +2,10 @@ namespace Doctrine\Tests\ORM\Hydration; +use Doctrine\ORM\Internal\Hydration\ScalarHydrator; use Doctrine\Tests\Mocks\HydratorMockStatement; use Doctrine\ORM\Query\ResultSetMapping; +use Doctrine\Tests\Models\CMS\CmsUser; class ScalarHydratorTest extends HydrationTestCase { @@ -13,30 +15,30 @@ class ScalarHydratorTest extends HydrationTestCase public function testNewHydrationSimpleEntityQuery() { $rsm = new ResultSetMapping; - $rsm->addEntityResult('Doctrine\Tests\Models\CMS\CmsUser', 'u'); + $rsm->addEntityResult(CmsUser::class, 'u'); $rsm->addFieldResult('u', 'u__id', 'id'); $rsm->addFieldResult('u', 'u__name', 'name'); // Faked result set - $resultSet = array( - array( + $resultSet = [ + [ 'u__id' => '1', 'u__name' => 'romanb' - ), - array( + ], + [ 'u__id' => '2', 'u__name' => 'jwage' - ) - ); + ] + ]; $stmt = new HydratorMockStatement($resultSet); - $hydrator = new \Doctrine\ORM\Internal\Hydration\ScalarHydrator($this->_em); + $hydrator = new ScalarHydrator($this->_em); $result = $hydrator->hydrateAll($stmt, $rsm); - $this->assertTrue(is_array($result)); - $this->assertEquals(2, count($result)); + $this->assertInternalType('array', $result); + $this->assertCount(2, $result); $this->assertEquals('romanb', $result[0]['u_name']); $this->assertEquals(1, $result[0]['u_id']); $this->assertEquals('jwage', $result[1]['u_name']); @@ -53,18 +55,18 @@ public function testHydrateScalarResults() $rsm->addScalarResult('bar2', 'bar', 'string'); $rsm->addScalarResult('baz3', 'baz', 'string'); - $resultSet = array( - array( + $resultSet = [ + [ 'foo1' => 'A', 'bar2' => 'B', 'baz3' => 'C', - ), - ); + ], + ]; $stmt = new HydratorMockStatement($resultSet); - $hydrator = new \Doctrine\ORM\Internal\Hydration\ScalarHydrator($this->_em); + $hydrator = new ScalarHydrator($this->_em); - $result = $hydrator->hydrateAll($stmt, $rsm); + self::assertCount(1, $hydrator->hydrateAll($stmt, $rsm)); } /** @@ -73,27 +75,27 @@ public function testHydrateScalarResults() public function testSkipUnknownColumns() { $rsm = new ResultSetMapping; - $rsm->addEntityResult('Doctrine\Tests\Models\CMS\CmsUser', 'u'); + $rsm->addEntityResult(CmsUser::class, 'u'); $rsm->addFieldResult('u', 'u__id', 'id'); $rsm->addFieldResult('u', 'u__name', 'name'); $rsm->addScalarResult('foo1', 'foo', 'string'); $rsm->addScalarResult('bar2', 'bar', 'string'); $rsm->addScalarResult('baz3', 'baz', 'string'); - $resultSet = array( - array( + $resultSet = [ + [ 'u__id' => '1', 'u__name' => 'romanb', 'foo1' => 'A', 'bar2' => 'B', 'baz3' => 'C', 'foo' => 'bar', // Unknown! - ), - ); + ], + ]; $stmt = new HydratorMockStatement($resultSet); - $hydrator = new \Doctrine\ORM\Internal\Hydration\ScalarHydrator($this->_em); + $hydrator = new ScalarHydrator($this->_em); - $result = $hydrator->hydrateAll($stmt, $rsm); + self::assertCount(1, $hydrator->hydrateAll($stmt, $rsm)); } } diff --git a/tests/Doctrine/Tests/ORM/Hydration/SimpleObjectHydratorTest.php b/tests/Doctrine/Tests/ORM/Hydration/SimpleObjectHydratorTest.php index eb33c23c2cf..ffcd81e3571 100644 --- a/tests/Doctrine/Tests/ORM/Hydration/SimpleObjectHydratorTest.php +++ b/tests/Doctrine/Tests/ORM/Hydration/SimpleObjectHydratorTest.php @@ -2,8 +2,13 @@ namespace Doctrine\Tests\ORM\Hydration; -use Doctrine\Tests\Mocks\HydratorMockStatement; use Doctrine\ORM\Query\ResultSetMapping; +use Doctrine\Tests\Mocks\HydratorMockStatement; +use Doctrine\Tests\Models\CMS\CmsAddress; +use Doctrine\Tests\Models\Company\CompanyPerson; +use Doctrine\Tests\Models\Issue5989\Issue5989Employee; +use Doctrine\Tests\Models\Issue5989\Issue5989Manager; +use Doctrine\Tests\Models\Issue5989\Issue5989Person; class SimpleObjectHydratorTest extends HydrationTestCase { @@ -16,17 +21,17 @@ class SimpleObjectHydratorTest extends HydrationTestCase public function testMissingDiscriminatorColumnException() { $rsm = new ResultSetMapping; - $rsm->addEntityResult('Doctrine\Tests\Models\Company\CompanyPerson', 'p'); + $rsm->addEntityResult(CompanyPerson::class, 'p'); $rsm->addFieldResult('p', 'p__id', 'id'); $rsm->addFieldResult('p', 'p__name', 'name'); $rsm->addMetaResult('p ', 'discr', 'discr', false, 'string'); $rsm->setDiscriminatorColumn('p', 'discr'); - $resultSet = array( - array( + $resultSet = [ + [ 'u__id' => '1', 'u__name' => 'Fabio B. Silva' - ), - ); + ], + ]; $stmt = new HydratorMockStatement($resultSet); $hydrator = new \Doctrine\ORM\Internal\Hydration\SimpleObjectHydrator($this->_em); @@ -36,16 +41,16 @@ public function testMissingDiscriminatorColumnException() public function testExtraFieldInResultSetShouldBeIgnore() { $rsm = new ResultSetMapping; - $rsm->addEntityResult('Doctrine\Tests\Models\CMS\CmsAddress', 'a'); + $rsm->addEntityResult(CmsAddress::class, 'a'); $rsm->addFieldResult('a', 'a__id', 'id'); $rsm->addFieldResult('a', 'a__city', 'city'); - $resultSet = array( - array( + $resultSet = [ + [ 'a__id' => '1', 'a__city' => 'Cracow', 'doctrine_rownum' => '1' - ), - ); + ], + ]; $expectedEntity = new \Doctrine\Tests\Models\CMS\CmsAddress(); $expectedEntity->id = 1; @@ -67,23 +72,53 @@ public function testInvalidDiscriminatorValueException() { $rsm = new ResultSetMapping; - $rsm->addEntityResult('Doctrine\Tests\Models\Company\CompanyPerson', 'p'); + $rsm->addEntityResult(CompanyPerson::class, 'p'); $rsm->addFieldResult('p', 'p__id', 'id'); $rsm->addFieldResult('p', 'p__name', 'name'); $rsm->addMetaResult('p', 'discr', 'discr', false, 'string'); $rsm->setDiscriminatorColumn('p', 'discr'); - $resultSet = array( - array( + $resultSet = [ + [ 'p__id' => '1', 'p__name' => 'Fabio B. Silva', 'discr' => 'subworker' - ), - ); + ], + ]; $stmt = new HydratorMockStatement($resultSet); $hydrator = new \Doctrine\ORM\Internal\Hydration\SimpleObjectHydrator($this->_em); $hydrator->hydrateAll($stmt, $rsm); } + + /** + * @group issue-5989 + */ + public function testNullValueShouldNotOverwriteFieldWithSameNameInJoinedInheritance() + { + $rsm = new ResultSetMapping; + $rsm->addEntityResult(Issue5989Person::class, 'p'); + $rsm->addFieldResult('p', 'p__id', 'id'); + $rsm->addFieldResult('p', 'm__tags', 'tags', Issue5989Manager::class); + $rsm->addFieldResult('p', 'e__tags', 'tags', Issue5989Employee::class); + $rsm->addMetaResult('p', 'discr', 'discr', false, 'string'); + $resultSet = [ + [ + 'p__id' => '1', + 'm__tags' => 'tag1,tag2', + 'e__tags' => null, + 'discr' => 'manager' + ], + ]; + + $expectedEntity = new Issue5989Manager(); + $expectedEntity->id = 1; + $expectedEntity->tags = ['tag1', 'tag2']; + + $stmt = new HydratorMockStatement($resultSet); + $hydrator = new \Doctrine\ORM\Internal\Hydration\SimpleObjectHydrator($this->_em); + $result = $hydrator->hydrateAll($stmt, $rsm); + $this->assertEquals($result[0], $expectedEntity); + } } diff --git a/tests/Doctrine/Tests/ORM/Hydration/SingleScalarHydratorTest.php b/tests/Doctrine/Tests/ORM/Hydration/SingleScalarHydratorTest.php index 219c7384ccc..f9d91be638d 100644 --- a/tests/Doctrine/Tests/ORM/Hydration/SingleScalarHydratorTest.php +++ b/tests/Doctrine/Tests/ORM/Hydration/SingleScalarHydratorTest.php @@ -2,47 +2,59 @@ namespace Doctrine\Tests\ORM\Hydration; +use Doctrine\ORM\Internal\Hydration\SingleScalarHydrator; +use Doctrine\ORM\NonUniqueResultException; use Doctrine\Tests\Mocks\HydratorMockStatement; use Doctrine\ORM\Query\ResultSetMapping; +use Doctrine\Tests\Models\CMS\CmsUser; class SingleScalarHydratorTest extends HydrationTestCase { /** Result set provider for the HYDRATE_SINGLE_SCALAR tests */ - public static function singleScalarResultSetProvider() { - return array( - // valid - array('name' => 'result1', - 'resultSet' => array( - array( - 'u__name' => 'romanb' - ) - )), - // valid - array('name' => 'result2', - 'resultSet' => array( - array( - 'u__id' => '1' - ) - )), - // invalid - array('name' => 'result3', - 'resultSet' => array( - array( - 'u__id' => '1', - 'u__name' => 'romanb' - ) - )), - // invalid - array('name' => 'result4', - 'resultSet' => array( - array( - 'u__id' => '1' - ), - array( - 'u__id' => '2' - ) - )), - ); + public static function singleScalarResultSetProvider(): array + { + return [ + // valid + 'valid' => [ + 'name' => 'result1', + 'resultSet' => [ + [ + 'u__name' => 'romanb', + ], + ], + ], + // valid + [ + 'name' => 'result2', + 'resultSet' => [ + [ + 'u__id' => '1', + ], + ], + ], + // invalid + [ + 'name' => 'result3', + 'resultSet' => [ + [ + 'u__id' => '1', + 'u__name' => 'romanb', + ], + ], + ], + // invalid + [ + 'name' => 'result4', + 'resultSet' => [ + [ + 'u__id' => '1', + ], + [ + 'u__id' => '2', + ], + ], + ], + ]; } /** @@ -53,24 +65,29 @@ public static function singleScalarResultSetProvider() { public function testHydrateSingleScalar($name, $resultSet) { $rsm = new ResultSetMapping; - $rsm->addEntityResult('Doctrine\Tests\Models\CMS\CmsUser', 'u'); + $rsm->addEntityResult(CmsUser::class, 'u'); $rsm->addFieldResult('u', 'u__id', 'id'); $rsm->addFieldResult('u', 'u__name', 'name'); $stmt = new HydratorMockStatement($resultSet); - $hydrator = new \Doctrine\ORM\Internal\Hydration\SingleScalarHydrator($this->_em); + $hydrator = new SingleScalarHydrator($this->_em); - if ($name == 'result1') { + if ($name === 'result1') { $result = $hydrator->hydrateAll($stmt, $rsm); $this->assertEquals('romanb', $result); - } else if ($name == 'result2') { + return; + } + + if ($name === 'result2') { $result = $hydrator->hydrateAll($stmt, $rsm); $this->assertEquals(1, $result); - } else if ($name == 'result3' || $name == 'result4') { - try { - $result = $hydrator->hydrateAll($stmt, $rsm); - $this->fail(); - } catch (\Doctrine\ORM\NonUniqueResultException $e) {} + + return; + } + + if (in_array($name, ['result3', 'result4'], true)) { + $this->expectException(NonUniqueResultException::class); + $hydrator->hydrateAll($stmt, $rsm); } } } diff --git a/tests/Doctrine/Tests/ORM/Id/AssignedGeneratorTest.php b/tests/Doctrine/Tests/ORM/Id/AssignedGeneratorTest.php index 855a9256f61..aa0240ebcd5 100644 --- a/tests/Doctrine/Tests/ORM/Id/AssignedGeneratorTest.php +++ b/tests/Doctrine/Tests/ORM/Id/AssignedGeneratorTest.php @@ -22,19 +22,22 @@ protected function setUp() $this->_assignedGen = new AssignedGenerator; } - public function testThrowsExceptionIfIdNotAssigned() + /** + * @dataProvider entitiesWithoutId + */ + public function testThrowsExceptionIfIdNotAssigned($entity) { - try { - $entity = new AssignedSingleIdEntity; - $this->_assignedGen->generate($this->_em, $entity); - $this->fail('Assigned generator did not throw exception even though ID was missing.'); - } catch (ORMException $expected) {} + $this->expectException(ORMException::class); - try { - $entity = new AssignedCompositeIdEntity; - $this->_assignedGen->generate($this->_em, $entity); - $this->fail('Assigned generator did not throw exception even though ID was missing.'); - } catch (ORMException $expected) {} + $this->_assignedGen->generate($this->_em, $entity); + } + + public function entitiesWithoutId(): array + { + return [ + 'single' => [new AssignedSingleIdEntity()], + 'composite' => [new AssignedCompositeIdEntity()], + ]; } public function testCorrectIdGeneration() @@ -42,13 +45,13 @@ public function testCorrectIdGeneration() $entity = new AssignedSingleIdEntity; $entity->myId = 1; $id = $this->_assignedGen->generate($this->_em, $entity); - $this->assertEquals(array('myId' => 1), $id); + $this->assertEquals(['myId' => 1], $id); $entity = new AssignedCompositeIdEntity; $entity->myId2 = 2; $entity->myId1 = 4; $id = $this->_assignedGen->generate($this->_em, $entity); - $this->assertEquals(array('myId1' => 4, 'myId2' => 2), $id); + $this->assertEquals(['myId1' => 4, 'myId2' => 2], $id); } } diff --git a/tests/Doctrine/Tests/ORM/Id/SequenceGeneratorTest.php b/tests/Doctrine/Tests/ORM/Id/SequenceGeneratorTest.php index 5d7f7a59b7f..5e4247715b0 100644 --- a/tests/Doctrine/Tests/ORM/Id/SequenceGeneratorTest.php +++ b/tests/Doctrine/Tests/ORM/Id/SequenceGeneratorTest.php @@ -2,38 +2,58 @@ namespace Doctrine\Tests\ORM\Id; +use Doctrine\ORM\EntityManager; use Doctrine\ORM\Id\SequenceGenerator; +use Doctrine\Tests\Mocks\ConnectionMock; +use Doctrine\Tests\Mocks\StatementArrayMock; use Doctrine\Tests\OrmTestCase; -/** - * Description of SequenceGeneratorTest - * - * @author robo - */ class SequenceGeneratorTest extends OrmTestCase { - private $_em; - private $_seqGen; - - protected function setUp() + /** + * @var EntityManager + */ + private $entityManager; + + /** + * @var SequenceGenerator + */ + private $sequenceGenerator; + + /** + * @var ConnectionMock + */ + private $connection; + + protected function setUp() : void { - $this->_em = $this->_getTestEntityManager(); - $this->_seqGen = new SequenceGenerator('seq', 10); + parent::setUp(); + + $this->entityManager = $this->_getTestEntityManager(); + $this->sequenceGenerator = new SequenceGenerator('seq', 10); + $this->connection = $this->entityManager->getConnection(); + + self::assertInstanceOf(ConnectionMock::class, $this->connection); } - public function testGeneration() + public function testGeneration() : void { - for ($i=0; $i < 42; ++$i) { + $this->connection->setFetchOneException(new \BadMethodCallException( + 'Fetch* method used. Query method should be used instead, ' + . 'as NEXTVAL should be run on a master server in master-slave setup.' + )); + + for ($i = 0; $i < 42; ++$i) { if ($i % 10 == 0) { - $this->_em->getConnection()->setFetchOneResult((int)($i / 10) * 10); + $this->connection->setQueryResult(new StatementArrayMock([[(int)($i / 10) * 10]])); } - $id = $this->_seqGen->generate($this->_em, null); - $this->assertEquals($i, $id); - $this->assertEquals((int)($i / 10) * 10 + 10, $this->_seqGen->getCurrentMaxValue()); - $this->assertEquals($i + 1, $this->_seqGen->getNextValue()); - } + $id = $this->sequenceGenerator->generate($this->entityManager, null); + self::assertSame($i, $id); + self::assertSame((int)($i / 10) * 10 + 10, $this->sequenceGenerator->getCurrentMaxValue()); + self::assertSame($i + 1, $this->sequenceGenerator->getNextValue()); + } } } diff --git a/tests/Doctrine/Tests/ORM/Internal/HydrationCompleteHandlerTest.php b/tests/Doctrine/Tests/ORM/Internal/HydrationCompleteHandlerTest.php index 1063b5aca4c..e4e9bcdf7df 100644 --- a/tests/Doctrine/Tests/ORM/Internal/HydrationCompleteHandlerTest.php +++ b/tests/Doctrine/Tests/ORM/Internal/HydrationCompleteHandlerTest.php @@ -25,7 +25,7 @@ use Doctrine\ORM\Events; use Doctrine\ORM\Internal\HydrationCompleteHandler; use Doctrine\ORM\Mapping\ClassMetadata; -use PHPUnit_Framework_TestCase; +use PHPUnit\Framework\TestCase; use stdClass; /** @@ -33,7 +33,7 @@ * * @covers \Doctrine\ORM\Internal\HydrationCompleteHandler */ -class HydrationCompleteHandlerTest extends PHPUnit_Framework_TestCase +class HydrationCompleteHandlerTest extends TestCase { /** * @var \Doctrine\ORM\Event\ListenersInvoker|\PHPUnit_Framework_MockObject_MockObject @@ -61,7 +61,7 @@ protected function setUp() } /** - * @dataProvider testGetValidListenerInvocationFlags + * @dataProvider invocationFlagProvider * * @param int $listenersFlag */ @@ -99,7 +99,7 @@ public function testDefersPostLoadOfEntity($listenersFlag) } /** - * @dataProvider testGetValidListenerInvocationFlags + * @dataProvider invocationFlagProvider * * @param int $listenersFlag */ @@ -125,7 +125,7 @@ public function testDefersPostLoadOfEntityOnlyOnce($listenersFlag) } /** - * @dataProvider testGetValidListenerInvocationFlags + * @dataProvider invocationFlagProvider * * @param int $listenersFlag */ @@ -158,7 +158,7 @@ public function testDefersMultiplePostLoadOfEntity($listenersFlag) Events::postLoad, $this->logicalOr($entity1, $entity2), $this->callback(function (LifecycleEventArgs $args) use ($entityManager, $entity1, $entity2) { - return in_array($args->getEntity(), array($entity1, $entity2), true) + return in_array($args->getEntity(), [$entity1, $entity2], true) && $entityManager === $args->getObjectManager(); }), $listenersFlag @@ -187,15 +187,15 @@ public function testSkipsDeferredPostLoadOfMetadataWithNoInvokedListeners() $this->handler->hydrationComplete(); } - public function testGetValidListenerInvocationFlags() + public function invocationFlagProvider() { - return array( - array(ListenersInvoker::INVOKE_LISTENERS), - array(ListenersInvoker::INVOKE_CALLBACKS), - array(ListenersInvoker::INVOKE_MANAGER), - array(ListenersInvoker::INVOKE_LISTENERS | ListenersInvoker::INVOKE_CALLBACKS), - array(ListenersInvoker::INVOKE_LISTENERS | ListenersInvoker::INVOKE_MANAGER), - array(ListenersInvoker::INVOKE_LISTENERS | ListenersInvoker::INVOKE_CALLBACKS | ListenersInvoker::INVOKE_MANAGER), - ); + return [ + [ListenersInvoker::INVOKE_LISTENERS], + [ListenersInvoker::INVOKE_CALLBACKS], + [ListenersInvoker::INVOKE_MANAGER], + [ListenersInvoker::INVOKE_LISTENERS | ListenersInvoker::INVOKE_CALLBACKS], + [ListenersInvoker::INVOKE_LISTENERS | ListenersInvoker::INVOKE_MANAGER], + [ListenersInvoker::INVOKE_LISTENERS | ListenersInvoker::INVOKE_CALLBACKS | ListenersInvoker::INVOKE_MANAGER], + ]; } } diff --git a/tests/Doctrine/Tests/ORM/LazyCriteriaCollectionTest.php b/tests/Doctrine/Tests/ORM/LazyCriteriaCollectionTest.php index 512b21115c9..9286da614f8 100644 --- a/tests/Doctrine/Tests/ORM/LazyCriteriaCollectionTest.php +++ b/tests/Doctrine/Tests/ORM/LazyCriteriaCollectionTest.php @@ -2,9 +2,11 @@ namespace Doctrine\Tests\ORM; +use Doctrine\Common\Collections\Collection; use Doctrine\Common\Collections\Criteria; use Doctrine\ORM\LazyCriteriaCollection; use Doctrine\ORM\Persisters\Entity\EntityPersister; +use PHPUnit\Framework\TestCase; use stdClass; /** @@ -12,7 +14,7 @@ * * @covers \Doctrine\ORM\LazyCriteriaCollection */ -class LazyCriteriaCollectionTest extends \PHPUnit_Framework_TestCase +class LazyCriteriaCollectionTest extends TestCase { /** * @var \Doctrine\ORM\Persisters\Entity\EntityPersister|\PHPUnit_Framework_MockObject_MockObject @@ -64,12 +66,12 @@ public function testCountUsesWrappedCollectionWhenInitialized() ->expects($this->once()) ->method('loadCriteria') ->with($this->criteria) - ->will($this->returnValue(array('foo', 'bar', 'baz'))); + ->will($this->returnValue(['foo', 'bar', 'baz'])); // should never call the persister's count $this->persister->expects($this->never())->method('count'); - $this->assertSame(array('foo', 'bar', 'baz'), $this->lazyCriteriaCollection->toArray()); + $this->assertSame(['foo', 'bar', 'baz'], $this->lazyCriteriaCollection->toArray()); $this->assertSame(3, $this->lazyCriteriaCollection->count()); } @@ -89,7 +91,7 @@ public function testMatchingUsesThePersisterOnlyOnce() ->expects($this->once()) ->method('loadCriteria') ->with($this->criteria) - ->will($this->returnValue(array($foo, $bar, $baz))); + ->will($this->returnValue([$foo, $bar, $baz])); $criteria = new Criteria(); @@ -97,10 +99,10 @@ public function testMatchingUsesThePersisterOnlyOnce() $filtered = $this->lazyCriteriaCollection->matching($criteria); - $this->assertInstanceOf('Doctrine\Common\Collections\Collection', $filtered); - $this->assertEquals(array($foo), $filtered->toArray()); + $this->assertInstanceOf(Collection::class, $filtered); + $this->assertEquals([$foo], $filtered->toArray()); - $this->assertEquals(array($foo), $this->lazyCriteriaCollection->matching($criteria)->toArray()); + $this->assertEquals([$foo], $this->lazyCriteriaCollection->matching($criteria)->toArray()); } public function testIsEmptyUsesCountWhenNotInitialized() @@ -124,12 +126,12 @@ public function testIsEmptyUsesWrappedCollectionWhenInitialized() ->expects($this->once()) ->method('loadCriteria') ->with($this->criteria) - ->will($this->returnValue(array('foo', 'bar', 'baz'))); + ->will($this->returnValue(['foo', 'bar', 'baz'])); // should never call the persister's count $this->persister->expects($this->never())->method('count'); - $this->assertSame(array('foo', 'bar', 'baz'), $this->lazyCriteriaCollection->toArray()); + $this->assertSame(['foo', 'bar', 'baz'], $this->lazyCriteriaCollection->toArray()); $this->assertFalse($this->lazyCriteriaCollection->isEmpty()); } diff --git a/tests/Doctrine/Tests/ORM/Mapping/AbstractMappingDriverTest.php b/tests/Doctrine/Tests/ORM/Mapping/AbstractMappingDriverTest.php index 8d90931f953..e13d7aa7e5b 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/AbstractMappingDriverTest.php +++ b/tests/Doctrine/Tests/ORM/Mapping/AbstractMappingDriverTest.php @@ -5,16 +5,37 @@ use Doctrine\Common\Persistence\Mapping\RuntimeReflectionService; use Doctrine\ORM\EntityManager; use Doctrine\ORM\Events; +use Doctrine\ORM\Mapping\ClassMetadata; use Doctrine\ORM\Mapping\ClassMetadataFactory; +use Doctrine\ORM\Mapping\ClassMetadataInfo; +use Doctrine\ORM\Mapping\DefaultNamingStrategy; use Doctrine\ORM\Mapping\DiscriminatorColumn; use Doctrine\ORM\Mapping\Id; use Doctrine\ORM\Mapping\MappingException; use Doctrine\ORM\Mapping\UnderscoreNamingStrategy; use Doctrine\Tests\Models\Cache\City; -use Doctrine\ORM\Mapping\ClassMetadata; -use Doctrine\ORM\Mapping\ClassMetadataInfo; +use Doctrine\Tests\Models\CMS\CmsAddress; +use Doctrine\Tests\Models\CMS\CmsAddressListener; +use Doctrine\Tests\Models\CMS\CmsUser; +use Doctrine\Tests\Models\Company\CompanyContract; +use Doctrine\Tests\Models\Company\CompanyContractListener; +use Doctrine\Tests\Models\Company\CompanyFixContract; +use Doctrine\Tests\Models\Company\CompanyFlexContract; +use Doctrine\Tests\Models\Company\CompanyFlexUltraContract; +use Doctrine\Tests\Models\Company\CompanyFlexUltraContractListener; +use Doctrine\Tests\Models\Company\CompanyPerson; +use Doctrine\Tests\Models\DDC1476\DDC1476EntityWithDefaultFieldType; use Doctrine\Tests\Models\DDC2825\ExplicitSchemaAndTable; use Doctrine\Tests\Models\DDC2825\SchemaAndTableInTableName; +use Doctrine\Tests\Models\DDC3579\DDC3579Admin; +use Doctrine\Tests\Models\DDC5934\DDC5934Contract; +use Doctrine\Tests\Models\DDC869\DDC869ChequePayment; +use Doctrine\Tests\Models\DDC869\DDC869CreditCardPayment; +use Doctrine\Tests\Models\DDC869\DDC869PaymentRepository; +use Doctrine\Tests\Models\DDC889\DDC889Class; +use Doctrine\Tests\Models\DDC889\DDC889Entity; +use Doctrine\Tests\Models\DDC964\DDC964Admin; +use Doctrine\Tests\Models\DDC964\DDC964Guest; use Doctrine\Tests\OrmTestCase; abstract class AbstractMappingDriverTest extends OrmTestCase @@ -47,18 +68,10 @@ protected function createClassMetadataFactory(EntityManager $em = null) return $factory; } - public function testLoadMapping() + public function testEntityTableNameAndInheritance() { - $entityClassName = 'Doctrine\Tests\ORM\Mapping\User'; - return $this->createClassMetadata($entityClassName); - } + $class = $this->createClassMetadata(User::class); - /** - * @depends testLoadMapping - * @param ClassMetadata $class - */ - public function testEntityTableNameAndInheritance($class) - { $this->assertEquals('cms_users', $class->getTableName()); $this->assertEquals(ClassMetadata::INHERITANCE_TYPE_NONE, $class->inheritanceType); @@ -72,25 +85,27 @@ public function testEntityTableNameAndInheritance($class) public function testEntityIndexes($class) { $this->assertArrayHasKey('indexes', $class->table, 'ClassMetadata should have indexes key in table property.'); - $this->assertEquals(array( - 'name_idx' => array('columns' => array('name')), - 0 => array('columns' => array('user_email')) - ), $class->table['indexes']); + $this->assertEquals( + [ + 'name_idx' => ['columns' => ['name']], + 0 => ['columns' => ['user_email']] + ], $class->table['indexes']); return $class; } public function testEntityIndexFlagsAndPartialIndexes() { - $class = $this->createClassMetadata('Doctrine\Tests\ORM\Mapping\Comment'); + $class = $this->createClassMetadata(Comment::class); - $this->assertEquals(array( - 0 => array( - 'columns' => array('content'), - 'flags' => array('fulltext'), - 'options' => array('where' => 'content IS NOT NULL'), - ) - ), $class->table['indexes']); + $this->assertEquals( + [ + 0 => [ + 'columns' => ['content'], + 'flags' => ['fulltext'], + 'options' => ['where' => 'content IS NOT NULL'], + ] + ], $class->table['indexes']); } /** @@ -102,9 +117,10 @@ public function testEntityUniqueConstraints($class) $this->assertArrayHasKey('uniqueConstraints', $class->table, 'ClassMetadata should have uniqueConstraints key in table property when Unique Constraints are set.'); - $this->assertEquals(array( - "search_idx" => array("columns" => array("name", "user_email"), 'options' => array('where' => 'name IS NOT NULL')) - ), $class->table['uniqueConstraints']); + $this->assertEquals( + [ + "search_idx" => ["columns" => ["name", "user_email"], 'options' => ['where' => 'name IS NOT NULL']] + ], $class->table['uniqueConstraints']); return $class; } @@ -117,9 +133,10 @@ public function testEntityOptions($class) { $this->assertArrayHasKey('options', $class->table, 'ClassMetadata should have options key in table property.'); - $this->assertEquals(array( - 'foo' => 'bar', 'baz' => array('key' => 'val') - ), $class->table['options']); + $this->assertEquals( + [ + 'foo' => 'bar', 'baz' => ['key' => 'val'] + ], $class->table['options']); return $class; } @@ -132,23 +149,23 @@ public function testEntitySequence($class) { $this->assertInternalType('array', $class->sequenceGeneratorDefinition, 'No Sequence Definition set on this driver.'); $this->assertEquals( - array( + [ 'sequenceName' => 'tablename_seq', 'allocationSize' => 100, 'initialValue' => 1, - ), + ], $class->sequenceGeneratorDefinition ); } public function testEntityCustomGenerator() { - $class = $this->createClassMetadata('Doctrine\Tests\ORM\Mapping\Animal'); + $class = $this->createClassMetadata(Animal::class); $this->assertEquals(ClassMetadata::GENERATOR_TYPE_CUSTOM, $class->generatorType, "Generator Type"); $this->assertEquals( - array("class" => "stdClass"), + ["class" => "stdClass"], $class->customGeneratorDefinition, "Custom Generator Definition"); } @@ -210,11 +227,14 @@ public function testStringFieldMappings($class) /** * @depends testEntityTableNameAndInheritance + * * @param ClassMetadata $class + * + * @return ClassMetadata */ - public function testFieldOptions($class) + public function testFieldOptions(ClassMetadata $class) { - $expected = array('foo' => 'bar', 'baz' => array('key' => 'val')); + $expected = ['foo' => 'bar', 'baz' => ['key' => 'val'], 'fixed' => false]; $this->assertEquals($expected, $class->fieldMappings['name']['options']); return $class; @@ -226,7 +246,7 @@ public function testFieldOptions($class) */ public function testIdFieldOptions($class) { - $this->assertEquals(array('foo' => 'bar'), $class->fieldMappings['id']['options']); + $this->assertEquals(['foo' => 'bar', 'unsigned' => false], $class->fieldMappings['id']['options']); return $class; } @@ -237,13 +257,31 @@ public function testIdFieldOptions($class) */ public function testIdentifier($class) { - $this->assertEquals(array('id'), $class->identifier); + $this->assertEquals(['id'], $class->identifier); $this->assertEquals('integer', $class->fieldMappings['id']['type']); $this->assertEquals(ClassMetadata::GENERATOR_TYPE_AUTO, $class->generatorType, "ID-Generator is not ClassMetadata::GENERATOR_TYPE_AUTO"); return $class; } + /** + * @group #6129 + * + * @return ClassMetadata + */ + public function testBooleanValuesForOptionIsSetCorrectly() + { + $class = $this->createClassMetadata(User::class); + + $this->assertInternalType('bool', $class->fieldMappings['id']['options']['unsigned']); + $this->assertFalse($class->fieldMappings['id']['options']['unsigned']); + + $this->assertInternalType('bool', $class->fieldMappings['name']['options']['fixed']); + $this->assertFalse($class->fieldMappings['name']['options']['fixed']); + + return $class; + } + /** * @depends testIdentifier * @param ClassMetadata $class @@ -290,7 +328,7 @@ public function testInverseOneToManyAssociation($class) $this->assertTrue($class->associationMappings['phonenumbers']['orphanRemoval']); // Test Order By - $this->assertEquals(array('number' => 'ASC'), $class->associationMappings['phonenumbers']['orderBy']); + $this->assertEquals(['number' => 'ASC'], $class->associationMappings['phonenumbers']['orderBy']); return $class; } @@ -385,10 +423,10 @@ public function testDiscriminatorColumnDefaults() $this->markTestSkipped('PHP Mapping Drivers have no defaults.'); } - $class = $this->createClassMetadata('Doctrine\Tests\ORM\Mapping\Animal'); + $class = $this->createClassMetadata(Animal::class); $this->assertEquals( - array('name' => 'discr', 'type' => 'string', 'length' => '32', 'fieldName' => 'discr', 'columnDefinition' => null), + ['name' => 'discr', 'type' => 'string', 'length' => '32', 'fieldName' => 'discr', 'columnDefinition' => null], $class->discriminatorColumn ); } @@ -402,27 +440,25 @@ public function testMappedSuperclassWithRepository() $factory = $this->createClassMetadataFactory($em); - $class = $factory->getMetadataFor('Doctrine\Tests\Models\DDC869\DDC869CreditCardPayment'); + $class = $factory->getMetadataFor(DDC869CreditCardPayment::class); $this->assertTrue(isset($class->fieldMappings['id'])); $this->assertTrue(isset($class->fieldMappings['value'])); $this->assertTrue(isset($class->fieldMappings['creditCardNumber'])); - $this->assertEquals($class->customRepositoryClassName, "Doctrine\Tests\Models\DDC869\DDC869PaymentRepository"); - $this->assertInstanceOf("Doctrine\Tests\Models\DDC869\DDC869PaymentRepository", - $em->getRepository("Doctrine\Tests\Models\DDC869\DDC869CreditCardPayment")); - $this->assertTrue($em->getRepository("Doctrine\Tests\Models\DDC869\DDC869ChequePayment")->isTrue()); + $this->assertEquals($class->customRepositoryClassName, DDC869PaymentRepository::class); + $this->assertInstanceOf(DDC869PaymentRepository::class, $em->getRepository(DDC869CreditCardPayment::class)); + $this->assertTrue($em->getRepository(DDC869ChequePayment::class)->isTrue()); - $class = $factory->getMetadataFor('Doctrine\Tests\Models\DDC869\DDC869ChequePayment'); + $class = $factory->getMetadataFor(DDC869ChequePayment::class); $this->assertTrue(isset($class->fieldMappings['id'])); $this->assertTrue(isset($class->fieldMappings['value'])); $this->assertTrue(isset($class->fieldMappings['serialNumber'])); - $this->assertEquals($class->customRepositoryClassName, "Doctrine\Tests\Models\DDC869\DDC869PaymentRepository"); - $this->assertInstanceOf("Doctrine\Tests\Models\DDC869\DDC869PaymentRepository", - $em->getRepository("Doctrine\Tests\Models\DDC869\DDC869ChequePayment")); - $this->assertTrue($em->getRepository("Doctrine\Tests\Models\DDC869\DDC869ChequePayment")->isTrue()); + $this->assertEquals($class->customRepositoryClassName, DDC869PaymentRepository::class); + $this->assertInstanceOf(DDC869PaymentRepository::class, $em->getRepository(DDC869ChequePayment::class)); + $this->assertTrue($em->getRepository(DDC869ChequePayment::class)->isTrue()); } /** @@ -431,7 +467,7 @@ public function testMappedSuperclassWithRepository() public function testDefaultFieldType() { $factory = $this->createClassMetadataFactory(); - $class = $factory->getMetadataFor('Doctrine\Tests\Models\DDC1476\DDC1476EntityWithDefaultFieldType'); + $class = $factory->getMetadataFor(DDC1476EntityWithDefaultFieldType::class); $this->assertArrayHasKey('id', $class->fieldMappings); @@ -468,7 +504,7 @@ public function testDefaultFieldType() */ public function testIdentifierColumnDefinition() { - $class = $this->createClassMetadata(__NAMESPACE__ . '\DDC1170Entity'); + $class = $this->createClassMetadata(DDC1170Entity::class); $this->assertArrayHasKey('id', $class->fieldMappings); @@ -490,11 +526,11 @@ public function testNamingStrategy() $factory = $this->createClassMetadataFactory($em); - $this->assertInstanceOf('Doctrine\ORM\Mapping\DefaultNamingStrategy', $em->getConfiguration()->getNamingStrategy()); + $this->assertInstanceOf(DefaultNamingStrategy::class, $em->getConfiguration()->getNamingStrategy()); $em->getConfiguration()->setNamingStrategy(new UnderscoreNamingStrategy(CASE_UPPER)); - $this->assertInstanceOf('Doctrine\ORM\Mapping\UnderscoreNamingStrategy', $em->getConfiguration()->getNamingStrategy()); + $this->assertInstanceOf(UnderscoreNamingStrategy::class, $em->getConfiguration()->getNamingStrategy()); - $class = $factory->getMetadataFor('Doctrine\Tests\Models\DDC1476\DDC1476EntityWithDefaultFieldType'); + $class = $factory->getMetadataFor(DDC1476EntityWithDefaultFieldType::class); $this->assertEquals('ID', $class->getColumnName('id')); $this->assertEquals('NAME', $class->getColumnName('name')); @@ -507,7 +543,7 @@ public function testNamingStrategy() */ public function testDiscriminatorColumnDefinition() { - $class = $this->createClassMetadata(__NAMESPACE__ . '\DDC807Entity'); + $class = $this->createClassMetadata(DDC807Entity::class); $this->assertArrayHasKey('columnDefinition', $class->discriminatorColumn); $this->assertArrayHasKey('name', $class->discriminatorColumn); @@ -524,7 +560,7 @@ public function testInvalidEntityOrMappedSuperClassShouldMentionParentClasses() $this->expectException(MappingException::class); $this->expectExceptionMessage('Class "Doctrine\Tests\Models\DDC889\DDC889Class" sub class of "Doctrine\Tests\Models\DDC889\DDC889SuperClass" is not a valid entity or mapped super class.'); - $this->createClassMetadata('Doctrine\Tests\Models\DDC889\DDC889Class'); + $this->createClassMetadata(DDC889Class::class); } /** @@ -537,13 +573,13 @@ public function testIdentifierRequiredShouldMentionParentClasses() $this->expectException(MappingException::class); $this->expectExceptionMessage('No identifier/primary key specified for Entity "Doctrine\Tests\Models\DDC889\DDC889Entity" sub class of "Doctrine\Tests\Models\DDC889\DDC889SuperClass". Every Entity must have an identifier/primary key.'); - $factory->getMetadataFor('Doctrine\Tests\Models\DDC889\DDC889Entity'); + $factory->getMetadataFor(DDC889Entity::class); } public function testNamedQuery() { $driver = $this->_loadDriver(); - $class = $this->createClassMetadata(__NAMESPACE__.'\User'); + $class = $this->createClassMetadata(User::class); $this->assertCount(1, $class->getNamedQueries(), sprintf("Named queries not processed correctly by driver %s", get_class($driver))); } @@ -554,7 +590,7 @@ public function testNamedQuery() public function testNamedNativeQuery() { - $class = $this->createClassMetadata('Doctrine\Tests\Models\CMS\CmsAddress'); + $class = $this->createClassMetadata(CmsAddress::class); //named native query $this->assertCount(3, $class->namedNativeQueries); @@ -569,7 +605,7 @@ public function testNamedNativeQuery() $findByIdQuery = $class->getNamedNativeQuery('find-by-id'); $this->assertEquals('find-by-id', $findByIdQuery['name']); - $this->assertEquals('Doctrine\Tests\Models\CMS\CmsAddress',$findByIdQuery['resultClass']); + $this->assertEquals(CmsAddress::class,$findByIdQuery['resultClass']); $this->assertEquals('SELECT * FROM cms_addresses WHERE id = ?', $findByIdQuery['query']); $countQuery = $class->getNamedNativeQuery('count'); @@ -585,19 +621,19 @@ public function testNamedNativeQuery() $findAllMapping = $class->getSqlResultSetMapping('mapping-find-all'); $this->assertEquals('mapping-find-all', $findAllMapping['name']); - $this->assertEquals('Doctrine\Tests\Models\CMS\CmsAddress', $findAllMapping['entities'][0]['entityClass']); - $this->assertEquals(array('name'=>'id','column'=>'id'), $findAllMapping['entities'][0]['fields'][0]); - $this->assertEquals(array('name'=>'city','column'=>'city'), $findAllMapping['entities'][0]['fields'][1]); - $this->assertEquals(array('name'=>'country','column'=>'country'), $findAllMapping['entities'][0]['fields'][2]); + $this->assertEquals(CmsAddress::class, $findAllMapping['entities'][0]['entityClass']); + $this->assertEquals(['name'=>'id','column'=>'id'], $findAllMapping['entities'][0]['fields'][0]); + $this->assertEquals(['name'=>'city','column'=>'city'], $findAllMapping['entities'][0]['fields'][1]); + $this->assertEquals(['name'=>'country','column'=>'country'], $findAllMapping['entities'][0]['fields'][2]); $withoutFieldsMapping = $class->getSqlResultSetMapping('mapping-without-fields'); $this->assertEquals('mapping-without-fields', $withoutFieldsMapping['name']); - $this->assertEquals('Doctrine\Tests\Models\CMS\CmsAddress', $withoutFieldsMapping['entities'][0]['entityClass']); - $this->assertEquals(array(), $withoutFieldsMapping['entities'][0]['fields']); + $this->assertEquals(CmsAddress::class, $withoutFieldsMapping['entities'][0]['entityClass']); + $this->assertEquals([], $withoutFieldsMapping['entities'][0]['fields']); $countMapping = $class->getSqlResultSetMapping('mapping-count'); $this->assertEquals('mapping-count', $countMapping['name']); - $this->assertEquals(array('name'=>'count'), $countMapping['columns'][0]); + $this->assertEquals(['name'=>'count'], $countMapping['columns'][0]); } @@ -607,68 +643,68 @@ public function testNamedNativeQuery() public function testSqlResultSetMapping() { - $userMetadata = $this->createClassMetadata('Doctrine\Tests\Models\CMS\CmsUser'); - $personMetadata = $this->createClassMetadata('Doctrine\Tests\Models\Company\CompanyPerson'); + $userMetadata = $this->createClassMetadata(CmsUser::class); + $personMetadata = $this->createClassMetadata(CompanyPerson::class); // user asserts $this->assertCount(4, $userMetadata->getSqlResultSetMappings()); $mapping = $userMetadata->getSqlResultSetMapping('mappingJoinedAddress'); - $this->assertEquals(array(),$mapping['columns']); + $this->assertEquals([],$mapping['columns']); $this->assertEquals('mappingJoinedAddress', $mapping['name']); $this->assertNull($mapping['entities'][0]['discriminatorColumn']); - $this->assertEquals(array('name'=>'id','column'=>'id'), $mapping['entities'][0]['fields'][0]); - $this->assertEquals(array('name'=>'name','column'=>'name'), $mapping['entities'][0]['fields'][1]); - $this->assertEquals(array('name'=>'status','column'=>'status'), $mapping['entities'][0]['fields'][2]); - $this->assertEquals(array('name'=>'address.zip','column'=>'zip'), $mapping['entities'][0]['fields'][3]); - $this->assertEquals(array('name'=>'address.city','column'=>'city'), $mapping['entities'][0]['fields'][4]); - $this->assertEquals(array('name'=>'address.country','column'=>'country'), $mapping['entities'][0]['fields'][5]); - $this->assertEquals(array('name'=>'address.id','column'=>'a_id'), $mapping['entities'][0]['fields'][6]); + $this->assertEquals(['name'=>'id','column'=>'id'], $mapping['entities'][0]['fields'][0]); + $this->assertEquals(['name'=>'name','column'=>'name'], $mapping['entities'][0]['fields'][1]); + $this->assertEquals(['name'=>'status','column'=>'status'], $mapping['entities'][0]['fields'][2]); + $this->assertEquals(['name'=>'address.zip','column'=>'zip'], $mapping['entities'][0]['fields'][3]); + $this->assertEquals(['name'=>'address.city','column'=>'city'], $mapping['entities'][0]['fields'][4]); + $this->assertEquals(['name'=>'address.country','column'=>'country'], $mapping['entities'][0]['fields'][5]); + $this->assertEquals(['name'=>'address.id','column'=>'a_id'], $mapping['entities'][0]['fields'][6]); $this->assertEquals($userMetadata->name, $mapping['entities'][0]['entityClass']); $mapping = $userMetadata->getSqlResultSetMapping('mappingJoinedPhonenumber'); - $this->assertEquals(array(),$mapping['columns']); + $this->assertEquals([],$mapping['columns']); $this->assertEquals('mappingJoinedPhonenumber', $mapping['name']); $this->assertNull($mapping['entities'][0]['discriminatorColumn']); - $this->assertEquals(array('name'=>'id','column'=>'id'), $mapping['entities'][0]['fields'][0]); - $this->assertEquals(array('name'=>'name','column'=>'name'), $mapping['entities'][0]['fields'][1]); - $this->assertEquals(array('name'=>'status','column'=>'status'), $mapping['entities'][0]['fields'][2]); - $this->assertEquals(array('name'=>'phonenumbers.phonenumber','column'=>'number'), $mapping['entities'][0]['fields'][3]); + $this->assertEquals(['name'=>'id','column'=>'id'], $mapping['entities'][0]['fields'][0]); + $this->assertEquals(['name'=>'name','column'=>'name'], $mapping['entities'][0]['fields'][1]); + $this->assertEquals(['name'=>'status','column'=>'status'], $mapping['entities'][0]['fields'][2]); + $this->assertEquals(['name'=>'phonenumbers.phonenumber','column'=>'number'], $mapping['entities'][0]['fields'][3]); $this->assertEquals($userMetadata->name, $mapping['entities'][0]['entityClass']); $mapping = $userMetadata->getSqlResultSetMapping('mappingUserPhonenumberCount'); - $this->assertEquals(array('name'=>'numphones'),$mapping['columns'][0]); + $this->assertEquals(['name'=>'numphones'],$mapping['columns'][0]); $this->assertEquals('mappingUserPhonenumberCount', $mapping['name']); $this->assertNull($mapping['entities'][0]['discriminatorColumn']); - $this->assertEquals(array('name'=>'id','column'=>'id'), $mapping['entities'][0]['fields'][0]); - $this->assertEquals(array('name'=>'name','column'=>'name'), $mapping['entities'][0]['fields'][1]); - $this->assertEquals(array('name'=>'status','column'=>'status'), $mapping['entities'][0]['fields'][2]); + $this->assertEquals(['name'=>'id','column'=>'id'], $mapping['entities'][0]['fields'][0]); + $this->assertEquals(['name'=>'name','column'=>'name'], $mapping['entities'][0]['fields'][1]); + $this->assertEquals(['name'=>'status','column'=>'status'], $mapping['entities'][0]['fields'][2]); $this->assertEquals($userMetadata->name, $mapping['entities'][0]['entityClass']); $mapping = $userMetadata->getSqlResultSetMapping('mappingMultipleJoinsEntityResults'); - $this->assertEquals(array('name'=>'numphones'),$mapping['columns'][0]); + $this->assertEquals(['name'=>'numphones'],$mapping['columns'][0]); $this->assertEquals('mappingMultipleJoinsEntityResults', $mapping['name']); $this->assertNull($mapping['entities'][0]['discriminatorColumn']); - $this->assertEquals(array('name'=>'id','column'=>'u_id'), $mapping['entities'][0]['fields'][0]); - $this->assertEquals(array('name'=>'name','column'=>'u_name'), $mapping['entities'][0]['fields'][1]); - $this->assertEquals(array('name'=>'status','column'=>'u_status'), $mapping['entities'][0]['fields'][2]); + $this->assertEquals(['name'=>'id','column'=>'u_id'], $mapping['entities'][0]['fields'][0]); + $this->assertEquals(['name'=>'name','column'=>'u_name'], $mapping['entities'][0]['fields'][1]); + $this->assertEquals(['name'=>'status','column'=>'u_status'], $mapping['entities'][0]['fields'][2]); $this->assertEquals($userMetadata->name, $mapping['entities'][0]['entityClass']); $this->assertNull($mapping['entities'][1]['discriminatorColumn']); - $this->assertEquals(array('name'=>'id','column'=>'a_id'), $mapping['entities'][1]['fields'][0]); - $this->assertEquals(array('name'=>'zip','column'=>'a_zip'), $mapping['entities'][1]['fields'][1]); - $this->assertEquals(array('name'=>'country','column'=>'a_country'), $mapping['entities'][1]['fields'][2]); - $this->assertEquals('Doctrine\Tests\Models\CMS\CmsAddress', $mapping['entities'][1]['entityClass']); + $this->assertEquals(['name'=>'id','column'=>'a_id'], $mapping['entities'][1]['fields'][0]); + $this->assertEquals(['name'=>'zip','column'=>'a_zip'], $mapping['entities'][1]['fields'][1]); + $this->assertEquals(['name'=>'country','column'=>'a_country'], $mapping['entities'][1]['fields'][2]); + $this->assertEquals(CmsAddress::class, $mapping['entities'][1]['entityClass']); //person asserts $this->assertCount(1, $personMetadata->getSqlResultSetMappings()); $mapping = $personMetadata->getSqlResultSetMapping('mappingFetchAll'); - $this->assertEquals(array(),$mapping['columns']); + $this->assertEquals([],$mapping['columns']); $this->assertEquals('mappingFetchAll', $mapping['name']); $this->assertEquals('discriminator', $mapping['entities'][0]['discriminatorColumn']); - $this->assertEquals(array('name'=>'id','column'=>'id'), $mapping['entities'][0]['fields'][0]); - $this->assertEquals(array('name'=>'name','column'=>'name'), $mapping['entities'][0]['fields'][1]); + $this->assertEquals(['name'=>'id','column'=>'id'], $mapping['entities'][0]['fields'][0]); + $this->assertEquals(['name'=>'name','column'=>'name'], $mapping['entities'][0]['fields'][1]); $this->assertEquals($personMetadata->name, $mapping['entities'][0]['entityClass']); } @@ -679,8 +715,8 @@ public function testAssociationOverridesMapping() { $factory = $this->createClassMetadataFactory(); - $adminMetadata = $factory->getMetadataFor('Doctrine\Tests\Models\DDC964\DDC964Admin'); - $guestMetadata = $factory->getMetadataFor('Doctrine\Tests\Models\DDC964\DDC964Guest'); + $adminMetadata = $factory->getMetadataFor(DDC964Admin::class); + $guestMetadata = $factory->getMetadataFor(DDC964Guest::class); // assert groups association mappings @@ -708,18 +744,18 @@ public function testAssociationOverridesMapping() $this->assertEquals('user_id', $guestGroups['joinTable']['joinColumns'][0]['name']); $this->assertEquals('group_id', $guestGroups['joinTable']['inverseJoinColumns'][0]['name']); - $this->assertEquals(array('user_id'=>'id'), $guestGroups['relationToSourceKeyColumns']); - $this->assertEquals(array('group_id'=>'id'), $guestGroups['relationToTargetKeyColumns']); - $this->assertEquals(array('user_id','group_id'), $guestGroups['joinTableColumns']); + $this->assertEquals(['user_id'=>'id'], $guestGroups['relationToSourceKeyColumns']); + $this->assertEquals(['group_id'=>'id'], $guestGroups['relationToTargetKeyColumns']); + $this->assertEquals(['user_id','group_id'], $guestGroups['joinTableColumns']); $this->assertEquals('ddc964_users_admingroups', $adminGroups['joinTable']['name']); $this->assertEquals('adminuser_id', $adminGroups['joinTable']['joinColumns'][0]['name']); $this->assertEquals('admingroup_id', $adminGroups['joinTable']['inverseJoinColumns'][0]['name']); - $this->assertEquals(array('adminuser_id'=>'id'), $adminGroups['relationToSourceKeyColumns']); - $this->assertEquals(array('admingroup_id'=>'id'), $adminGroups['relationToTargetKeyColumns']); - $this->assertEquals(array('adminuser_id','admingroup_id'), $adminGroups['joinTableColumns']); + $this->assertEquals(['adminuser_id'=>'id'], $adminGroups['relationToSourceKeyColumns']); + $this->assertEquals(['admingroup_id'=>'id'], $adminGroups['relationToTargetKeyColumns']); + $this->assertEquals(['adminuser_id','admingroup_id'], $adminGroups['joinTableColumns']); // assert address association mappings @@ -744,15 +780,15 @@ public function testAssociationOverridesMapping() // assert override $this->assertEquals('address_id', $guestAddress['joinColumns'][0]['name']); - $this->assertEquals(array('address_id'=>'id'), $guestAddress['sourceToTargetKeyColumns']); - $this->assertEquals(array('address_id'=>'address_id'), $guestAddress['joinColumnFieldNames']); - $this->assertEquals(array('id'=>'address_id'), $guestAddress['targetToSourceKeyColumns']); + $this->assertEquals(['address_id'=>'id'], $guestAddress['sourceToTargetKeyColumns']); + $this->assertEquals(['address_id'=>'address_id'], $guestAddress['joinColumnFieldNames']); + $this->assertEquals(['id'=>'address_id'], $guestAddress['targetToSourceKeyColumns']); $this->assertEquals('adminaddress_id', $adminAddress['joinColumns'][0]['name']); - $this->assertEquals(array('adminaddress_id'=>'id'), $adminAddress['sourceToTargetKeyColumns']); - $this->assertEquals(array('adminaddress_id'=>'adminaddress_id'), $adminAddress['joinColumnFieldNames']); - $this->assertEquals(array('id'=>'adminaddress_id'), $adminAddress['targetToSourceKeyColumns']); + $this->assertEquals(['adminaddress_id'=>'id'], $adminAddress['sourceToTargetKeyColumns']); + $this->assertEquals(['adminaddress_id'=>'adminaddress_id'], $adminAddress['joinColumnFieldNames']); + $this->assertEquals(['id'=>'adminaddress_id'], $adminAddress['targetToSourceKeyColumns']); } /* @@ -762,7 +798,7 @@ public function testInversedByOverrideMapping() { $factory = $this->createClassMetadataFactory(); - $adminMetadata = $factory->getMetadataFor('Doctrine\Tests\Models\DDC3579\DDC3579Admin'); + $adminMetadata = $factory->getMetadataFor(DDC3579Admin::class); // assert groups association mappings $this->assertArrayHasKey('groups', $adminMetadata->associationMappings); @@ -772,6 +808,18 @@ public function testInversedByOverrideMapping() $this->assertEquals('admins', $adminGroups['inversedBy']); } + /** + * @group DDC-5934 + */ + public function testFetchOverrideMapping() + { + // check override metadata + $contractMetadata = $this->createClassMetadataFactory()->getMetadataFor(DDC5934Contract::class); + + $this->assertArrayHasKey('members', $contractMetadata->associationMappings); + $this->assertSame(ClassMetadata::FETCH_EXTRA_LAZY, $contractMetadata->associationMappings['members']['fetch']); + } + /** * @group DDC-964 */ @@ -779,14 +827,14 @@ public function testAttributeOverridesMapping() { $factory = $this->createClassMetadataFactory(); - $guestMetadata = $factory->getMetadataFor('Doctrine\Tests\Models\DDC964\DDC964Guest'); - $adminMetadata = $factory->getMetadataFor('Doctrine\Tests\Models\DDC964\DDC964Admin'); + $guestMetadata = $factory->getMetadataFor(DDC964Guest::class); + $adminMetadata = $factory->getMetadataFor(DDC964Admin::class); $this->assertTrue($adminMetadata->fieldMappings['id']['id']); $this->assertEquals('id', $adminMetadata->fieldMappings['id']['fieldName']); $this->assertEquals('user_id', $adminMetadata->fieldMappings['id']['columnName']); - $this->assertEquals(array('user_id'=>'id','user_name'=>'name'), $adminMetadata->fieldNames); - $this->assertEquals(array('id'=>'user_id','name'=>'user_name'), $adminMetadata->columnNames); + $this->assertEquals(['user_id'=>'id','user_name'=>'name'], $adminMetadata->fieldNames); + $this->assertEquals(['id'=>'user_id','name'=>'user_name'], $adminMetadata->columnNames); $this->assertEquals(150, $adminMetadata->fieldMappings['id']['length']); @@ -800,8 +848,8 @@ public function testAttributeOverridesMapping() $this->assertTrue($guestMetadata->fieldMappings['id']['id']); $this->assertEquals('guest_id', $guestMetadata->fieldMappings['id']['columnName']); $this->assertEquals('id', $guestMetadata->fieldMappings['id']['fieldName']); - $this->assertEquals(array('guest_id'=>'id','guest_name'=>'name'), $guestMetadata->fieldNames); - $this->assertEquals(array('id'=>'guest_id','name'=>'guest_name'), $guestMetadata->columnNames); + $this->assertEquals(['guest_id'=>'id','guest_name'=>'name'], $guestMetadata->fieldNames); + $this->assertEquals(['id'=>'guest_id','name'=>'guest_name'], $guestMetadata->columnNames); $this->assertEquals(140, $guestMetadata->fieldMappings['id']['length']); $this->assertEquals('name', $guestMetadata->fieldMappings['name']['fieldName']); @@ -818,10 +866,10 @@ public function testEntityListeners() { $em = $this->_getTestEntityManager(); $factory = $this->createClassMetadataFactory($em); - $superClass = $factory->getMetadataFor('Doctrine\Tests\Models\Company\CompanyContract'); - $flexClass = $factory->getMetadataFor('Doctrine\Tests\Models\Company\CompanyFixContract'); - $fixClass = $factory->getMetadataFor('Doctrine\Tests\Models\Company\CompanyFlexContract'); - $ultraClass = $factory->getMetadataFor('Doctrine\Tests\Models\Company\CompanyFlexUltraContract'); + $superClass = $factory->getMetadataFor(CompanyContract::class); + $flexClass = $factory->getMetadataFor(CompanyFixContract::class); + $fixClass = $factory->getMetadataFor(CompanyFlexContract::class); + $ultraClass = $factory->getMetadataFor(CompanyFlexUltraContract::class); $this->assertArrayHasKey(Events::prePersist, $superClass->entityListeners); $this->assertArrayHasKey(Events::postPersist, $superClass->entityListeners); @@ -832,8 +880,8 @@ public function testEntityListeners() $postPersist = $superClass->entityListeners[Events::postPersist][0]; $prePersist = $superClass->entityListeners[Events::prePersist][0]; - $this->assertEquals('Doctrine\Tests\Models\Company\CompanyContractListener', $postPersist['class']); - $this->assertEquals('Doctrine\Tests\Models\Company\CompanyContractListener', $prePersist['class']); + $this->assertEquals(CompanyContractListener::class, $postPersist['class']); + $this->assertEquals(CompanyContractListener::class, $prePersist['class']); $this->assertEquals('postPersistHandler', $postPersist['method']); $this->assertEquals('prePersistHandler', $prePersist['method']); @@ -849,7 +897,7 @@ public function testEntityListenersOverride() { $em = $this->_getTestEntityManager(); $factory = $this->createClassMetadataFactory($em); - $ultraClass = $factory->getMetadataFor('Doctrine\Tests\Models\Company\CompanyFlexUltraContract'); + $ultraClass = $factory->getMetadataFor(CompanyFlexUltraContract::class); //overridden listeners $this->assertArrayHasKey(Events::postPersist, $ultraClass->entityListeners); @@ -861,17 +909,17 @@ public function testEntityListenersOverride() $postPersist = $ultraClass->entityListeners[Events::postPersist][0]; $prePersist = $ultraClass->entityListeners[Events::prePersist][0]; - $this->assertEquals('Doctrine\Tests\Models\Company\CompanyContractListener', $postPersist['class']); - $this->assertEquals('Doctrine\Tests\Models\Company\CompanyContractListener', $prePersist['class']); + $this->assertEquals(CompanyContractListener::class, $postPersist['class']); + $this->assertEquals(CompanyContractListener::class, $prePersist['class']); $this->assertEquals('postPersistHandler', $postPersist['method']); $this->assertEquals('prePersistHandler', $prePersist['method']); $prePersist = $ultraClass->entityListeners[Events::prePersist][1]; - $this->assertEquals('Doctrine\Tests\Models\Company\CompanyFlexUltraContractListener', $prePersist['class']); + $this->assertEquals(CompanyFlexUltraContractListener::class, $prePersist['class']); $this->assertEquals('prePersistHandler1', $prePersist['method']); $prePersist = $ultraClass->entityListeners[Events::prePersist][2]; - $this->assertEquals('Doctrine\Tests\Models\Company\CompanyFlexUltraContractListener', $prePersist['class']); + $this->assertEquals(CompanyFlexUltraContractListener::class, $prePersist['class']); $this->assertEquals('prePersistHandler2', $prePersist['method']); } @@ -883,7 +931,7 @@ public function testEntityListenersNamingConvention() { $em = $this->_getTestEntityManager(); $factory = $this->createClassMetadataFactory($em); - $metadata = $factory->getMetadataFor('Doctrine\Tests\Models\CMS\CmsAddress'); + $metadata = $factory->getMetadataFor(CmsAddress::class); $this->assertArrayHasKey(Events::postPersist, $metadata->entityListeners); $this->assertArrayHasKey(Events::prePersist, $metadata->entityListeners); @@ -913,14 +961,14 @@ public function testEntityListenersNamingConvention() $preFlush = $metadata->entityListeners[Events::preFlush][0]; - $this->assertEquals('Doctrine\Tests\Models\CMS\CmsAddressListener', $postPersist['class']); - $this->assertEquals('Doctrine\Tests\Models\CMS\CmsAddressListener', $prePersist['class']); - $this->assertEquals('Doctrine\Tests\Models\CMS\CmsAddressListener', $postUpdate['class']); - $this->assertEquals('Doctrine\Tests\Models\CMS\CmsAddressListener', $preUpdate['class']); - $this->assertEquals('Doctrine\Tests\Models\CMS\CmsAddressListener', $postRemove['class']); - $this->assertEquals('Doctrine\Tests\Models\CMS\CmsAddressListener', $preRemove['class']); - $this->assertEquals('Doctrine\Tests\Models\CMS\CmsAddressListener', $postLoad['class']); - $this->assertEquals('Doctrine\Tests\Models\CMS\CmsAddressListener', $preFlush['class']); + $this->assertEquals(CmsAddressListener::class, $postPersist['class']); + $this->assertEquals(CmsAddressListener::class, $prePersist['class']); + $this->assertEquals(CmsAddressListener::class, $postUpdate['class']); + $this->assertEquals(CmsAddressListener::class, $preUpdate['class']); + $this->assertEquals(CmsAddressListener::class, $postRemove['class']); + $this->assertEquals(CmsAddressListener::class, $preRemove['class']); + $this->assertEquals(CmsAddressListener::class, $postLoad['class']); + $this->assertEquals(CmsAddressListener::class, $preFlush['class']); $this->assertEquals(Events::postPersist, $postPersist['method']); $this->assertEquals(Events::prePersist, $prePersist['method']); @@ -939,7 +987,7 @@ public function testSecondLevelCacheMapping() { $em = $this->_getTestEntityManager(); $factory = $this->createClassMetadataFactory($em); - $class = $factory->getMetadataFor(City::CLASSNAME); + $class = $factory->getMetadataFor(City::class); $this->assertArrayHasKey('usage', $class->cache); $this->assertArrayHasKey('region', $class->cache); $this->assertEquals(ClassMetadata::CACHE_USAGE_READ_ONLY, $class->cache['usage']); @@ -967,7 +1015,7 @@ public function testSecondLevelCacheMapping() public function testSchemaDefinitionViaExplicitTableSchemaAnnotationProperty() { /* @var $metadata \Doctrine\ORM\Mapping\ClassMetadata */ - $metadata = $this->createClassMetadataFactory()->getMetadataFor(ExplicitSchemaAndTable::CLASSNAME); + $metadata = $this->createClassMetadataFactory()->getMetadataFor(ExplicitSchemaAndTable::class); $this->assertSame('explicit_schema', $metadata->getSchemaName()); $this->assertSame('explicit_table', $metadata->getTableName()); @@ -980,7 +1028,7 @@ public function testSchemaDefinitionViaExplicitTableSchemaAnnotationProperty() public function testSchemaDefinitionViaSchemaDefinedInTableNameInTableAnnotationProperty() { /* @var $metadata \Doctrine\ORM\Mapping\ClassMetadata */ - $metadata = $this->createClassMetadataFactory()->getMetadataFor(SchemaAndTableInTableName::CLASSNAME); + $metadata = $this->createClassMetadataFactory()->getMetadataFor(SchemaAndTableInTableName::class); $this->assertSame('implicit_schema', $metadata->getSchemaName()); $this->assertSame('implicit_table', $metadata->getTableName()); @@ -995,9 +1043,9 @@ public function testDiscriminatorColumnDefaultLength() if (strpos(get_class($this), 'PHPMappingDriver') !== false) { $this->markTestSkipped('PHP Mapping Drivers have no defaults.'); } - $class = $this->createClassMetadata(__NAMESPACE__ . '\SingleTableEntityNoDiscriminatorColumnMapping'); + $class = $this->createClassMetadata(SingleTableEntityNoDiscriminatorColumnMapping::class); $this->assertEquals(255, $class->discriminatorColumn['length']); - $class = $this->createClassMetadata(__NAMESPACE__ . '\SingleTableEntityIncompleteDiscriminatorColumnMapping'); + $class = $this->createClassMetadata(SingleTableEntityIncompleteDiscriminatorColumnMapping::class); $this->assertEquals(255, $class->discriminatorColumn['length']); } @@ -1010,9 +1058,9 @@ public function testDiscriminatorColumnDefaultType() if (strpos(get_class($this), 'PHPMappingDriver') !== false) { $this->markTestSkipped('PHP Mapping Drivers have no defaults.'); } - $class = $this->createClassMetadata(__NAMESPACE__ . '\SingleTableEntityNoDiscriminatorColumnMapping'); + $class = $this->createClassMetadata(SingleTableEntityNoDiscriminatorColumnMapping::class); $this->assertEquals('string', $class->discriminatorColumn['type']); - $class = $this->createClassMetadata(__NAMESPACE__ . '\SingleTableEntityIncompleteDiscriminatorColumnMapping'); + $class = $this->createClassMetadata(SingleTableEntityIncompleteDiscriminatorColumnMapping::class); $this->assertEquals('string', $class->discriminatorColumn['type']); } @@ -1025,9 +1073,9 @@ public function testDiscriminatorColumnDefaultName() if (strpos(get_class($this), 'PHPMappingDriver') !== false) { $this->markTestSkipped('PHP Mapping Drivers have no defaults.'); } - $class = $this->createClassMetadata(__NAMESPACE__ . '\SingleTableEntityNoDiscriminatorColumnMapping'); + $class = $this->createClassMetadata(SingleTableEntityNoDiscriminatorColumnMapping::class); $this->assertEquals('dtype', $class->discriminatorColumn['name']); - $class = $this->createClassMetadata(__NAMESPACE__ . '\SingleTableEntityIncompleteDiscriminatorColumnMapping'); + $class = $this->createClassMetadata(SingleTableEntityIncompleteDiscriminatorColumnMapping::class); $this->assertEquals('dtype', $class->discriminatorColumn['name']); } @@ -1048,14 +1096,14 @@ class User { /** * @Id - * @Column(type="integer", options={"foo": "bar"}) + * @Column(type="integer", options={"foo": "bar", "unsigned": false}) * @generatedValue(strategy="AUTO") * @SequenceGenerator(sequenceName="tablename_seq", initialValue=1, allocationSize=100) **/ public $id; /** - * @Column(length=50, nullable=true, unique=true, options={"foo": "bar", "baz": {"key": "val"}}) + * @Column(length=50, nullable=true, unique=true, options={"foo": "bar", "baz": {"key": "val"}, "fixed": false}) */ public $name; @@ -1116,126 +1164,144 @@ public function doStuffOnPostPersist() public static function loadMetadata(ClassMetadataInfo $metadata) { $metadata->setInheritanceType(ClassMetadataInfo::INHERITANCE_TYPE_NONE); - $metadata->setPrimaryTable(array( + $metadata->setPrimaryTable( + [ 'name' => 'cms_users', - 'options' => array('foo' => 'bar', 'baz' => array('key' => 'val')), - )); + 'options' => ['foo' => 'bar', 'baz' => ['key' => 'val']], + ] + ); $metadata->setChangeTrackingPolicy(ClassMetadataInfo::CHANGETRACKING_DEFERRED_IMPLICIT); $metadata->addLifecycleCallback('doStuffOnPrePersist', 'prePersist'); $metadata->addLifecycleCallback('doOtherStuffOnPrePersistToo', 'prePersist'); $metadata->addLifecycleCallback('doStuffOnPostPersist', 'postPersist'); - $metadata->mapField(array( + $metadata->mapField( + [ 'id' => true, 'fieldName' => 'id', 'type' => 'integer', 'columnName' => 'id', - 'options' => array('foo' => 'bar'), - )); - $metadata->mapField(array( + 'options' => ['foo' => 'bar', 'unsigned' => false], + ] + ); + $metadata->mapField( + [ 'fieldName' => 'name', 'type' => 'string', 'length' => 50, 'unique' => true, 'nullable' => true, 'columnName' => 'name', - 'options' => array('foo' => 'bar', 'baz' => array('key' => 'val')), - )); - $metadata->mapField(array( + 'options' => ['foo' => 'bar', 'baz' => ['key' => 'val'], 'fixed' => false], + ] + ); + $metadata->mapField( + [ 'fieldName' => 'email', 'type' => 'string', 'columnName' => 'user_email', 'columnDefinition' => 'CHAR(32) NOT NULL', - )); - $mapping = array('fieldName' => 'version', 'type' => 'integer'); + ] + ); + $mapping = ['fieldName' => 'version', 'type' => 'integer']; $metadata->setVersionMapping($mapping); $metadata->mapField($mapping); $metadata->setIdGeneratorType(ClassMetadataInfo::GENERATOR_TYPE_AUTO); - $metadata->mapOneToOne(array( + $metadata->mapOneToOne( + [ 'fieldName' => 'address', - 'targetEntity' => 'Doctrine\\Tests\\ORM\\Mapping\\Address', + 'targetEntity' => Address::class, 'cascade' => - array( + [ 0 => 'remove', - ), + ], 'mappedBy' => NULL, 'inversedBy' => 'user', 'joinColumns' => - array( + [ 0 => - array( + [ 'name' => 'address_id', 'referencedColumnName' => 'id', 'onDelete' => 'CASCADE', - ), - ), + ], + ], 'orphanRemoval' => false, - )); - $metadata->mapOneToMany(array( + ] + ); + $metadata->mapOneToMany( + [ 'fieldName' => 'phonenumbers', - 'targetEntity' => 'Doctrine\\Tests\\ORM\\Mapping\\Phonenumber', + 'targetEntity' => Phonenumber::class, 'cascade' => - array( + [ 1 => 'persist', - ), + ], 'mappedBy' => 'user', 'orphanRemoval' => true, 'orderBy' => - array( + [ 'number' => 'ASC', - ), - )); - $metadata->mapManyToMany(array( + ], + ] + ); + $metadata->mapManyToMany( + [ 'fieldName' => 'groups', - 'targetEntity' => 'Doctrine\\Tests\\ORM\\Mapping\\Group', + 'targetEntity' => Group::class, 'cascade' => - array( + [ 0 => 'remove', 1 => 'persist', 2 => 'refresh', 3 => 'merge', 4 => 'detach', - ), + ], 'mappedBy' => NULL, 'joinTable' => - array( + [ 'name' => 'cms_users_groups', 'joinColumns' => - array( + [ 0 => - array( + [ 'name' => 'user_id', 'referencedColumnName' => 'id', 'unique' => false, 'nullable' => false, - ), - ), + ], + ], 'inverseJoinColumns' => - array( + [ 0 => - array( + [ 'name' => 'group_id', 'referencedColumnName' => 'id', 'columnDefinition' => 'INT NULL', - ), - ), - ), + ], + ], + ], 'orderBy' => NULL, - )); - $metadata->table['uniqueConstraints'] = array( - 'search_idx' => array('columns' => array('name', 'user_email'), 'options'=> array('where' => 'name IS NOT NULL')), + ] ); - $metadata->table['indexes'] = array( - 'name_idx' => array('columns' => array('name')), 0 => array('columns' => array('user_email')) - ); - $metadata->setSequenceGeneratorDefinition(array( + $metadata->table['uniqueConstraints'] = [ + 'search_idx' => ['columns' => ['name', 'user_email'], 'options'=> ['where' => 'name IS NOT NULL']], + ]; + $metadata->table['indexes'] = [ + 'name_idx' => ['columns' => ['name']], 0 => ['columns' => ['user_email']] + ]; + $metadata->setSequenceGeneratorDefinition( + [ 'sequenceName' => 'tablename_seq', 'allocationSize' => 100, 'initialValue' => 1, - )); - $metadata->addNamedQuery(array( + ] + ); + $metadata->addNamedQuery( + [ 'name' => 'all', 'query' => 'SELECT u FROM __CLASS__ u' - )); + ] + ); } } @@ -1256,7 +1322,7 @@ abstract class Animal public static function loadMetadata(ClassMetadataInfo $metadata) { $metadata->setIdGeneratorType(ClassMetadataInfo::GENERATOR_TYPE_CUSTOM); - $metadata->setCustomGeneratorDefinition(array("class" => "stdClass")); + $metadata->setCustomGeneratorDefinition(["class" => "stdClass"]); } } @@ -1323,16 +1389,20 @@ public function getValue() public static function loadMetadata(ClassMetadataInfo $metadata) { - $metadata->mapField(array( + $metadata->mapField( + [ 'id' => true, 'fieldName' => 'id', 'columnDefinition' => 'INT unsigned NOT NULL', - )); + ] + ); - $metadata->mapField(array( + $metadata->mapField( + [ 'fieldName' => 'value', 'columnDefinition' => 'VARCHAR(255) NOT NULL' - )); + ] + ); $metadata->setIdGeneratorType(ClassMetadataInfo::GENERATOR_TYPE_NONE); } @@ -1356,16 +1426,20 @@ class DDC807Entity public static function loadMetadata(ClassMetadataInfo $metadata) { - $metadata->mapField(array( + $metadata->mapField( + [ 'id' => true, 'fieldName' => 'id', - )); + ] + ); - $metadata->setDiscriminatorColumn(array( + $metadata->setDiscriminatorColumn( + [ 'name' => "dtype", 'type' => "string", 'columnDefinition' => "ENUM('ONE','TWO')" - )); + ] + ); $metadata->setIdGeneratorType(ClassMetadataInfo::GENERATOR_TYPE_NONE); } @@ -1392,13 +1466,16 @@ class Comment public static function loadMetadata(ClassMetadataInfo $metadata) { $metadata->setInheritanceType(ClassMetadataInfo::INHERITANCE_TYPE_NONE); - $metadata->setPrimaryTable(array( - 'indexes' => array( - array('columns' => array('content'), 'flags' => array('fulltext'), 'options' => array('where' => 'content IS NOT NULL')) - ) - )); + $metadata->setPrimaryTable( + [ + 'indexes' => [ + ['columns' => ['content'], 'flags' => ['fulltext'], 'options' => ['where' => 'content IS NOT NULL']] + ] + ] + ); - $metadata->mapField(array( + $metadata->mapField( + [ 'fieldName' => 'content', 'type' => 'text', 'scale' => 0, @@ -1407,7 +1484,8 @@ public static function loadMetadata(ClassMetadataInfo $metadata) 'nullable' => false, 'precision' => 0, 'columnName' => 'content', - )); + ] + ); } } @@ -1430,10 +1508,12 @@ class SingleTableEntityNoDiscriminatorColumnMapping public static function loadMetadata(ClassMetadataInfo $metadata) { - $metadata->mapField(array( + $metadata->mapField( + [ 'id' => true, 'fieldName' => 'id', - )); + ] + ); $metadata->setIdGeneratorType(ClassMetadataInfo::GENERATOR_TYPE_NONE); } @@ -1462,10 +1542,12 @@ class SingleTableEntityIncompleteDiscriminatorColumnMapping public static function loadMetadata(ClassMetadataInfo $metadata) { - $metadata->mapField(array( + $metadata->mapField( + [ 'id' => true, 'fieldName' => 'id', - )); + ] + ); $metadata->setIdGeneratorType(ClassMetadataInfo::GENERATOR_TYPE_NONE); } @@ -1474,4 +1556,4 @@ public static function loadMetadata(ClassMetadataInfo $metadata) class SingleTableEntityIncompleteDiscriminatorColumnMappingSub1 extends SingleTableEntityIncompleteDiscriminatorColumnMapping {} class SingleTableEntityIncompleteDiscriminatorColumnMappingSub2 - extends SingleTableEntityIncompleteDiscriminatorColumnMapping {} \ No newline at end of file + extends SingleTableEntityIncompleteDiscriminatorColumnMapping {} diff --git a/tests/Doctrine/Tests/ORM/Mapping/AnnotationDriverTest.php b/tests/Doctrine/Tests/ORM/Mapping/AnnotationDriverTest.php index ac17b63a221..b30ed703bc4 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/AnnotationDriverTest.php +++ b/tests/Doctrine/Tests/ORM/Mapping/AnnotationDriverTest.php @@ -5,10 +5,17 @@ use Doctrine\Common\Annotations\AnnotationException; use Doctrine\Common\Annotations\AnnotationReader; use Doctrine\Common\Persistence\Mapping\RuntimeReflectionService; +use Doctrine\ORM\Mapping; use Doctrine\ORM\Mapping\ClassMetadata; use Doctrine\ORM\Mapping\ClassMetadataFactory; use Doctrine\ORM\Mapping\Driver\AnnotationDriver; use Doctrine\ORM\Mapping\MappingException; +use Doctrine\Tests\Models\CMS\CmsUser; +use Doctrine\Tests\Models\DDC1872\DDC1872ExampleEntityWithoutOverride; +use Doctrine\Tests\Models\DDC1872\DDC1872ExampleEntityWithOverride; +use Doctrine\Tests\Models\DirectoryTree\Directory; +use Doctrine\Tests\Models\DirectoryTree\File; +use Doctrine\Tests\Models\ECommerce\ECommerceCart; class AnnotationDriverTest extends AbstractMappingDriverTest { @@ -32,11 +39,10 @@ public function testLoadMetadataForNonEntityThrowsException() */ public function testFailingSecondLevelCacheAssociation() { - $className = 'Doctrine\Tests\ORM\Mapping\AnnotationSLC'; $mappingDriver = $this->_loadDriver(); - $class = new ClassMetadata($className); - $mappingDriver->loadMetadataForClass($className, $class); + $class = new ClassMetadata(AnnotationSLC::class); + $mappingDriver->loadMetadataForClass(AnnotationSLC::class, $class); } /** @@ -44,11 +50,11 @@ public function testFailingSecondLevelCacheAssociation() */ public function testColumnWithMissingTypeDefaultsToString() { - $cm = new ClassMetadata('Doctrine\Tests\ORM\Mapping\ColumnWithoutType'); + $cm = new ClassMetadata(ColumnWithoutType::class); $cm->initializeReflection(new RuntimeReflectionService()); $annotationDriver = $this->_loadDriver(); - $annotationDriver->loadMetadataForClass('Doctrine\Tests\ORM\Mapping\InvalidColumn', $cm); + $annotationDriver->loadMetadataForClass(Mapping\InvalidColumn::class, $cm); $this->assertEquals('string', $cm->fieldMappings['id']['type']); } @@ -85,13 +91,12 @@ public function testGetAllClassNamesIsIdempotentEvenWithDifferentDriverInstances */ public function testGetAllClassNamesReturnsAlreadyLoadedClassesIfAppropriate() { - $rightClassName = 'Doctrine\Tests\Models\CMS\CmsUser'; - $this->_ensureIsLoaded($rightClassName); + $this->_ensureIsLoaded(CmsUser::class); $annotationDriver = $this->_loadDriverForCMSModels(); $classes = $annotationDriver->getAllClassNames(); - $this->assertContains($rightClassName, $classes); + $this->assertContains(CmsUser::class, $classes); } /** @@ -99,19 +104,18 @@ public function testGetAllClassNamesReturnsAlreadyLoadedClassesIfAppropriate() */ public function testGetClassNamesReturnsOnlyTheAppropriateClasses() { - $extraneousClassName = 'Doctrine\Tests\Models\ECommerce\ECommerceCart'; - $this->_ensureIsLoaded($extraneousClassName); + $this->_ensureIsLoaded(ECommerceCart::class); $annotationDriver = $this->_loadDriverForCMSModels(); $classes = $annotationDriver->getAllClassNames(); - $this->assertNotContains($extraneousClassName, $classes); + $this->assertNotContains(ECommerceCart::class, $classes); } protected function _loadDriverForCMSModels() { $annotationDriver = $this->_loadDriver(); - $annotationDriver->addPaths(array(__DIR__ . '/../../Models/CMS/')); + $annotationDriver->addPaths([__DIR__ . '/../../Models/CMS/']); return $annotationDriver; } @@ -133,18 +137,18 @@ protected function _ensureIsLoaded($entityClassName) public function testJoinTablesWithMappedSuperclassForAnnotationDriver() { $annotationDriver = $this->_loadDriver(); - $annotationDriver->addPaths(array(__DIR__ . '/../../Models/DirectoryTree/')); + $annotationDriver->addPaths([__DIR__ . '/../../Models/DirectoryTree/']); $em = $this->_getTestEntityManager(); $em->getConfiguration()->setMetadataDriverImpl($annotationDriver); $factory = new ClassMetadataFactory(); $factory->setEntityManager($em); - $classPage = $factory->getMetadataFor('Doctrine\Tests\Models\DirectoryTree\File'); - $this->assertEquals('Doctrine\Tests\Models\DirectoryTree\File', $classPage->associationMappings['parentDirectory']['sourceEntity']); + $classPage = $factory->getMetadataFor(File::class); + $this->assertEquals(File::class, $classPage->associationMappings['parentDirectory']['sourceEntity']); - $classDirectory = $factory->getMetadataFor('Doctrine\Tests\Models\DirectoryTree\Directory'); - $this->assertEquals('Doctrine\Tests\Models\DirectoryTree\Directory', $classDirectory->associationMappings['parentDirectory']['sourceEntity']); + $classDirectory = $factory->getMetadataFor(Directory::class); + $this->assertEquals(Directory::class, $classDirectory->associationMappings['parentDirectory']['sourceEntity']); } /** @@ -165,7 +169,7 @@ public function testInvalidMappedSuperClassWithManyToManyAssociation() "mapped superclass 'Doctrine\Tests\ORM\Mapping\InvalidMappedSuperClass#users'" ); - $usingInvalidMsc = $factory->getMetadataFor('Doctrine\Tests\ORM\Mapping\UsingInvalidMappedSuperClass'); + $usingInvalidMsc = $factory->getMetadataFor(UsingInvalidMappedSuperClass::class); } /** @@ -183,10 +187,10 @@ public function testInvalidMappedSuperClassWithInheritanceInformation() $this->expectException(MappingException::class); $this->expectExceptionMessage( "It is not supported to define inheritance information on a mapped " . - "superclass 'Doctrine\Tests\ORM\Mapping\MappedSuperClassInheritence'." + "superclass '" . MappedSuperClassInheritence::class . "'." ); - $usingInvalidMsc = $factory->getMetadataFor('Doctrine\Tests\ORM\Mapping\MappedSuperClassInheritence'); + $usingInvalidMsc = $factory->getMetadataFor(MappedSuperClassInheritence::class); } /** @@ -201,11 +205,11 @@ public function testInheritanceSkipsParentLifecycleCallbacks() $factory = new ClassMetadataFactory(); $factory->setEntityManager($em); - $cm = $factory->getMetadataFor('Doctrine\Tests\ORM\Mapping\AnnotationChild'); - $this->assertEquals(array("postLoad" => array("postLoad"), "preUpdate" => array("preUpdate")), $cm->lifecycleCallbacks); + $cm = $factory->getMetadataFor(AnnotationChild::class); + $this->assertEquals(["postLoad" => ["postLoad"], "preUpdate" => ["preUpdate"]], $cm->lifecycleCallbacks); - $cm = $factory->getMetadataFor('Doctrine\Tests\ORM\Mapping\AnnotationParent'); - $this->assertEquals(array("postLoad" => array("postLoad"), "preUpdate" => array("preUpdate")), $cm->lifecycleCallbacks); + $cm = $factory->getMetadataFor(AnnotationParent::class); + $this->assertEquals(["postLoad" => ["postLoad"], "preUpdate" => ["preUpdate"]], $cm->lifecycleCallbacks); } /** @@ -217,10 +221,11 @@ public function testMappedSuperclassInMiddleOfInheritanceHierarchy() $em = $this->_getTestEntityManager(); $em->getConfiguration()->setMetadataDriverImpl($annotationDriver); + $factory = new ClassMetadataFactory(); $factory->setEntityManager($em); - $cm = $factory->getMetadataFor('Doctrine\Tests\ORM\Mapping\ChildEntity'); + self::assertInstanceOf(ClassMetadata::class, $factory->getMetadataFor(ChildEntity::class)); } public function testInvalidFetchOptionThrowsException() @@ -235,15 +240,15 @@ public function testInvalidFetchOptionThrowsException() $this->expectException(AnnotationException::class); $this->expectExceptionMessage('[Enum Error] Attribute "fetch" of @Doctrine\ORM\Mapping\OneToMany declared on property Doctrine\Tests\ORM\Mapping\InvalidFetchOption::$collection accept only [LAZY, EAGER, EXTRA_LAZY], but got eager.'); - $factory->getMetadataFor('Doctrine\Tests\ORM\Mapping\InvalidFetchOption'); + $factory->getMetadataFor(InvalidFetchOption::class); } public function testAttributeOverridesMappingWithTrait() { $factory = $this->createClassMetadataFactory(); - $metadataWithoutOverride = $factory->getMetadataFor('Doctrine\Tests\Models\DDC1872\DDC1872ExampleEntityWithoutOverride'); - $metadataWithOverride = $factory->getMetadataFor('Doctrine\Tests\Models\DDC1872\DDC1872ExampleEntityWithOverride'); + $metadataWithoutOverride = $factory->getMetadataFor(DDC1872ExampleEntityWithoutOverride::class); + $metadataWithOverride = $factory->getMetadataFor(DDC1872ExampleEntityWithOverride::class); $this->assertEquals('trait_foo', $metadataWithoutOverride->fieldMappings['foo']['columnName']); $this->assertEquals('foo_overridden', $metadataWithOverride->fieldMappings['foo']['columnName']); diff --git a/tests/Doctrine/Tests/ORM/Mapping/AnsiQuoteStrategyTest.php b/tests/Doctrine/Tests/ORM/Mapping/AnsiQuoteStrategyTest.php index d5f2a973837..a0b422c0f76 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/AnsiQuoteStrategyTest.php +++ b/tests/Doctrine/Tests/ORM/Mapping/AnsiQuoteStrategyTest.php @@ -5,6 +5,10 @@ use Doctrine\Common\Persistence\Mapping\RuntimeReflectionService; use Doctrine\ORM\Mapping\AnsiQuoteStrategy; use Doctrine\ORM\Mapping\ClassMetadata; +use Doctrine\Tests\Models\CMS\CmsAddress; +use Doctrine\Tests\Models\CMS\CmsUser; +use Doctrine\Tests\Models\DDC117\DDC117Article; +use Doctrine\Tests\Models\DDC117\DDC117ArticleDetails; use Doctrine\Tests\OrmTestCase; /** @@ -47,9 +51,9 @@ private function createClassMetadata($className) public function testGetColumnName() { - $class = $this->createClassMetadata('Doctrine\Tests\Models\CMS\CmsUser'); - $class->mapField(array('fieldName' => 'name', 'columnName' => 'name')); - $class->mapField(array('fieldName' => 'id', 'columnName' => 'id', 'id' => true)); + $class = $this->createClassMetadata(CmsUser::class); + $class->mapField(['fieldName' => 'name', 'columnName' => 'name']); + $class->mapField(['fieldName' => 'id', 'columnName' => 'id', 'id' => true]); $this->assertEquals('id' ,$this->strategy->getColumnName('id', $class, $this->platform)); $this->assertEquals('name' ,$this->strategy->getColumnName('name', $class, $this->platform)); @@ -57,40 +61,44 @@ public function testGetColumnName() public function testGetTableName() { - $class = $this->createClassMetadata('Doctrine\Tests\Models\CMS\CmsUser'); + $class = $this->createClassMetadata(CmsUser::class); - $class->setPrimaryTable(array('name'=>'cms_user')); + $class->setPrimaryTable(['name'=>'cms_user']); $this->assertEquals('cms_user' ,$this->strategy->getTableName($class, $this->platform)); } public function testJoinTableName() { - $class = $this->createClassMetadata('Doctrine\Tests\Models\CMS\CmsAddress'); - - $class->mapManyToMany(array( + $class = $this->createClassMetadata(CmsAddress::class); + + $class->mapManyToMany( + [ 'fieldName' => 'user', 'targetEntity' => 'CmsUser', 'inversedBy' => 'users', - 'joinTable' => array( + 'joinTable' => [ 'name' => 'cmsaddress_cmsuser' - ) - )); - + ] + ] + ); + $this->assertEquals('cmsaddress_cmsuser', $this->strategy->getJoinTableName($class->associationMappings['user'], $class, $this->platform)); - + } public function testIdentifierColumnNames() { - $class = $this->createClassMetadata('Doctrine\Tests\Models\CMS\CmsAddress'); + $class = $this->createClassMetadata(CmsAddress::class); - $class->mapField(array( + $class->mapField( + [ 'id' => true, 'fieldName' => 'id', 'columnName' => 'id', - )); + ] + ); - $this->assertEquals(array('id'), $this->strategy->getIdentifierColumnNames($class, $this->platform)); + $this->assertEquals(['id'], $this->strategy->getIdentifierColumnNames($class, $this->platform)); } @@ -101,16 +109,20 @@ public function testColumnAlias() public function testJoinColumnName() { - $class = $this->createClassMetadata('Doctrine\Tests\Models\DDC117\DDC117ArticleDetails'); + $class = $this->createClassMetadata(DDC117ArticleDetails::class); - $class->mapOneToOne(array( + $class->mapOneToOne( + [ 'id' => true, 'fieldName' => 'article', - 'targetEntity' => 'Doctrine\Tests\Models\DDC117\DDC117Article', - 'joinColumns' => array(array( + 'targetEntity' => DDC117Article::class, + 'joinColumns' => [ + [ 'name' => 'article' - )), - )); + ] + ], + ] + ); $joinColumn = $class->associationMappings['article']['joinColumns'][0]; $this->assertEquals('article',$this->strategy->getJoinColumnName($joinColumn, $class, $this->platform)); @@ -118,16 +130,20 @@ public function testJoinColumnName() public function testReferencedJoinColumnName() { - $cm = $this->createClassMetadata('Doctrine\Tests\Models\DDC117\DDC117ArticleDetails'); + $cm = $this->createClassMetadata(DDC117ArticleDetails::class); - $cm->mapOneToOne(array( + $cm->mapOneToOne( + [ 'id' => true, 'fieldName' => 'article', - 'targetEntity' => 'Doctrine\Tests\Models\DDC117\DDC117Article', - 'joinColumns' => array(array( + 'targetEntity' => DDC117Article::class, + 'joinColumns' => [ + [ 'name' => 'article' - )), - )); + ] + ], + ] + ); $joinColumn = $cm->associationMappings['article']['joinColumns'][0]; $this->assertEquals('id',$this->strategy->getReferencedJoinColumnName($joinColumn, $cm, $this->platform)); @@ -135,15 +151,15 @@ public function testReferencedJoinColumnName() public function testGetSequenceName() { - $class = $this->createClassMetadata('Doctrine\Tests\Models\CMS\CmsUser'); - $definition = array( + $class = $this->createClassMetadata(CmsUser::class); + $definition = [ 'sequenceName' => 'user_id_seq', 'allocationSize' => 1, 'initialValue' => 2 - ); + ]; $class->setSequenceGeneratorDefinition($definition); $this->assertEquals('user_id_seq',$this->strategy->getSequenceName($definition, $class, $this->platform)); } -} \ No newline at end of file +} diff --git a/tests/Doctrine/Tests/ORM/Mapping/BasicInheritanceMappingTest.php b/tests/Doctrine/Tests/ORM/Mapping/BasicInheritanceMappingTest.php index be2bee9f58e..292954506a4 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/BasicInheritanceMappingTest.php +++ b/tests/Doctrine/Tests/ORM/Mapping/BasicInheritanceMappingTest.php @@ -3,10 +3,15 @@ namespace Doctrine\Tests\ORM\Mapping; use Doctrine\Common\Persistence\Mapping\RuntimeReflectionService; +use Doctrine\ORM\EntityRepository; +use Doctrine\ORM\Id\SequenceGenerator; use Doctrine\ORM\Mapping\ClassMetadataFactory; use Doctrine\ORM\Mapping\ClassMetadataInfo; use Doctrine\ORM\Mapping\MappingException; +use Doctrine\Tests\Models\DDC869\DDC869ChequePayment; +use Doctrine\Tests\Models\DDC869\DDC869CreditCardPayment; use Doctrine\Tests\Models\DDC869\DDC869Payment; +use Doctrine\Tests\Models\DDC869\DDC869PaymentRepository; use Doctrine\Tests\OrmTestCase; class BasicInheritanceMappingTest extends OrmTestCase @@ -29,12 +34,12 @@ public function testGetMetadataForTransientClassThrowsException() { $this->expectException(\Doctrine\ORM\Mapping\MappingException::class); - $this->cmf->getMetadataFor('Doctrine\Tests\ORM\Mapping\TransientBaseClass'); + $this->cmf->getMetadataFor(TransientBaseClass::class); } public function testGetMetadataForSubclassWithTransientBaseClass() { - $class = $this->cmf->getMetadataFor('Doctrine\Tests\ORM\Mapping\EntitySubClass'); + $class = $this->cmf->getMetadataFor(EntitySubClass::class); $this->assertEmpty($class->subClasses); $this->assertEmpty($class->parentClasses); @@ -44,7 +49,7 @@ public function testGetMetadataForSubclassWithTransientBaseClass() public function testGetMetadataForSubclassWithMappedSuperclass() { - $class = $this->cmf->getMetadataFor('Doctrine\Tests\ORM\Mapping\EntitySubClass2'); + $class = $this->cmf->getMetadataFor(EntitySubClass2::class); $this->assertEmpty($class->subClasses); $this->assertEmpty($class->parentClasses); @@ -66,28 +71,28 @@ public function testGetMetadataForSubclassWithMappedSuperclass() */ public function testGetMetadataForSubclassWithMappedSuperclassWithRepository() { - $class = $this->cmf->getMetadataFor('Doctrine\Tests\Models\DDC869\DDC869CreditCardPayment'); + $class = $this->cmf->getMetadataFor(DDC869CreditCardPayment::class); $this->assertArrayHasKey('id', $class->fieldMappings); $this->assertArrayHasKey('value', $class->fieldMappings); $this->assertArrayHasKey('creditCardNumber', $class->fieldMappings); - $this->assertEquals($class->customRepositoryClassName, 'Doctrine\Tests\Models\DDC869\DDC869PaymentRepository'); + $this->assertEquals($class->customRepositoryClassName, DDC869PaymentRepository::class); - $class = $this->cmf->getMetadataFor('Doctrine\Tests\Models\DDC869\DDC869ChequePayment'); + $class = $this->cmf->getMetadataFor(DDC869ChequePayment::class); $this->assertArrayHasKey('id', $class->fieldMappings); $this->assertArrayHasKey('value', $class->fieldMappings); $this->assertArrayHasKey('serialNumber', $class->fieldMappings); - $this->assertEquals($class->customRepositoryClassName, 'Doctrine\Tests\Models\DDC869\DDC869PaymentRepository'); + $this->assertEquals($class->customRepositoryClassName, DDC869PaymentRepository::class); // override repositoryClass - $class = $this->cmf->getMetadataFor('Doctrine\Tests\ORM\Mapping\SubclassWithRepository'); + $class = $this->cmf->getMetadataFor(SubclassWithRepository::class); $this->assertArrayHasKey('id', $class->fieldMappings); $this->assertArrayHasKey('value', $class->fieldMappings); - $this->assertEquals($class->customRepositoryClassName, 'Doctrine\ORM\EntityRepository'); + $this->assertEquals($class->customRepositoryClassName, EntityRepository::class); } /** @@ -96,7 +101,7 @@ public function testGetMetadataForSubclassWithMappedSuperclassWithRepository() public function testSerializationWithPrivateFieldsFromMappedSuperclass() { - $class = $this->cmf->getMetadataFor(__NAMESPACE__ . '\\EntitySubClass2'); + $class = $this->cmf->getMetadataFor(EntitySubClass2::class); $class2 = unserialize(serialize($class)); $class2->wakeupReflection(new RuntimeReflectionService); @@ -111,7 +116,7 @@ public function testSerializationWithPrivateFieldsFromMappedSuperclass() */ public function testUnmappedSuperclassInHierarchy() { - $class = $this->cmf->getMetadataFor(__NAMESPACE__ . '\\HierarchyD'); + $class = $this->cmf->getMetadataFor(HierarchyD::class); $this->assertArrayHasKey('id', $class->fieldMappings); $this->assertArrayHasKey('a', $class->fieldMappings); @@ -131,7 +136,7 @@ public function testUnmappedEntityInHierarchy() . ' avoid this exception from occurring.' ); - $this->cmf->getMetadataFor(__NAMESPACE__ . '\\HierarchyE'); + $this->cmf->getMetadataFor(HierarchyE::class); } /** @@ -140,7 +145,7 @@ public function testUnmappedEntityInHierarchy() */ public function testMappedSuperclassWithId() { - $class = $this->cmf->getMetadataFor(__NAMESPACE__ . '\\SuperclassEntity'); + $class = $this->cmf->getMetadataFor(SuperclassEntity::class); $this->assertArrayHasKey('id', $class->fieldMappings); } @@ -151,12 +156,12 @@ public function testMappedSuperclassWithId() */ public function testGeneratedValueFromMappedSuperclass() { - $class = $this->cmf->getMetadataFor(__NAMESPACE__ . '\\SuperclassEntity'); + $class = $this->cmf->getMetadataFor(SuperclassEntity::class); /* @var $class ClassMetadataInfo */ - $this->assertInstanceOf('Doctrine\ORM\Id\SequenceGenerator', $class->idGenerator); + $this->assertInstanceOf(SequenceGenerator::class, $class->idGenerator); $this->assertEquals( - array('allocationSize' => 1, 'initialValue' => 10, 'sequenceName' => 'foo'), + ['allocationSize' => 1, 'initialValue' => 10, 'sequenceName' => 'foo'], $class->sequenceGeneratorDefinition ); } @@ -167,12 +172,12 @@ public function testGeneratedValueFromMappedSuperclass() */ public function testSequenceDefinitionInHierarchyWithSandwichMappedSuperclass() { - $class = $this->cmf->getMetadataFor(__NAMESPACE__ . '\\HierarchyD'); + $class = $this->cmf->getMetadataFor(HierarchyD::class); /* @var $class ClassMetadataInfo */ - $this->assertInstanceOf('Doctrine\ORM\Id\SequenceGenerator', $class->idGenerator); + $this->assertInstanceOf(SequenceGenerator::class, $class->idGenerator); $this->assertEquals( - array('allocationSize' => 1, 'initialValue' => 10, 'sequenceName' => 'foo'), + ['allocationSize' => 1, 'initialValue' => 10, 'sequenceName' => 'foo'], $class->sequenceGeneratorDefinition ); } @@ -183,12 +188,12 @@ public function testSequenceDefinitionInHierarchyWithSandwichMappedSuperclass() */ public function testMultipleMappedSuperclasses() { - $class = $this->cmf->getMetadataFor(__NAMESPACE__ . '\\MediumSuperclassEntity'); + $class = $this->cmf->getMetadataFor(MediumSuperclassEntity::class); /* @var $class ClassMetadataInfo */ - $this->assertInstanceOf('Doctrine\ORM\Id\SequenceGenerator', $class->idGenerator); + $this->assertInstanceOf(SequenceGenerator::class, $class->idGenerator); $this->assertEquals( - array('allocationSize' => 1, 'initialValue' => 10, 'sequenceName' => 'foo'), + ['allocationSize' => 1, 'initialValue' => 10, 'sequenceName' => 'foo'], $class->sequenceGeneratorDefinition ); } @@ -200,7 +205,7 @@ public function testMultipleMappedSuperclasses() */ public function testMappedSuperclassIndex() { - $class = $this->cmf->getMetadataFor(__NAMESPACE__ . '\\EntityIndexSubClass'); + $class = $this->cmf->getMetadataFor(EntityIndexSubClass::class); /* @var $class ClassMetadataInfo */ $this->assertArrayHasKey('mapped1', $class->fieldMappings); diff --git a/tests/Doctrine/Tests/ORM/Mapping/ClassMetadataBuilderTest.php b/tests/Doctrine/Tests/ORM/Mapping/ClassMetadataBuilderTest.php index 996c4059882..657ad65b474 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/ClassMetadataBuilderTest.php +++ b/tests/Doctrine/Tests/ORM/Mapping/ClassMetadataBuilderTest.php @@ -1,27 +1,15 @@ . - */ namespace Doctrine\Tests\ORM\Mapping; use Doctrine\Common\Persistence\Mapping\RuntimeReflectionService; -use Doctrine\ORM\Mapping\ClassMetadata; use Doctrine\ORM\Mapping\Builder\ClassMetadataBuilder; +use Doctrine\ORM\Mapping\Builder\EmbeddedBuilder; +use Doctrine\ORM\Mapping\Builder\FieldBuilder; +use Doctrine\ORM\Mapping\ClassMetadata; +use Doctrine\Tests\Models\CMS\CmsGroup; +use Doctrine\Tests\Models\CMS\CmsUser; +use Doctrine\Tests\Models\ValueObjects\Name; use Doctrine\Tests\OrmTestCase; /** @@ -40,7 +28,7 @@ class ClassMetadataBuilderTest extends OrmTestCase public function setUp() { - $this->cm = new ClassMetadata('Doctrine\Tests\Models\CMS\CmsUser'); + $this->cm = new ClassMetadata(CmsUser::class); $this->cm->initializeReflection(new RuntimeReflectionService()); $this->builder = new ClassMetadataBuilder($this->cm); } @@ -61,21 +49,17 @@ public function testSetEmbedable() public function testAddEmbeddedWithOnlyRequiredParams() { - $this->assertIsFluent( - $this->builder->addEmbedded( - 'name', - 'Doctrine\Tests\Models\ValueObjects\Name' - ) - ); + $this->assertIsFluent($this->builder->addEmbedded('name', Name::class)); - $this->assertEquals(array( - 'name' => array( - 'class' => 'Doctrine\Tests\Models\ValueObjects\Name', + $this->assertEquals( + [ + 'name' => [ + 'class' => Name::class, 'columnPrefix' => null, 'declaredField' => null, 'originalField' => null, - ) - ), $this->cm->embeddedClasses); + ] + ], $this->cm->embeddedClasses); } public function testAddEmbeddedWithPrefix() @@ -83,63 +67,64 @@ public function testAddEmbeddedWithPrefix() $this->assertIsFluent( $this->builder->addEmbedded( 'name', - 'Doctrine\Tests\Models\ValueObjects\Name', + Name::class, 'nm_' ) ); - $this->assertEquals(array( - 'name' => array( - 'class' => 'Doctrine\Tests\Models\ValueObjects\Name', + $this->assertEquals( + [ + 'name' => [ + 'class' => Name::class, 'columnPrefix' => 'nm_', 'declaredField' => null, 'originalField' => null, - ) - ), $this->cm->embeddedClasses); + ] + ], $this->cm->embeddedClasses); } public function testCreateEmbeddedWithoutExtraParams() { - $embeddedBuilder = ($this->builder->createEmbedded('name', 'Doctrine\Tests\Models\ValueObjects\Name')); - $this->assertInstanceOf('Doctrine\ORM\Mapping\Builder\EmbeddedBuilder', $embeddedBuilder); + $embeddedBuilder = ($this->builder->createEmbedded('name', Name::class)); + $this->assertInstanceOf(EmbeddedBuilder::class, $embeddedBuilder); $this->assertFalse(isset($this->cm->embeddedClasses['name'])); $this->assertIsFluent($embeddedBuilder->build()); $this->assertEquals( - array( - 'class' => 'Doctrine\Tests\Models\ValueObjects\Name', + [ + 'class' => Name::class, 'columnPrefix' => null, 'declaredField' => null, 'originalField' => null - ), + ], $this->cm->embeddedClasses['name'] ); } public function testCreateEmbeddedWithColumnPrefix() { - $embeddedBuilder = ($this->builder->createEmbedded('name', 'Doctrine\Tests\Models\ValueObjects\Name')); + $embeddedBuilder = ($this->builder->createEmbedded('name', Name::class)); $this->assertEquals($embeddedBuilder, $embeddedBuilder->setColumnPrefix('nm_')); $this->assertIsFluent($embeddedBuilder->build()); $this->assertEquals( - array( - 'class' => 'Doctrine\Tests\Models\ValueObjects\Name', + [ + 'class' => Name::class, 'columnPrefix' => 'nm_', 'declaredField' => null, 'originalField' => null - ), + ], $this->cm->embeddedClasses['name'] ); } public function testSetCustomRepositoryClass() { - $this->assertIsFluent($this->builder->setCustomRepositoryClass('Doctrine\Tests\Models\CMS\CmsGroup')); - $this->assertEquals('Doctrine\Tests\Models\CMS\CmsGroup', $this->cm->customRepositoryClassName); + $this->assertIsFluent($this->builder->setCustomRepositoryClass(CmsGroup::class)); + $this->assertEquals(CmsGroup::class, $this->cm->customRepositoryClassName); } public function testSetReadOnly() @@ -156,28 +141,28 @@ public function testSetTable() public function testAddIndex() { - $this->assertIsFluent($this->builder->addIndex(array('username', 'name'), 'users_idx')); - $this->assertEquals(array('users_idx' => array('columns' => array('username', 'name'))), $this->cm->table['indexes']); + $this->assertIsFluent($this->builder->addIndex(['username', 'name'], 'users_idx')); + $this->assertEquals(['users_idx' => ['columns' => ['username', 'name']]], $this->cm->table['indexes']); } public function testAddUniqueConstraint() { - $this->assertIsFluent($this->builder->addUniqueConstraint(array('username', 'name'), 'users_idx')); - $this->assertEquals(array('users_idx' => array('columns' => array('username', 'name'))), $this->cm->table['uniqueConstraints']); + $this->assertIsFluent($this->builder->addUniqueConstraint(['username', 'name'], 'users_idx')); + $this->assertEquals(['users_idx' => ['columns' => ['username', 'name']]], $this->cm->table['uniqueConstraints']); } public function testSetPrimaryTableRelated() { - $this->builder->addUniqueConstraint(array('username', 'name'), 'users_idx'); - $this->builder->addIndex(array('username', 'name'), 'users_idx'); + $this->builder->addUniqueConstraint(['username', 'name'], 'users_idx'); + $this->builder->addIndex(['username', 'name'], 'users_idx'); $this->builder->setTable('users'); $this->assertEquals( - array( + [ 'name' => 'users', - 'indexes' => array('users_idx' => array('columns' => array('username', 'name'))), - 'uniqueConstraints' => array('users_idx' => array('columns' => array('username', 'name'))), - ), + 'indexes' => ['users_idx' => ['columns' => ['username', 'name']]], + 'uniqueConstraints' => ['users_idx' => ['columns' => ['username', 'name']]], + ], $this->cm->table ); } @@ -197,15 +182,16 @@ public function testSetInheritanceSingleTable() public function testSetDiscriminatorColumn() { $this->assertIsFluent($this->builder->setDiscriminatorColumn('discr', 'string', '124')); - $this->assertEquals(array('fieldName' => 'discr', 'name' => 'discr', 'type' => 'string', 'length' => '124'), $this->cm->discriminatorColumn); + $this->assertEquals(['fieldName' => 'discr', 'name' => 'discr', 'type' => 'string', 'length' => '124'], $this->cm->discriminatorColumn); } public function testAddDiscriminatorMapClass() { - $this->assertIsFluent($this->builder->addDiscriminatorMapClass('test', 'Doctrine\Tests\Models\CMS\CmsUser')); - $this->assertIsFluent($this->builder->addDiscriminatorMapClass('test2', 'Doctrine\Tests\Models\CMS\CmsGroup')); + $this->assertIsFluent($this->builder->addDiscriminatorMapClass('test', CmsUser::class)); + $this->assertIsFluent($this->builder->addDiscriminatorMapClass('test2', CmsGroup::class)); - $this->assertEquals(array('test' => 'Doctrine\Tests\Models\CMS\CmsUser', 'test2' => 'Doctrine\Tests\Models\CMS\CmsGroup'), $this->cm->discriminatorMap); + $this->assertEquals( + ['test' => CmsUser::class, 'test2' => CmsGroup::class], $this->cm->discriminatorMap); $this->assertEquals('test', $this->cm->discriminatorValue); } @@ -224,23 +210,24 @@ public function testChangeTrackingPolicyNotify() public function testAddField() { $this->assertIsFluent($this->builder->addField('name', 'string')); - $this->assertEquals(array('columnName' => 'name', 'fieldName' => 'name', 'type' => 'string'), $this->cm->fieldMappings['name']); + $this->assertEquals(['columnName' => 'name', 'fieldName' => 'name', 'type' => 'string'], $this->cm->fieldMappings['name']); } public function testCreateField() { $fieldBuilder = ($this->builder->createField('name', 'string')); - $this->assertInstanceOf('Doctrine\ORM\Mapping\Builder\FieldBuilder', $fieldBuilder); + $this->assertInstanceOf(FieldBuilder::class, $fieldBuilder); $this->assertFalse(isset($this->cm->fieldMappings['name'])); $this->assertIsFluent($fieldBuilder->build()); - $this->assertEquals(array('columnName' => 'name', 'fieldName' => 'name', 'type' => 'string'), $this->cm->fieldMappings['name']); + $this->assertEquals(['columnName' => 'name', 'fieldName' => 'name', 'type' => 'string'], $this->cm->fieldMappings['name']); } public function testCreateVersionedField() { $this->builder->createField('name', 'integer')->columnName('username')->length(124)->nullable()->columnDefinition('foobar')->unique()->isVersionField()->build(); - $this->assertEquals(array( + $this->assertEquals( + [ 'columnDefinition' => 'foobar', 'columnName' => 'username', 'default' => 1, @@ -249,88 +236,91 @@ public function testCreateVersionedField() 'type' => 'integer', 'nullable' => true, 'unique' => true, - ), $this->cm->fieldMappings['name']); + ], $this->cm->fieldMappings['name']); } public function testCreatePrimaryField() { $this->builder->createField('id', 'integer')->makePrimaryKey()->generatedValue()->build(); - $this->assertEquals(array('id'), $this->cm->identifier); - $this->assertEquals(array('columnName' => 'id', 'fieldName' => 'id', 'id' => true, 'type' => 'integer'), $this->cm->fieldMappings['id']); + $this->assertEquals(['id'], $this->cm->identifier); + $this->assertEquals(['columnName' => 'id', 'fieldName' => 'id', 'id' => true, 'type' => 'integer'], $this->cm->fieldMappings['id']); } public function testCreateUnsignedOptionField() { $this->builder->createField('state', 'integer')->option('unsigned', true)->build(); - $this->assertEquals(array('fieldName' => 'state', 'type' => 'integer', 'options' => array('unsigned' => true), 'columnName' => 'state'), $this->cm->fieldMappings['state']); + $this->assertEquals( + ['fieldName' => 'state', 'type' => 'integer', 'options' => ['unsigned' => true], 'columnName' => 'state'], $this->cm->fieldMappings['state']); } public function testAddLifecycleEvent() { $this->builder->addLifecycleEvent('getStatus', 'postLoad'); - $this->assertEquals(array('postLoad' => array('getStatus')), $this->cm->lifecycleCallbacks); + $this->assertEquals(['postLoad' => ['getStatus']], $this->cm->lifecycleCallbacks); } public function testCreateManyToOne() { $this->assertIsFluent( - $this->builder->createManyToOne('groups', 'Doctrine\Tests\Models\CMS\CmsGroup') + $this->builder->createManyToOne('groups', CmsGroup::class) ->addJoinColumn('group_id', 'id', true, false, 'CASCADE') ->cascadeAll() ->fetchExtraLazy() ->build() ); - $this->assertEquals(array('groups' => array ( + $this->assertEquals( + [ + 'groups' => [ 'fieldName' => 'groups', - 'targetEntity' => 'Doctrine\\Tests\\Models\\CMS\\CmsGroup', - 'cascade' => array ( + 'targetEntity' => CmsGroup::class, + 'cascade' => [ 0 => 'remove', 1 => 'persist', 2 => 'refresh', 3 => 'merge', 4 => 'detach', - ), + ], 'fetch' => 4, - 'joinColumns' => array ( + 'joinColumns' => [ 0 => - array ( + [ 'name' => 'group_id', 'referencedColumnName' => 'id', 'nullable' => true, 'unique' => false, 'onDelete' => 'CASCADE', 'columnDefinition' => NULL, - ), - ), + ], + ], 'type' => 2, 'mappedBy' => NULL, 'inversedBy' => NULL, 'isOwningSide' => true, - 'sourceEntity' => 'Doctrine\\Tests\\Models\\CMS\\CmsUser', + 'sourceEntity' => CmsUser::class, 'isCascadeRemove' => true, 'isCascadePersist' => true, 'isCascadeRefresh' => true, 'isCascadeMerge' => true, 'isCascadeDetach' => true, 'sourceToTargetKeyColumns' => - array ( + [ 'group_id' => 'id', - ), + ], 'joinColumnFieldNames' => - array ( + [ 'group_id' => 'group_id', - ), + ], 'targetToSourceKeyColumns' => - array ( + [ 'id' => 'group_id', - ), + ], 'orphanRemoval' => false, - ), - ), $this->cm->associationMappings); + ], + ], $this->cm->associationMappings); } public function testCreateManyToOneWithIdentity() @@ -338,7 +328,7 @@ public function testCreateManyToOneWithIdentity() $this->assertIsFluent( $this ->builder - ->createManyToOne('groups', 'Doctrine\Tests\Models\CMS\CmsGroup') + ->createManyToOne('groups', CmsGroup::class) ->addJoinColumn('group_id', 'id', true, false, 'CASCADE') ->cascadeAll() ->fetchExtraLazy() @@ -347,55 +337,55 @@ public function testCreateManyToOneWithIdentity() ); $this->assertEquals( - array( - 'groups' => array( + [ + 'groups' => [ 'fieldName' => 'groups', - 'targetEntity' => 'Doctrine\\Tests\\Models\\CMS\\CmsGroup', - 'cascade' => array( + 'targetEntity' => CmsGroup::class, + 'cascade' => [ 0 => 'remove', 1 => 'persist', 2 => 'refresh', 3 => 'merge', 4 => 'detach', - ), + ], 'fetch' => 4, - 'joinColumns' => array( + 'joinColumns' => [ 0 => - array( + [ 'name' => 'group_id', 'referencedColumnName' => 'id', 'nullable' => true, 'unique' => false, 'onDelete' => 'CASCADE', 'columnDefinition' => NULL, - ), - ), + ], + ], 'type' => 2, 'mappedBy' => NULL, 'inversedBy' => NULL, 'isOwningSide' => true, - 'sourceEntity' => 'Doctrine\\Tests\\Models\\CMS\\CmsUser', + 'sourceEntity' => CmsUser::class, 'isCascadeRemove' => true, 'isCascadePersist' => true, 'isCascadeRefresh' => true, 'isCascadeMerge' => true, 'isCascadeDetach' => true, 'sourceToTargetKeyColumns' => - array( + [ 'group_id' => 'id', - ), + ], 'joinColumnFieldNames' => - array( + [ 'group_id' => 'group_id', - ), + ], 'targetToSourceKeyColumns' => - array( + [ 'id' => 'group_id', - ), + ], 'orphanRemoval' => false, 'id' => true - ), - ), + ], + ], $this->cm->associationMappings ); } @@ -403,60 +393,62 @@ public function testCreateManyToOneWithIdentity() public function testCreateOneToOne() { $this->assertIsFluent( - $this->builder->createOneToOne('groups', 'Doctrine\Tests\Models\CMS\CmsGroup') + $this->builder->createOneToOne('groups', CmsGroup::class) ->addJoinColumn('group_id', 'id', true, false, 'CASCADE') ->cascadeAll() ->fetchExtraLazy() ->build() ); - $this->assertEquals(array('groups' => array ( + $this->assertEquals( + [ + 'groups' => [ 'fieldName' => 'groups', - 'targetEntity' => 'Doctrine\\Tests\\Models\\CMS\\CmsGroup', - 'cascade' => array ( + 'targetEntity' => CmsGroup::class, + 'cascade' => [ 0 => 'remove', 1 => 'persist', 2 => 'refresh', 3 => 'merge', 4 => 'detach', - ), + ], 'fetch' => 4, - 'joinColumns' => array ( + 'joinColumns' => [ 0 => - array ( + [ 'name' => 'group_id', 'referencedColumnName' => 'id', 'nullable' => true, 'unique' => true, 'onDelete' => 'CASCADE', 'columnDefinition' => NULL, - ), - ), + ], + ], 'type' => 1, 'mappedBy' => NULL, 'inversedBy' => NULL, 'isOwningSide' => true, - 'sourceEntity' => 'Doctrine\\Tests\\Models\\CMS\\CmsUser', + 'sourceEntity' => CmsUser::class, 'isCascadeRemove' => true, 'isCascadePersist' => true, 'isCascadeRefresh' => true, 'isCascadeMerge' => true, 'isCascadeDetach' => true, 'sourceToTargetKeyColumns' => - array ( + [ 'group_id' => 'id', - ), + ], 'joinColumnFieldNames' => - array ( + [ 'group_id' => 'group_id', - ), + ], 'targetToSourceKeyColumns' => - array ( + [ 'id' => 'group_id', - ), + ], 'orphanRemoval' => false - ), - ), $this->cm->associationMappings); + ], + ], $this->cm->associationMappings); } public function testCreateOneToOneWithIdentity() @@ -464,7 +456,7 @@ public function testCreateOneToOneWithIdentity() $this->assertIsFluent( $this ->builder - ->createOneToOne('groups', 'Doctrine\Tests\Models\CMS\CmsGroup') + ->createOneToOne('groups', CmsGroup::class) ->addJoinColumn('group_id', 'id', true, false, 'CASCADE') ->cascadeAll() ->fetchExtraLazy() @@ -473,55 +465,55 @@ public function testCreateOneToOneWithIdentity() ); $this->assertEquals( - array( - 'groups' => array( + [ + 'groups' => [ 'fieldName' => 'groups', - 'targetEntity' => 'Doctrine\\Tests\\Models\\CMS\\CmsGroup', - 'cascade' => array( + 'targetEntity' => CmsGroup::class, + 'cascade' => [ 0 => 'remove', 1 => 'persist', 2 => 'refresh', 3 => 'merge', 4 => 'detach', - ), + ], 'fetch' => 4, 'id' => true, - 'joinColumns' => array( + 'joinColumns' => [ 0 => - array( + [ 'name' => 'group_id', 'referencedColumnName' => 'id', 'nullable' => true, 'unique' => false, 'onDelete' => 'CASCADE', 'columnDefinition' => NULL, - ), - ), + ], + ], 'type' => 1, 'mappedBy' => NULL, 'inversedBy' => NULL, 'isOwningSide' => true, - 'sourceEntity' => 'Doctrine\\Tests\\Models\\CMS\\CmsUser', + 'sourceEntity' => CmsUser::class, 'isCascadeRemove' => true, 'isCascadePersist' => true, 'isCascadeRefresh' => true, 'isCascadeMerge' => true, 'isCascadeDetach' => true, 'sourceToTargetKeyColumns' => - array( + [ 'group_id' => 'id', - ), + ], 'joinColumnFieldNames' => - array( + [ 'group_id' => 'group_id', - ), + ], 'targetToSourceKeyColumns' => - array( + [ 'id' => 'group_id', - ), + ], 'orphanRemoval' => false - ), - ), + ], + ], $this->cm->associationMappings ); } @@ -532,7 +524,7 @@ public function testThrowsExceptionOnCreateOneToOneWithIdentityOnInverseSide() $this ->builder - ->createOneToOne('groups', 'Doctrine\Tests\Models\CMS\CmsGroup') + ->createOneToOne('groups', CmsGroup::class) ->mappedBy('test') ->fetchExtraLazy() ->makePrimaryKey() @@ -542,7 +534,7 @@ public function testThrowsExceptionOnCreateOneToOneWithIdentityOnInverseSide() public function testCreateManyToMany() { $this->assertIsFluent( - $this->builder->createManyToMany('groups', 'Doctrine\Tests\Models\CMS\CmsGroup') + $this->builder->createManyToMany('groups', CmsGroup::class) ->setJoinTable('groups_users') ->addJoinColumn('group_id', 'id', true, false, 'CASCADE') ->addInverseJoinColumn('user_id', 'id') @@ -551,53 +543,54 @@ public function testCreateManyToMany() ->build() ); - $this->assertEquals(array( + $this->assertEquals( + [ 'groups' => - array( + [ 'fieldName' => 'groups', - 'targetEntity' => 'Doctrine\\Tests\\Models\\CMS\\CmsGroup', + 'targetEntity' => CmsGroup::class, 'cascade' => - array( + [ 0 => 'remove', 1 => 'persist', 2 => 'refresh', 3 => 'merge', 4 => 'detach', - ), + ], 'fetch' => 4, 'joinTable' => - array( + [ 'joinColumns' => - array( + [ 0 => - array( + [ 'name' => 'group_id', 'referencedColumnName' => 'id', 'nullable' => true, 'unique' => false, 'onDelete' => 'CASCADE', 'columnDefinition' => NULL, - ), - ), + ], + ], 'inverseJoinColumns' => - array( + [ 0 => - array( + [ 'name' => 'user_id', 'referencedColumnName' => 'id', 'nullable' => true, 'unique' => false, 'onDelete' => NULL, 'columnDefinition' => NULL, - ), - ), + ], + ], 'name' => 'groups_users', - ), + ], 'type' => 8, 'mappedBy' => NULL, 'inversedBy' => NULL, 'isOwningSide' => true, - 'sourceEntity' => 'Doctrine\\Tests\\Models\\CMS\\CmsUser', + 'sourceEntity' => CmsUser::class, 'isCascadeRemove' => true, 'isCascadePersist' => true, 'isCascadeRefresh' => true, @@ -605,28 +598,28 @@ public function testCreateManyToMany() 'isCascadeDetach' => true, 'isOnDeleteCascade' => true, 'relationToSourceKeyColumns' => - array( + [ 'group_id' => 'id', - ), + ], 'joinTableColumns' => - array( + [ 0 => 'group_id', 1 => 'user_id', - ), + ], 'relationToTargetKeyColumns' => - array( + [ 'user_id' => 'id', - ), + ], 'orphanRemoval' => false, - ), - ), $this->cm->associationMappings); + ], + ], $this->cm->associationMappings); } public function testThrowsExceptionOnCreateManyToManyWithIdentity() { $this->expectException(\Doctrine\ORM\Mapping\MappingException::class); - $this->builder->createManyToMany('groups', 'Doctrine\Tests\Models\CMS\CmsGroup') + $this->builder->createManyToMany('groups', CmsGroup::class) ->makePrimaryKey() ->setJoinTable('groups_users') ->addJoinColumn('group_id', 'id', true, false, 'CASCADE') @@ -639,50 +632,51 @@ public function testThrowsExceptionOnCreateManyToManyWithIdentity() public function testCreateOneToMany() { $this->assertIsFluent( - $this->builder->createOneToMany('groups', 'Doctrine\Tests\Models\CMS\CmsGroup') + $this->builder->createOneToMany('groups', CmsGroup::class) ->mappedBy('test') - ->setOrderBy(array('test')) + ->setOrderBy(['test']) ->setIndexBy('test') ->build() ); - $this->assertEquals(array( + $this->assertEquals( + [ 'groups' => - array( + [ 'fieldName' => 'groups', - 'targetEntity' => 'Doctrine\\Tests\\Models\\CMS\\CmsGroup', + 'targetEntity' => CmsGroup::class, 'mappedBy' => 'test', 'orderBy' => - array( + [ 0 => 'test', - ), + ], 'indexBy' => 'test', 'type' => 4, 'inversedBy' => NULL, 'isOwningSide' => false, - 'sourceEntity' => 'Doctrine\\Tests\\Models\\CMS\\CmsUser', + 'sourceEntity' => CmsUser::class, 'fetch' => 2, 'cascade' => - array( - ), + [ + ], 'isCascadeRemove' => false, 'isCascadePersist' => false, 'isCascadeRefresh' => false, 'isCascadeMerge' => false, 'isCascadeDetach' => false, 'orphanRemoval' => false, - ), - ), $this->cm->associationMappings); + ], + ], $this->cm->associationMappings); } public function testThrowsExceptionOnCreateOneToManyWithIdentity() { $this->expectException(\Doctrine\ORM\Mapping\MappingException::class); - $this->builder->createOneToMany('groups', 'Doctrine\Tests\Models\CMS\CmsGroup') + $this->builder->createOneToMany('groups', CmsGroup::class) ->makePrimaryKey() ->mappedBy('test') - ->setOrderBy(array('test')) + ->setOrderBy(['test']) ->setIndexBy('test') ->build(); } @@ -691,86 +685,88 @@ public function testOrphanRemovalOnCreateOneToOne() { $this->assertIsFluent( $this->builder - ->createOneToOne('groups', 'Doctrine\Tests\Models\CMS\CmsGroup') + ->createOneToOne('groups', CmsGroup::class) ->addJoinColumn('group_id', 'id', true, false, 'CASCADE') ->orphanRemoval() ->build() ); - $this->assertEquals(array( - 'groups' => array( + $this->assertEquals( + [ + 'groups' => [ 'fieldName' => 'groups', - 'targetEntity' => 'Doctrine\\Tests\\Models\\CMS\\CmsGroup', - 'cascade' => array (), + 'targetEntity' => CmsGroup::class, + 'cascade' => [], 'fetch' => 2, - 'joinColumns' => array ( + 'joinColumns' => [ 0 => - array ( + [ 'name' => 'group_id', 'referencedColumnName' => 'id', 'nullable' => true, 'unique' => true, 'onDelete' => 'CASCADE', 'columnDefinition' => NULL, - ), - ), + ], + ], 'type' => 1, 'mappedBy' => NULL, 'inversedBy' => NULL, 'isOwningSide' => true, - 'sourceEntity' => 'Doctrine\\Tests\\Models\\CMS\\CmsUser', + 'sourceEntity' => CmsUser::class, 'isCascadeRemove' => true, 'isCascadePersist' => false, 'isCascadeRefresh' => false, 'isCascadeMerge' => false, 'isCascadeDetach' => false, 'sourceToTargetKeyColumns' => - array ( + [ 'group_id' => 'id', - ), + ], 'joinColumnFieldNames' => - array ( + [ 'group_id' => 'group_id', - ), + ], 'targetToSourceKeyColumns' => - array ( + [ 'id' => 'group_id', - ), + ], 'orphanRemoval' => true - ), - ), $this->cm->associationMappings); + ], + ], $this->cm->associationMappings); } public function testOrphanRemovalOnCreateOneToMany() { $this->assertIsFluent( $this->builder - ->createOneToMany('groups', 'Doctrine\Tests\Models\CMS\CmsGroup') + ->createOneToMany('groups', CmsGroup::class) ->mappedBy('test') ->orphanRemoval() ->build() ); - $this->assertEquals(array( + $this->assertEquals( + [ 'groups' => - array( + [ 'fieldName' => 'groups', - 'targetEntity' => 'Doctrine\\Tests\\Models\\CMS\\CmsGroup', + 'targetEntity' => CmsGroup::class, 'mappedBy' => 'test', 'type' => 4, 'inversedBy' => NULL, 'isOwningSide' => false, - 'sourceEntity' => 'Doctrine\\Tests\\Models\\CMS\\CmsUser', + 'sourceEntity' => CmsUser::class, 'fetch' => 2, - 'cascade' => array(), + 'cascade' => [], 'isCascadeRemove' => true, 'isCascadePersist' => false, 'isCascadeRefresh' => false, 'isCascadeMerge' => false, 'isCascadeDetach' => false, 'orphanRemoval' => true, - ), - ), $this->cm->associationMappings); + ], + ], $this->cm->associationMappings); } public function testExceptionOnOrphanRemovalOnManyToOne() @@ -778,7 +774,7 @@ public function testExceptionOnOrphanRemovalOnManyToOne() $this->expectException(\Doctrine\ORM\Mapping\MappingException::class); $this->builder - ->createManyToOne('groups', 'Doctrine\Tests\Models\CMS\CmsGroup') + ->createManyToOne('groups', CmsGroup::class) ->addJoinColumn('group_id', 'id', true, false, 'CASCADE') ->orphanRemoval() ->build(); @@ -787,61 +783,62 @@ public function testExceptionOnOrphanRemovalOnManyToOne() public function testOrphanRemovalOnManyToMany() { $this->builder - ->createManyToMany('groups', 'Doctrine\Tests\Models\CMS\CmsGroup') + ->createManyToMany('groups', CmsGroup::class) ->addJoinColumn('group_id', 'id', true, false, 'CASCADE') ->orphanRemoval() ->build(); - $this->assertEquals(array( - 'groups' => array( + $this->assertEquals( + [ + 'groups' => [ 'fieldName' => 'groups', - 'targetEntity' => 'Doctrine\\Tests\\Models\\CMS\\CmsGroup', - 'cascade' => array(), + 'targetEntity' => CmsGroup::class, + 'cascade' => [], 'fetch' => 2, - 'joinTable' => array( - 'joinColumns' => array( - 0 => array( + 'joinTable' => [ + 'joinColumns' => [ + 0 => [ 'name' => 'group_id', 'referencedColumnName' => 'id', 'nullable' => true, 'unique' => false, 'onDelete' => 'CASCADE', 'columnDefinition' => NULL, - ), - ), - 'inverseJoinColumns' => array( - 0 => array( + ], + ], + 'inverseJoinColumns' => [ + 0 => [ 'name' => 'cmsgroup_id', 'referencedColumnName' => 'id', 'onDelete' => 'CASCADE' - ) - ), + ] + ], 'name' => 'cmsuser_cmsgroup', - ), + ], 'type' => 8, 'mappedBy' => NULL, 'inversedBy' => NULL, 'isOwningSide' => true, - 'sourceEntity' => 'Doctrine\\Tests\\Models\\CMS\\CmsUser', + 'sourceEntity' => CmsUser::class, 'isCascadeRemove' => false, 'isCascadePersist' => false, 'isCascadeRefresh' => false, 'isCascadeMerge' => false, 'isCascadeDetach' => false, 'isOnDeleteCascade' => true, - 'relationToSourceKeyColumns' => array( + 'relationToSourceKeyColumns' => [ 'group_id' => 'id', - ), - 'joinTableColumns' => array( + ], + 'joinTableColumns' => [ 0 => 'group_id', 1 => 'cmsgroup_id', - ), - 'relationToTargetKeyColumns' => array( + ], + 'relationToTargetKeyColumns' => [ 'cmsgroup_id' => 'id', - ), + ], 'orphanRemoval' => true, - ), - ), $this->cm->associationMappings); + ], + ], $this->cm->associationMappings); } public function assertIsFluent($ret) diff --git a/tests/Doctrine/Tests/ORM/Mapping/ClassMetadataFactoryTest.php b/tests/Doctrine/Tests/ORM/Mapping/ClassMetadataFactoryTest.php index f40d657b53c..8c73bf1c2de 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/ClassMetadataFactoryTest.php +++ b/tests/Doctrine/Tests/ORM/Mapping/ClassMetadataFactoryTest.php @@ -20,7 +20,15 @@ use Doctrine\Tests\Mocks\DriverMock; use Doctrine\Tests\Mocks\EntityManagerMock; use Doctrine\Tests\Mocks\MetadataDriverMock; +use Doctrine\Tests\Models\CMS\CmsArticle; +use Doctrine\Tests\Models\CMS\CmsUser; +use Doctrine\Tests\Models\DDC4006\DDC4006User; +use Doctrine\Tests\Models\JoinedInheritanceType\AnotherChildClass; +use Doctrine\Tests\Models\JoinedInheritanceType\ChildClass; +use Doctrine\Tests\Models\JoinedInheritanceType\RootClass; +use Doctrine\Tests\Models\Quote; use Doctrine\Tests\OrmTestCase; +use DoctrineGlobal_Article; class ClassMetadataFactoryTest extends OrmTestCase { @@ -42,7 +50,7 @@ public function testGetMetadataForSingleClass() $cmf->setMetadataFor($cm1->name, $cm1); // Prechecks - $this->assertEquals(array(), $cm1->parentClasses); + $this->assertEquals([], $cm1->parentClasses); $this->assertEquals(ClassMetadata::INHERITANCE_TYPE_NONE, $cm1->inheritanceType); $this->assertTrue($cm1->hasField('name')); $this->assertEquals(2, count($cm1->associationMappings)); @@ -55,7 +63,7 @@ public function testGetMetadataForSingleClass() $this->assertSame($cm1, $cmMap1); $this->assertEquals('group', $cmMap1->table['name']); $this->assertTrue($cmMap1->table['quoted']); - $this->assertEquals(array(), $cmMap1->parentClasses); + $this->assertEquals([], $cmMap1->parentClasses); $this->assertTrue($cmMap1->hasField('name')); } @@ -63,24 +71,21 @@ public function testGetMetadataFor_ReturnsLoadedCustomIdGenerator() { $cm1 = $this->_createValidClassMetadata(); $cm1->setIdGeneratorType(ClassMetadata::GENERATOR_TYPE_CUSTOM); - $cm1->customGeneratorDefinition = array( - "class" => "Doctrine\Tests\ORM\Mapping\CustomIdGenerator"); + $cm1->customGeneratorDefinition = ['class' => CustomIdGenerator::class]; $cmf = $this->_createTestFactory(); $cmf->setMetadataForClass($cm1->name, $cm1); $actual = $cmf->getMetadataFor($cm1->name); - $this->assertEquals(ClassMetadata::GENERATOR_TYPE_CUSTOM, - $actual->generatorType); - $this->assertInstanceOf("Doctrine\Tests\ORM\Mapping\CustomIdGenerator", - $actual->idGenerator); + $this->assertEquals(ClassMetadata::GENERATOR_TYPE_CUSTOM, $actual->generatorType); + $this->assertInstanceOf(CustomIdGenerator::class, $actual->idGenerator); } public function testGetMetadataFor_ThrowsExceptionOnUnknownCustomGeneratorClass() { $cm1 = $this->_createValidClassMetadata(); $cm1->setIdGeneratorType(ClassMetadata::GENERATOR_TYPE_CUSTOM); - $cm1->customGeneratorDefinition = array("class" => "NotExistingGenerator"); + $cm1->customGeneratorDefinition = ["class" => "NotExistingGenerator"]; $cmf = $this->_createTestFactory(); $cmf->setMetadataForClass($cm1->name, $cm1); $this->expectException(ORMException::class); @@ -103,15 +108,15 @@ public function testHasGetMetadata_NamespaceSeparatorIsNotNormalized() { require_once __DIR__."/../../Models/Global/GlobalNamespaceModel.php"; - $metadataDriver = $this->createAnnotationDriver(array(__DIR__ . '/../../Models/Global/')); + $metadataDriver = $this->createAnnotationDriver([__DIR__ . '/../../Models/Global/']); $entityManager = $this->_createEntityManager($metadataDriver); $mf = $entityManager->getMetadataFactory(); - $m1 = $mf->getMetadataFor("DoctrineGlobal_Article"); - $h1 = $mf->hasMetadataFor("DoctrineGlobal_Article"); - $h2 = $mf->hasMetadataFor("\DoctrineGlobal_Article"); - $m2 = $mf->getMetadataFor("\DoctrineGlobal_Article"); + $m1 = $mf->getMetadataFor(DoctrineGlobal_Article::class); + $h1 = $mf->hasMetadataFor(DoctrineGlobal_Article::class); + $h2 = $mf->hasMetadataFor('\\' . DoctrineGlobal_Article::class); + $m2 = $mf->getMetadataFor('\\' . DoctrineGlobal_Article::class); $this->assertNotSame($m1, $m2); $this->assertFalse($h2); @@ -127,17 +132,17 @@ public function testIsTransient() $driver = $this->createMock(MappingDriver::class); $driver->expects($this->at(0)) ->method('isTransient') - ->with($this->equalTo('Doctrine\Tests\Models\CMS\CmsUser')) + ->with($this->equalTo(CmsUser::class)) ->will($this->returnValue(true)); $driver->expects($this->at(1)) ->method('isTransient') - ->with($this->equalTo('Doctrine\Tests\Models\CMS\CmsArticle')) + ->with($this->equalTo(CmsArticle::class)) ->will($this->returnValue(false)); $em = $this->_createEntityManager($driver); - $this->assertTrue($em->getMetadataFactory()->isTransient('Doctrine\Tests\Models\CMS\CmsUser')); - $this->assertFalse($em->getMetadataFactory()->isTransient('Doctrine\Tests\Models\CMS\CmsArticle')); + $this->assertTrue($em->getMetadataFactory()->isTransient(CmsUser::class)); + $this->assertFalse($em->getMetadataFactory()->isTransient(CmsArticle::class)); } /** @@ -149,11 +154,11 @@ public function testIsTransientEntityNamespace() $driver = $this->createMock(MappingDriver::class); $driver->expects($this->at(0)) ->method('isTransient') - ->with($this->equalTo('Doctrine\Tests\Models\CMS\CmsUser')) + ->with($this->equalTo(CmsUser::class)) ->will($this->returnValue(true)); $driver->expects($this->at(1)) ->method('isTransient') - ->with($this->equalTo('Doctrine\Tests\Models\CMS\CmsArticle')) + ->with($this->equalTo(CmsArticle::class)) ->will($this->returnValue(false)); $em = $this->_createEntityManager($driver); @@ -165,21 +170,23 @@ public function testIsTransientEntityNamespace() public function testAddDefaultDiscriminatorMap() { + self::markTestSkipped('This test is just incorrect and must be fixed'); + $cmf = new ClassMetadataFactory(); - $driver = $this->createAnnotationDriver(array(__DIR__ . '/../../Models/JoinedInheritanceType/')); + $driver = $this->createAnnotationDriver([__DIR__ . '/../../Models/JoinedInheritanceType/']); $em = $this->_createEntityManager($driver); $cmf->setEntityManager($em); - $rootMetadata = $cmf->getMetadataFor('Doctrine\Tests\Models\JoinedInheritanceType\RootClass'); - $childMetadata = $cmf->getMetadataFor('Doctrine\Tests\Models\JoinedInheritanceType\ChildClass'); - $anotherChildMetadata = $cmf->getMetadataFor('Doctrine\Tests\Models\JoinedInheritanceType\AnotherChildClass'); + $rootMetadata = $cmf->getMetadataFor(RootClass::class); + $childMetadata = $cmf->getMetadataFor(ChildClass::class); + $anotherChildMetadata = $cmf->getMetadataFor(AnotherChildClass::class); $rootDiscriminatorMap = $rootMetadata->discriminatorMap; $childDiscriminatorMap = $childMetadata->discriminatorMap; $anotherChildDiscriminatorMap = $anotherChildMetadata->discriminatorMap; - $rootClass = 'Doctrine\Tests\Models\JoinedInheritanceType\RootClass'; - $childClass = 'Doctrine\Tests\Models\JoinedInheritanceType\ChildClass'; - $anotherChildClass = 'Doctrine\Tests\Models\JoinedInheritanceType\AnotherChildClass'; + $rootClass = RootClass::class; + $childClass = ChildClass::class; + $anotherChildClass = AnotherChildClass::class; $rootClassKey = array_search($rootClass, $rootDiscriminatorMap); $childClassKey = array_search($childClass, $rootDiscriminatorMap); @@ -194,12 +201,12 @@ public function testAddDefaultDiscriminatorMap() // ClassMetadataFactory::addDefaultDiscriminatorMap shouldn't be called again, because the // discriminator map is already cached - $cmf = $this->getMockBuilder(ClassMetadataFactory::class)->setMethods(array('addDefaultDiscriminatorMap'))->getMock(); + $cmf = $this->getMockBuilder(ClassMetadataFactory::class)->setMethods(['addDefaultDiscriminatorMap'])->getMock(); $cmf->setEntityManager($em); $cmf->expects($this->never()) ->method('addDefaultDiscriminatorMap'); - $rootMetadata = $cmf->getMetadataFor('Doctrine\Tests\Models\JoinedInheritanceType\RootClass'); + $rootMetadata = $cmf->getMetadataFor(RootClass::class); } public function testGetAllMetadataWorksWithBadConnection() @@ -219,7 +226,7 @@ public function testGetAllMetadataWorksWithBadConnection() // getting all the metadata should work, even if get DatabasePlatform blows up $metadata = $cmf->getAllMetadata(); // this will just be an empty array - there was no error - $this->assertEquals(array(), $metadata); + $this->assertEquals([], $metadata); } protected function _createEntityManager($metadataDriver, $conn = null) @@ -230,7 +237,7 @@ protected function _createEntityManager($metadataDriver, $conn = null) $config->setProxyNamespace('Doctrine\Tests\Proxies'); $eventManager = new EventManager(); if (!$conn) { - $conn = new ConnectionMock(array(), $driverMock, $config, $eventManager); + $conn = new ConnectionMock([], $driverMock, $config, $eventManager); } $config->setMetadataDriverImpl($metadataDriver); @@ -256,20 +263,22 @@ protected function _createTestFactory() protected function _createValidClassMetadata() { // Self-made metadata - $cm1 = new ClassMetadata('Doctrine\Tests\ORM\Mapping\TestEntity1'); + $cm1 = new ClassMetadata(TestEntity1::class); $cm1->initializeReflection(new RuntimeReflectionService()); - $cm1->setPrimaryTable(array('name' => '`group`')); + $cm1->setPrimaryTable(['name' => '`group`']); // Add a mapped field - $cm1->mapField(array('fieldName' => 'name', 'type' => 'string')); + $cm1->mapField(['fieldName' => 'name', 'type' => 'string']); // Add a mapped field - $cm1->mapField(array('fieldName' => 'id', 'type' => 'integer', 'id' => true)); + $cm1->mapField(['fieldName' => 'id', 'type' => 'integer', 'id' => true]); // and a mapped association - $cm1->mapOneToOne(array('fieldName' => 'other', 'targetEntity' => 'TestEntity1', 'mappedBy' => 'this')); + $cm1->mapOneToOne(['fieldName' => 'other', 'targetEntity' => 'TestEntity1', 'mappedBy' => 'this']); // and an association on the owning side - $joinColumns = array( - array('name' => 'other_id', 'referencedColumnName' => 'id') + $joinColumns = [ + ['name' => 'other_id', 'referencedColumnName' => 'id'] + ]; + $cm1->mapOneToOne( + ['fieldName' => 'association', 'targetEntity' => 'TestEntity1', 'joinColumns' => $joinColumns] ); - $cm1->mapOneToOne(array('fieldName' => 'association', 'targetEntity' => 'TestEntity1', 'joinColumns' => $joinColumns)); // and an id generator type $cm1->setIdGeneratorType(ClassMetadata::GENERATOR_TYPE_AUTO); return $cm1; @@ -281,15 +290,15 @@ protected function _createValidClassMetadata() public function testQuoteMetadata() { $cmf = new ClassMetadataFactory(); - $driver = $this->createAnnotationDriver(array(__DIR__ . '/../../Models/Quote/')); + $driver = $this->createAnnotationDriver([__DIR__ . '/../../Models/Quote/']); $em = $this->_createEntityManager($driver); $cmf->setEntityManager($em); - $userMetadata = $cmf->getMetadataFor('Doctrine\Tests\Models\Quote\User'); - $phoneMetadata = $cmf->getMetadataFor('Doctrine\Tests\Models\Quote\Phone'); - $groupMetadata = $cmf->getMetadataFor('Doctrine\Tests\Models\Quote\Group'); - $addressMetadata = $cmf->getMetadataFor('Doctrine\Tests\Models\Quote\Address'); + $userMetadata = $cmf->getMetadataFor(Quote\User::class); + $phoneMetadata = $cmf->getMetadataFor(Quote\Phone::class); + $groupMetadata = $cmf->getMetadataFor(Quote\Group::class); + $addressMetadata = $cmf->getMetadataFor(Quote\Address::class); // Phone Class Metadata @@ -368,7 +377,7 @@ public function testFallbackLoadingCausesEventTriggeringThatCanModifyFetchedMeta $cmf = new ClassMetadataFactory(); $mockDriver = new MetadataDriverMock(); $em = $this->_createEntityManager($mockDriver); - $listener = $this->getMockBuilder(\stdClass::class)->setMethods(array('onClassMetadataNotFound'))->getMock(); + $listener = $this->getMockBuilder(\stdClass::class)->setMethods(['onClassMetadataNotFound'])->getMock(); $eventManager = $em->getEventManager(); $cmf->setEntityManager($em); @@ -384,7 +393,7 @@ public function testFallbackLoadingCausesEventTriggeringThatCanModifyFetchedMeta $args->setFoundMetadata($metadata); })); - $eventManager->addEventListener(array(Events::onClassMetadataNotFound), $listener); + $eventManager->addEventListener([Events::onClassMetadataNotFound], $listener); $this->assertSame($metadata, $cmf->getMetadataFor('Foo')); } @@ -412,11 +421,13 @@ public function testRejectsEmbeddableWithoutValidClassName() { $metadata = $this->_createValidClassMetadata(); - $metadata->mapEmbedded(array( + $metadata->mapEmbedded( + [ 'fieldName' => 'embedded', 'class' => '', 'columnPrefix' => false, - )); + ] + ); $cmf = $this->_createTestFactory(); @@ -434,11 +445,11 @@ public function testRejectsEmbeddableWithoutValidClassName() public function testInheritsIdGeneratorMappingFromEmbeddable() { $cmf = new ClassMetadataFactory(); - $driver = $this->createAnnotationDriver(array(__DIR__ . '/../../Models/DDC4006/')); + $driver = $this->createAnnotationDriver([__DIR__ . '/../../Models/DDC4006/']); $em = $this->_createEntityManager($driver); $cmf->setEntityManager($em); - $userMetadata = $cmf->getMetadataFor('Doctrine\Tests\Models\DDC4006\DDC4006User'); + $userMetadata = $cmf->getMetadataFor(DDC4006User::class); $this->assertTrue($userMetadata->isIdGeneratorIdentity()); } @@ -447,8 +458,8 @@ public function testInheritsIdGeneratorMappingFromEmbeddable() /* Test subject class with overridden factory method for mocking purposes */ class ClassMetadataFactoryTestSubject extends ClassMetadataFactory { - private $mockMetadata = array(); - private $requestedClasses = array(); + private $mockMetadata = []; + private $requestedClasses = []; /** @override */ protected function newClassMetadataInstance($className) diff --git a/tests/Doctrine/Tests/ORM/Mapping/ClassMetadataLoadEventTest.php b/tests/Doctrine/Tests/ORM/Mapping/ClassMetadataLoadEventTest.php index 04cea38944c..bf268cf829a 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/ClassMetadataLoadEventTest.php +++ b/tests/Doctrine/Tests/ORM/Mapping/ClassMetadataLoadEventTest.php @@ -17,7 +17,7 @@ public function testEvent() $metadataFactory = $em->getMetadataFactory(); $evm = $em->getEventManager(); $evm->addEventListener(Events::loadClassMetadata, $this); - $classMetadata = $metadataFactory->getMetadataFor('Doctrine\Tests\ORM\Mapping\LoadEventTestEntity'); + $classMetadata = $metadataFactory->getMetadataFor(LoadEventTestEntity::class); $this->assertTrue($classMetadata->hasField('about')); $this->assertArrayHasKey('about', $classMetadata->reflFields); $this->assertInstanceOf('ReflectionProperty', $classMetadata->reflFields['about']); @@ -26,11 +26,11 @@ public function testEvent() public function loadClassMetadata(LoadClassMetadataEventArgs $eventArgs) { $classMetadata = $eventArgs->getClassMetadata(); - $field = array( + $field = [ 'fieldName' => 'about', 'type' => 'string', 'length' => 255 - ); + ]; $classMetadata->mapField($field); } } diff --git a/tests/Doctrine/Tests/ORM/Mapping/ClassMetadataTest.php b/tests/Doctrine/Tests/ORM/Mapping/ClassMetadataTest.php index 44243e11353..a7be70be848 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/ClassMetadataTest.php +++ b/tests/Doctrine/Tests/ORM/Mapping/ClassMetadataTest.php @@ -4,13 +4,22 @@ use Doctrine\Common\Persistence\Mapping\RuntimeReflectionService; use Doctrine\Common\Persistence\Mapping\StaticReflectionService; -use Doctrine\ORM\Mapping\ClassMetadata; use Doctrine\ORM\Events; +use Doctrine\ORM\Mapping\ClassMetadata; use Doctrine\ORM\Mapping\DefaultNamingStrategy; use Doctrine\ORM\Mapping\MappingException; use Doctrine\ORM\Mapping\UnderscoreNamingStrategy; +use Doctrine\Tests\Models\CMS; +use Doctrine\Tests\Models\Company\CompanyContract; +use Doctrine\Tests\Models\CustomType\CustomTypeParent; +use Doctrine\Tests\Models\DDC117\DDC117Article; +use Doctrine\Tests\Models\DDC117\DDC117ArticleDetails; +use Doctrine\Tests\Models\DDC6412\DDC6412File; +use Doctrine\Tests\Models\DDC964\DDC964Admin; +use Doctrine\Tests\Models\DDC964\DDC964Guest; +use Doctrine\Tests\Models\Routing\RoutingLeg; use Doctrine\Tests\OrmTestCase; -use Doctrine\Tests\Proxies\__CG__\Doctrine\Tests\Models\CMS\CmsUser; +use DoctrineGlobal_Article; require_once __DIR__ . '/../../Models/Global/GlobalNamespaceModel.php'; @@ -18,27 +27,27 @@ class ClassMetadataTest extends OrmTestCase { public function testClassMetadataInstanceSerialization() { - $cm = new ClassMetadata('Doctrine\Tests\Models\CMS\CmsUser'); + $cm = new ClassMetadata(CMS\CmsUser::class); $cm->initializeReflection(new RuntimeReflectionService()); // Test initial state $this->assertTrue(count($cm->getReflectionProperties()) == 0); $this->assertInstanceOf('ReflectionClass', $cm->reflClass); - $this->assertEquals('Doctrine\Tests\Models\CMS\CmsUser', $cm->name); - $this->assertEquals('Doctrine\Tests\Models\CMS\CmsUser', $cm->rootEntityName); - $this->assertEquals(array(), $cm->subClasses); - $this->assertEquals(array(), $cm->parentClasses); + $this->assertEquals(CMS\CmsUser::class, $cm->name); + $this->assertEquals(CMS\CmsUser::class, $cm->rootEntityName); + $this->assertEquals([], $cm->subClasses); + $this->assertEquals([], $cm->parentClasses); $this->assertEquals(ClassMetadata::INHERITANCE_TYPE_NONE, $cm->inheritanceType); // Customize state $cm->setInheritanceType(ClassMetadata::INHERITANCE_TYPE_SINGLE_TABLE); - $cm->setSubclasses(array("One", "Two", "Three")); - $cm->setParentClasses(array("UserParent")); + $cm->setSubclasses(["One", "Two", "Three"]); + $cm->setParentClasses(["UserParent"]); $cm->setCustomRepositoryClass("UserRepository"); - $cm->setDiscriminatorColumn(array('name' => 'disc', 'type' => 'integer')); - $cm->mapOneToOne(array('fieldName' => 'phonenumbers', 'targetEntity' => 'CmsAddress', 'mappedBy' => 'foo')); + $cm->setDiscriminatorColumn(['name' => 'disc', 'type' => 'integer']); + $cm->mapOneToOne(['fieldName' => 'phonenumbers', 'targetEntity' => 'CmsAddress', 'mappedBy' => 'foo']); $cm->markReadOnly(); - $cm->addNamedQuery(array('name' => 'dql', 'query' => 'foo')); + $cm->addNamedQuery(['name' => 'dql', 'query' => 'foo']); $this->assertEquals(1, count($cm->associationMappings)); $serialized = serialize($cm); @@ -48,38 +57,38 @@ public function testClassMetadataInstanceSerialization() // Check state $this->assertTrue(count($cm->getReflectionProperties()) > 0); $this->assertEquals('Doctrine\Tests\Models\CMS', $cm->namespace); - $this->assertInstanceOf('ReflectionClass', $cm->reflClass); - $this->assertEquals('Doctrine\Tests\Models\CMS\CmsUser', $cm->name); + $this->assertInstanceOf(\ReflectionClass::class, $cm->reflClass); + $this->assertEquals(CMS\CmsUser::class, $cm->name); $this->assertEquals('UserParent', $cm->rootEntityName); - $this->assertEquals(array('Doctrine\Tests\Models\CMS\One', 'Doctrine\Tests\Models\CMS\Two', 'Doctrine\Tests\Models\CMS\Three'), $cm->subClasses); - $this->assertEquals(array('UserParent'), $cm->parentClasses); - $this->assertEquals('Doctrine\Tests\Models\CMS\UserRepository', $cm->customRepositoryClassName); - $this->assertEquals(array('name' => 'disc', 'type' => 'integer', 'fieldName' => 'disc'), $cm->discriminatorColumn); + $this->assertEquals([CMS\One::class, CMS\Two::class, CMS\Three::class], $cm->subClasses); + $this->assertEquals(['UserParent'], $cm->parentClasses); + $this->assertEquals(CMS\UserRepository::class, $cm->customRepositoryClassName); + $this->assertEquals(['name' => 'disc', 'type' => 'integer', 'fieldName' => 'disc'], $cm->discriminatorColumn); $this->assertTrue($cm->associationMappings['phonenumbers']['type'] == ClassMetadata::ONE_TO_ONE); $this->assertEquals(1, count($cm->associationMappings)); $oneOneMapping = $cm->getAssociationMapping('phonenumbers'); $this->assertTrue($oneOneMapping['fetch'] == ClassMetadata::FETCH_LAZY); $this->assertEquals('phonenumbers', $oneOneMapping['fieldName']); - $this->assertEquals('Doctrine\Tests\Models\CMS\CmsAddress', $oneOneMapping['targetEntity']); + $this->assertEquals(CMS\CmsAddress::class, $oneOneMapping['targetEntity']); $this->assertTrue($cm->isReadOnly); - $this->assertEquals(array('dql' => array('name'=>'dql','query'=>'foo','dql'=>'foo')), $cm->namedQueries); + $this->assertEquals(['dql' => ['name'=>'dql','query'=>'foo','dql'=>'foo']], $cm->namedQueries); } public function testFieldIsNullable() { - $cm = new ClassMetadata('Doctrine\Tests\Models\CMS\CmsUser'); + $cm = new ClassMetadata(CMS\CmsUser::class); $cm->initializeReflection(new RuntimeReflectionService()); // Explicit Nullable - $cm->mapField(array('fieldName' => 'status', 'nullable' => true, 'type' => 'string', 'length' => 50)); + $cm->mapField(['fieldName' => 'status', 'nullable' => true, 'type' => 'string', 'length' => 50]); $this->assertTrue($cm->isNullable('status')); // Explicit Not Nullable - $cm->mapField(array('fieldName' => 'username', 'nullable' => false, 'type' => 'string', 'length' => 50)); + $cm->mapField(['fieldName' => 'username', 'nullable' => false, 'type' => 'string', 'length' => 50]); $this->assertFalse($cm->isNullable('username')); // Implicit Not Nullable - $cm->mapField(array('fieldName' => 'name', 'type' => 'string', 'length' => 50)); + $cm->mapField(['fieldName' => 'name', 'type' => 'string', 'length' => 50]); $this->assertFalse($cm->isNullable('name'), "By default a field should not be nullable."); } @@ -92,50 +101,54 @@ public function testMapAssociationInGlobalNamespace() $cm = new ClassMetadata('DoctrineGlobal_Article'); $cm->initializeReflection(new RuntimeReflectionService()); - $cm->mapManyToMany(array( + $cm->mapManyToMany( + [ 'fieldName' => 'author', 'targetEntity' => 'DoctrineGlobal_User', - 'joinTable' => array( + 'joinTable' => [ 'name' => 'bar', - 'joinColumns' => array(array('name' => 'bar_id', 'referencedColumnName' => 'id')), - 'inverseJoinColumns' => array(array('name' => 'baz_id', 'referencedColumnName' => 'id')), - ), - )); + 'joinColumns' => [['name' => 'bar_id', 'referencedColumnName' => 'id']], + 'inverseJoinColumns' => [['name' => 'baz_id', 'referencedColumnName' => 'id']], + ], + ] + ); $this->assertEquals("DoctrineGlobal_User", $cm->associationMappings['author']['targetEntity']); } public function testMapManyToManyJoinTableDefaults() { - $cm = new ClassMetadata('Doctrine\Tests\Models\CMS\CmsUser'); + $cm = new ClassMetadata(CMS\CmsUser::class); $cm->initializeReflection(new RuntimeReflectionService()); $cm->mapManyToMany( - array( + [ 'fieldName' => 'groups', 'targetEntity' => 'CmsGroup' - )); + ] + ); $assoc = $cm->associationMappings['groups']; - //$this->assertInstanceOf('Doctrine\ORM\Mapping\ManyToManyMapping', $assoc); - $this->assertEquals(array( + $this->assertEquals( + [ 'name' => 'cmsuser_cmsgroup', - 'joinColumns' => array(array('name' => 'cmsuser_id', 'referencedColumnName' => 'id', 'onDelete' => 'CASCADE')), - 'inverseJoinColumns' => array(array('name' => 'cmsgroup_id', 'referencedColumnName' => 'id', 'onDelete' => 'CASCADE')) - ), $assoc['joinTable']); + 'joinColumns' => [['name' => 'cmsuser_id', 'referencedColumnName' => 'id', 'onDelete' => 'CASCADE']], + 'inverseJoinColumns' => [['name' => 'cmsgroup_id', 'referencedColumnName' => 'id', 'onDelete' => 'CASCADE']] + ], $assoc['joinTable']); $this->assertTrue($assoc['isOnDeleteCascade']); } public function testSerializeManyToManyJoinTableCascade() { - $cm = new ClassMetadata('Doctrine\Tests\Models\CMS\CmsUser'); + $cm = new ClassMetadata(CMS\CmsUser::class); $cm->initializeReflection(new RuntimeReflectionService()); $cm->mapManyToMany( - array( + [ 'fieldName' => 'groups', 'targetEntity' => 'CmsGroup' - )); + ] + ); - /* @var $assoc \Doctrine\ORM\Mapping\ManyToManyMapping */ + /* @var $assoc \Doctrine\ORM\Mapping\ManyToMany */ $assoc = $cm->associationMappings['groups']; $assoc = unserialize(serialize($assoc)); @@ -151,7 +164,7 @@ public function testSetDiscriminatorMapInGlobalNamespace() $cm = new ClassMetadata('DoctrineGlobal_User'); $cm->initializeReflection(new RuntimeReflectionService()); - $cm->setDiscriminatorMap(array('descr' => 'DoctrineGlobal_Article', 'foo' => 'DoctrineGlobal_User')); + $cm->setDiscriminatorMap(['descr' => 'DoctrineGlobal_Article', 'foo' => 'DoctrineGlobal_User']); $this->assertEquals("DoctrineGlobal_Article", $cm->discriminatorMap['descr']); $this->assertEquals("DoctrineGlobal_User", $cm->discriminatorMap['foo']); @@ -166,7 +179,7 @@ public function testSetSubClassesInGlobalNamespace() $cm = new ClassMetadata('DoctrineGlobal_User'); $cm->initializeReflection(new RuntimeReflectionService()); - $cm->setSubclasses(array('DoctrineGlobal_Article')); + $cm->setSubclasses(['DoctrineGlobal_Article']); $this->assertEquals("DoctrineGlobal_Article", $cm->subClasses[0]); } @@ -176,11 +189,11 @@ public function testSetSubClassesInGlobalNamespace() */ public function testSetInvalidVersionMapping_ThrowsException() { - $field = array(); + $field = []; $field['fieldName'] = 'foo'; $field['type'] = 'string'; - $cm = new ClassMetadata('Doctrine\Tests\Models\CMS\CmsUser'); + $cm = new ClassMetadata(CMS\CmsUser::class); $cm->initializeReflection(new RuntimeReflectionService()); $this->expectException(\Doctrine\ORM\Mapping\MappingException::class); @@ -189,7 +202,7 @@ public function testSetInvalidVersionMapping_ThrowsException() public function testGetSingleIdentifierFieldName_MultipleIdentifierEntity_ThrowsException() { - $cm = new ClassMetadata('Doctrine\Tests\Models\CMS\CmsUser'); + $cm = new ClassMetadata(CMS\CmsUser::class); $cm->initializeReflection(new RuntimeReflectionService()); $cm->isIdentifierComposite = true; @@ -197,13 +210,22 @@ public function testGetSingleIdentifierFieldName_MultipleIdentifierEntity_Throws $cm->getSingleIdentifierFieldName(); } + public function testGetSingleIdentifierFieldName_NoIdEntity_ThrowsException() + { + $cm = new ClassMetadata(DDC6412File::class); + $cm->initializeReflection(new RuntimeReflectionService()); + + $this->expectException(\Doctrine\ORM\Mapping\MappingException::class); + $cm->getSingleIdentifierFieldName(); + } + public function testDuplicateAssociationMappingException() { - $cm = new ClassMetadata('Doctrine\Tests\Models\CMS\CmsUser'); + $cm = new ClassMetadata(CMS\CmsUser::class); $cm->initializeReflection(new RuntimeReflectionService()); - $a1 = array('fieldName' => 'foo', 'sourceEntity' => 'stdClass', 'targetEntity' => 'stdClass', 'mappedBy' => 'foo'); - $a2 = array('fieldName' => 'foo', 'sourceEntity' => 'stdClass', 'targetEntity' => 'stdClass', 'mappedBy' => 'foo'); + $a1 = ['fieldName' => 'foo', 'sourceEntity' => 'stdClass', 'targetEntity' => 'stdClass', 'mappedBy' => 'foo']; + $a2 = ['fieldName' => 'foo', 'sourceEntity' => 'stdClass', 'targetEntity' => 'stdClass', 'mappedBy' => 'foo']; $cm->addInheritedAssociationMapping($a1); $this->expectException(\Doctrine\ORM\Mapping\MappingException::class); @@ -212,57 +234,57 @@ public function testDuplicateAssociationMappingException() public function testDuplicateColumnName_ThrowsMappingException() { - $cm = new ClassMetadata('Doctrine\Tests\Models\CMS\CmsUser'); + $cm = new ClassMetadata(CMS\CmsUser::class); $cm->initializeReflection(new RuntimeReflectionService()); - $cm->mapField(array('fieldName' => 'name', 'columnName' => 'name')); + $cm->mapField(['fieldName' => 'name', 'columnName' => 'name']); $this->expectException(\Doctrine\ORM\Mapping\MappingException::class); - $cm->mapField(array('fieldName' => 'username', 'columnName' => 'name')); + $cm->mapField(['fieldName' => 'username', 'columnName' => 'name']); } public function testDuplicateColumnName_DiscriminatorColumn_ThrowsMappingException() { - $cm = new ClassMetadata('Doctrine\Tests\Models\CMS\CmsUser'); + $cm = new ClassMetadata(CMS\CmsUser::class); $cm->initializeReflection(new RuntimeReflectionService()); - $cm->mapField(array('fieldName' => 'name', 'columnName' => 'name')); + $cm->mapField(['fieldName' => 'name', 'columnName' => 'name']); $this->expectException(\Doctrine\ORM\Mapping\MappingException::class); - $cm->setDiscriminatorColumn(array('name' => 'name')); + $cm->setDiscriminatorColumn(['name' => 'name']); } public function testDuplicateColumnName_DiscriminatorColumn2_ThrowsMappingException() { - $cm = new ClassMetadata('Doctrine\Tests\Models\CMS\CmsUser'); + $cm = new ClassMetadata(CMS\CmsUser::class); $cm->initializeReflection(new RuntimeReflectionService()); - $cm->setDiscriminatorColumn(array('name' => 'name')); + $cm->setDiscriminatorColumn(['name' => 'name']); $this->expectException(\Doctrine\ORM\Mapping\MappingException::class); - $cm->mapField(array('fieldName' => 'name', 'columnName' => 'name')); + $cm->mapField(['fieldName' => 'name', 'columnName' => 'name']); } public function testDuplicateFieldAndAssociationMapping1_ThrowsException() { - $cm = new ClassMetadata('Doctrine\Tests\Models\CMS\CmsUser'); + $cm = new ClassMetadata(CMS\CmsUser::class); $cm->initializeReflection(new RuntimeReflectionService()); - $cm->mapField(array('fieldName' => 'name', 'columnName' => 'name')); + $cm->mapField(['fieldName' => 'name', 'columnName' => 'name']); $this->expectException(\Doctrine\ORM\Mapping\MappingException::class); - $cm->mapOneToOne(array('fieldName' => 'name', 'targetEntity' => 'CmsUser')); + $cm->mapOneToOne(['fieldName' => 'name', 'targetEntity' => 'CmsUser']); } public function testDuplicateFieldAndAssociationMapping2_ThrowsException() { - $cm = new ClassMetadata('Doctrine\Tests\Models\CMS\CmsUser'); + $cm = new ClassMetadata(CMS\CmsUser::class); $cm->initializeReflection(new RuntimeReflectionService()); - $cm->mapOneToOne(array('fieldName' => 'name', 'targetEntity' => 'CmsUser')); + $cm->mapOneToOne(['fieldName' => 'name', 'targetEntity' => 'CmsUser']); $this->expectException(\Doctrine\ORM\Mapping\MappingException::class); - $cm->mapField(array('fieldName' => 'name', 'columnName' => 'name')); + $cm->mapField(['fieldName' => 'name', 'columnName' => 'name']); } /** @@ -270,7 +292,7 @@ public function testDuplicateFieldAndAssociationMapping2_ThrowsException() */ public function testGetTemporaryTableNameSchema() { - $cm = new ClassMetadata('Doctrine\Tests\Models\CMS\CmsUser'); + $cm = new ClassMetadata(CMS\CmsUser::class); $cm->initializeReflection(new RuntimeReflectionService()); $cm->setTableName('foo.bar'); @@ -280,50 +302,63 @@ public function testGetTemporaryTableNameSchema() public function testDefaultTableName() { - $cm = new ClassMetadata('Doctrine\Tests\Models\CMS\CmsUser'); + $cm = new ClassMetadata(CMS\CmsUser::class); $cm->initializeReflection(new RuntimeReflectionService()); // When table's name is not given - $primaryTable = array(); + $primaryTable = []; $cm->setPrimaryTable($primaryTable); $this->assertEquals('CmsUser', $cm->getTableName()); $this->assertEquals('CmsUser', $cm->table['name']); - $cm = new ClassMetadata('Doctrine\Tests\Models\CMS\CmsAddress'); + $cm = new ClassMetadata(CMS\CmsAddress::class); $cm->initializeReflection(new RuntimeReflectionService()); // When joinTable's name is not given - $cm->mapManyToMany(array( - 'fieldName' => 'user', - 'targetEntity' => 'CmsUser', - 'inversedBy' => 'users', - 'joinTable' => array('joinColumns' => array(array('referencedColumnName' => 'id')), - 'inverseJoinColumns' => array(array('referencedColumnName' => 'id'))))); + $cm->mapManyToMany( + [ + 'fieldName' => 'user', + 'targetEntity' => 'CmsUser', + 'inversedBy' => 'users', + 'joinTable' => [ + 'joinColumns' => [['referencedColumnName' => 'id']], + 'inverseJoinColumns' => [['referencedColumnName' => 'id']] + ] + ] + ); $this->assertEquals('cmsaddress_cmsuser', $cm->associationMappings['user']['joinTable']['name']); } public function testDefaultJoinColumnName() { - $cm = new ClassMetadata('Doctrine\Tests\Models\CMS\CmsAddress'); + $cm = new ClassMetadata(CMS\CmsAddress::class); $cm->initializeReflection(new RuntimeReflectionService()); // this is really dirty, but it's the simplest way to test whether // joinColumn's name will be automatically set to user_id - $cm->mapOneToOne(array( + $cm->mapOneToOne( + [ 'fieldName' => 'user', 'targetEntity' => 'CmsUser', - 'joinColumns' => array(array('referencedColumnName' => 'id')))); + 'joinColumns' => [['referencedColumnName' => 'id']] + ] + ); $this->assertEquals('user_id', $cm->associationMappings['user']['joinColumns'][0]['name']); - $cm = new ClassMetadata('Doctrine\Tests\Models\CMS\CmsAddress'); + $cm = new ClassMetadata(CMS\CmsAddress::class); $cm->initializeReflection(new RuntimeReflectionService()); - $cm->mapManyToMany(array( + $cm->mapManyToMany( + [ 'fieldName' => 'user', 'targetEntity' => 'CmsUser', 'inversedBy' => 'users', - 'joinTable' => array('name' => 'user_CmsUser', - 'joinColumns' => array(array('referencedColumnName' => 'id')), - 'inverseJoinColumns' => array(array('referencedColumnName' => 'id'))))); + 'joinTable' => [ + 'name' => 'user_CmsUser', + 'joinColumns' => [['referencedColumnName' => 'id']], + 'inverseJoinColumns' => [['referencedColumnName' => 'id']] + ] + ] + ); $this->assertEquals('cmsaddress_id', $cm->associationMappings['user']['joinTable']['joinColumns'][0]['name']); $this->assertEquals('cmsuser_id', $cm->associationMappings['user']['joinTable']['inverseJoinColumns'][0]['name']); } @@ -334,22 +369,26 @@ public function testDefaultJoinColumnName() public function testUnderscoreNamingStrategyDefaults() { $namingStrategy = new UnderscoreNamingStrategy(CASE_UPPER); - $oneToOneMetadata = new ClassMetadata('Doctrine\Tests\Models\CMS\CmsAddress', $namingStrategy); - $manyToManyMetadata = new ClassMetadata('Doctrine\Tests\Models\CMS\CmsAddress', $namingStrategy); + $oneToOneMetadata = new ClassMetadata(CMS\CmsAddress::class, $namingStrategy); + $manyToManyMetadata = new ClassMetadata(CMS\CmsAddress::class, $namingStrategy); - $oneToOneMetadata->mapOneToOne(array( + $oneToOneMetadata->mapOneToOne( + [ 'fieldName' => 'user', 'targetEntity' => 'CmsUser' - )); + ] + ); - $manyToManyMetadata->mapManyToMany(array( + $manyToManyMetadata->mapManyToMany( + [ 'fieldName' => 'user', 'targetEntity' => 'CmsUser' - )); + ] + ); - $this->assertEquals(array('USER_ID'=>'ID'), $oneToOneMetadata->associationMappings['user']['sourceToTargetKeyColumns']); - $this->assertEquals(array('USER_ID'=>'USER_ID'), $oneToOneMetadata->associationMappings['user']['joinColumnFieldNames']); - $this->assertEquals(array('ID'=>'USER_ID'), $oneToOneMetadata->associationMappings['user']['targetToSourceKeyColumns']); + $this->assertEquals(['USER_ID'=>'ID'], $oneToOneMetadata->associationMappings['user']['sourceToTargetKeyColumns']); + $this->assertEquals(['USER_ID'=>'USER_ID'], $oneToOneMetadata->associationMappings['user']['joinColumnFieldNames']); + $this->assertEquals(['ID'=>'USER_ID'], $oneToOneMetadata->associationMappings['user']['targetToSourceKeyColumns']); $this->assertEquals('USER_ID', $oneToOneMetadata->associationMappings['user']['joinColumns'][0]['name']); $this->assertEquals('ID', $oneToOneMetadata->associationMappings['user']['joinColumns'][0]['referencedColumnName']); @@ -357,9 +396,9 @@ public function testUnderscoreNamingStrategyDefaults() $this->assertEquals('CMS_ADDRESS_CMS_USER', $manyToManyMetadata->associationMappings['user']['joinTable']['name']); - $this->assertEquals(array('CMS_ADDRESS_ID','CMS_USER_ID'), $manyToManyMetadata->associationMappings['user']['joinTableColumns']); - $this->assertEquals(array('CMS_ADDRESS_ID'=>'ID'), $manyToManyMetadata->associationMappings['user']['relationToSourceKeyColumns']); - $this->assertEquals(array('CMS_USER_ID'=>'ID'), $manyToManyMetadata->associationMappings['user']['relationToTargetKeyColumns']); + $this->assertEquals(['CMS_ADDRESS_ID','CMS_USER_ID'], $manyToManyMetadata->associationMappings['user']['joinTableColumns']); + $this->assertEquals(['CMS_ADDRESS_ID'=>'ID'], $manyToManyMetadata->associationMappings['user']['relationToSourceKeyColumns']); + $this->assertEquals(['CMS_USER_ID'=>'ID'], $manyToManyMetadata->associationMappings['user']['relationToTargetKeyColumns']); $this->assertEquals('CMS_ADDRESS_ID', $manyToManyMetadata->associationMappings['user']['joinTable']['joinColumns'][0]['name']); $this->assertEquals('CMS_USER_ID', $manyToManyMetadata->associationMappings['user']['joinTable']['inverseJoinColumns'][0]['name']); @@ -369,7 +408,7 @@ public function testUnderscoreNamingStrategyDefaults() $cm = new ClassMetadata('DoctrineGlobal_Article', $namingStrategy); - $cm->mapManyToMany(array('fieldName' => 'author', 'targetEntity' => 'Doctrine\Tests\Models\CMS\CmsUser')); + $cm->mapManyToMany(['fieldName' => 'author', 'targetEntity' => CMS\CmsUser::class]); $this->assertEquals('DOCTRINE_GLOBAL_ARTICLE_CMS_USER', $cm->associationMappings['author']['joinTable']['name']); } @@ -378,13 +417,13 @@ public function testUnderscoreNamingStrategyDefaults() */ public function testSetMultipleIdentifierSetsComposite() { - $cm = new ClassMetadata('Doctrine\Tests\Models\CMS\CmsUser'); + $cm = new ClassMetadata(CMS\CmsUser::class); $cm->initializeReflection(new RuntimeReflectionService()); - $cm->mapField(array('fieldName' => 'name')); - $cm->mapField(array('fieldName' => 'username')); + $cm->mapField(['fieldName' => 'name']); + $cm->mapField(['fieldName' => 'username']); - $cm->setIdentifier(array('name', 'username')); + $cm->setIdentifier(['name', 'username']); $this->assertTrue($cm->isIdentifierComposite); } @@ -393,11 +432,11 @@ public function testSetMultipleIdentifierSetsComposite() */ public function testMappingNotFound() { - $cm = new ClassMetadata('Doctrine\Tests\Models\CMS\CmsUser'); + $cm = new ClassMetadata(CMS\CmsUser::class); $cm->initializeReflection(new RuntimeReflectionService()); $this->expectException(MappingException::class); - $this->expectExceptionMessage("No mapping found for field 'foo' on class 'Doctrine\Tests\Models\CMS\CmsUser'."); + $this->expectExceptionMessage("No mapping found for field 'foo' on class '" . CMS\CmsUser::class . "'."); $cm->getFieldMapping('foo'); } @@ -410,7 +449,7 @@ public function testJoinTableMappingDefaults() $cm = new ClassMetadata('DoctrineGlobal_Article'); $cm->initializeReflection(new RuntimeReflectionService()); - $cm->mapManyToMany(array('fieldName' => 'author', 'targetEntity' => 'Doctrine\Tests\Models\CMS\CmsUser')); + $cm->mapManyToMany(['fieldName' => 'author', 'targetEntity' => CMS\CmsUser::class]); $this->assertEquals('doctrineglobal_article_cmsuser', $cm->associationMappings['author']['joinTable']['name']); } @@ -420,18 +459,20 @@ public function testJoinTableMappingDefaults() */ public function testMapIdentifierAssociation() { - $cm = new ClassMetadata('Doctrine\Tests\Models\DDC117\DDC117ArticleDetails'); + $cm = new ClassMetadata(DDC117ArticleDetails::class); $cm->initializeReflection(new RuntimeReflectionService()); - $cm->mapOneToOne(array( + $cm->mapOneToOne( + [ 'fieldName' => 'article', 'id' => true, - 'targetEntity' => 'Doctrine\Tests\Models\DDC117\DDC117Article', - 'joinColumns' => array(), - )); + 'targetEntity' => DDC117Article::class, + 'joinColumns' => [], + ] + ); $this->assertTrue($cm->containsForeignIdentifier, "Identifier Association should set 'containsForeignIdentifier' boolean flag."); - $this->assertEquals(array("article"), $cm->identifier); + $this->assertEquals(["article"], $cm->identifier); } /** @@ -439,19 +480,21 @@ public function testMapIdentifierAssociation() */ public function testOrphanRemovalIdentifierAssociation() { - $cm = new ClassMetadata('Doctrine\Tests\Models\DDC117\DDC117ArticleDetails'); + $cm = new ClassMetadata(DDC117ArticleDetails::class); $cm->initializeReflection(new RuntimeReflectionService()); $this->expectException(MappingException::class); $this->expectExceptionMessage('The orphan removal option is not allowed on an association that'); - $cm->mapOneToOne(array( + $cm->mapOneToOne( + [ 'fieldName' => 'article', 'id' => true, - 'targetEntity' => 'Doctrine\Tests\Models\DDC117\DDC117Article', + 'targetEntity' => DDC117Article::class, 'orphanRemoval' => true, - 'joinColumns' => array(), - )); + 'joinColumns' => [], + ] + ); } /** @@ -459,19 +502,21 @@ public function testOrphanRemovalIdentifierAssociation() */ public function testInverseIdentifierAssociation() { - $cm = new ClassMetadata('Doctrine\Tests\Models\DDC117\DDC117ArticleDetails'); + $cm = new ClassMetadata(DDC117ArticleDetails::class); $cm->initializeReflection(new RuntimeReflectionService()); $this->expectException(MappingException::class); $this->expectExceptionMessage('An inverse association is not allowed to be identifier in'); - $cm->mapOneToOne(array( + $cm->mapOneToOne( + [ 'fieldName' => 'article', 'id' => true, 'mappedBy' => 'details', // INVERSE! - 'targetEntity' => 'Doctrine\Tests\Models\DDC117\DDC117Article', - 'joinColumns' => array(), - )); + 'targetEntity' => DDC117Article::class, + 'joinColumns' => [], + ] + ); } /** @@ -479,18 +524,20 @@ public function testInverseIdentifierAssociation() */ public function testIdentifierAssociationManyToMany() { - $cm = new ClassMetadata('Doctrine\Tests\Models\DDC117\DDC117ArticleDetails'); + $cm = new ClassMetadata(DDC117ArticleDetails::class); $cm->initializeReflection(new RuntimeReflectionService()); $this->expectException(MappingException::class); $this->expectExceptionMessage('Many-to-many or one-to-many associations are not allowed to be identifier in'); - $cm->mapManyToMany(array( + $cm->mapManyToMany( + [ 'fieldName' => 'article', 'id' => true, - 'targetEntity' => 'Doctrine\Tests\Models\DDC117\DDC117Article', - 'joinColumns' => array(), - )); + 'targetEntity' => DDC117Article::class, + 'joinColumns' => [], + ] + ); } /** @@ -499,26 +546,28 @@ public function testIdentifierAssociationManyToMany() public function testEmptyFieldNameThrowsException() { $this->expectException(MappingException::class); - $this->expectExceptionMessage("The field or association mapping misses the 'fieldName' attribute in entity 'Doctrine\Tests\Models\CMS\CmsUser'."); + $this->expectExceptionMessage("The field or association mapping misses the 'fieldName' attribute in entity '" . CMS\CmsUser::class . "'."); - $cm = new ClassMetadata('Doctrine\Tests\Models\CMS\CmsUser'); + $cm = new ClassMetadata(CMS\CmsUser::class); $cm->initializeReflection(new RuntimeReflectionService()); - $cm->mapField(array('fieldName' => '')); + $cm->mapField(['fieldName' => '']); } public function testRetrievalOfNamedQueries() { - $cm = new ClassMetadata('Doctrine\Tests\Models\CMS\CmsUser'); + $cm = new ClassMetadata(CMS\CmsUser::class); $cm->initializeReflection(new RuntimeReflectionService()); $this->assertEquals(0, count($cm->getNamedQueries())); - $cm->addNamedQuery(array( + $cm->addNamedQuery( + [ 'name' => 'userById', 'query' => 'SELECT u FROM __CLASS__ u WHERE u.id = ?1' - )); + ] + ); $this->assertEquals(1, count($cm->getNamedQueries())); } @@ -528,34 +577,38 @@ public function testRetrievalOfNamedQueries() */ public function testRetrievalOfResultSetMappings() { - $cm = new ClassMetadata('Doctrine\Tests\Models\CMS\CmsUser'); + $cm = new ClassMetadata(CMS\CmsUser::class); $cm->initializeReflection(new RuntimeReflectionService()); $this->assertEquals(0, count($cm->getSqlResultSetMappings())); - $cm->addSqlResultSetMapping(array( + $cm->addSqlResultSetMapping( + [ 'name' => 'find-all', - 'entities' => array( - array( - 'entityClass' => 'Doctrine\Tests\Models\CMS\CmsUser', - ), - ), - )); + 'entities' => [ + [ + 'entityClass' => CMS\CmsUser::class, + ], + ], + ] + ); $this->assertEquals(1, count($cm->getSqlResultSetMappings())); } public function testExistanceOfNamedQuery() { - $cm = new ClassMetadata('Doctrine\Tests\Models\CMS\CmsUser'); + $cm = new ClassMetadata(CMS\CmsUser::class); $cm->initializeReflection(new RuntimeReflectionService()); - $cm->addNamedQuery(array( + $cm->addNamedQuery( + [ 'name' => 'all', 'query' => 'SELECT u FROM __CLASS__ u' - )); + ] + ); $this->assertTrue($cm->hasNamedQuery('all')); $this->assertFalse($cm->hasNamedQuery('userById')); @@ -566,32 +619,36 @@ public function testExistanceOfNamedQuery() */ public function testRetrieveOfNamedNativeQuery() { - $cm = new ClassMetadata('Doctrine\Tests\Models\CMS\CmsUser'); + $cm = new ClassMetadata(CMS\CmsUser::class); $cm->initializeReflection(new RuntimeReflectionService()); - $cm->addNamedNativeQuery(array( + $cm->addNamedNativeQuery( + [ 'name' => 'find-all', 'query' => 'SELECT * FROM cms_users', 'resultSetMapping' => 'result-mapping-name', - 'resultClass' => 'Doctrine\Tests\Models\CMS\CmsUser', - )); + 'resultClass' => CMS\CmsUser::class, + ] + ); - $cm->addNamedNativeQuery(array( + $cm->addNamedNativeQuery( + [ 'name' => 'find-by-id', 'query' => 'SELECT * FROM cms_users WHERE id = ?', 'resultClass' => '__CLASS__', 'resultSetMapping' => 'result-mapping-name', - )); + ] + ); $mapping = $cm->getNamedNativeQuery('find-all'); $this->assertEquals('SELECT * FROM cms_users', $mapping['query']); $this->assertEquals('result-mapping-name', $mapping['resultSetMapping']); - $this->assertEquals('Doctrine\Tests\Models\CMS\CmsUser', $mapping['resultClass']); + $this->assertEquals(CMS\CmsUser::class, $mapping['resultClass']); $mapping = $cm->getNamedNativeQuery('find-by-id'); $this->assertEquals('SELECT * FROM cms_users WHERE id = ?', $mapping['query']); $this->assertEquals('result-mapping-name', $mapping['resultSetMapping']); - $this->assertEquals('Doctrine\Tests\Models\CMS\CmsUser', $mapping['resultClass']); + $this->assertEquals(CMS\CmsUser::class, $mapping['resultClass']); } /** @@ -599,55 +656,57 @@ public function testRetrieveOfNamedNativeQuery() */ public function testRetrieveOfSqlResultSetMapping() { - $cm = new ClassMetadata('Doctrine\Tests\Models\CMS\CmsUser'); + $cm = new ClassMetadata(CMS\CmsUser::class); $cm->initializeReflection(new RuntimeReflectionService()); - $cm->addSqlResultSetMapping(array( + $cm->addSqlResultSetMapping( + [ 'name' => 'find-all', - 'entities' => array( - array( + 'entities' => [ + [ 'entityClass' => '__CLASS__', - 'fields' => array( - array( + 'fields' => [ + [ 'name' => 'id', 'column'=> 'id' - ), - array( + ], + [ 'name' => 'name', 'column'=> 'name' - ) - ) - ), - array( - 'entityClass' => 'Doctrine\Tests\Models\CMS\CmsEmail', - 'fields' => array( - array( + ] + ] + ], + [ + 'entityClass' => CMS\CmsEmail::class, + 'fields' => [ + [ 'name' => 'id', 'column'=> 'id' - ), - array( + ], + [ 'name' => 'email', 'column'=> 'email' - ) - ) - ) - ), - 'columns' => array( - array( + ] + ] + ] + ], + 'columns' => [ + [ 'name' => 'scalarColumn' - ) - ) - )); + ] + ] + ] + ); $mapping = $cm->getSqlResultSetMapping('find-all'); - $this->assertEquals('Doctrine\Tests\Models\CMS\CmsUser', $mapping['entities'][0]['entityClass']); - $this->assertEquals(array('name'=>'id','column'=>'id'), $mapping['entities'][0]['fields'][0]); - $this->assertEquals(array('name'=>'name','column'=>'name'), $mapping['entities'][0]['fields'][1]); + $this->assertEquals(CMS\CmsUser::class, $mapping['entities'][0]['entityClass']); + $this->assertEquals(['name'=>'id','column'=>'id'], $mapping['entities'][0]['fields'][0]); + $this->assertEquals(['name'=>'name','column'=>'name'], $mapping['entities'][0]['fields'][1]); - $this->assertEquals('Doctrine\Tests\Models\CMS\CmsEmail', $mapping['entities'][1]['entityClass']); - $this->assertEquals(array('name'=>'id','column'=>'id'), $mapping['entities'][1]['fields'][0]); - $this->assertEquals(array('name'=>'email','column'=>'email'), $mapping['entities'][1]['fields'][1]); + $this->assertEquals(CMS\CmsEmail::class, $mapping['entities'][1]['entityClass']); + $this->assertEquals(['name'=>'id','column'=>'id'], $mapping['entities'][1]['fields'][0]); + $this->assertEquals(['name'=>'email','column'=>'email'], $mapping['entities'][1]['fields'][1]); $this->assertEquals('scalarColumn', $mapping['columns'][0]['name']); } @@ -657,17 +716,19 @@ public function testRetrieveOfSqlResultSetMapping() */ public function testExistanceOfSqlResultSetMapping() { - $cm = new ClassMetadata('Doctrine\Tests\Models\CMS\CmsUser'); + $cm = new ClassMetadata(CMS\CmsUser::class); $cm->initializeReflection(new RuntimeReflectionService()); - $cm->addSqlResultSetMapping(array( + $cm->addSqlResultSetMapping( + [ 'name' => 'find-all', - 'entities' => array( - array( - 'entityClass' => 'Doctrine\Tests\Models\CMS\CmsUser', - ), - ), - )); + 'entities' => [ + [ + 'entityClass' => CMS\CmsUser::class, + ], + ], + ] + ); $this->assertTrue($cm->hasSqlResultSetMapping('find-all')); $this->assertFalse($cm->hasSqlResultSetMapping('find-by-id')); @@ -678,16 +739,18 @@ public function testExistanceOfSqlResultSetMapping() */ public function testExistanceOfNamedNativeQuery() { - $cm = new ClassMetadata('Doctrine\Tests\Models\CMS\CmsUser'); + $cm = new ClassMetadata(CMS\CmsUser::class); $cm->initializeReflection(new RuntimeReflectionService()); - $cm->addNamedNativeQuery(array( + $cm->addNamedNativeQuery( + [ 'name' => 'find-all', 'query' => 'SELECT * FROM cms_users', - 'resultClass' => 'Doctrine\Tests\Models\CMS\CmsUser', + 'resultClass' => CMS\CmsUser::class, 'resultSetMapping' => 'result-mapping-name' - )); + ] + ); $this->assertTrue($cm->hasNamedNativeQuery('find-all')); $this->assertFalse($cm->hasNamedNativeQuery('find-by-id')); @@ -695,14 +758,16 @@ public function testExistanceOfNamedNativeQuery() public function testRetrieveOfNamedQuery() { - $cm = new ClassMetadata('Doctrine\Tests\Models\CMS\CmsUser'); + $cm = new ClassMetadata(CMS\CmsUser::class); $cm->initializeReflection(new RuntimeReflectionService()); - $cm->addNamedQuery(array( + $cm->addNamedQuery( + [ 'name' => 'userById', 'query' => 'SELECT u FROM __CLASS__ u WHERE u.id = ?1' - )); + ] + ); $this->assertEquals('SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.id = ?1', $cm->getNamedQuery('userById')); } @@ -712,17 +777,19 @@ public function testRetrieveOfNamedQuery() */ public function testRetrievalOfNamedNativeQueries() { - $cm = new ClassMetadata('Doctrine\Tests\Models\CMS\CmsUser'); + $cm = new ClassMetadata(CMS\CmsUser::class); $cm->initializeReflection(new RuntimeReflectionService()); $this->assertEquals(0, count($cm->getNamedNativeQueries())); - $cm->addNamedNativeQuery(array( + $cm->addNamedNativeQuery( + [ 'name' => 'find-all', 'query' => 'SELECT * FROM cms_users', - 'resultClass' => 'Doctrine\Tests\Models\CMS\CmsUser', + 'resultClass' => CMS\CmsUser::class, 'resultSetMapping' => 'result-mapping-name' - )); + ] + ); $this->assertEquals(1, count($cm->getNamedNativeQueries())); } @@ -732,7 +799,7 @@ public function testRetrievalOfNamedNativeQueries() */ public function testSerializeEntityListeners() { - $metadata = new ClassMetadata('Doctrine\Tests\Models\Company\CompanyContract'); + $metadata = new ClassMetadata(CompanyContract::class); $metadata->initializeReflection(new RuntimeReflectionService()); $metadata->addEntityListener(Events::prePersist, 'CompanyContractListener', 'prePersistHandler'); @@ -750,18 +817,22 @@ public function testSerializeEntityListeners() */ public function testNamingCollisionNamedQueryShouldThrowException() { - $cm = new ClassMetadata('Doctrine\Tests\Models\CMS\CmsUser'); + $cm = new ClassMetadata(CMS\CmsUser::class); $cm->initializeReflection(new RuntimeReflectionService()); - $cm->addNamedQuery(array( + $cm->addNamedQuery( + [ 'name' => 'userById', 'query' => 'SELECT u FROM __CLASS__ u WHERE u.id = ?1' - )); + ] + ); - $cm->addNamedQuery(array( + $cm->addNamedQuery( + [ 'name' => 'userById', 'query' => 'SELECT u FROM __CLASS__ u WHERE u.id = ?1' - )); + ] + ); } /** @@ -772,22 +843,26 @@ public function testNamingCollisionNamedQueryShouldThrowException() */ public function testNamingCollisionNamedNativeQueryShouldThrowException() { - $cm = new ClassMetadata('Doctrine\Tests\Models\CMS\CmsUser'); + $cm = new ClassMetadata(CMS\CmsUser::class); $cm->initializeReflection(new RuntimeReflectionService()); - $cm->addNamedNativeQuery(array( + $cm->addNamedNativeQuery( + [ 'name' => 'find-all', 'query' => 'SELECT * FROM cms_users', - 'resultClass' => 'Doctrine\Tests\Models\CMS\CmsUser', + 'resultClass' => CMS\CmsUser::class, 'resultSetMapping' => 'result-mapping-name' - )); + ] + ); - $cm->addNamedNativeQuery(array( + $cm->addNamedNativeQuery( + [ 'name' => 'find-all', 'query' => 'SELECT * FROM cms_users', - 'resultClass' => 'Doctrine\Tests\Models\CMS\CmsUser', + 'resultClass' => CMS\CmsUser::class, 'resultSetMapping' => 'result-mapping-name' - )); + ] + ); } /** @@ -798,26 +873,30 @@ public function testNamingCollisionNamedNativeQueryShouldThrowException() */ public function testNamingCollisionSqlResultSetMappingShouldThrowException() { - $cm = new ClassMetadata('Doctrine\Tests\Models\CMS\CmsUser'); + $cm = new ClassMetadata(CMS\CmsUser::class); $cm->initializeReflection(new RuntimeReflectionService()); - $cm->addSqlResultSetMapping(array( + $cm->addSqlResultSetMapping( + [ 'name' => 'find-all', - 'entities' => array( - array( - 'entityClass' => 'Doctrine\Tests\Models\CMS\CmsUser', - ), - ), - )); - - $cm->addSqlResultSetMapping(array( + 'entities' => [ + [ + 'entityClass' => CMS\CmsUser::class, + ], + ], + ] + ); + + $cm->addSqlResultSetMapping( + [ 'name' => 'find-all', - 'entities' => array( - array( - 'entityClass' => 'Doctrine\Tests\Models\CMS\CmsUser', - ), - ), - )); + 'entities' => [ + [ + 'entityClass' => CMS\CmsUser::class, + ], + ], + ] + ); } /** @@ -825,11 +904,11 @@ public function testNamingCollisionSqlResultSetMappingShouldThrowException() */ public function testClassCaseSensitivity() { - $user = new CmsUser(); - $cm = new ClassMetadata('DOCTRINE\TESTS\MODELS\CMS\CMSUSER'); + $user = new CMS\CmsUser(); + $cm = new ClassMetadata(strtoupper(CMS\CmsUser::class)); $cm->initializeReflection(new RuntimeReflectionService()); - $this->assertEquals('Doctrine\Tests\Models\CMS\CmsUser', $cm->name); + $this->assertEquals(CMS\CmsUser::class, $cm->name); } /** @@ -837,12 +916,12 @@ public function testClassCaseSensitivity() */ public function testLifecycleCallbackNotFound() { - $cm = new ClassMetadata('Doctrine\Tests\Models\CMS\CmsUser'); + $cm = new ClassMetadata(CMS\CmsUser::class); $cm->initializeReflection(new RuntimeReflectionService()); $cm->addLifecycleCallback('notfound', 'postLoad'); $this->expectException(MappingException::class); - $this->expectExceptionMessage("Entity 'Doctrine\Tests\Models\CMS\CmsUser' has no method 'notfound' to be registered as lifecycle callback."); + $this->expectExceptionMessage("Entity '" . CMS\CmsUser::class . "' has no method 'notfound' to be registered as lifecycle callback."); $cm->validateLifecycleCallbacks(new RuntimeReflectionService()); } @@ -852,12 +931,12 @@ public function testLifecycleCallbackNotFound() */ public function testTargetEntityNotFound() { - $cm = new ClassMetadata('Doctrine\Tests\Models\CMS\CmsUser'); + $cm = new ClassMetadata(CMS\CmsUser::class); $cm->initializeReflection(new RuntimeReflectionService()); - $cm->mapManyToOne(array('fieldName' => 'address', 'targetEntity' => 'UnknownClass')); + $cm->mapManyToOne(['fieldName' => 'address', 'targetEntity' => 'UnknownClass']); $this->expectException(MappingException::class); - $this->expectExceptionMessage("The target-entity Doctrine\Tests\Models\CMS\UnknownClass cannot be found in 'Doctrine\Tests\Models\CMS\CmsUser#address'."); + $this->expectExceptionMessage("The target-entity Doctrine\\Tests\\Models\\CMS\\UnknownClass cannot be found in '" . CMS\CmsUser::class . "#address'."); $cm->validateAssociations(); } @@ -870,11 +949,13 @@ public function testTargetEntityNotFound() */ public function testNameIsMandatoryForNamedQueryMappingException() { - $cm = new ClassMetadata('Doctrine\Tests\Models\CMS\CmsUser'); + $cm = new ClassMetadata(CMS\CmsUser::class); $cm->initializeReflection(new RuntimeReflectionService()); - $cm->addNamedQuery(array( + $cm->addNamedQuery( + [ 'query' => 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u', - )); + ] + ); } /** @@ -885,13 +966,15 @@ public function testNameIsMandatoryForNamedQueryMappingException() */ public function testNameIsMandatoryForNameNativeQueryMappingException() { - $cm = new ClassMetadata('Doctrine\Tests\Models\CMS\CmsUser'); + $cm = new ClassMetadata(CMS\CmsUser::class); $cm->initializeReflection(new RuntimeReflectionService()); - $cm->addNamedQuery(array( + $cm->addNamedQuery( + [ 'query' => 'SELECT * FROM cms_users', - 'resultClass' => 'Doctrine\Tests\Models\CMS\CmsUser', + 'resultClass' => CMS\CmsUser::class, 'resultSetMapping' => 'result-mapping-name' - )); + ] + ); } /** @@ -902,16 +985,18 @@ public function testNameIsMandatoryForNameNativeQueryMappingException() */ public function testNameIsMandatoryForEntityNameSqlResultSetMappingException() { - $cm = new ClassMetadata('Doctrine\Tests\Models\CMS\CmsUser'); + $cm = new ClassMetadata(CMS\CmsUser::class); $cm->initializeReflection(new RuntimeReflectionService()); - $cm->addSqlResultSetMapping(array( + $cm->addSqlResultSetMapping( + [ 'name' => 'find-all', - 'entities' => array( - array( - 'fields' => array() - ) - ), - )); + 'entities' => [ + [ + 'fields' => [] + ] + ], + ] + ); } /** @@ -920,9 +1005,9 @@ public function testNameIsMandatoryForEntityNameSqlResultSetMappingException() */ public function testNameIsMandatoryForDiscriminatorColumnsMappingException() { - $cm = new ClassMetadata('Doctrine\Tests\Models\CMS\CmsUser'); + $cm = new ClassMetadata(CMS\CmsUser::class); $cm->initializeReflection(new RuntimeReflectionService()); - $cm->setDiscriminatorColumn(array()); + $cm->setDiscriminatorColumn([]); } /** @@ -933,23 +1018,27 @@ public function testNameIsMandatoryForDiscriminatorColumnsMappingException() public function testFullyQualifiedClassNameShouldBeGivenToNamingStrategy() { $namingStrategy = new MyNamespacedNamingStrategy(); - $addressMetadata = new ClassMetadata('Doctrine\Tests\Models\CMS\CmsAddress', $namingStrategy); - $articleMetadata = new ClassMetadata('DoctrineGlobal_Article', $namingStrategy); - $routingMetadata = new ClassMetadata('Doctrine\Tests\Models\Routing\RoutingLeg',$namingStrategy); + $addressMetadata = new ClassMetadata(CMS\CmsAddress::class, $namingStrategy); + $articleMetadata = new ClassMetadata(DoctrineGlobal_Article::class, $namingStrategy); + $routingMetadata = new ClassMetadata(RoutingLeg::class, $namingStrategy); $addressMetadata->initializeReflection(new RuntimeReflectionService()); $articleMetadata->initializeReflection(new RuntimeReflectionService()); $routingMetadata->initializeReflection(new RuntimeReflectionService()); - $addressMetadata->mapManyToMany(array( + $addressMetadata->mapManyToMany( + [ 'fieldName' => 'user', 'targetEntity' => 'CmsUser' - )); + ] + ); - $articleMetadata->mapManyToMany(array( + $articleMetadata->mapManyToMany( + [ 'fieldName' => 'author', - 'targetEntity' => 'Doctrine\Tests\Models\CMS\CmsUser' - )); + 'targetEntity' => CMS\CmsUser::class + ] + ); $this->assertEquals('routing_routingleg', $routingMetadata->table['name']); $this->assertEquals('cms_cmsaddress_cms_cmsuser', $addressMetadata->associationMappings['user']['joinTable']['name']); @@ -963,17 +1052,18 @@ public function testFullyQualifiedClassNameShouldBeGivenToNamingStrategy() public function testFullyQualifiedClassNameShouldBeGivenToNamingStrategyPropertyToColumnName() { $namingStrategy = new MyPrefixNamingStrategy(); - $metadata = new ClassMetadata('Doctrine\Tests\Models\CMS\CmsAddress', $namingStrategy); + $metadata = new ClassMetadata(CMS\CmsAddress::class, $namingStrategy); $metadata->initializeReflection(new RuntimeReflectionService()); - $metadata->mapField(array('fieldName'=>'country')); - $metadata->mapField(array('fieldName'=>'city')); + $metadata->mapField(['fieldName'=>'country']); + $metadata->mapField(['fieldName'=>'city']); - $this->assertEquals($metadata->fieldNames, array( + $this->assertEquals($metadata->fieldNames, [ 'cmsaddress_country' => 'country', 'cmsaddress_city' => 'city' - )); + ] + ); } /** @@ -981,13 +1071,13 @@ public function testFullyQualifiedClassNameShouldBeGivenToNamingStrategyProperty */ public function testInvalidCascade() { - $cm = new ClassMetadata('Doctrine\Tests\Models\CMS\CmsUser'); + $cm = new ClassMetadata(CMS\CmsUser::class); $cm->initializeReflection(new RuntimeReflectionService()); $this->expectException(MappingException::class); - $this->expectExceptionMessage("You have specified invalid cascade options for Doctrine\Tests\Models\CMS\CmsUser::\$address: 'invalid'; available options: 'remove', 'persist', 'refresh', 'merge', and 'detach'"); + $this->expectExceptionMessage("You have specified invalid cascade options for " . CMS\CmsUser::class . "::\$address: 'invalid'; available options: 'remove', 'persist', 'refresh', 'merge', and 'detach'"); - $cm->mapManyToOne(array('fieldName' => 'address', 'targetEntity' => 'UnknownClass', 'cascade' => array('invalid'))); + $cm->mapManyToOne(['fieldName' => 'address', 'targetEntity' => 'UnknownClass', 'cascade' => ['invalid']]); } /** @@ -997,11 +1087,11 @@ public function testInvalidCascade() */ public function testInvalidPropertyAssociationOverrideNameException() { - $cm = new ClassMetadata('Doctrine\Tests\Models\DDC964\DDC964Admin'); + $cm = new ClassMetadata(DDC964Admin::class); $cm->initializeReflection(new RuntimeReflectionService()); - $cm->mapManyToOne(array('fieldName' => 'address', 'targetEntity' => 'DDC964Address')); + $cm->mapManyToOne(['fieldName' => 'address', 'targetEntity' => 'DDC964Address']); - $cm->setAssociationOverride('invalidPropertyName', array()); + $cm->setAssociationOverride('invalidPropertyName', []); } /** @@ -1011,11 +1101,11 @@ public function testInvalidPropertyAssociationOverrideNameException() */ public function testInvalidPropertyAttributeOverrideNameException() { - $cm = new ClassMetadata('Doctrine\Tests\Models\DDC964\DDC964Guest'); + $cm = new ClassMetadata(DDC964Guest::class); $cm->initializeReflection(new RuntimeReflectionService()); - $cm->mapField(array('fieldName' => 'name')); + $cm->mapField(['fieldName' => 'name']); - $cm->setAttributeOverride('invalidPropertyName', array()); + $cm->setAttributeOverride('invalidPropertyName', []); } /** @@ -1025,11 +1115,11 @@ public function testInvalidPropertyAttributeOverrideNameException() */ public function testInvalidOverrideAttributeFieldTypeException() { - $cm = new ClassMetadata('Doctrine\Tests\Models\DDC964\DDC964Guest'); + $cm = new ClassMetadata(DDC964Guest::class); $cm->initializeReflection(new RuntimeReflectionService()); - $cm->mapField(array('fieldName' => 'name', 'type'=>'string')); + $cm->mapField(['fieldName' => 'name', 'type'=>'string']); - $cm->setAttributeOverride('name', array('type'=>'date')); + $cm->setAttributeOverride('name', ['type'=>'date']); } /** @@ -1040,7 +1130,7 @@ public function testInvalidOverrideAttributeFieldTypeException() */ public function testInvalidEntityListenerClassException() { - $cm = new ClassMetadata('Doctrine\Tests\Models\CMS\CmsUser'); + $cm = new ClassMetadata(CMS\CmsUser::class); $cm->initializeReflection(new RuntimeReflectionService()); $cm->addEntityListener(Events::postLoad, '\InvalidClassName', 'postLoadHandler'); @@ -1054,7 +1144,7 @@ public function testInvalidEntityListenerClassException() */ public function testInvalidEntityListenerMethodException() { - $cm = new ClassMetadata('Doctrine\Tests\Models\CMS\CmsUser'); + $cm = new ClassMetadata(CMS\CmsUser::class); $cm->initializeReflection(new RuntimeReflectionService()); $cm->addEntityListener(Events::postLoad, '\Doctrine\Tests\Models\Company\CompanyContractListener', 'invalidMethod'); @@ -1062,26 +1152,26 @@ public function testInvalidEntityListenerMethodException() public function testManyToManySelfReferencingNamingStrategyDefaults() { - $cm = new ClassMetadata('Doctrine\Tests\Models\CustomType\CustomTypeParent'); + $cm = new ClassMetadata(CustomTypeParent::class); $cm->initializeReflection(new RuntimeReflectionService()); $cm->mapManyToMany( - array( + [ 'fieldName' => 'friendsWithMe', 'targetEntity' => 'CustomTypeParent' - ) + ] ); $this->assertEquals( - array( + [ 'name' => 'customtypeparent_customtypeparent', - 'joinColumns' => array(array('name' => 'customtypeparent_source', 'referencedColumnName' => 'id', 'onDelete' => 'CASCADE')), - 'inverseJoinColumns' => array(array('name' => 'customtypeparent_target', 'referencedColumnName' => 'id', 'onDelete' => 'CASCADE')), - ), + 'joinColumns' => [['name' => 'customtypeparent_source', 'referencedColumnName' => 'id', 'onDelete' => 'CASCADE']], + 'inverseJoinColumns' => [['name' => 'customtypeparent_target', 'referencedColumnName' => 'id', 'onDelete' => 'CASCADE']], + ], $cm->associationMappings['friendsWithMe']['joinTable'] ); - $this->assertEquals(array('customtypeparent_source', 'customtypeparent_target'), $cm->associationMappings['friendsWithMe']['joinTableColumns']); - $this->assertEquals(array('customtypeparent_source' => 'id'), $cm->associationMappings['friendsWithMe']['relationToSourceKeyColumns']); - $this->assertEquals(array('customtypeparent_target' => 'id'), $cm->associationMappings['friendsWithMe']['relationToTargetKeyColumns']); + $this->assertEquals(['customtypeparent_source', 'customtypeparent_target'], $cm->associationMappings['friendsWithMe']['joinTableColumns']); + $this->assertEquals(['customtypeparent_source' => 'id'], $cm->associationMappings['friendsWithMe']['relationToSourceKeyColumns']); + $this->assertEquals(['customtypeparent_target' => 'id'], $cm->associationMappings['friendsWithMe']['relationToTargetKeyColumns']); } /** @@ -1089,24 +1179,28 @@ public function testManyToManySelfReferencingNamingStrategyDefaults() */ public function testSetSequenceGeneratorThrowsExceptionWhenSequenceNameIsMissing() { - $cm = new ClassMetadata('Doctrine\Tests\Models\CMS\CmsUser'); + $cm = new ClassMetadata(CMS\CmsUser::class); $cm->initializeReflection(new RuntimeReflectionService()); $this->expectException(\Doctrine\ORM\Mapping\MappingException::class); - $cm->setSequenceGeneratorDefinition(array()); + $cm->setSequenceGeneratorDefinition([]); } /** * @group DDC-2662 + * @group 6682 */ - public function testQuotedSequenceName() + public function testQuotedSequenceName() : void { - $cm = new ClassMetadata('Doctrine\Tests\Models\CMS\CmsUser'); - $cm->initializeReflection(new RuntimeReflectionService()); + $cm = new ClassMetadata(CMS\CmsUser::class); - $cm->setSequenceGeneratorDefinition(array('sequenceName' => '`foo`')); + $cm->initializeReflection(new RuntimeReflectionService()); + $cm->setSequenceGeneratorDefinition(['sequenceName' => '`foo`']); - $this->assertEquals(array('sequenceName' => 'foo', 'quoted' => true), $cm->sequenceGeneratorDefinition); + self::assertSame( + ['sequenceName' => 'foo', 'quoted' => true, 'allocationSize' => '1', 'initialValue' => '1'], + $cm->sequenceGeneratorDefinition + ); } /** @@ -1114,7 +1208,7 @@ public function testQuotedSequenceName() */ public function testIsIdentifierMappedSuperClass() { - $class = new ClassMetadata(__NAMESPACE__ . '\\DDC2700MappedSuperClass'); + $class = new ClassMetadata(DDC2700MappedSuperClass::class); $this->assertFalse($class->isIdentifier('foo')); } @@ -1124,9 +1218,9 @@ public function testIsIdentifierMappedSuperClass() */ public function testCanInstantiateInternalPhpClassSubclass() { - $classMetadata = new ClassMetadata(__NAMESPACE__ . '\\MyArrayObjectEntity'); + $classMetadata = new ClassMetadata(MyArrayObjectEntity::class); - $this->assertInstanceOf(__NAMESPACE__ . '\\MyArrayObjectEntity', $classMetadata->newInstance()); + $this->assertInstanceOf(MyArrayObjectEntity::class, $classMetadata->newInstance()); } /** @@ -1135,48 +1229,68 @@ public function testCanInstantiateInternalPhpClassSubclass() public function testCanInstantiateInternalPhpClassSubclassFromUnserializedMetadata() { /* @var $classMetadata ClassMetadata */ - $classMetadata = unserialize(serialize(new ClassMetadata(__NAMESPACE__ . '\\MyArrayObjectEntity'))); + $classMetadata = unserialize(serialize(new ClassMetadata(MyArrayObjectEntity::class))); $classMetadata->wakeupReflection(new RuntimeReflectionService()); - $this->assertInstanceOf(__NAMESPACE__ . '\\MyArrayObjectEntity', $classMetadata->newInstance()); + $this->assertInstanceOf(MyArrayObjectEntity::class, $classMetadata->newInstance()); } public function testWakeupReflectionWithEmbeddableAndStaticReflectionService() { - $classMetadata = new ClassMetadata('Doctrine\Tests\ORM\Mapping\TestEntity1'); + $classMetadata = new ClassMetadata(TestEntity1::class); - $classMetadata->mapEmbedded(array( + $classMetadata->mapEmbedded( + [ 'fieldName' => 'test', - 'class' => 'Doctrine\Tests\ORM\Mapping\TestEntity1', + 'class' => TestEntity1::class, 'columnPrefix' => false, - )); + ] + ); - $field = array( + $field = [ 'fieldName' => 'test.embeddedProperty', 'type' => 'string', - 'originalClass' => 'Doctrine\Tests\ORM\Mapping\TestEntity1', + 'originalClass' => TestEntity1::class, 'declaredField' => 'test', 'originalField' => 'embeddedProperty' - ); + ]; $classMetadata->mapField($field); $classMetadata->wakeupReflection(new StaticReflectionService()); - $this->assertEquals(array('test' => null, 'test.embeddedProperty' => null), $classMetadata->getReflectionProperties()); + $this->assertEquals(['test' => null, 'test.embeddedProperty' => null], $classMetadata->getReflectionProperties()); } public function testGetColumnNamesWithGivenFieldNames() { - $metadata = new ClassMetadata('Doctrine\Tests\Models\CMS\CmsUser'); + $metadata = new ClassMetadata(CMS\CmsUser::class); $metadata->initializeReflection(new RuntimeReflectionService()); - $metadata->mapField(array('fieldName' => 'status', 'type' => 'string', 'columnName' => 'foo')); - $metadata->mapField(array('fieldName' => 'username', 'type' => 'string', 'columnName' => 'bar')); - $metadata->mapField(array('fieldName' => 'name', 'type' => 'string', 'columnName' => 'baz')); + $metadata->mapField(['fieldName' => 'status', 'type' => 'string', 'columnName' => 'foo']); + $metadata->mapField(['fieldName' => 'username', 'type' => 'string', 'columnName' => 'bar']); + $metadata->mapField(['fieldName' => 'name', 'type' => 'string', 'columnName' => 'baz']); self::assertSame(['foo', 'baz'], $metadata->getColumnNames(['status', 'name'])); } + + /** + * @group DDC-6460 + */ + public function testInlineEmbeddable() + { + $classMetadata = new ClassMetadata(TestEntity1::class); + + $classMetadata->mapEmbedded( + [ + 'fieldName' => 'test', + 'class' => TestEntity1::class, + 'columnPrefix' => false, + ] + ); + + $this->assertTrue($classMetadata->hasField('test')); + } } /** diff --git a/tests/Doctrine/Tests/ORM/Mapping/DefaultQuoteStrategyTest.php b/tests/Doctrine/Tests/ORM/Mapping/DefaultQuoteStrategyTest.php index 9c20cb8b9dd..765518c41bb 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/DefaultQuoteStrategyTest.php +++ b/tests/Doctrine/Tests/ORM/Mapping/DefaultQuoteStrategyTest.php @@ -2,6 +2,7 @@ namespace Doctrine\Tests\ORM\Mapping; +use Doctrine\DBAL\Platforms\AbstractPlatform; use Doctrine\ORM\Mapping\DefaultQuoteStrategy; use Doctrine\Tests\Models\NonPublicSchemaJoins\User as NonPublicSchemaUser; use Doctrine\Tests\OrmTestCase; @@ -20,10 +21,10 @@ class DefaultQuoteStrategyTest extends OrmTestCase public function testGetJoinTableName() { $em = $this->_getTestEntityManager(); - $metadata = $em->getClassMetadata(NonPublicSchemaUser::CLASSNAME); - /* @var $platform \Doctrine\DBAL\Platforms\AbstractPlatform */ + $metadata = $em->getClassMetadata(NonPublicSchemaUser::class); $strategy = new DefaultQuoteStrategy(); - $platform = $this->getMockForAbstractClass('Doctrine\DBAL\Platforms\AbstractPlatform'); + /* @var $platform AbstractPlatform */ + $platform = $this->getMockForAbstractClass(AbstractPlatform::class); $this->assertSame( 'readers.author_reader', diff --git a/tests/Doctrine/Tests/ORM/Mapping/FieldBuilderTest.php b/tests/Doctrine/Tests/ORM/Mapping/FieldBuilderTest.php index 3d759aade95..0ec0798aae1 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/FieldBuilderTest.php +++ b/tests/Doctrine/Tests/ORM/Mapping/FieldBuilderTest.php @@ -1,33 +1,17 @@ . - */ namespace Doctrine\Tests\ORM\Mapping; use Doctrine\ORM\Mapping\Builder\ClassMetadataBuilder; use Doctrine\ORM\Mapping\ClassMetadataInfo; +use Doctrine\Tests\Models\CMS\CmsUser; use Doctrine\Tests\OrmTestCase; class FieldBuilderTest extends OrmTestCase { public function testCustomIdGeneratorCanBeSet() { - $cmBuilder = new ClassMetadataBuilder(new ClassMetadataInfo('Doctrine\Tests\Models\CMS\CmsUser')); + $cmBuilder = new ClassMetadataBuilder(new ClassMetadataInfo(CmsUser::class)); $fieldBuilder = $cmBuilder->createField('aField', 'string'); diff --git a/tests/Doctrine/Tests/ORM/Mapping/NamingStrategy/JoinColumnClassNamingStrategy.php b/tests/Doctrine/Tests/ORM/Mapping/NamingStrategy/JoinColumnClassNamingStrategy.php index 8de8fa94004..c4f967589f9 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/NamingStrategy/JoinColumnClassNamingStrategy.php +++ b/tests/Doctrine/Tests/ORM/Mapping/NamingStrategy/JoinColumnClassNamingStrategy.php @@ -1,23 +1,5 @@ . - */ - namespace Doctrine\Tests\ORM\Mapping\NamingStrategy; use Doctrine\ORM\Mapping\DefaultNamingStrategy; diff --git a/tests/Doctrine/Tests/ORM/Mapping/NamingStrategyTest.php b/tests/Doctrine/Tests/ORM/Mapping/NamingStrategyTest.php index 6274a146800..c9eda5d9149 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/NamingStrategyTest.php +++ b/tests/Doctrine/Tests/ORM/Mapping/NamingStrategyTest.php @@ -1,293 +1,301 @@ */ - static public function dataClassToTableName() + public static function dataClassToTableName() : array { - return array( + return [ // DefaultNamingStrategy - array(self::defaultNaming(), 'SomeClassName', - 'SomeClassName' - ), - array(self::defaultNaming(), 'SomeClassName', - '\SomeClassName' - ), - array(self::defaultNaming(), 'Name', - '\Some\Class\Name' - ), + [self::defaultNaming(), 'SomeClassName', 'SomeClassName'], + [self::defaultNaming(), 'SomeClassName', '\SomeClassName'], + [self::defaultNaming(), 'Name', '\Some\Class\Name'], + [self::defaultNaming(), 'Name2Test', '\Some\Class\Name2Test'], // UnderscoreNamingStrategy - array(self::underscoreNamingLower(), 'some_class_name', - '\Name\Space\SomeClassName' - ), - array(self::underscoreNamingLower(), 'name', - '\Some\Class\Name' - ), - array(self::underscoreNamingUpper(), 'SOME_CLASS_NAME', - '\Name\Space\SomeClassName' - ), - array(self::underscoreNamingUpper(), 'NAME', - '\Some\Class\Name' - ), - ); + [self::underscoreNamingLower(), 'some_class_name', '\Name\Space\SomeClassName'], + [self::underscoreNamingLower(), 'name', '\Some\Class\Name'], + [self::underscoreNamingLower(), 'name2test', '\Some\Class\Name2Test'], + [self::underscoreNamingUpper(), 'SOME_CLASS_NAME', '\Name\Space\SomeClassName'], + [self::underscoreNamingUpper(), 'NAME', '\Some\Class\Name'], + [self::underscoreNamingUpper(), 'NAME2TEST', '\Some\Class\Name2Test'], + + // NumberAwareUnderscoreNamingStrategy + [self::numberAwareUnderscoreNamingLower(), 'some_class_name', '\Name\Space\SomeClassName'], + [self::numberAwareUnderscoreNamingLower(), 'name', '\Some\Class\Name'], + [self::numberAwareUnderscoreNamingLower(), 'name2_test', '\Some\Class\Name2Test'], + [self::numberAwareUnderscoreNamingLower(), 'name2test', '\Some\Class\Name2test'], + [self::numberAwareUnderscoreNamingUpper(), 'SOME_CLASS_NAME', '\Name\Space\SomeClassName'], + [self::numberAwareUnderscoreNamingUpper(), 'NAME', '\Some\Class\Name'], + [self::numberAwareUnderscoreNamingUpper(), 'NAME2_TEST', '\Some\Class\Name2Test'], + [self::numberAwareUnderscoreNamingUpper(), 'NAME2TEST', '\Some\Class\Name2test'], + ]; } /** * @dataProvider dataClassToTableName */ - public function testClassToTableName(NamingStrategy $strategy, $expected, $className) + public function testClassToTableName(NamingStrategy $strategy, string $expected, string $className) : void { - $this->assertEquals($expected, $strategy->classToTableName($className)); + self::assertSame($expected, $strategy->classToTableName($className)); } /** * Data Provider for NamingStrategy#propertyToColumnName - * - * @return array + * + * @return array */ - static public function dataPropertyToColumnName() + public static function dataPropertyToColumnName() : array { - return array( + return [ // DefaultNamingStrategy - array(self::defaultNaming(), 'someProperty', - 'someProperty' - ), - array(self::defaultNaming(), 'SOME_PROPERTY', - 'SOME_PROPERTY' - ), - array(self::defaultNaming(), 'some_property', - 'some_property' - ), + [self::defaultNaming(), 'someProperty', 'someProperty'], + [self::defaultNaming(), 'SOME_PROPERTY', 'SOME_PROPERTY'], + [self::defaultNaming(), 'some_property', 'some_property'], + [self::defaultNaming(), 'base64Encoded', 'base64Encoded'], + [self::defaultNaming(), 'base64_encoded', 'base64_encoded'], // UnderscoreNamingStrategy - array(self::underscoreNamingLower(), 'some_property', - 'someProperty' - ), - array(self::underscoreNamingUpper(), 'SOME_PROPERTY', - 'someProperty' - ), - array(self::underscoreNamingUpper(), 'SOME_PROPERTY', - 'some_property' - ), - array(self::underscoreNamingUpper(), 'SOME_PROPERTY', - 'SOME_PROPERTY' - ), - ); + [self::underscoreNamingLower(), 'some_property', 'someProperty'], + [self::underscoreNamingLower(), 'base64encoded', 'base64Encoded'], + [self::underscoreNamingLower(), 'base64encoded', 'base64encoded'], + [self::underscoreNamingUpper(), 'SOME_PROPERTY', 'someProperty'], + [self::underscoreNamingUpper(), 'SOME_PROPERTY', 'some_property'], + [self::underscoreNamingUpper(), 'SOME_PROPERTY', 'SOME_PROPERTY'], + [self::underscoreNamingUpper(), 'BASE64ENCODED', 'base64Encoded'], + [self::underscoreNamingUpper(), 'BASE64ENCODED', 'base64encoded'], + + // NumberAwareUnderscoreNamingStrategy + [self::numberAwareUnderscoreNamingLower(), 'some_property', 'someProperty'], + [self::numberAwareUnderscoreNamingLower(), 'base64_encoded', 'base64Encoded'], + [self::numberAwareUnderscoreNamingLower(), 'base64encoded', 'base64encoded'], + [self::numberAwareUnderscoreNamingUpper(), 'SOME_PROPERTY', 'someProperty'], + [self::numberAwareUnderscoreNamingUpper(), 'SOME_PROPERTY', 'some_property'], + [self::numberAwareUnderscoreNamingUpper(), 'SOME_PROPERTY', 'SOME_PROPERTY'], + [self::numberAwareUnderscoreNamingUpper(), 'BASE64_ENCODED', 'base64Encoded'], + [self::numberAwareUnderscoreNamingUpper(), 'BASE64ENCODED', 'base64encoded'], + ]; } - + /** * @dataProvider dataPropertyToColumnName - * - * @param NamingStrategy $strategy - * @param string $expected - * @param string $propertyName */ - public function testPropertyToColumnName(NamingStrategy $strategy, $expected, $propertyName) + public function testPropertyToColumnName(NamingStrategy $strategy, string $expected, string $propertyName) : void { - $this->assertEquals($expected, $strategy->propertyToColumnName($propertyName)); + self::assertSame($expected, $strategy->propertyToColumnName($propertyName)); } /** * Data Provider for NamingStrategy#referenceColumnName * - * @return array + * @return array */ - static public function dataReferenceColumnName() + public static function dataReferenceColumnName() : array { - return array( + return [ // DefaultNamingStrategy - array(self::defaultNaming(), 'id'), + [self::defaultNaming(), 'id'], // UnderscoreNamingStrategy - array(self::underscoreNamingLower(), 'id'), - array(self::underscoreNamingUpper(), 'ID'), - ); + [self::underscoreNamingLower(), 'id'], + [self::underscoreNamingUpper(), 'ID'], + + // NumberAwareUnderscoreNamingStrategy + [self::numberAwareUnderscoreNamingLower(), 'id'], + [self::numberAwareUnderscoreNamingUpper(), 'ID'], + ]; } /** * @dataProvider dataReferenceColumnName - * - * @param NamingStrategy $strategy - * @param string $expected */ - public function testReferenceColumnName(NamingStrategy $strategy, $expected) + public function testReferenceColumnName(NamingStrategy $strategy, string $expected) : void { - $this->assertEquals($expected, $strategy->referenceColumnName()); + self::assertSame($expected, $strategy->referenceColumnName()); } /** * Data Provider for NamingStrategy#joinColumnName * - * @return array + * @return array */ - static public function dataJoinColumnName() + public static function dataJoinColumnName() : array { - return array( + return [ // DefaultNamingStrategy - array(self::defaultNaming(), 'someColumn_id', 'someColumn', null), - array(self::defaultNaming(), 'some_column_id', 'some_column', null), + [self::defaultNaming(), 'someColumn_id', 'someColumn', null], + [self::defaultNaming(), 'some_column_id', 'some_column', null], + [self::defaultNaming(), 'base64Encoded_id', 'base64Encoded', null], + [self::defaultNaming(), 'base64_encoded_id', 'base64_encoded', null], // UnderscoreNamingStrategy - array(self::underscoreNamingLower(), 'some_column_id', 'someColumn', null), - array(self::underscoreNamingUpper(), 'SOME_COLUMN_ID', 'someColumn', null), + [self::underscoreNamingLower(), 'some_column_id', 'someColumn', null], + [self::underscoreNamingLower(), 'base64encoded_id', 'base64Encoded', null], + [self::underscoreNamingUpper(), 'SOME_COLUMN_ID', 'someColumn', null], + [self::underscoreNamingUpper(), 'BASE64ENCODED_ID', 'base64Encoded', null], + + // NumberAwareUnderscoreNamingStrategy + [self::numberAwareUnderscoreNamingLower(), 'some_column_id', 'someColumn', null], + [self::numberAwareUnderscoreNamingLower(), 'base64_encoded_id', 'base64Encoded', null], + [self::numberAwareUnderscoreNamingLower(), 'base64encoded_id', 'base64encoded', null], + [self::numberAwareUnderscoreNamingUpper(), 'SOME_COLUMN_ID', 'someColumn', null], + [self::numberAwareUnderscoreNamingUpper(), 'BASE64_ENCODED_ID', 'base64Encoded', null], + [self::numberAwareUnderscoreNamingUpper(), 'BASE64ENCODED_ID', 'base64encoded', null], + // JoinColumnClassNamingStrategy - array(new JoinColumnClassNamingStrategy(), 'classname_someColumn_id', 'someColumn', 'Some\ClassName'), - array(new JoinColumnClassNamingStrategy(), 'classname_some_column_id', 'some_column', 'ClassName'), - ); + [new JoinColumnClassNamingStrategy(), 'classname_someColumn_id', 'someColumn', 'Some\ClassName'], + [new JoinColumnClassNamingStrategy(), 'classname_some_column_id', 'some_column', 'ClassName'], + ]; } /** * @dataProvider dataJoinColumnName - * - * @param NamingStrategy $strategy - * @param string $expected - * @param string $propertyName */ - public function testJoinColumnName(NamingStrategy $strategy, $expected, $propertyName, $className = null) - { - $this->assertEquals($expected, $strategy->joinColumnName($propertyName, $className)); + public function testJoinColumnName( + NamingStrategy $strategy, + string $expected, + string $propertyName, + ?string $className = null + ) : void { + self::assertSame($expected, $strategy->joinColumnName($propertyName, $className)); } /** * Data Provider for NamingStrategy#joinTableName * - * @return array + * @return array */ - static public function dataJoinTableName() + public static function dataJoinTableName() : array { - return array( + return [ // DefaultNamingStrategy - array(self::defaultNaming(), 'someclassname_classname', - 'SomeClassName', 'Some\ClassName', null, - ), - array(self::defaultNaming(), 'someclassname_classname', - '\SomeClassName', 'ClassName', null, - ), - array(self::defaultNaming(), 'name_classname', - '\Some\Class\Name', 'ClassName', null, - ), + [self::defaultNaming(), 'someclassname_classname', 'SomeClassName', 'Some\ClassName', null], + [self::defaultNaming(), 'someclassname_classname', '\SomeClassName', 'ClassName', null], + [self::defaultNaming(), 'name_classname', '\Some\Class\Name', 'ClassName', null], // UnderscoreNamingStrategy - array(self::underscoreNamingLower(), 'some_class_name_class_name', - 'SomeClassName', 'Some\ClassName', null, - ), - array(self::underscoreNamingLower(), 'some_class_name_class_name', - '\SomeClassName', 'ClassName', null, - ), - array(self::underscoreNamingLower(), 'name_class_name', - '\Some\Class\Name', 'ClassName', null, - ), - - array(self::underscoreNamingUpper(), 'SOME_CLASS_NAME_CLASS_NAME', - 'SomeClassName', 'Some\ClassName', null, - ), - array(self::underscoreNamingUpper(), 'SOME_CLASS_NAME_CLASS_NAME', - '\SomeClassName', 'ClassName', null, - ), - array(self::underscoreNamingUpper(), 'NAME_CLASS_NAME', - '\Some\Class\Name', 'ClassName', null, - ), - ); + [self::underscoreNamingLower(), 'some_class_name_class_name', 'SomeClassName', 'Some\ClassName', null], + [self::underscoreNamingLower(), 'class1test_class2test', 'Class1Test', 'Some\Class2Test', null], + [self::underscoreNamingLower(), 'some_class_name_class_name', '\SomeClassName', 'ClassName', null], + [self::underscoreNamingLower(), 'name_class_name', '\Some\Class\Name', 'ClassName', null], + [self::underscoreNamingUpper(), 'SOME_CLASS_NAME_CLASS_NAME', 'SomeClassName', 'Some\ClassName', null], + [self::underscoreNamingUpper(), 'CLASS1TEST_CLASS2TEST', 'Class1Test', 'Some\Class2Test', null], + [self::underscoreNamingUpper(), 'SOME_CLASS_NAME_CLASS_NAME', '\SomeClassName', 'ClassName', null], + [self::underscoreNamingUpper(), 'NAME_CLASS_NAME', '\Some\Class\Name', 'ClassName', null], + + // NumberAwareUnderscoreNamingStrategy + [self::numberAwareUnderscoreNamingLower(), 'some_class_name_class_name', 'SomeClassName', 'Some\ClassName', null], + [self::numberAwareUnderscoreNamingLower(), 'class1_test_class2_test', 'Class1Test', 'Some\Class2Test', null], + [self::numberAwareUnderscoreNamingLower(), 'some_class_name_class_name', '\SomeClassName', 'ClassName', null], + [self::numberAwareUnderscoreNamingLower(), 'name_class_name', '\Some\Class\Name', 'ClassName', null], + [self::numberAwareUnderscoreNamingUpper(), 'SOME_CLASS_NAME_CLASS_NAME', 'SomeClassName', 'Some\ClassName', null], + [self::numberAwareUnderscoreNamingUpper(), 'CLASS1_TEST_CLASS2_TEST', 'Class1Test', 'Some\Class2Test', null], + [self::numberAwareUnderscoreNamingUpper(), 'SOME_CLASS_NAME_CLASS_NAME', '\SomeClassName', 'ClassName', null], + [self::numberAwareUnderscoreNamingUpper(), 'NAME_CLASS_NAME', '\Some\Class\Name', 'ClassName', null], + ]; } /** * @dataProvider dataJoinTableName - * - * @param NamingStrategy $strategy - * @param string $expected - * @param string $ownerEntity - * @param string $associatedEntity - * @param string $propertyName */ - public function testJoinTableName(NamingStrategy $strategy, $expected, $ownerEntity, $associatedEntity, $propertyName = null) - { - $this->assertEquals($expected, $strategy->joinTableName($ownerEntity, $associatedEntity, $propertyName)); + public function testJoinTableName( + NamingStrategy $strategy, + string $expected, + string $ownerEntity, + string $associatedEntity, + ?string $propertyName = null + ) : void { + self::assertSame($expected, $strategy->joinTableName($ownerEntity, $associatedEntity, $propertyName)); } /** * Data Provider for NamingStrategy#joinKeyColumnName * - * @return array + * @return array */ - static public function dataJoinKeyColumnName() + public static function dataJoinKeyColumnName() : array { - return array( + return [ // DefaultNamingStrategy - array(self::defaultNaming(), 'someclassname_id', - 'SomeClassName', null, null, - ), - array(self::defaultNaming(), 'name_identifier', - '\Some\Class\Name', 'identifier', null, - ), + [self::defaultNaming(), 'someclassname_id', 'SomeClassName', null, null], + [self::defaultNaming(), 'name_identifier', '\Some\Class\Name', 'identifier', null], // UnderscoreNamingStrategy - array(self::underscoreNamingLower(), 'some_class_name_id', - 'SomeClassName', null, null, - ), - array(self::underscoreNamingLower(), 'class_name_identifier', - '\Some\Class\ClassName', 'identifier', null, - ), - - array(self::underscoreNamingUpper(), 'SOME_CLASS_NAME_ID', - 'SomeClassName', null, null, - ), - array(self::underscoreNamingUpper(), 'CLASS_NAME_IDENTIFIER', - '\Some\Class\ClassName', 'IDENTIFIER', null, - ), - ); + [self::underscoreNamingLower(), 'some_class_name2test_id', 'SomeClassName2Test', null, null], + [self::underscoreNamingLower(), 'some_class_name_id', 'SomeClassName', null, null], + [self::underscoreNamingLower(), 'class_name_identifier', '\Some\Class\ClassName', 'identifier', null], + [self::underscoreNamingLower(), 'name2test_identifier', '\Some\Class\Name2Test', 'identifier', null], + [self::underscoreNamingUpper(), 'SOME_CLASS_NAME_ID', 'SomeClassName', null, null], + [self::underscoreNamingUpper(), 'SOME_CLASS_NAME2TEST_ID', 'SomeClassName2Test', null, null], + [self::underscoreNamingUpper(), 'CLASS_NAME_IDENTIFIER', '\Some\Class\ClassName', 'IDENTIFIER', null], + [self::underscoreNamingUpper(), 'NAME2TEST_IDENTIFIER', '\Some\Class\Name2Test', 'IDENTIFIER', null], + + // NumberAwareUnderscoreNamingStrategy + [self::numberAwareUnderscoreNamingLower(), 'some_class_name2_test_id', 'SomeClassName2Test', null, null], + [self::numberAwareUnderscoreNamingLower(), 'some_class_name_id', 'SomeClassName', null, null], + [self::numberAwareUnderscoreNamingLower(), 'class_name_identifier', '\Some\Class\ClassName', 'identifier', null], + [self::numberAwareUnderscoreNamingLower(), 'name2_test_identifier', '\Some\Class\Name2Test', 'identifier', null], + [self::numberAwareUnderscoreNamingUpper(), 'SOME_CLASS_NAME_ID', 'SomeClassName', null, null], + [self::numberAwareUnderscoreNamingUpper(), 'SOME_CLASS_NAME2_TEST_ID', 'SomeClassName2Test', null, null], + [self::numberAwareUnderscoreNamingUpper(), 'CLASS_NAME_IDENTIFIER', '\Some\Class\ClassName', 'IDENTIFIER', null], + [self::numberAwareUnderscoreNamingUpper(), 'NAME2_TEST_IDENTIFIER', '\Some\Class\Name2Test', 'IDENTIFIER', null], + ]; } /** * @dataProvider dataJoinKeyColumnName - * - * @param NamingStrategy $strategy - * @param string $expected - * @param string $propertyEntityName - * @param string $referencedColumnName - * @param string $propertyName */ - public function testJoinKeyColumnName(NamingStrategy $strategy, $expected, $propertyEntityName, $referencedColumnName = null, $propertyName = null) - { - $this->assertEquals($expected, $strategy->joinKeyColumnName($propertyEntityName, $referencedColumnName, $propertyName)); + public function testJoinKeyColumnName( + NamingStrategy $strategy, + string $expected, + string $propertyEntityName, + ?string $referencedColumnName = null, + ?string $propertyName = null + ) : void { + self::assertSame($expected, $strategy->joinKeyColumnName($propertyEntityName, $referencedColumnName, $propertyName)); } } diff --git a/tests/Doctrine/Tests/ORM/Mapping/PHPMappingDriverTest.php b/tests/Doctrine/Tests/ORM/Mapping/PHPMappingDriverTest.php index cfc7f0cc8d7..04493dbc424 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/PHPMappingDriverTest.php +++ b/tests/Doctrine/Tests/ORM/Mapping/PHPMappingDriverTest.php @@ -2,8 +2,10 @@ namespace Doctrine\Tests\ORM\Mapping; -use Doctrine\ORM\Mapping\ClassMetadata, - Doctrine\Common\Persistence\Mapping\Driver\PHPDriver; +use Doctrine\Common\Persistence\Mapping\Driver\PHPDriver; +use Doctrine\ORM\Mapping\ClassMetadata; +use Doctrine\Tests\Models\DDC889\DDC889Class; +use Doctrine\Tests\ORM\Mapping; class PHPMappingDriverTest extends AbstractMappingDriverTest { @@ -30,7 +32,7 @@ protected function _loadDriver() */ public function testinvalidEntityOrMappedSuperClassShouldMentionParentClasses() { - $this->createClassMetadata('Doctrine\Tests\Models\DDC889\DDC889Class'); + self::assertInstanceOf(ClassMetadata::class, $this->createClassMetadata(DDC889Class::class)); } /** @@ -39,10 +41,9 @@ public function testinvalidEntityOrMappedSuperClassShouldMentionParentClasses() */ public function testFailingSecondLevelCacheAssociation() { - $className = 'Doctrine\Tests\ORM\Mapping\PHPSLC'; $mappingDriver = $this->_loadDriver(); - $class = new ClassMetadata($className); - $mappingDriver->loadMetadataForClass($className, $class); + $class = new ClassMetadata(Mapping\PHPSLC::class); + $mappingDriver->loadMetadataForClass(Mapping\PHPSLC::class, $class); } } diff --git a/tests/Doctrine/Tests/ORM/Mapping/QuoteStrategyTest.php b/tests/Doctrine/Tests/ORM/Mapping/QuoteStrategyTest.php index 0b736dd0b59..2af97169c80 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/QuoteStrategyTest.php +++ b/tests/Doctrine/Tests/ORM/Mapping/QuoteStrategyTest.php @@ -3,8 +3,13 @@ namespace Doctrine\Tests\ORM\Mapping; use Doctrine\Common\Persistence\Mapping\RuntimeReflectionService; -use Doctrine\ORM\Mapping\DefaultQuoteStrategy; use Doctrine\ORM\Mapping\ClassMetadata; +use Doctrine\ORM\Mapping\DefaultQuoteStrategy; +use Doctrine\ORM\Mapping\QuoteStrategy; +use Doctrine\Tests\Models\CMS\CmsAddress; +use Doctrine\Tests\Models\CMS\CmsUser; +use Doctrine\Tests\Models\DDC117\DDC117Article; +use Doctrine\Tests\Models\DDC117\DDC117ArticleDetails; use Doctrine\Tests\OrmTestCase; /** @@ -48,85 +53,92 @@ public function testConfiguration() $em = $this->_getTestEntityManager(); $config = $em->getConfiguration(); - $this->assertInstanceOf('Doctrine\ORM\Mapping\QuoteStrategy', $config->getQuoteStrategy()); - $this->assertInstanceOf('Doctrine\ORM\Mapping\DefaultQuoteStrategy', $config->getQuoteStrategy()); + $this->assertInstanceOf(QuoteStrategy::class, $config->getQuoteStrategy()); + $this->assertInstanceOf(DefaultQuoteStrategy::class, $config->getQuoteStrategy()); $config->setQuoteStrategy(new MyQuoteStrategy()); - $this->assertInstanceOf('Doctrine\ORM\Mapping\QuoteStrategy', $config->getQuoteStrategy()); - $this->assertInstanceOf('Doctrine\Tests\ORM\Mapping\MyQuoteStrategy', $config->getQuoteStrategy()); + $this->assertInstanceOf(QuoteStrategy::class, $config->getQuoteStrategy()); + $this->assertInstanceOf(MyQuoteStrategy::class, $config->getQuoteStrategy()); } public function testGetColumnName() { - $cm = $this->createClassMetadata('Doctrine\Tests\Models\CMS\CmsUser'); - $cm->mapField(array('fieldName' => 'name', 'columnName' => '`name`')); - $cm->mapField(array('fieldName' => 'id', 'columnName' => 'id')); - + $cm = $this->createClassMetadata(CmsUser::class); + $cm->mapField(['fieldName' => 'name', 'columnName' => '`name`']); + $cm->mapField(['fieldName' => 'id', 'columnName' => 'id']); + $this->assertEquals('id' ,$this->strategy->getColumnName('id', $cm, $this->platform)); $this->assertEquals('"name"' ,$this->strategy->getColumnName('name', $cm, $this->platform)); } public function testGetTableName() { - $cm = $this->createClassMetadata('Doctrine\Tests\Models\CMS\CmsUser'); - $cm->setPrimaryTable(array('name'=>'`cms_user`')); - $this->assertEquals('"cms_user"' ,$this->strategy->getTableName($cm, $this->platform)); + $cm = $this->createClassMetadata(CmsUser::class); + $cm->setPrimaryTable(['name'=>'`cms_user`']); + $this->assertEquals('"cms_user"', $this->strategy->getTableName($cm, $this->platform)); - $cm = new ClassMetadata('Doctrine\Tests\Models\CMS\CmsUser'); + $cm = new ClassMetadata(CmsUser::class); $cm->initializeReflection(new RuntimeReflectionService()); - $cm->setPrimaryTable(array('name'=>'cms_user')); - $this->assertEquals('cms_user' ,$this->strategy->getTableName($cm, $this->platform)); + $cm->setPrimaryTable(['name'=>'cms_user']); + $this->assertEquals('cms_user', $this->strategy->getTableName($cm, $this->platform)); } - + public function testJoinTableName() { - $cm1 = $this->createClassMetadata('Doctrine\Tests\Models\CMS\CmsAddress'); - $cm2 = $this->createClassMetadata('Doctrine\Tests\Models\CMS\CmsAddress'); - - $cm1->mapManyToMany(array( + $cm1 = $this->createClassMetadata(CmsAddress::class); + $cm2 = $this->createClassMetadata(CmsAddress::class); + + $cm1->mapManyToMany( + [ 'fieldName' => 'user', 'targetEntity' => 'CmsUser', 'inversedBy' => 'users', - 'joinTable' => array( + 'joinTable' => [ 'name' => '`cmsaddress_cmsuser`' - ) - )); - - $cm2->mapManyToMany(array( + ] + ] + ); + + $cm2->mapManyToMany( + [ 'fieldName' => 'user', 'targetEntity' => 'CmsUser', 'inversedBy' => 'users', - 'joinTable' => array( + 'joinTable' => [ 'name' => 'cmsaddress_cmsuser' - ) - ) + ] + ] ); $this->assertEquals('"cmsaddress_cmsuser"', $this->strategy->getJoinTableName($cm1->associationMappings['user'], $cm1, $this->platform)); $this->assertEquals('cmsaddress_cmsuser', $this->strategy->getJoinTableName($cm2->associationMappings['user'], $cm2, $this->platform)); - + } public function testIdentifierColumnNames() { - $cm1 = $this->createClassMetadata('Doctrine\Tests\Models\CMS\CmsAddress'); - $cm2 = $this->createClassMetadata('Doctrine\Tests\Models\CMS\CmsAddress'); + $cm1 = $this->createClassMetadata(CmsAddress::class); + $cm2 = $this->createClassMetadata(CmsAddress::class); - $cm1->mapField(array( + $cm1->mapField( + [ 'id' => true, 'fieldName' => 'id', 'columnName' => '`id`', - )); + ] + ); - $cm2->mapField(array( + $cm2->mapField( + [ 'id' => true, 'fieldName' => 'id', 'columnName' => 'id', - )); + ] + ); - $this->assertEquals(array('"id"'), $this->strategy->getIdentifierColumnNames($cm1, $this->platform)); - $this->assertEquals(array('id'), $this->strategy->getIdentifierColumnNames($cm2, $this->platform)); + $this->assertEquals(['"id"'], $this->strategy->getIdentifierColumnNames($cm1, $this->platform)); + $this->assertEquals(['id'], $this->strategy->getIdentifierColumnNames($cm2, $this->platform)); } @@ -141,32 +153,40 @@ public function testColumnAlias() public function testQuoteIdentifierJoinColumns() { - $cm = $this->createClassMetadata('Doctrine\Tests\Models\DDC117\DDC117ArticleDetails'); + $cm = $this->createClassMetadata(DDC117ArticleDetails::class); - $cm->mapOneToOne(array( + $cm->mapOneToOne( + [ 'id' => true, 'fieldName' => 'article', - 'targetEntity' => 'Doctrine\Tests\Models\DDC117\DDC117Article', - 'joinColumns' => array(array( + 'targetEntity' => DDC117Article::class, + 'joinColumns' => [ + [ 'name' => '`article`' - )), - )); + ] + ], + ] + ); - $this->assertEquals(array('"article"'), $this->strategy->getIdentifierColumnNames($cm, $this->platform)); + $this->assertEquals(['"article"'], $this->strategy->getIdentifierColumnNames($cm, $this->platform)); } public function testJoinColumnName() { - $cm = $this->createClassMetadata('Doctrine\Tests\Models\DDC117\DDC117ArticleDetails'); + $cm = $this->createClassMetadata(DDC117ArticleDetails::class); - $cm->mapOneToOne(array( + $cm->mapOneToOne( + [ 'id' => true, 'fieldName' => 'article', - 'targetEntity' => 'Doctrine\Tests\Models\DDC117\DDC117Article', - 'joinColumns' => array(array( + 'targetEntity' => DDC117Article::class, + 'joinColumns' => [ + [ 'name' => '`article`' - )), - )); + ] + ], + ] + ); $joinColumn = $cm->associationMappings['article']['joinColumns'][0]; $this->assertEquals('"article"',$this->strategy->getJoinColumnName($joinColumn, $cm, $this->platform)); @@ -174,16 +194,20 @@ public function testJoinColumnName() public function testReferencedJoinColumnName() { - $cm = $this->createClassMetadata('Doctrine\Tests\Models\DDC117\DDC117ArticleDetails'); + $cm = $this->createClassMetadata(DDC117ArticleDetails::class); - $cm->mapOneToOne(array( + $cm->mapOneToOne( + [ 'id' => true, 'fieldName' => 'article', - 'targetEntity' => 'Doctrine\Tests\Models\DDC117\DDC117Article', - 'joinColumns' => array(array( + 'targetEntity' => DDC117Article::class, + 'joinColumns' => [ + [ 'name' => '`article`' - )), - )); + ] + ], + ] + ); $joinColumn = $cm->associationMappings['article']['joinColumns'][0]; $this->assertEquals('"id"',$this->strategy->getReferencedJoinColumnName($joinColumn, $cm, $this->platform)); diff --git a/tests/Doctrine/Tests/ORM/Mapping/Reflection/ReflectionPropertiesGetterTest.php b/tests/Doctrine/Tests/ORM/Mapping/Reflection/ReflectionPropertiesGetterTest.php index 1b18deb114d..29906d59b9d 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/Reflection/ReflectionPropertiesGetterTest.php +++ b/tests/Doctrine/Tests/ORM/Mapping/Reflection/ReflectionPropertiesGetterTest.php @@ -7,7 +7,7 @@ use Doctrine\ORM\Mapping\Reflection\ReflectionPropertiesGetter; use Doctrine\Tests\Models\Reflection\ClassWithMixedProperties; use Doctrine\Tests\Models\Reflection\ParentClass; -use PHPUnit_Framework_TestCase; +use PHPUnit\Framework\TestCase; use ReflectionClass; /** @@ -15,12 +15,12 @@ * * @covers \Doctrine\ORM\Mapping\Reflection\ReflectionPropertiesGetter */ -class ReflectionPropertiesGetterTest extends PHPUnit_Framework_TestCase +class ReflectionPropertiesGetterTest extends TestCase { public function testRetrievesProperties() { $properties = (new ReflectionPropertiesGetter(new RuntimeReflectionService())) - ->getProperties(ClassWithMixedProperties::CLASSNAME); + ->getProperties(ClassWithMixedProperties::class); $this->assertCount(5, $properties); @@ -32,7 +32,7 @@ public function testRetrievesProperties() public function testRetrievedInstancesAreNotStatic() { $properties = (new ReflectionPropertiesGetter(new RuntimeReflectionService())) - ->getProperties(ClassWithMixedProperties::CLASSNAME); + ->getProperties(ClassWithMixedProperties::class); foreach ($properties as $property) { $this->assertFalse($property->isStatic()); @@ -42,18 +42,18 @@ public function testRetrievedInstancesAreNotStatic() public function testExpectedKeys() { $properties = (new ReflectionPropertiesGetter(new RuntimeReflectionService())) - ->getProperties(ClassWithMixedProperties::CLASSNAME); + ->getProperties(ClassWithMixedProperties::class); $this->assertArrayHasKey( - "\0" . ClassWithMixedProperties::CLASSNAME . "\0" . 'privateProperty', + "\0" . ClassWithMixedProperties::class . "\0" . 'privateProperty', $properties ); $this->assertArrayHasKey( - "\0" . ClassWithMixedProperties::CLASSNAME . "\0" . 'privatePropertyOverride', + "\0" . ClassWithMixedProperties::class . "\0" . 'privatePropertyOverride', $properties ); $this->assertArrayHasKey( - "\0" . ParentClass::CLASSNAME . "\0" . 'privatePropertyOverride', + "\0" . ParentClass::class . "\0" . 'privatePropertyOverride', $properties ); $this->assertArrayHasKey( @@ -70,7 +70,7 @@ public function testPropertiesAreAccessible() { $object = new ClassWithMixedProperties(); $properties = (new ReflectionPropertiesGetter(new RuntimeReflectionService())) - ->getProperties(ClassWithMixedProperties::CLASSNAME); + ->getProperties(ClassWithMixedProperties::class); foreach ($properties as $property) { $this->assertSame($property->getName(), $property->getValue($object)); @@ -82,8 +82,8 @@ public function testPropertyGetterIsIdempotent() $getter = (new ReflectionPropertiesGetter(new RuntimeReflectionService())); $this->assertSame( - $getter->getProperties(ClassWithMixedProperties::CLASSNAME), - $getter->getProperties(ClassWithMixedProperties::CLASSNAME) + $getter->getProperties(ClassWithMixedProperties::class), + $getter->getProperties(ClassWithMixedProperties::class) ); } @@ -95,10 +95,10 @@ public function testPropertyGetterWillSkipPropertiesNotRetrievedByTheRuntimeRefl $reflectionService ->expects($this->exactly(2)) ->method('getClass') - ->with($this->logicalOr(ClassWithMixedProperties::CLASSNAME, ParentClass::CLASSNAME)) + ->with($this->logicalOr(ClassWithMixedProperties::class, ParentClass::class)) ->will($this->returnValueMap([ - [ClassWithMixedProperties::CLASSNAME, new ReflectionClass(ClassWithMixedProperties::CLASSNAME)], - [ParentClass::CLASSNAME, new ReflectionClass(ParentClass::CLASSNAME)], + [ClassWithMixedProperties::class, new ReflectionClass(ClassWithMixedProperties::class)], + [ParentClass::class, new ReflectionClass(ParentClass::class)], ])); $reflectionService @@ -107,7 +107,7 @@ public function testPropertyGetterWillSkipPropertiesNotRetrievedByTheRuntimeRefl $getter = (new ReflectionPropertiesGetter($reflectionService)); - $this->assertEmpty($getter->getProperties(ClassWithMixedProperties::CLASSNAME)); + $this->assertEmpty($getter->getProperties(ClassWithMixedProperties::class)); } public function testPropertyGetterWillSkipClassesNotRetrievedByTheRuntimeReflectionService() @@ -118,12 +118,12 @@ public function testPropertyGetterWillSkipClassesNotRetrievedByTheRuntimeReflect $reflectionService ->expects($this->once()) ->method('getClass') - ->with(ClassWithMixedProperties::CLASSNAME); + ->with(ClassWithMixedProperties::class); $reflectionService->expects($this->never())->method('getAccessibleProperty'); $getter = (new ReflectionPropertiesGetter($reflectionService)); - $this->assertEmpty($getter->getProperties(ClassWithMixedProperties::CLASSNAME)); + $this->assertEmpty($getter->getProperties(ClassWithMixedProperties::class)); } } diff --git a/tests/Doctrine/Tests/ORM/Mapping/ReflectionEmbeddedPropertyTest.php b/tests/Doctrine/Tests/ORM/Mapping/ReflectionEmbeddedPropertyTest.php index 9be006e5a27..82761282ad4 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/ReflectionEmbeddedPropertyTest.php +++ b/tests/Doctrine/Tests/ORM/Mapping/ReflectionEmbeddedPropertyTest.php @@ -4,7 +4,12 @@ use Doctrine\Instantiator\Instantiator; use Doctrine\ORM\Mapping\ReflectionEmbeddedProperty; +use Doctrine\Tests\Models\Generic\BooleanModel; use Doctrine\Tests\Models\Mapping\Entity; +use Doctrine\Tests\Models\Reflection\AbstractEmbeddable; +use Doctrine\Tests\Models\Reflection\ArrayObjectExtendingClass; +use Doctrine\Tests\Models\Reflection\ConcreteEmbeddable; +use PHPUnit\Framework\TestCase; use ReflectionProperty; /** @@ -12,7 +17,7 @@ * * @covers \Doctrine\ORM\Mapping\ReflectionEmbeddedProperty */ -class ReflectionEmbeddedPropertyTest extends \PHPUnit_Framework_TestCase +class ReflectionEmbeddedPropertyTest extends TestCase { /** * @param ReflectionProperty $parentProperty property of the embeddable/entity where to write the embeddable to @@ -69,76 +74,40 @@ public function testWillSkipReadingPropertiesFromNullEmbeddable( */ public function getTestedReflectionProperties() { - return array( - array( - $this->getReflectionProperty( - 'Doctrine\\Tests\\Models\\Generic\\BooleanModel', - 'id' - ), - $this->getReflectionProperty( - 'Doctrine\\Tests\\Models\\Generic\\BooleanModel', - 'id' - ), - 'Doctrine\\Tests\\Models\\Generic\\BooleanModel' - ), + return [ + [ + $this->getReflectionProperty(BooleanModel::class, 'id'), + $this->getReflectionProperty(BooleanModel::class, 'id'), + BooleanModel::class + ], // reflection on embeddables that have properties defined in abstract ancestors: - array( - $this->getReflectionProperty( - 'Doctrine\\Tests\\Models\\Generic\\BooleanModel', - 'id' - ), - $this->getReflectionProperty( - 'Doctrine\\Tests\\Models\\Reflection\\AbstractEmbeddable', - 'propertyInAbstractClass' - ), - 'Doctrine\\Tests\\Models\\Reflection\\ConcreteEmbeddable' - ), - array( - $this->getReflectionProperty( - 'Doctrine\\Tests\\Models\\Generic\\BooleanModel', - 'id' - ), - $this->getReflectionProperty( - 'Doctrine\\Tests\\Models\\Reflection\\ConcreteEmbeddable', - 'propertyInConcreteClass' - ), - 'Doctrine\\Tests\\Models\\Reflection\\ConcreteEmbeddable' - ), + [ + $this->getReflectionProperty(BooleanModel::class, 'id'), + $this->getReflectionProperty(AbstractEmbeddable::class, 'propertyInAbstractClass'), + ConcreteEmbeddable::class + ], + [ + $this->getReflectionProperty(BooleanModel::class, 'id'), + $this->getReflectionProperty(ConcreteEmbeddable::class, 'propertyInConcreteClass'), + ConcreteEmbeddable::class + ], // reflection on classes extending internal PHP classes: - array( - $this->getReflectionProperty( - 'Doctrine\\Tests\\Models\\Reflection\\ArrayObjectExtendingClass', - 'publicProperty' - ), - $this->getReflectionProperty( - 'Doctrine\\Tests\\Models\\Reflection\\ArrayObjectExtendingClass', - 'privateProperty' - ), - 'Doctrine\\Tests\\Models\\Reflection\\ArrayObjectExtendingClass' - ), - array( - $this->getReflectionProperty( - 'Doctrine\\Tests\\Models\\Reflection\\ArrayObjectExtendingClass', - 'publicProperty' - ), - $this->getReflectionProperty( - 'Doctrine\\Tests\\Models\\Reflection\\ArrayObjectExtendingClass', - 'protectedProperty' - ), - 'Doctrine\\Tests\\Models\\Reflection\\ArrayObjectExtendingClass' - ), - array( - $this->getReflectionProperty( - 'Doctrine\\Tests\\Models\\Reflection\\ArrayObjectExtendingClass', - 'publicProperty' - ), - $this->getReflectionProperty( - 'Doctrine\\Tests\\Models\\Reflection\\ArrayObjectExtendingClass', - 'publicProperty' - ), - 'Doctrine\\Tests\\Models\\Reflection\\ArrayObjectExtendingClass' - ), - ); + [ + $this->getReflectionProperty(ArrayObjectExtendingClass::class, 'publicProperty'), + $this->getReflectionProperty(ArrayObjectExtendingClass::class, 'privateProperty'), + ArrayObjectExtendingClass::class + ], + [ + $this->getReflectionProperty(ArrayObjectExtendingClass::class, 'publicProperty'), + $this->getReflectionProperty(ArrayObjectExtendingClass::class, 'protectedProperty'), + ArrayObjectExtendingClass::class + ], + [ + $this->getReflectionProperty(ArrayObjectExtendingClass::class, 'publicProperty'), + $this->getReflectionProperty(ArrayObjectExtendingClass::class, 'publicProperty'), + ArrayObjectExtendingClass::class + ], + ]; } /** diff --git a/tests/Doctrine/Tests/ORM/Mapping/StaticPHPMappingDriverTest.php b/tests/Doctrine/Tests/ORM/Mapping/StaticPHPMappingDriverTest.php index 598a42ce88a..3bc5a5d5d2e 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/StaticPHPMappingDriverTest.php +++ b/tests/Doctrine/Tests/ORM/Mapping/StaticPHPMappingDriverTest.php @@ -3,6 +3,8 @@ namespace Doctrine\Tests\ORM\Mapping; use Doctrine\Common\Persistence\Mapping\Driver\StaticPHPDriver; +use Doctrine\ORM\Mapping\ClassMetadata; +use Doctrine\Tests\Models\DDC889\DDC889Class; class StaticPHPMappingDriverTest extends AbstractMappingDriverTest { @@ -11,7 +13,6 @@ protected function _loadDriver() return new StaticPHPDriver(__DIR__ . DIRECTORY_SEPARATOR . 'php'); } - /** * All class with static::loadMetadata are entities for php driver * @@ -19,7 +20,7 @@ protected function _loadDriver() */ public function testinvalidEntityOrMappedSuperClassShouldMentionParentClasses() { - $this->createClassMetadata('Doctrine\Tests\Models\DDC889\DDC889Class'); + self::assertInstanceOf(ClassMetadata::class, $this->createClassMetadata(DDC889Class::class)); } /** diff --git a/tests/Doctrine/Tests/ORM/Mapping/Symfony/AbstractDriverTest.php b/tests/Doctrine/Tests/ORM/Mapping/Symfony/AbstractDriverTest.php index e116c67634b..85b3b2138dd 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/Symfony/AbstractDriverTest.php +++ b/tests/Doctrine/Tests/ORM/Mapping/Symfony/AbstractDriverTest.php @@ -1,36 +1,22 @@ . -*/ namespace Doctrine\Tests\ORM\Mapping\Symfony; use Doctrine\Common\Persistence\Mapping\MappingException; +use PHPUnit\Framework\TestCase; /** * @group DDC-1418 */ -abstract class AbstractDriverTest extends \PHPUnit_Framework_TestCase +abstract class AbstractDriverTest extends TestCase { public function testFindMappingFile() { - $driver = $this->getDriver(array( + $driver = $this->getDriver( + [ 'MyNamespace\MySubnamespace\EntityFoo' => 'foo', 'MyNamespace\MySubnamespace\Entity' => $this->dir, - )); + ] + ); touch($filename = $this->dir.'/Foo'.$this->getFileExtension()); $this->assertEquals($filename, $driver->getLocator()->findMappingFile('MyNamespace\MySubnamespace\Entity\Foo')); @@ -38,9 +24,11 @@ public function testFindMappingFile() public function testFindMappingFileInSubnamespace() { - $driver = $this->getDriver(array( + $driver = $this->getDriver( + [ 'MyNamespace\MySubnamespace\Entity' => $this->dir, - )); + ] + ); touch($filename = $this->dir.'/Foo.Bar'.$this->getFileExtension()); $this->assertEquals($filename, $driver->getLocator()->findMappingFile('MyNamespace\MySubnamespace\Entity\Foo\Bar')); @@ -51,9 +39,11 @@ public function testFindMappingFileNamespacedFoundFileNotFound() $this->expectException(MappingException::class); $this->expectExceptionMessage('No mapping file found named'); - $driver = $this->getDriver(array( + $driver = $this->getDriver( + [ 'MyNamespace\MySubnamespace\Entity' => $this->dir, - )); + ] + ); $driver->getLocator()->findMappingFile('MyNamespace\MySubnamespace\Entity\Foo'); } @@ -63,9 +53,11 @@ public function testFindMappingNamespaceNotFound() $this->expectException(MappingException::class); $this->expectExceptionMessage("No mapping file found named 'Foo" . $this->getFileExtension() . "' for class 'MyOtherNamespace\MySubnamespace\Entity\Foo'."); - $driver = $this->getDriver(array( + $driver = $this->getDriver( + [ 'MyNamespace\MySubnamespace\Entity' => $this->dir, - )); + ] + ); $driver->getLocator()->findMappingFile('MyOtherNamespace\MySubnamespace\Entity\Foo'); } @@ -92,5 +84,5 @@ protected function tearDown() } abstract protected function getFileExtension(); - abstract protected function getDriver(array $paths = array()); + abstract protected function getDriver(array $paths = []); } diff --git a/tests/Doctrine/Tests/ORM/Mapping/Symfony/XmlDriverTest.php b/tests/Doctrine/Tests/ORM/Mapping/Symfony/XmlDriverTest.php index 5908b674a13..2fa83681316 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/Symfony/XmlDriverTest.php +++ b/tests/Doctrine/Tests/ORM/Mapping/Symfony/XmlDriverTest.php @@ -1,21 +1,4 @@ . -*/ namespace Doctrine\Tests\ORM\Mapping\Symfony; @@ -31,7 +14,7 @@ protected function getFileExtension() return '.orm.xml'; } - protected function getDriver(array $paths = array()) + protected function getDriver(array $paths = []) { $driver = new SimplifiedXmlDriver(array_flip($paths)); diff --git a/tests/Doctrine/Tests/ORM/Mapping/Symfony/YamlDriverTest.php b/tests/Doctrine/Tests/ORM/Mapping/Symfony/YamlDriverTest.php index c5d8d1cd1b3..f167132f6bc 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/Symfony/YamlDriverTest.php +++ b/tests/Doctrine/Tests/ORM/Mapping/Symfony/YamlDriverTest.php @@ -1,39 +1,26 @@ . -*/ namespace Doctrine\Tests\ORM\Mapping\Symfony; use \Doctrine\ORM\Mapping\Driver\SimplifiedYamlDriver; +use Doctrine\Tests\VerifyDeprecations; /** * @group DDC-1418 */ class YamlDriverTest extends AbstractDriverTest { + use VerifyDeprecations; + protected function getFileExtension() { return '.orm.yml'; } - protected function getDriver(array $paths = array()) + protected function getDriver(array $paths = []) { $driver = new SimplifiedYamlDriver(array_flip($paths)); + $this->expectDeprecationMessage('YAML mapping driver is deprecated and will be removed in Doctrine ORM 3.0, please migrate to annotation or XML driver.'); return $driver; } diff --git a/tests/Doctrine/Tests/ORM/Mapping/XmlMappingDriverTest.php b/tests/Doctrine/Tests/ORM/Mapping/XmlMappingDriverTest.php index 735c16ed586..8ff6c0183f5 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/XmlMappingDriverTest.php +++ b/tests/Doctrine/Tests/ORM/Mapping/XmlMappingDriverTest.php @@ -2,10 +2,20 @@ namespace Doctrine\Tests\ORM\Mapping; +use Doctrine\Common\Collections\Criteria; use Doctrine\Common\Persistence\Mapping\RuntimeReflectionService; use Doctrine\ORM\Mapping\ClassMetadata; use Doctrine\ORM\Mapping\ClassMetadataFactory; use Doctrine\ORM\Mapping\Driver\XmlDriver; +use Doctrine\Tests\Models\DDC117\DDC117Translation; +use Doctrine\Tests\Models\DDC3293\DDC3293User; +use Doctrine\Tests\Models\DDC3293\DDC3293UserPrefixed; +use Doctrine\Tests\Models\DDC889\DDC889Class; +use Doctrine\Tests\Models\Generic\SerializationModel; +use Doctrine\Tests\Models\GH7141\GH7141Article; +use Doctrine\Tests\Models\GH7316\GH7316Article; +use Doctrine\Tests\Models\ValueObjects\Name; +use Doctrine\Tests\Models\ValueObjects\Person; class XmlMappingDriverTest extends AbstractMappingDriverTest { @@ -16,34 +26,32 @@ protected function _loadDriver() public function testClassTableInheritanceDiscriminatorMap() { - $className = 'Doctrine\Tests\ORM\Mapping\CTI'; $mappingDriver = $this->_loadDriver(); - $class = new ClassMetadata($className); + $class = new ClassMetadata(CTI::class); $class->initializeReflection(new RuntimeReflectionService()); - $mappingDriver->loadMetadataForClass($className, $class); + $mappingDriver->loadMetadataForClass(CTI::class, $class); - $expectedMap = array( - 'foo' => 'Doctrine\Tests\ORM\Mapping\CTIFoo', - 'bar' => 'Doctrine\Tests\ORM\Mapping\CTIBar', - 'baz' => 'Doctrine\Tests\ORM\Mapping\CTIBaz', - ); + $expectedMap = [ + 'foo' => CTIFoo::class, + 'bar' => CTIBar::class, + 'baz' => CTIBaz::class, + ]; $this->assertEquals(3, count($class->discriminatorMap)); $this->assertEquals($expectedMap, $class->discriminatorMap); } /** - * @expectedException Doctrine\ORM\Cache\CacheException + * @expectedException \Doctrine\ORM\Cache\CacheException * @expectedExceptionMessage Entity association field "Doctrine\Tests\ORM\Mapping\XMLSLC#foo" not configured as part of the second-level cache. */ public function testFailingSecondLevelCacheAssociation() { - $className = 'Doctrine\Tests\ORM\Mapping\XMLSLC'; $mappingDriver = $this->_loadDriver(); - $class = new ClassMetadata($className); - $mappingDriver->loadMetadataForClass($className, $class); + $class = new ClassMetadata(XMLSLC::class); + $mappingDriver->loadMetadataForClass(XMLSLC::class, $class); } public function testIdentifierWithAssociationKey() @@ -55,9 +63,9 @@ public function testIdentifierWithAssociationKey() $em->getConfiguration()->setMetadataDriverImpl($driver); $factory->setEntityManager($em); - $class = $factory->getMetadataFor('Doctrine\Tests\Models\DDC117\DDC117Translation'); + $class = $factory->getMetadataFor(DDC117Translation::class); - $this->assertEquals(array('language', 'article'), $class->identifier); + $this->assertEquals(['language', 'article'], $class->identifier); $this->assertArrayHasKey('article', $class->associationMappings); $this->assertArrayHasKey('id', $class->associationMappings['article']); @@ -66,7 +74,7 @@ public function testIdentifierWithAssociationKey() public function testEmbeddableMapping() { - $class = $this->createClassMetadata('Doctrine\Tests\Models\ValueObjects\Name'); + $class = $this->createClassMetadata(Name::class); $this->assertEquals(true, $class->isEmbeddedClass); } @@ -86,8 +94,7 @@ public function testEmbeddedMappingsWithUseColumnPrefix() $this->assertEquals( '__prefix__', - $factory - ->getMetadataFor('Doctrine\Tests\Models\DDC3293\DDC3293UserPrefixed') + $factory->getMetadataFor(DDC3293UserPrefixed::class) ->embeddedClasses['address']['columnPrefix'] ); } @@ -106,25 +113,24 @@ public function testEmbeddedMappingsWithFalseUseColumnPrefix() $factory->setEntityManager($em); $this->assertFalse( - $factory - ->getMetadataFor('Doctrine\Tests\Models\DDC3293\DDC3293User') + $factory->getMetadataFor(DDC3293User::class) ->embeddedClasses['address']['columnPrefix'] ); } public function testEmbeddedMapping() { - $class = $this->createClassMetadata('Doctrine\Tests\Models\ValueObjects\Person'); + $class = $this->createClassMetadata(Person::class); $this->assertEquals( - array( - 'name' => array( - 'class' => 'Doctrine\Tests\Models\ValueObjects\Name', + [ + 'name' => [ + 'class' => Name::class, 'columnPrefix' => 'nm_', 'declaredField' => null, 'originalField' => null, - ) - ), + ] + ], $class->embeddedClasses ); } @@ -132,12 +138,12 @@ public function testEmbeddedMapping() /** * @group DDC-1468 * - * @expectedException Doctrine\Common\Persistence\Mapping\MappingException + * @expectedException \Doctrine\Common\Persistence\Mapping\MappingException * @expectedExceptionMessage Invalid mapping file 'Doctrine.Tests.Models.Generic.SerializationModel.dcm.xml' for class 'Doctrine\Tests\Models\Generic\SerializationModel'. */ public function testInvalidMappingFileException() { - $this->createClassMetadata('Doctrine\Tests\Models\Generic\SerializationModel'); + $this->createClassMetadata(SerializationModel::class); } /** @@ -147,8 +153,8 @@ public function testInvalidMappingFileException() */ public function testValidateXmlSchema($xmlMappingFile) { - $xsdSchemaFile = __DIR__ . '/../../../../../doctrine-mapping.xsd'; - $dom = new \DOMDocument('UTF-8'); + $xsdSchemaFile = __DIR__ . '/../../../../../doctrine-mapping.xsd'; + $dom = new \DOMDocument(); $dom->load($xmlMappingFile); @@ -158,19 +164,51 @@ public function testValidateXmlSchema($xmlMappingFile) static public function dataValidSchema() { $list = glob(__DIR__ . '/xml/*.xml'); - $invalid = array( + $invalid = [ 'Doctrine.Tests.Models.DDC889.DDC889Class.dcm' - ); + ]; $list = array_filter($list, function($item) use ($invalid){ return ! in_array(pathinfo($item, PATHINFO_FILENAME), $invalid); }); return array_map(function($item){ - return array($item); + return [$item]; }, $list); } + /** + * @group GH-7141 + */ + public function testOneToManyDefaultOrderByAsc() + { + $driver = $this->_loadDriver(); + $class = new ClassMetadata(GH7141Article::class); + + $class->initializeReflection(new RuntimeReflectionService()); + $driver->loadMetadataForClass(GH7141Article::class, $class); + + + $this->assertEquals( + Criteria::ASC, + $class->getMetadataValue('associationMappings')['tags']['orderBy']['position'] + ); + } + + public function testManyToManyDefaultOrderByAsc() : void + { + $class = new ClassMetadata(GH7316Article::class); + $class->initializeReflection(new RuntimeReflectionService()); + + $driver = $this->_loadDriver(); + $driver->loadMetadataForClass(GH7316Article::class, $class); + + self::assertEquals( + Criteria::ASC, + $class->getMetadataValue('associationMappings')['tags']['orderBy']['position'] + ); + } + /** * @group DDC-889 * @expectedException \Doctrine\Common\Persistence\Mapping\MappingException @@ -178,7 +216,7 @@ static public function dataValidSchema() */ public function testinvalidEntityOrMappedSuperClassShouldMentionParentClasses() { - $this->createClassMetadata('Doctrine\Tests\Models\DDC889\DDC889Class'); + $this->createClassMetadata(DDC889Class::class); } } diff --git a/tests/Doctrine/Tests/ORM/Mapping/YamlMappingDriverTest.php b/tests/Doctrine/Tests/ORM/Mapping/YamlMappingDriverTest.php index c752c6a82ee..7781b1622f7 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/YamlMappingDriverTest.php +++ b/tests/Doctrine/Tests/ORM/Mapping/YamlMappingDriverTest.php @@ -2,15 +2,22 @@ namespace Doctrine\Tests\ORM\Mapping; -use Doctrine\ORM\Mapping\ClassMetadata, - Doctrine\ORM\Mapping\Driver\YamlDriver; +use Doctrine\ORM\Mapping\ClassMetadata; use Doctrine\ORM\Mapping\ClassMetadataFactory; +use Doctrine\ORM\Mapping\Driver\YamlDriver; +use Doctrine\Tests\Models\DirectoryTree\Directory; +use Doctrine\Tests\Models\DirectoryTree\File; +use Doctrine\Tests\Models\Generic\SerializationModel; +use Doctrine\Tests\VerifyDeprecations; +use Symfony\Component\Yaml\Yaml; class YamlMappingDriverTest extends AbstractMappingDriverTest { + use VerifyDeprecations; + protected function _loadDriver() { - if (!class_exists('Symfony\Component\Yaml\Yaml', true)) { + if (!class_exists(Yaml::class, true)) { $this->markTestSkipped('Please install Symfony YAML Component into the include path of your PHP installation.'); } @@ -25,20 +32,21 @@ protected function _loadDriver() public function testJoinTablesWithMappedSuperclassForYamlDriver() { $yamlDriver = $this->_loadDriver(); - $yamlDriver->getLocator()->addPaths(array(__DIR__ . DIRECTORY_SEPARATOR . 'yaml')); + $yamlDriver->getLocator()->addPaths([__DIR__ . DIRECTORY_SEPARATOR . 'yaml']); $em = $this->_getTestEntityManager(); $em->getConfiguration()->setMetadataDriverImpl($yamlDriver); $factory = new ClassMetadataFactory(); $factory->setEntityManager($em); - $classPage = new ClassMetadata('Doctrine\Tests\Models\DirectoryTree\File'); - $classPage = $factory->getMetadataFor('Doctrine\Tests\Models\DirectoryTree\File'); - $this->assertEquals('Doctrine\Tests\Models\DirectoryTree\File', $classPage->associationMappings['parentDirectory']['sourceEntity']); + $classPage = new ClassMetadata(File::class); + $classPage = $factory->getMetadataFor(File::class); + $this->assertEquals(File::class, $classPage->associationMappings['parentDirectory']['sourceEntity']); - $classDirectory = new ClassMetadata('Doctrine\Tests\Models\DirectoryTree\Directory'); - $classDirectory = $factory->getMetadataFor('Doctrine\Tests\Models\DirectoryTree\Directory'); - $this->assertEquals('Doctrine\Tests\Models\DirectoryTree\Directory', $classDirectory->associationMappings['parentDirectory']['sourceEntity']); + $classDirectory = new ClassMetadata(Directory::class); + $classDirectory = $factory->getMetadataFor(Directory::class); + $this->assertEquals(Directory::class, $classDirectory->associationMappings['parentDirectory']['sourceEntity']); + $this->assertHasDeprecationMessages(); } /** @@ -49,7 +57,7 @@ public function testJoinTablesWithMappedSuperclassForYamlDriver() */ public function testInvalidMappingFileException() { - $this->createClassMetadata('Doctrine\Tests\Models\Generic\SerializationModel'); + $this->createClassMetadata(SerializationModel::class); } /** @@ -57,7 +65,7 @@ public function testInvalidMappingFileException() */ public function testSpacesShouldBeIgnoredWhenUseExplode() { - $metadata = $this->createClassMetadata(__NAMESPACE__.'\DDC2069Entity'); + $metadata = $this->createClassMetadata(DDC2069Entity::class); $unique = $metadata->table['uniqueConstraints'][0]['columns']; $indexes = $metadata->table['indexes'][0]['columns']; @@ -72,6 +80,13 @@ public function testSpacesShouldBeIgnoredWhenUseExplode() $this->assertEquals(255, $nameField['length']); $this->assertEquals(255, $valueField['length']); + $this->assertHasDeprecationMessages(); + } + + public function testDeprecation() : void + { + $this->createClassMetadata(DDC2069Entity::class); + $this->expectDeprecationMessage('YAML mapping driver is deprecated and will be removed in Doctrine ORM 3.0, please migrate to annotation or XML driver.'); } } diff --git a/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.CMS.CmsAddress.php b/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.CMS.CmsAddress.php index b0ac6cadeb2..7238eb15a05 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.CMS.CmsAddress.php +++ b/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.CMS.CmsAddress.php @@ -1,100 +1,127 @@ setPrimaryTable(array( +use Doctrine\ORM\Events; +use Doctrine\Tests\Models\CMS\CmsAddress; + +$metadata->setPrimaryTable( + [ 'name' => 'company_person', -)); + ] +); -$metadata->mapField(array ( +$metadata->mapField( + [ 'id' => true, 'fieldName' => 'id', 'type' => 'integer', -)); + ] +); -$metadata->mapField(array ( +$metadata->mapField( + [ 'fieldName' => 'zip', 'length' => 50, -)); + ] +); -$metadata->mapField(array ( +$metadata->mapField( + [ 'fieldName' => 'city', 'length' => 50, -)); + ] +); -$metadata->mapOneToOne(array( +$metadata->mapOneToOne( + [ 'fieldName' => 'user', 'targetEntity' => 'CmsUser', - 'joinColumns' => array(array('referencedColumnName' => 'id')) -)); + 'joinColumns' => [['referencedColumnName' => 'id']] + ] +); -$metadata->addNamedNativeQuery(array ( +$metadata->addNamedNativeQuery( + [ 'name' => 'find-all', 'query' => 'SELECT id, country, city FROM cms_addresses', 'resultSetMapping' => 'mapping-find-all', -)); + ] +); -$metadata->addNamedNativeQuery(array ( +$metadata->addNamedNativeQuery( + [ 'name' => 'find-by-id', 'query' => 'SELECT * FROM cms_addresses WHERE id = ?', - 'resultClass' => 'Doctrine\\Tests\\Models\\CMS\\CmsAddress', -)); + 'resultClass' => CmsAddress::class, + ] +); -$metadata->addNamedNativeQuery(array ( +$metadata->addNamedNativeQuery( + [ 'name' => 'count', 'query' => 'SELECT COUNT(*) AS count FROM cms_addresses', 'resultSetMapping' => 'mapping-count', -)); + ] +); -$metadata->addSqlResultSetMapping(array ( +$metadata->addSqlResultSetMapping( + [ 'name' => 'mapping-find-all', - 'columns' => array(), - 'entities' => array ( array ( - 'fields' => array ( - array ( + 'columns' => [], + 'entities' => [ + [ + 'fields' => [ + [ 'name' => 'id', 'column' => 'id', - ), - array ( + ], + [ 'name' => 'city', 'column' => 'city', - ), - array ( + ], + [ 'name' => 'country', 'column' => 'country', - ), - ), - 'entityClass' => 'Doctrine\Tests\Models\CMS\CmsAddress', - ), - ), -)); - -$metadata->addSqlResultSetMapping(array ( + ], + ], + 'entityClass' => CmsAddress::class, + ], + ], + ] +); + +$metadata->addSqlResultSetMapping( + [ 'name' => 'mapping-without-fields', - 'columns' => array(), - 'entities' => array(array ( - 'entityClass' => 'Doctrine\\Tests\\Models\\CMS\\CmsAddress', - 'fields' => array() - ) - ) -)); - -$metadata->addSqlResultSetMapping(array ( + 'columns' => [], + 'entities' => [ + [ + 'entityClass' => CmsAddress::class, + 'fields' => [] + ] + ] + ] +); + +$metadata->addSqlResultSetMapping( + [ 'name' => 'mapping-count', - 'columns' =>array ( - array ( + 'columns' => [ + [ 'name' => 'count', - ), - ) -)); + ], + ] + ] +); -$metadata->addEntityListener(\Doctrine\ORM\Events::postPersist, 'CmsAddressListener', 'postPersist'); -$metadata->addEntityListener(\Doctrine\ORM\Events::prePersist, 'CmsAddressListener', 'prePersist'); +$metadata->addEntityListener(Events::postPersist, 'CmsAddressListener', 'postPersist'); +$metadata->addEntityListener(Events::prePersist, 'CmsAddressListener', 'prePersist'); -$metadata->addEntityListener(\Doctrine\ORM\Events::postUpdate, 'CmsAddressListener', 'postUpdate'); -$metadata->addEntityListener(\Doctrine\ORM\Events::preUpdate, 'CmsAddressListener', 'preUpdate'); +$metadata->addEntityListener(Events::postUpdate, 'CmsAddressListener', 'postUpdate'); +$metadata->addEntityListener(Events::preUpdate, 'CmsAddressListener', 'preUpdate'); -$metadata->addEntityListener(\Doctrine\ORM\Events::postRemove, 'CmsAddressListener', 'postRemove'); -$metadata->addEntityListener(\Doctrine\ORM\Events::preRemove, 'CmsAddressListener', 'preRemove'); +$metadata->addEntityListener(Events::postRemove, 'CmsAddressListener', 'postRemove'); +$metadata->addEntityListener(Events::preRemove, 'CmsAddressListener', 'preRemove'); -$metadata->addEntityListener(\Doctrine\ORM\Events::preFlush, 'CmsAddressListener', 'preFlush'); -$metadata->addEntityListener(\Doctrine\ORM\Events::postLoad, 'CmsAddressListener', 'postLoad'); \ No newline at end of file +$metadata->addEntityListener(Events::preFlush, 'CmsAddressListener', 'preFlush'); +$metadata->addEntityListener(Events::postLoad, 'CmsAddressListener', 'postLoad'); diff --git a/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.CMS.CmsUser.php b/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.CMS.CmsUser.php index dfa89851a04..4b0075ecfe4 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.CMS.CmsUser.php +++ b/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.CMS.CmsUser.php @@ -1,184 +1,213 @@ setPrimaryTable(array( +use Doctrine\Tests\Models\CMS\CmsAddress; +use Doctrine\Tests\Models\CMS\CmsUser; + +$metadata->setPrimaryTable( + [ 'name' => 'cms_users', -)); + ] +); -$metadata->addNamedNativeQuery(array ( +$metadata->addNamedNativeQuery( + [ 'name' => 'fetchIdAndUsernameWithResultClass', 'query' => 'SELECT id, username FROM cms_users WHERE username = ?', - 'resultClass' => 'Doctrine\\Tests\\Models\\CMS\\CmsUser', -)); + 'resultClass' => CmsUser::class, + ] +); -$metadata->addNamedNativeQuery(array ( +$metadata->addNamedNativeQuery( + [ 'name' => 'fetchAllColumns', 'query' => 'SELECT * FROM cms_users WHERE username = ?', - 'resultClass' => 'Doctrine\\Tests\\Models\\CMS\\CmsUser', -)); + 'resultClass' => CmsUser::class, + ] +); -$metadata->addNamedNativeQuery(array ( +$metadata->addNamedNativeQuery( + [ 'name' => 'fetchJoinedAddress', 'query' => 'SELECT u.id, u.name, u.status, a.id AS a_id, a.country, a.zip, a.city FROM cms_users u INNER JOIN cms_addresses a ON u.id = a.user_id WHERE u.username = ?', 'resultSetMapping' => 'mappingJoinedAddress', -)); + ] +); -$metadata->addNamedNativeQuery(array ( +$metadata->addNamedNativeQuery( + [ 'name' => 'fetchJoinedPhonenumber', 'query' => 'SELECT id, name, status, phonenumber AS number FROM cms_users INNER JOIN cms_phonenumbers ON id = user_id WHERE username = ?', 'resultSetMapping' => 'mappingJoinedPhonenumber', -)); + ] +); -$metadata->addNamedNativeQuery(array ( +$metadata->addNamedNativeQuery( + [ 'name' => 'fetchUserPhonenumberCount', 'query' => 'SELECT id, name, status, COUNT(phonenumber) AS numphones FROM cms_users INNER JOIN cms_phonenumbers ON id = user_id WHERE username IN (?) GROUP BY id, name, status, username ORDER BY username', 'resultSetMapping' => 'mappingUserPhonenumberCount', -)); + ] +); -$metadata->addNamedNativeQuery(array ( +$metadata->addNamedNativeQuery( + [ "name" => "fetchMultipleJoinsEntityResults", "resultSetMapping" => "mappingMultipleJoinsEntityResults", "query" => "SELECT u.id AS u_id, u.name AS u_name, u.status AS u_status, a.id AS a_id, a.zip AS a_zip, a.country AS a_country, COUNT(p.phonenumber) AS numphones FROM cms_users u INNER JOIN cms_addresses a ON u.id = a.user_id INNER JOIN cms_phonenumbers p ON u.id = p.user_id GROUP BY u.id, u.name, u.status, u.username, a.id, a.zip, a.country ORDER BY u.username" -)); + ] +); -$metadata->addSqlResultSetMapping(array ( +$metadata->addSqlResultSetMapping( + [ 'name' => 'mappingJoinedAddress', - 'columns' => array(), - 'entities' => array(array ( - 'fields'=> array ( - array ( + 'columns' => [], + 'entities' => [ + [ + 'fields'=> [ + [ 'name' => 'id', 'column' => 'id', - ), - array ( + ], + [ 'name' => 'name', 'column' => 'name', - ), - array ( + ], + [ 'name' => 'status', 'column' => 'status', - ), - array ( + ], + [ 'name' => 'address.zip', 'column' => 'zip', - ), - array ( + ], + [ 'name' => 'address.city', 'column' => 'city', - ), - array ( + ], + [ 'name' => 'address.country', 'column' => 'country', - ), - array ( + ], + [ 'name' => 'address.id', 'column' => 'a_id', - ), - ), - 'entityClass' => 'Doctrine\Tests\Models\CMS\CmsUser', + ], + ], + 'entityClass' => CmsUser::class, 'discriminatorColumn' => null - ), - ), -)); + ], + ], + ] +); -$metadata->addSqlResultSetMapping(array ( +$metadata->addSqlResultSetMapping( + [ 'name' => 'mappingJoinedPhonenumber', - 'columns' => array(), - 'entities' => array(array( - 'fields'=> array ( - array ( + 'columns' => [], + 'entities' => [ + [ + 'fields'=> [ + [ 'name' => 'id', 'column' => 'id', - ), - array ( + ], + [ 'name' => 'name', 'column' => 'name', - ), - array ( + ], + [ 'name' => 'status', 'column' => 'status', - ), - array ( + ], + [ 'name' => 'phonenumbers.phonenumber', 'column' => 'number', - ), - ), - 'entityClass' => 'Doctrine\\Tests\\Models\\CMS\\CmsUser', + ], + ], + 'entityClass' => CmsUser::class, 'discriminatorColumn' => null - ), - ), -)); + ], + ], + ] +); -$metadata->addSqlResultSetMapping(array ( +$metadata->addSqlResultSetMapping( + [ 'name' => 'mappingUserPhonenumberCount', - 'columns' => array(), - 'entities' => array ( - array( - 'fields' => array ( - array ( + 'columns' => [], + 'entities' => [ + [ + 'fields' => [ + [ 'name' => 'id', 'column' => 'id', - ), - array ( + ], + [ 'name' => 'name', 'column' => 'name', - ), - array ( + ], + [ 'name' => 'status', 'column' => 'status', - ) - ), - 'entityClass' => 'Doctrine\Tests\Models\CMS\CmsUser', + ] + ], + 'entityClass' => CmsUser::class, 'discriminatorColumn' => null - ) - ), - 'columns' => array ( - array ( + ] + ], + 'columns' => [ + [ 'name' => 'numphones', - ) - ) -)); + ] + ] + ] +); -$metadata->addSqlResultSetMapping(array( +$metadata->addSqlResultSetMapping( + [ 'name' => 'mappingMultipleJoinsEntityResults', - 'entities' => array(array( - 'fields' => array( - array( + 'entities' => [ + [ + 'fields' => [ + [ 'name' => 'id', 'column' => 'u_id', - ), - array( + ], + [ 'name' => 'name', 'column' => 'u_name', - ), - array( + ], + [ 'name' => 'status', 'column' => 'u_status', - ) - ), - 'entityClass' => 'Doctrine\Tests\Models\CMS\CmsUser', + ] + ], + 'entityClass' => CmsUser::class, 'discriminatorColumn' => null, - ), - array( - 'fields' => array( - array( + ], + [ + 'fields' => [ + [ 'name' => 'id', 'column' => 'a_id', - ), - array( + ], + [ 'name' => 'zip', 'column' => 'a_zip', - ), - array( + ], + [ 'name' => 'country', 'column' => 'a_country', - ), - ), - 'entityClass' => 'Doctrine\Tests\Models\CMS\CmsAddress', + ], + ], + 'entityClass' => CmsAddress::class, 'discriminatorColumn' => null, - ), - ), - 'columns' => array(array( + ], + ], + 'columns' => [ + [ 'name' => 'numphones', - ) - ) -)); \ No newline at end of file + ] + ] + ] +); diff --git a/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.Cache.City.php b/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.Cache.City.php index 6dd477fa628..6ee9a78fc0b 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.Cache.City.php +++ b/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.Cache.City.php @@ -1,54 +1,73 @@ setInheritanceType(ClassMetadataInfo::INHERITANCE_TYPE_NONE); -$metadata->setPrimaryTable(array('name' => 'cache_city')); +$metadata->setPrimaryTable(['name' => 'cache_city']); $metadata->setIdGeneratorType(ClassMetadataInfo::GENERATOR_TYPE_IDENTITY); $metadata->setChangeTrackingPolicy(ClassMetadataInfo::CHANGETRACKING_DEFERRED_IMPLICIT); -$metadata->enableCache(array( +$metadata->enableCache( + [ 'usage' => ClassMetadataInfo::CACHE_USAGE_READ_ONLY -)); + ] +); -$metadata->mapField(array( +$metadata->mapField( + [ 'fieldName' => 'id', 'type' => 'integer', 'id' => true, - )); + ] +); -$metadata->mapField(array( +$metadata->mapField( + [ 'fieldName' => 'name', 'type' => 'string', -)); + ] +); -$metadata->mapOneToOne(array( +$metadata->mapOneToOne( + [ 'fieldName' => 'state', - 'targetEntity' => 'Doctrine\\Tests\\Models\\Cache\\State', + 'targetEntity' => State::class, 'inversedBy' => 'cities', 'joinColumns' => - array(array( + [ + [ 'name' => 'state_id', 'referencedColumnName' => 'id', - )) -)); -$metadata->enableAssociationCache('state', array( + ] + ] + ] +); +$metadata->enableAssociationCache('state', [ 'usage' => ClassMetadataInfo::CACHE_USAGE_READ_ONLY -)); +] +); -$metadata->mapManyToMany(array( +$metadata->mapManyToMany( + [ 'fieldName' => 'travels', - 'targetEntity' => 'Doctrine\\Tests\\Models\\Cache\\Travel', + 'targetEntity' => Travel::class, 'mappedBy' => 'visitedCities', -)); + ] +); -$metadata->mapOneToMany(array( +$metadata->mapOneToMany( + [ 'fieldName' => 'attractions', - 'targetEntity' => 'Doctrine\\Tests\\Models\\Cache\\Attraction', + 'targetEntity' => Attraction::class, 'mappedBy' => 'city', - 'orderBy' => array('name' => 'ASC',), -)); -$metadata->enableAssociationCache('attractions', array( + 'orderBy' => ['name' => 'ASC',], + ] +); +$metadata->enableAssociationCache('attractions', [ 'usage' => ClassMetadataInfo::CACHE_USAGE_READ_ONLY -)); \ No newline at end of file +] +); diff --git a/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.Company.CompanyContract.php b/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.Company.CompanyContract.php index d307ba7f10b..33389ce9530 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.Company.CompanyContract.php +++ b/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.Company.CompanyContract.php @@ -4,28 +4,36 @@ $metadata->setInheritanceType(ClassMetadataInfo::INHERITANCE_TYPE_JOINED); $metadata->setTableName( 'company_contracts'); -$metadata->setDiscriminatorColumn(array( +$metadata->setDiscriminatorColumn( + [ 'name' => 'discr', 'type' => 'string', -)); + ] +); -$metadata->mapField(array( +$metadata->mapField( + [ 'id' => true, 'name' => 'id', 'fieldName' => 'id', -)); + ] +); -$metadata->mapField(array( +$metadata->mapField( + [ 'type' => 'boolean', 'name' => 'completed', 'fieldName' => 'completed', -)); + ] +); -$metadata->setDiscriminatorMap(array( +$metadata->setDiscriminatorMap( + [ "fix" => "CompanyFixContract", "flexible" => "CompanyFlexContract", "flexultra" => "CompanyFlexUltraContract" -)); + ] +); $metadata->addEntityListener(\Doctrine\ORM\Events::postPersist, 'CompanyContractListener', 'postPersistHandler'); $metadata->addEntityListener(\Doctrine\ORM\Events::prePersist, 'CompanyContractListener', 'prePersistHandler'); @@ -37,4 +45,4 @@ $metadata->addEntityListener(\Doctrine\ORM\Events::preRemove, 'CompanyContractListener', 'preRemoveHandler'); $metadata->addEntityListener(\Doctrine\ORM\Events::preFlush, 'CompanyContractListener', 'preFlushHandler'); -$metadata->addEntityListener(\Doctrine\ORM\Events::postLoad, 'CompanyContractListener', 'postLoadHandler'); \ No newline at end of file +$metadata->addEntityListener(\Doctrine\ORM\Events::postLoad, 'CompanyContractListener', 'postLoadHandler'); diff --git a/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.Company.CompanyFixContract.php b/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.Company.CompanyFixContract.php index 79b117729ed..3ea44ee7399 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.Company.CompanyFixContract.php +++ b/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.Company.CompanyFixContract.php @@ -1,7 +1,9 @@ mapField(array( +$metadata->mapField( + [ 'type' => 'integer', 'name' => 'fixPrice', 'fieldName' => 'fixPrice', -)); \ No newline at end of file + ] +); diff --git a/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.Company.CompanyFlexContract.php b/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.Company.CompanyFlexContract.php index 5f1542dde41..7cc2b5504c9 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.Company.CompanyFlexContract.php +++ b/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.Company.CompanyFlexContract.php @@ -1,13 +1,17 @@ mapField(array( +$metadata->mapField( + [ 'type' => 'integer', 'name' => 'hoursWorked', 'fieldName' => 'hoursWorked', -)); + ] +); -$metadata->mapField(array( +$metadata->mapField( + [ 'type' => 'integer', 'name' => 'pricePerHour', 'fieldName' => 'pricePerHour', -)); + ] +); diff --git a/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.Company.CompanyFlexUltraContract.php b/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.Company.CompanyFlexUltraContract.php index d16d4f3f547..9e392416ded 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.Company.CompanyFlexUltraContract.php +++ b/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.Company.CompanyFlexUltraContract.php @@ -1,10 +1,12 @@ mapField(array( +$metadata->mapField( + [ 'type' => 'integer', 'name' => 'maxPrice', 'fieldName' => 'maxPrice', -)); + ] +); $metadata->addEntityListener(\Doctrine\ORM\Events::postPersist, 'CompanyContractListener', 'postPersistHandler'); $metadata->addEntityListener(\Doctrine\ORM\Events::prePersist, 'CompanyContractListener', 'prePersistHandler'); @@ -18,4 +20,4 @@ $metadata->addEntityListener(\Doctrine\ORM\Events::postLoad, 'CompanyContractListener', 'postLoadHandler'); $metadata->addEntityListener(\Doctrine\ORM\Events::prePersist, 'CompanyFlexUltraContractListener', 'prePersistHandler1'); -$metadata->addEntityListener(\Doctrine\ORM\Events::prePersist, 'CompanyFlexUltraContractListener', 'prePersistHandler2'); \ No newline at end of file +$metadata->addEntityListener(\Doctrine\ORM\Events::prePersist, 'CompanyFlexUltraContractListener', 'prePersistHandler2'); diff --git a/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.Company.CompanyPerson.php b/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.Company.CompanyPerson.php index 32cc813da2e..d92bd218b8f 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.Company.CompanyPerson.php +++ b/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.Company.CompanyPerson.php @@ -1,37 +1,48 @@ setPrimaryTable(array( +use Doctrine\Tests\Models\Company\CompanyPerson; + +$metadata->setPrimaryTable( + [ 'name' => 'company_person', -)); + ] +); -$metadata->addNamedNativeQuery(array ( +$metadata->addNamedNativeQuery( + [ 'name' => 'fetchAllWithResultClass', 'query' => 'SELECT id, name, discr FROM company_persons ORDER BY name', - 'resultClass' => 'Doctrine\\Tests\\Models\\Company\\CompanyPerson', -)); + 'resultClass' => CompanyPerson::class, + ] +); -$metadata->addNamedNativeQuery(array ( +$metadata->addNamedNativeQuery( + [ 'name' => 'fetchAllWithSqlResultSetMapping', 'query' => 'SELECT id, name, discr AS discriminator FROM company_persons ORDER BY name', 'resultSetMapping' => 'mappingFetchAll', -)); + ] +); -$metadata->addSqlResultSetMapping(array ( +$metadata->addSqlResultSetMapping( + [ 'name' => 'mappingFetchAll', - 'columns' => array(), - 'entities' => array ( array ( - 'fields' => array ( - array ( + 'columns' => [], + 'entities' => [ + [ + 'fields' => [ + [ 'name' => 'id', 'column' => 'id', - ), - array ( + ], + [ 'name' => 'name', 'column' => 'name', - ), - ), - 'entityClass' => 'Doctrine\Tests\Models\Company\CompanyPerson', + ], + ], + 'entityClass' => CompanyPerson::class, 'discriminatorColumn' => 'discriminator', - ), - ), -)); \ No newline at end of file + ], + ], + ] +); diff --git a/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.DDC1476.DDC1476EntityWithDefaultFieldType.php b/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.DDC1476.DDC1476EntityWithDefaultFieldType.php index 56a99633a86..62459aad000 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.DDC1476.DDC1476EntityWithDefaultFieldType.php +++ b/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.DDC1476.DDC1476EntityWithDefaultFieldType.php @@ -2,11 +2,15 @@ use Doctrine\ORM\Mapping\ClassMetadataInfo; -$metadata->mapField(array( +$metadata->mapField( + [ 'id' => true, 'fieldName' => 'id', -)); -$metadata->mapField(array( + ] +); +$metadata->mapField( + [ 'fieldName' => 'name' -)); -$metadata->setIdGeneratorType(ClassMetadataInfo::GENERATOR_TYPE_NONE); \ No newline at end of file + ] +); +$metadata->setIdGeneratorType(ClassMetadataInfo::GENERATOR_TYPE_NONE); diff --git a/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.DDC2825.ExplicitSchemaAndTable.php b/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.DDC2825.ExplicitSchemaAndTable.php index 4a163c9bd01..85128c9ae4a 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.DDC2825.ExplicitSchemaAndTable.php +++ b/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.DDC2825.ExplicitSchemaAndTable.php @@ -4,14 +4,18 @@ /* @var $metadata ClassMetadata */ -$metadata->setPrimaryTable(array( +$metadata->setPrimaryTable( + [ 'name' => 'explicit_table', 'schema' => 'explicit_schema', -)); + ] +); -$metadata->mapField(array( +$metadata->mapField( + [ 'id' => true, 'fieldName' => 'id', -)); + ] +); $metadata->setIdGeneratorType(ClassMetadata::GENERATOR_TYPE_AUTO); diff --git a/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.DDC2825.SchemaAndTableInTableName.php b/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.DDC2825.SchemaAndTableInTableName.php index 045a9785817..fb2edfcfb26 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.DDC2825.SchemaAndTableInTableName.php +++ b/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.DDC2825.SchemaAndTableInTableName.php @@ -4,13 +4,17 @@ /* @var $metadata ClassMetadata */ -$metadata->setPrimaryTable(array( +$metadata->setPrimaryTable( + [ 'name' => 'implicit_schema.implicit_table', -)); + ] +); -$metadata->mapField(array( +$metadata->mapField( + [ 'id' => true, 'fieldName' => 'id', -)); + ] +); $metadata->setIdGeneratorType(ClassMetadata::GENERATOR_TYPE_AUTO); diff --git a/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.DDC3579.DDC3579Admin.php b/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.DDC3579.DDC3579Admin.php index dd59e65faff..9b7c87b3e9b 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.DDC3579.DDC3579Admin.php +++ b/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.DDC3579.DDC3579Admin.php @@ -1,5 +1,6 @@ setAssociationOverride('groups', array( +$metadata->setAssociationOverride('groups', [ 'inversedBy' => 'admins' -)); +] +); diff --git a/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.DDC3579.DDC3579User.php b/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.DDC3579.DDC3579User.php index 1eb3555ecc3..49aeacb1eee 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.DDC3579.DDC3579User.php +++ b/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.DDC3579.DDC3579User.php @@ -2,26 +2,32 @@ use Doctrine\ORM\Mapping\ClassMetadataInfo; -$metadata->mapField(array( +$metadata->mapField( + [ 'id' => true, 'fieldName' => 'id', 'type' => 'integer', 'columnName' => 'user_id', 'length' => 150, -)); + ] +); -$metadata->mapField(array( +$metadata->mapField( + [ 'fieldName' => 'name', 'type' => 'string', 'columnName'=> 'user_name', 'nullable' => true, 'unique' => false, 'length' => 250, -)); + ] +); -$metadata->mapManyToMany(array( +$metadata->mapManyToMany( + [ 'fieldName' => 'groups', 'targetEntity' => 'DDC3579Group' -)); + ] +); $metadata->setIdGeneratorType(ClassMetadataInfo::GENERATOR_TYPE_AUTO); diff --git a/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.DDC5934.DDC5934BaseContract.php b/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.DDC5934.DDC5934BaseContract.php new file mode 100644 index 00000000000..fca4bb1185e --- /dev/null +++ b/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.DDC5934.DDC5934BaseContract.php @@ -0,0 +1,17 @@ +mapField([ + 'id' => true, + 'fieldName' => 'id', + 'type' => 'integer', + 'columnName' => 'id', +]); + +$metadata->mapManyToMany([ + 'fieldName' => 'members', + 'targetEntity' => 'DDC5934Member', +]); + +$metadata->setIdGeneratorType(ClassMetadata::GENERATOR_TYPE_AUTO); diff --git a/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.DDC5934.DDC5934Contract.php b/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.DDC5934.DDC5934Contract.php new file mode 100644 index 00000000000..3ecf178a63c --- /dev/null +++ b/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.DDC5934.DDC5934Contract.php @@ -0,0 +1,7 @@ +setAssociationOverride('members', [ + 'fetch' => ClassMetadata::FETCH_EXTRA_LAZY, +]); diff --git a/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.DDC869.DDC869ChequePayment.php b/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.DDC869.DDC869ChequePayment.php index ad8b86d9e55..e97e16f9596 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.DDC869.DDC869ChequePayment.php +++ b/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.DDC869.DDC869ChequePayment.php @@ -1,5 +1,7 @@ mapField(array( +$metadata->mapField( + [ 'fieldName' => 'serialNumber', 'type' => 'string', -)); \ No newline at end of file + ] +); diff --git a/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.DDC869.DDC869CreditCardPayment.php b/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.DDC869.DDC869CreditCardPayment.php index 1318333a8f7..de9d8dae0ee 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.DDC869.DDC869CreditCardPayment.php +++ b/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.DDC869.DDC869CreditCardPayment.php @@ -1,5 +1,7 @@ mapField(array( +$metadata->mapField( + [ 'fieldName' => 'creditCardNumber', 'type' => 'string', -)); \ No newline at end of file + ] +); diff --git a/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.DDC869.DDC869Payment.php b/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.DDC869.DDC869Payment.php index 1d1f551ba35..1f3f12b2d5f 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.DDC869.DDC869Payment.php +++ b/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.DDC869.DDC869Payment.php @@ -1,17 +1,22 @@ mapField(array( +$metadata->mapField( + [ 'id' => true, 'fieldName' => 'id', 'type' => 'integer', 'columnName' => 'id', -)); -$metadata->mapField(array( + ] +); +$metadata->mapField( + [ 'fieldName' => 'value', 'type' => 'float', - )); + ] +); $metadata->isMappedSuperclass = true; -$metadata->setCustomRepositoryClass("Doctrine\Tests\Models\DDC869\DDC869PaymentRepository"); -$metadata->setIdGeneratorType(ClassMetadataInfo::GENERATOR_TYPE_AUTO); \ No newline at end of file +$metadata->setCustomRepositoryClass(DDC869PaymentRepository::class); +$metadata->setIdGeneratorType(ClassMetadataInfo::GENERATOR_TYPE_AUTO); diff --git a/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.DDC889.DDC889Class.php b/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.DDC889.DDC889Class.php index 90cfdc10bfd..e1161da1360 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.DDC889.DDC889Class.php +++ b/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.DDC889.DDC889Class.php @@ -2,11 +2,13 @@ use Doctrine\ORM\Mapping\ClassMetadataInfo; -$metadata->mapField(array( +$metadata->mapField( + [ 'id' => true, 'fieldName' => 'id', 'type' => 'integer', 'columnName' => 'id', -)); + ] +); -//$metadata->setIdGeneratorType(ClassMetadataInfo::GENERATOR_TYPE_AUTO); \ No newline at end of file +//$metadata->setIdGeneratorType(ClassMetadataInfo::GENERATOR_TYPE_AUTO); diff --git a/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.DDC889.DDC889SuperClass.php b/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.DDC889.DDC889SuperClass.php index e56cc9bfdea..f7f4816a8a3 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.DDC889.DDC889SuperClass.php +++ b/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.DDC889.DDC889SuperClass.php @@ -1,11 +1,14 @@ mapField(array( +$metadata->mapField( + [ 'fieldName' => 'name', 'type' => 'string', - )); + ] +); $metadata->isMappedSuperclass = true; -$metadata->setCustomRepositoryClass("Doctrine\Tests\Models\DDC889\DDC889SuperClass"); -$metadata->setIdGeneratorType(ClassMetadataInfo::GENERATOR_TYPE_AUTO); \ No newline at end of file +$metadata->setCustomRepositoryClass(DDC889SuperClass::class); +$metadata->setIdGeneratorType(ClassMetadataInfo::GENERATOR_TYPE_AUTO); diff --git a/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.DDC964.DDC964Admin.php b/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.DDC964.DDC964Admin.php index bb8920e7676..10175feca96 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.DDC964.DDC964Admin.php +++ b/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.DDC964.DDC964Admin.php @@ -1,21 +1,29 @@ setAssociationOverride('address',array( - 'joinColumns'=>array(array( +$metadata->setAssociationOverride('address', + [ + 'joinColumns'=> [ + [ 'name' => 'adminaddress_id', 'referencedColumnName' => 'id', - )) -)); + ] + ] + ] +); -$metadata->setAssociationOverride('groups',array( - 'joinTable' => array ( +$metadata->setAssociationOverride('groups', + [ + 'joinTable' => [ 'name' => 'ddc964_users_admingroups', - 'joinColumns' => array(array( + 'joinColumns' => [ + [ 'name' => 'adminuser_id', - )), + ] + ], - 'inverseJoinColumns' =>array (array ( + 'inverseJoinColumns' => [[ 'name' => 'admingroup_id', - )) - ) -)); \ No newline at end of file + ]] + ] + ] +); diff --git a/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.DDC964.DDC964Guest.php b/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.DDC964.DDC964Guest.php index 5094ecddf43..28f6f48c592 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.DDC964.DDC964Guest.php +++ b/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.DDC964.DDC964Guest.php @@ -1,13 +1,16 @@ setAttributeOverride('id', array( +$metadata->setAttributeOverride('id', [ 'columnName' => 'guest_id', 'type' => 'integer', 'length' => 140, -)); +] +); -$metadata->setAttributeOverride('name',array( +$metadata->setAttributeOverride('name', + [ 'columnName' => 'guest_name', 'nullable' => false, 'unique' => true, 'length' => 240, -)); \ No newline at end of file + ] +); diff --git a/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.DDC964.DDC964User.php b/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.DDC964.DDC964User.php index 7b66deef0c6..dc445f1ca6c 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.DDC964.DDC964User.php +++ b/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.Models.DDC964.DDC964User.php @@ -2,45 +2,57 @@ use Doctrine\ORM\Mapping\ClassMetadataInfo; -$metadata->mapField(array( +$metadata->mapField( + [ 'id' => true, 'fieldName' => 'id', 'type' => 'integer', 'columnName' => 'user_id', 'length' => 150, -)); -$metadata->mapField(array( + ] +); +$metadata->mapField( + [ 'fieldName' => 'name', 'type' => 'string', 'columnName'=> 'user_name', 'nullable' => true, 'unique' => false, 'length' => 250, -)); + ] +); -$metadata->mapManyToOne(array( +$metadata->mapManyToOne( + [ 'fieldName' => 'address', 'targetEntity' => 'DDC964Address', - 'cascade' => array('persist','merge'), - 'joinColumn' => array('name'=>'address_id', 'referencedColumnMame'=>'id'), -)); + 'cascade' => ['persist','merge'], + 'joinColumn' => ['name'=>'address_id', 'referencedColumnMame'=>'id'], + ] +); -$metadata->mapManyToMany(array( +$metadata->mapManyToMany( + [ 'fieldName' => 'groups', 'targetEntity' => 'DDC964Group', 'inversedBy' => 'users', - 'cascade' => array('persist','merge','detach'), - 'joinTable' => array( + 'cascade' => ['persist','merge','detach'], + 'joinTable' => [ 'name' => 'ddc964_users_groups', - 'joinColumns' => array(array( + 'joinColumns' => [ + [ 'name'=>'user_id', 'referencedColumnName'=>'id', - )), - 'inverseJoinColumns'=>array(array( + ] + ], + 'inverseJoinColumns'=> [ + [ 'name'=>'group_id', 'referencedColumnName'=>'id', - )) - ) -)); + ] + ] + ] + ] +); -$metadata->setIdGeneratorType(ClassMetadataInfo::GENERATOR_TYPE_AUTO); \ No newline at end of file +$metadata->setIdGeneratorType(ClassMetadataInfo::GENERATOR_TYPE_AUTO); diff --git a/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.ORM.Mapping.Animal.php b/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.ORM.Mapping.Animal.php index 005178eedee..5000a68a229 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.ORM.Mapping.Animal.php +++ b/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.ORM.Mapping.Animal.php @@ -1,21 +1,28 @@ setInheritanceType(ClassMetadataInfo::INHERITANCE_TYPE_SINGLE_TABLE); -$metadata->setDiscriminatorColumn(array( +$metadata->setDiscriminatorColumn( + [ 'name' => 'dtype', 'type' => 'string', 'length' => 255, 'fieldName' => 'dtype', - )); -$metadata->setDiscriminatorMap(array( - 'cat' => 'Doctrine\\Tests\\ORM\\Mapping\\Cat', - 'dog' => 'Doctrine\\Tests\\ORM\\Mapping\\Dog', - )); + ] +); +$metadata->setDiscriminatorMap( + [ + 'cat' => Cat::class, + 'dog' => Dog::class, + ] +); $metadata->setChangeTrackingPolicy(ClassMetadataInfo::CHANGETRACKING_DEFERRED_IMPLICIT); -$metadata->mapField(array( +$metadata->mapField( + [ 'fieldName' => 'id', 'type' => 'string', 'length' => NULL, @@ -25,6 +32,7 @@ 'unique' => false, 'id' => true, 'columnName' => 'id', - )); + ] +); $metadata->setIdGeneratorType(ClassMetadataInfo::GENERATOR_TYPE_CUSTOM); -$metadata->setCustomGeneratorDefinition(array("class" => "stdClass")); +$metadata->setCustomGeneratorDefinition(["class" => "stdClass"]); diff --git a/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.ORM.Mapping.Comment.php b/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.ORM.Mapping.Comment.php index 85cbed4dc58..a33ebbaeb37 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.ORM.Mapping.Comment.php +++ b/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.ORM.Mapping.Comment.php @@ -3,13 +3,16 @@ use Doctrine\ORM\Mapping\ClassMetadataInfo; $metadata->setInheritanceType(ClassMetadataInfo::INHERITANCE_TYPE_NONE); -$metadata->setPrimaryTable(array( - 'indexes' => array( - array('columns' => array('content'), 'flags' => array('fulltext'), 'options'=> array('where' => 'content IS NOT NULL')) - ) - )); +$metadata->setPrimaryTable( + [ + 'indexes' => [ + ['columns' => ['content'], 'flags' => ['fulltext'], 'options'=> ['where' => 'content IS NOT NULL']] + ] + ] +); -$metadata->mapField(array( +$metadata->mapField( + [ 'fieldName' => 'content', 'type' => 'text', 'scale' => 0, @@ -18,4 +21,5 @@ 'nullable' => false, 'precision' => 0, 'columnName' => 'content', -)); \ No newline at end of file + ] +); diff --git a/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.ORM.Mapping.DDC1170Entity.php b/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.ORM.Mapping.DDC1170Entity.php index 97f4624bad6..dd442ceb0e4 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.ORM.Mapping.DDC1170Entity.php +++ b/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.ORM.Mapping.DDC1170Entity.php @@ -2,15 +2,19 @@ use Doctrine\ORM\Mapping\ClassMetadataInfo; -$metadata->mapField(array( +$metadata->mapField( + [ 'id' => true, 'fieldName' => 'id', 'columnDefinition' => 'INT unsigned NOT NULL', -)); + ] +); -$metadata->mapField(array( +$metadata->mapField( + [ 'fieldName' => 'value', 'columnDefinition' => 'VARCHAR(255) NOT NULL' -)); + ] +); -$metadata->setIdGeneratorType(ClassMetadataInfo::GENERATOR_TYPE_NONE); \ No newline at end of file +$metadata->setIdGeneratorType(ClassMetadataInfo::GENERATOR_TYPE_NONE); diff --git a/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.ORM.Mapping.DDC807Entity.php b/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.ORM.Mapping.DDC807Entity.php index 1682d7a0de8..c9d8ad9f29d 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.ORM.Mapping.DDC807Entity.php +++ b/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.ORM.Mapping.DDC807Entity.php @@ -2,14 +2,18 @@ use Doctrine\ORM\Mapping\ClassMetadataInfo; -$metadata->mapField(array( +$metadata->mapField( + [ 'id' => true, 'fieldName' => 'id', -)); + ] +); -$metadata->setDiscriminatorColumn(array( +$metadata->setDiscriminatorColumn( + [ 'name' => "dtype", 'columnDefinition' => "ENUM('ONE','TWO')" -)); + ] +); -$metadata->setIdGeneratorType(ClassMetadataInfo::GENERATOR_TYPE_NONE); \ No newline at end of file +$metadata->setIdGeneratorType(ClassMetadataInfo::GENERATOR_TYPE_NONE); diff --git a/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.ORM.Mapping.PHPSLC.php b/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.ORM.Mapping.PHPSLC.php index c9341958a67..ad1ed23bfc7 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.ORM.Mapping.PHPSLC.php +++ b/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.ORM.Mapping.PHPSLC.php @@ -2,11 +2,15 @@ use Doctrine\ORM\Mapping\ClassMetadataInfo; -$metadata->enableCache(array( +$metadata->enableCache( + [ 'usage' => ClassMetadataInfo::CACHE_USAGE_READ_ONLY -)); -$metadata->mapManyToOne(array( + ] +); +$metadata->mapManyToOne( + [ 'fieldName' => 'foo', 'id' => true, 'targetEntity' => 'PHPSLCFoo' -)); \ No newline at end of file + ] +); diff --git a/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.ORM.Mapping.User.php b/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.ORM.Mapping.User.php index 67dbd752d3e..b716893b6fb 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.ORM.Mapping.User.php +++ b/tests/Doctrine/Tests/ORM/Mapping/php/Doctrine.Tests.ORM.Mapping.User.php @@ -1,128 +1,149 @@ setInheritanceType(ClassMetadataInfo::INHERITANCE_TYPE_NONE); -$metadata->setPrimaryTable(array( +$metadata->setPrimaryTable( + [ 'name' => 'cms_users', - )); + ] +); $metadata->setChangeTrackingPolicy(ClassMetadataInfo::CHANGETRACKING_DEFERRED_IMPLICIT); $metadata->addLifecycleCallback('doStuffOnPrePersist', 'prePersist'); $metadata->addLifecycleCallback('doOtherStuffOnPrePersistToo', 'prePersist'); $metadata->addLifecycleCallback('doStuffOnPostPersist', 'postPersist'); -$metadata->addNamedQuery(array( +$metadata->addNamedQuery( + [ 'name' => 'all', 'query' => 'SELECT u FROM __CLASS__ u' -)); -$metadata->mapField(array( + ] +); +$metadata->mapField( + [ 'id' => true, 'fieldName' => 'id', 'type' => 'integer', 'columnName' => 'id', - 'options' => array('foo' => 'bar'), - )); -$metadata->mapField(array( + 'options' => ['foo' => 'bar', 'unsigned' => false], + ] +); +$metadata->mapField( + [ 'fieldName' => 'name', 'type' => 'string', 'length' => 50, 'unique' => true, 'nullable' => true, 'columnName' => 'name', - 'options' => array('foo' => 'bar', 'baz' => array('key' => 'val')), - )); -$metadata->mapField(array( + 'options' => ['foo' => 'bar', 'baz' => ['key' => 'val'], 'fixed' => false], + ] +); +$metadata->mapField( + [ 'fieldName' => 'email', 'type' => 'string', 'columnName' => 'user_email', 'columnDefinition' => 'CHAR(32) NOT NULL', - )); -$mapping = array('fieldName' => 'version', 'type' => 'integer'); + ] +); +$mapping = ['fieldName' => 'version', 'type' => 'integer']; $metadata->setVersionMapping($mapping); $metadata->mapField($mapping); $metadata->setIdGeneratorType(ClassMetadataInfo::GENERATOR_TYPE_AUTO); -$metadata->mapOneToOne(array( +$metadata->mapOneToOne( + [ 'fieldName' => 'address', - 'targetEntity' => 'Doctrine\\Tests\\ORM\\Mapping\\Address', + 'targetEntity' => Address::class, 'cascade' => - array( + [ 0 => 'remove', - ), + ], 'mappedBy' => NULL, 'inversedBy' => 'user', 'joinColumns' => - array( + [ 0 => - array( + [ 'name' => 'address_id', 'referencedColumnName' => 'id', 'onDelete' => 'CASCADE', - ), - ), + ], + ], 'orphanRemoval' => false, - )); -$metadata->mapOneToMany(array( + ] +); +$metadata->mapOneToMany( + [ 'fieldName' => 'phonenumbers', - 'targetEntity' => 'Doctrine\\Tests\\ORM\\Mapping\\Phonenumber', + 'targetEntity' => Phonenumber::class, 'cascade' => - array( + [ 1 => 'persist', - ), + ], 'mappedBy' => 'user', 'orphanRemoval' => true, 'orderBy' => - array( + [ 'number' => 'ASC', - ), - )); -$metadata->mapManyToMany(array( + ], + ] +); +$metadata->mapManyToMany( + [ 'fieldName' => 'groups', - 'targetEntity' => 'Doctrine\\Tests\\ORM\\Mapping\\Group', + 'targetEntity' => Group::class, 'cascade' => - array( + [ 0 => 'remove', 1 => 'persist', 2 => 'refresh', 3 => 'merge', 4 => 'detach', - ), + ], 'mappedBy' => NULL, 'joinTable' => - array( + [ 'name' => 'cms_users_groups', 'joinColumns' => - array( + [ 0 => - array( + [ 'name' => 'user_id', 'referencedColumnName' => 'id', 'unique' => false, 'nullable' => false, - ), - ), + ], + ], 'inverseJoinColumns' => - array( + [ 0 => - array( + [ 'name' => 'group_id', 'referencedColumnName' => 'id', 'columnDefinition' => 'INT NULL', - ), - ), - ), + ], + ], + ], 'orderBy' => NULL, - )); -$metadata->table['options'] = array( - 'foo' => 'bar', - 'baz' => array('key' => 'val') -); -$metadata->table['uniqueConstraints'] = array( - 'search_idx' => array('columns' => array('name', 'user_email'), 'options' => array('where' => 'name IS NOT NULL')), + ] ); -$metadata->table['indexes'] = array( - 'name_idx' => array('columns' => array('name')), 0 => array('columns' => array('user_email')) -); -$metadata->setSequenceGeneratorDefinition(array( +$metadata->table['options'] = [ + 'foo' => 'bar', + 'baz' => ['key' => 'val'] +]; +$metadata->table['uniqueConstraints'] = [ + 'search_idx' => ['columns' => ['name', 'user_email'], 'options' => ['where' => 'name IS NOT NULL']], +]; +$metadata->table['indexes'] = [ + 'name_idx' => ['columns' => ['name']], 0 => ['columns' => ['user_email']] +]; +$metadata->setSequenceGeneratorDefinition( + [ 'sequenceName' => 'tablename_seq', 'allocationSize' => 100, 'initialValue' => 1, - )); + ] +); diff --git a/tests/Doctrine/Tests/ORM/Mapping/xml/CatNoId.dcm.xml b/tests/Doctrine/Tests/ORM/Mapping/xml/CatNoId.dcm.xml index 6025d350f1e..3f2457bd3d3 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/xml/CatNoId.dcm.xml +++ b/tests/Doctrine/Tests/ORM/Mapping/xml/CatNoId.dcm.xml @@ -1,7 +1,7 @@ + https://www.doctrine-project.org/schemas/orm/doctrine-mapping.xsd"> diff --git a/tests/Doctrine/Tests/ORM/Mapping/xml/DDC2429Book.orm.xml b/tests/Doctrine/Tests/ORM/Mapping/xml/DDC2429Book.orm.xml index 8640c6f51c4..08e26406bbd 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/xml/DDC2429Book.orm.xml +++ b/tests/Doctrine/Tests/ORM/Mapping/xml/DDC2429Book.orm.xml @@ -2,7 +2,7 @@ + https://www.doctrine-project.org/schemas/orm/doctrine-mapping.xsd"> diff --git a/tests/Doctrine/Tests/ORM/Mapping/xml/DDC2429Novel.orm.xml b/tests/Doctrine/Tests/ORM/Mapping/xml/DDC2429Novel.orm.xml index 43ce9428519..5a6f3f89fb8 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/xml/DDC2429Novel.orm.xml +++ b/tests/Doctrine/Tests/ORM/Mapping/xml/DDC2429Novel.orm.xml @@ -1,7 +1,7 @@ + https://www.doctrine-project.org/schemas/orm/doctrine-mapping.xsd"> diff --git a/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.Models.CMS.CmsAddress.dcm.xml b/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.Models.CMS.CmsAddress.dcm.xml index 7e7bd5aaa2f..e4b80346c43 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.Models.CMS.CmsAddress.dcm.xml +++ b/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.Models.CMS.CmsAddress.dcm.xml @@ -1,7 +1,7 @@ + https://www.doctrine-project.org/schemas/orm/doctrine-mapping.xsd"> diff --git a/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.Models.CMS.CmsUser.dcm.xml b/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.Models.CMS.CmsUser.dcm.xml index 122a45e6fe9..f91ed311512 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.Models.CMS.CmsUser.dcm.xml +++ b/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.Models.CMS.CmsUser.dcm.xml @@ -3,8 +3,8 @@ - + https://www.doctrine-project.org/schemas/orm/doctrine-mapping.xsd"> + diff --git a/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.Models.Cache.City.dcm.xml b/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.Models.Cache.City.dcm.xml index 84b786a7bd7..415302d0a80 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.Models.Cache.City.dcm.xml +++ b/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.Models.Cache.City.dcm.xml @@ -1,5 +1,5 @@ - + diff --git a/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.Models.Company.CompanyContract.dcm.xml b/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.Models.Company.CompanyContract.dcm.xml index 4fa0c23e1ff..b775e3ccc76 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.Models.Company.CompanyContract.dcm.xml +++ b/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.Models.Company.CompanyContract.dcm.xml @@ -3,8 +3,8 @@ - + https://www.doctrine-project.org/schemas/orm/doctrine-mapping.xsd"> + diff --git a/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.Models.Company.CompanyFixContract.dcm.xml b/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.Models.Company.CompanyFixContract.dcm.xml index bd1019d6894..bfa5431fc21 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.Models.Company.CompanyFixContract.dcm.xml +++ b/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.Models.Company.CompanyFixContract.dcm.xml @@ -3,8 +3,8 @@ - + https://www.doctrine-project.org/schemas/orm/doctrine-mapping.xsd"> + diff --git a/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.Models.Company.CompanyFlexContract.dcm.xml b/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.Models.Company.CompanyFlexContract.dcm.xml index 91ef0bb1ce0..21ca4238d1f 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.Models.Company.CompanyFlexContract.dcm.xml +++ b/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.Models.Company.CompanyFlexContract.dcm.xml @@ -3,8 +3,8 @@ - + https://www.doctrine-project.org/schemas/orm/doctrine-mapping.xsd"> + diff --git a/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.Models.Company.CompanyFlexUltraContract.dcm.xml b/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.Models.Company.CompanyFlexUltraContract.dcm.xml index 729bdfda035..381e67571f0 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.Models.Company.CompanyFlexUltraContract.dcm.xml +++ b/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.Models.Company.CompanyFlexUltraContract.dcm.xml @@ -3,8 +3,8 @@ - + https://www.doctrine-project.org/schemas/orm/doctrine-mapping.xsd"> + diff --git a/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.Models.Company.CompanyPerson.dcm.xml b/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.Models.Company.CompanyPerson.dcm.xml index 2ddd88a3249..d8db5107341 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.Models.Company.CompanyPerson.dcm.xml +++ b/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.Models.Company.CompanyPerson.dcm.xml @@ -3,8 +3,8 @@ - + https://www.doctrine-project.org/schemas/orm/doctrine-mapping.xsd"> + diff --git a/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.Models.DDC117.DDC117Translation.dcm.xml b/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.Models.DDC117.DDC117Translation.dcm.xml index ec3bc74fd5a..019f201b04a 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.Models.DDC117.DDC117Translation.dcm.xml +++ b/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.Models.DDC117.DDC117Translation.dcm.xml @@ -2,7 +2,7 @@ + https://www.doctrine-project.org/schemas/orm/doctrine-mapping.xsd"> diff --git a/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.Models.DDC1476.DDC1476EntityWithDefaultFieldType.dcm.xml b/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.Models.DDC1476.DDC1476EntityWithDefaultFieldType.dcm.xml index 29b5f1db5cd..fedfeada509 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.Models.DDC1476.DDC1476EntityWithDefaultFieldType.dcm.xml +++ b/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.Models.DDC1476.DDC1476EntityWithDefaultFieldType.dcm.xml @@ -2,8 +2,8 @@ - + https://www.doctrine-project.org/schemas/orm/doctrine-mapping.xsd"> + diff --git a/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.Models.DDC2825.ExplicitSchemaAndTable.dcm.xml b/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.Models.DDC2825.ExplicitSchemaAndTable.dcm.xml index 11bb55706d0..57063fb6ca4 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.Models.DDC2825.ExplicitSchemaAndTable.dcm.xml +++ b/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.Models.DDC2825.ExplicitSchemaAndTable.dcm.xml @@ -3,7 +3,7 @@ xmlns="http://doctrine-project.org/schemas/orm/doctrine-mapping" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://doctrine-project.org/schemas/orm/doctrine-mapping - https://raw.github.com/doctrine/doctrine2/master/doctrine-mapping.xsd" + https://www.doctrine-project.org/schemas/orm/doctrine-mapping.xsd" > diff --git a/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.Models.DDC2825.SchemaAndTableInTableName.dcm.xml b/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.Models.DDC2825.SchemaAndTableInTableName.dcm.xml index 3a89dd97369..b520f626cf1 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.Models.DDC2825.SchemaAndTableInTableName.dcm.xml +++ b/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.Models.DDC2825.SchemaAndTableInTableName.dcm.xml @@ -3,7 +3,7 @@ xmlns="http://doctrine-project.org/schemas/orm/doctrine-mapping" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://doctrine-project.org/schemas/orm/doctrine-mapping - https://raw.github.com/doctrine/doctrine2/master/doctrine-mapping.xsd" + https://www.doctrine-project.org/schemas/orm/doctrine-mapping.xsd" > diff --git a/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.Models.DDC3293.DDC3293Address.dcm.xml b/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.Models.DDC3293.DDC3293Address.dcm.xml index 39c0f33b2d0..54fbae8b410 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.Models.DDC3293.DDC3293Address.dcm.xml +++ b/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.Models.DDC3293.DDC3293Address.dcm.xml @@ -3,7 +3,7 @@ xmlns="http://doctrine-project.org/schemas/orm/doctrine-mapping" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://doctrine-project.org/schemas/orm/doctrine-mapping - https://raw.github.com/doctrine/doctrine2/master/doctrine-mapping.xsd"> + https://www.doctrine-project.org/schemas/orm/doctrine-mapping.xsd"> diff --git a/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.Models.DDC3293.DDC3293User.dcm.xml b/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.Models.DDC3293.DDC3293User.dcm.xml index bf24c1fd65d..c2d1e44910f 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.Models.DDC3293.DDC3293User.dcm.xml +++ b/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.Models.DDC3293.DDC3293User.dcm.xml @@ -3,7 +3,7 @@ xmlns="http://doctrine-project.org/schemas/orm/doctrine-mapping" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://doctrine-project.org/schemas/orm/doctrine-mapping - https://raw.github.com/doctrine/doctrine2/master/doctrine-mapping.xsd"> + https://www.doctrine-project.org/schemas/orm/doctrine-mapping.xsd"> diff --git a/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.Models.DDC3293.DDC3293UserPrefixed.dcm.xml b/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.Models.DDC3293.DDC3293UserPrefixed.dcm.xml index 1e0df304c05..3988ab32539 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.Models.DDC3293.DDC3293UserPrefixed.dcm.xml +++ b/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.Models.DDC3293.DDC3293UserPrefixed.dcm.xml @@ -3,7 +3,7 @@ xmlns="http://doctrine-project.org/schemas/orm/doctrine-mapping" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://doctrine-project.org/schemas/orm/doctrine-mapping - https://raw.github.com/doctrine/doctrine2/master/doctrine-mapping.xsd"> + https://www.doctrine-project.org/schemas/orm/doctrine-mapping.xsd"> diff --git a/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.Models.DDC3579.DDC3579Admin.dcm.xml b/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.Models.DDC3579.DDC3579Admin.dcm.xml index 1f92867067e..00695adbb28 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.Models.DDC3579.DDC3579Admin.dcm.xml +++ b/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.Models.DDC3579.DDC3579Admin.dcm.xml @@ -2,7 +2,7 @@ + https://www.doctrine-project.org/schemas/orm/doctrine-mapping.xsd"> diff --git a/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.Models.DDC3579.DDC3579User.dcm.xml b/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.Models.DDC3579.DDC3579User.dcm.xml index 3b6e213f121..a93fb6938ba 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.Models.DDC3579.DDC3579User.dcm.xml +++ b/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.Models.DDC3579.DDC3579User.dcm.xml @@ -2,7 +2,7 @@ + https://www.doctrine-project.org/schemas/orm/doctrine-mapping.xsd"> diff --git a/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.Models.DDC5934.DDC5934BaseContract.dcm.xml b/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.Models.DDC5934.DDC5934BaseContract.dcm.xml new file mode 100644 index 00000000000..07809813177 --- /dev/null +++ b/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.Models.DDC5934.DDC5934BaseContract.dcm.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + diff --git a/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.Models.DDC5934.DDC5934Contract.dcm.xml b/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.Models.DDC5934.DDC5934Contract.dcm.xml new file mode 100644 index 00000000000..4bd3f5af27f --- /dev/null +++ b/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.Models.DDC5934.DDC5934Contract.dcm.xml @@ -0,0 +1,13 @@ + + + + + + + + + + diff --git a/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.Models.DDC869.DDC869ChequePayment.dcm.xml b/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.Models.DDC869.DDC869ChequePayment.dcm.xml index 05e2540eff7..fcc022f7937 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.Models.DDC869.DDC869ChequePayment.dcm.xml +++ b/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.Models.DDC869.DDC869ChequePayment.dcm.xml @@ -2,7 +2,7 @@ + http://doctrine-project.org/schemas/orm/doctrine-mapping.xsd"> diff --git a/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.Models.DDC869.DDC869CreditCardPayment.dcm.xml b/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.Models.DDC869.DDC869CreditCardPayment.dcm.xml index daf01f03402..bcd02647ece 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.Models.DDC869.DDC869CreditCardPayment.dcm.xml +++ b/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.Models.DDC869.DDC869CreditCardPayment.dcm.xml @@ -2,8 +2,8 @@ - + https://www.doctrine-project.org/schemas/orm/doctrine-mapping.xsd"> + diff --git a/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.Models.DDC869.DDC869Payment.dcm.xml b/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.Models.DDC869.DDC869Payment.dcm.xml index be9f760b951..90426f1b096 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.Models.DDC869.DDC869Payment.dcm.xml +++ b/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.Models.DDC869.DDC869Payment.dcm.xml @@ -2,7 +2,7 @@ + http://doctrine-project.org/schemas/orm/doctrine-mapping.xsd"> diff --git a/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.Models.DDC889.DDC889Class.dcm.xml b/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.Models.DDC889.DDC889Class.dcm.xml index 4a8935c9a74..86e04112161 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.Models.DDC889.DDC889Class.dcm.xml +++ b/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.Models.DDC889.DDC889Class.dcm.xml @@ -2,8 +2,8 @@ - + https://www.doctrine-project.org/schemas/orm/doctrine-mapping.xsd"> + diff --git a/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.Models.DDC889.DDC889Entity.dcm.xml b/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.Models.DDC889.DDC889Entity.dcm.xml index 686bdbfc761..b366cbb6068 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.Models.DDC889.DDC889Entity.dcm.xml +++ b/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.Models.DDC889.DDC889Entity.dcm.xml @@ -2,8 +2,8 @@ - + https://www.doctrine-project.org/schemas/orm/doctrine-mapping.xsd"> + diff --git a/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.Models.DDC889.DDC889SuperClass.dcm.xml b/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.Models.DDC889.DDC889SuperClass.dcm.xml index 48fa4fb83f6..4b174a393e2 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.Models.DDC889.DDC889SuperClass.dcm.xml +++ b/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.Models.DDC889.DDC889SuperClass.dcm.xml @@ -2,8 +2,8 @@ - + https://www.doctrine-project.org/schemas/orm/doctrine-mapping.xsd"> + diff --git a/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.Models.DDC964.DDC964Admin.dcm.xml b/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.Models.DDC964.DDC964Admin.dcm.xml index f4bb4ebce0a..ea6e22fdbda 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.Models.DDC964.DDC964Admin.dcm.xml +++ b/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.Models.DDC964.DDC964Admin.dcm.xml @@ -2,8 +2,8 @@ - + https://www.doctrine-project.org/schemas/orm/doctrine-mapping.xsd"> + diff --git a/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.Models.DDC964.DDC964Guest.dcm.xml b/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.Models.DDC964.DDC964Guest.dcm.xml index 561066f6b83..5ad7a1e1488 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.Models.DDC964.DDC964Guest.dcm.xml +++ b/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.Models.DDC964.DDC964Guest.dcm.xml @@ -2,8 +2,8 @@ - + https://www.doctrine-project.org/schemas/orm/doctrine-mapping.xsd"> + diff --git a/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.Models.DDC964.DDC964User.dcm.xml b/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.Models.DDC964.DDC964User.dcm.xml index 68db74b48e5..83b878840a5 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.Models.DDC964.DDC964User.dcm.xml +++ b/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.Models.DDC964.DDC964User.dcm.xml @@ -2,8 +2,8 @@ - + https://www.doctrine-project.org/schemas/orm/doctrine-mapping.xsd"> + diff --git a/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.Models.GH7141.GH7141Article.dcm.xml b/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.Models.GH7141.GH7141Article.dcm.xml new file mode 100644 index 00000000000..34813ab7ef1 --- /dev/null +++ b/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.Models.GH7141.GH7141Article.dcm.xml @@ -0,0 +1,14 @@ + + + + + + + + + + + diff --git a/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.Models.GH7316.GH7316Article.dcm.xml b/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.Models.GH7316.GH7316Article.dcm.xml new file mode 100644 index 00000000000..3820cdc9be3 --- /dev/null +++ b/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.Models.GH7316.GH7316Article.dcm.xml @@ -0,0 +1,14 @@ + + + + + + + + + + + diff --git a/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.Models.Generic.SerializationModel.dcm.xml b/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.Models.Generic.SerializationModel.dcm.xml index 36af855f2a7..5974da2640a 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.Models.Generic.SerializationModel.dcm.xml +++ b/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.Models.Generic.SerializationModel.dcm.xml @@ -2,7 +2,7 @@ + https://www.doctrine-project.org/schemas/orm/doctrine-mapping.xsd"> diff --git a/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.Models.ValueObjects.Name.dcm.xml b/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.Models.ValueObjects.Name.dcm.xml index 97bb6a90eec..0cb3aed27ef 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.Models.ValueObjects.Name.dcm.xml +++ b/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.Models.ValueObjects.Name.dcm.xml @@ -2,7 +2,7 @@ + https://www.doctrine-project.org/schemas/orm/doctrine-mapping.xsd"> diff --git a/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.Models.ValueObjects.Person.dcm.xml b/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.Models.ValueObjects.Person.dcm.xml index c2480bca7d2..68752703815 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.Models.ValueObjects.Person.dcm.xml +++ b/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.Models.ValueObjects.Person.dcm.xml @@ -2,7 +2,7 @@ + https://www.doctrine-project.org/schemas/orm/doctrine-mapping.xsd"> diff --git a/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.ORM.Mapping.Animal.dcm.xml b/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.ORM.Mapping.Animal.dcm.xml index a4c4e9bfda7..8ad0e2a6522 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.ORM.Mapping.Animal.dcm.xml +++ b/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.ORM.Mapping.Animal.dcm.xml @@ -2,7 +2,7 @@ + https://www.doctrine-project.org/schemas/orm/doctrine-mapping.xsd"> diff --git a/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.ORM.Mapping.CTI.dcm.xml b/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.ORM.Mapping.CTI.dcm.xml index 14abaef7340..b26ca1089c6 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.ORM.Mapping.CTI.dcm.xml +++ b/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.ORM.Mapping.CTI.dcm.xml @@ -2,7 +2,7 @@ + https://www.doctrine-project.org/schemas/orm/doctrine-mapping.xsd"> diff --git a/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.ORM.Mapping.Comment.dcm.xml b/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.ORM.Mapping.Comment.dcm.xml index 8f02ca852c3..e83232f1a9f 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.ORM.Mapping.Comment.dcm.xml +++ b/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.ORM.Mapping.Comment.dcm.xml @@ -3,7 +3,7 @@ + https://www.doctrine-project.org/schemas/orm/doctrine-mapping.xsd"> diff --git a/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.ORM.Mapping.DDC1170Entity.dcm.xml b/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.ORM.Mapping.DDC1170Entity.dcm.xml index 9f5ad7fac65..a77f2e1bc48 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.ORM.Mapping.DDC1170Entity.dcm.xml +++ b/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.ORM.Mapping.DDC1170Entity.dcm.xml @@ -2,8 +2,8 @@ - + https://www.doctrine-project.org/schemas/orm/doctrine-mapping.xsd"> + diff --git a/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.ORM.Mapping.DDC807Entity.dcm.xml b/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.ORM.Mapping.DDC807Entity.dcm.xml index 82711dc2f89..9a33752340d 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.ORM.Mapping.DDC807Entity.dcm.xml +++ b/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.ORM.Mapping.DDC807Entity.dcm.xml @@ -2,8 +2,8 @@ - + https://www.doctrine-project.org/schemas/orm/doctrine-mapping.xsd"> + diff --git a/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.ORM.Mapping.SingleTableEntityIncompleteDiscriminatorColumnMapping.dcm.xml b/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.ORM.Mapping.SingleTableEntityIncompleteDiscriminatorColumnMapping.dcm.xml index 5dffe178d0b..af274cdafdd 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.ORM.Mapping.SingleTableEntityIncompleteDiscriminatorColumnMapping.dcm.xml +++ b/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.ORM.Mapping.SingleTableEntityIncompleteDiscriminatorColumnMapping.dcm.xml @@ -2,8 +2,8 @@ - + https://www.doctrine-project.org/schemas/orm/doctrine-mapping.xsd"> + diff --git a/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.ORM.Mapping.SingleTableEntityNoDiscriminatorColumnMapping.dcm.xml b/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.ORM.Mapping.SingleTableEntityNoDiscriminatorColumnMapping.dcm.xml index 3e03f4498eb..8f2854550eb 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.ORM.Mapping.SingleTableEntityNoDiscriminatorColumnMapping.dcm.xml +++ b/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.ORM.Mapping.SingleTableEntityNoDiscriminatorColumnMapping.dcm.xml @@ -2,8 +2,8 @@ - + https://www.doctrine-project.org/schemas/orm/doctrine-mapping.xsd"> + diff --git a/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.ORM.Mapping.User.dcm.xml b/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.ORM.Mapping.User.dcm.xml index 28b1e057122..1fa06126334 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.ORM.Mapping.User.dcm.xml +++ b/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.ORM.Mapping.User.dcm.xml @@ -3,7 +3,7 @@ + https://www.doctrine-project.org/schemas/orm/doctrine-mapping.xsd"> @@ -41,6 +41,7 @@ + @@ -50,6 +51,7 @@ + diff --git a/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.ORM.Mapping.XMLSLC.dcm.xml b/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.ORM.Mapping.XMLSLC.dcm.xml index ca8092b50d5..1dec40d7f92 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.ORM.Mapping.XMLSLC.dcm.xml +++ b/tests/Doctrine/Tests/ORM/Mapping/xml/Doctrine.Tests.ORM.Mapping.XMLSLC.dcm.xml @@ -2,7 +2,7 @@ + https://www.doctrine-project.org/schemas/orm/doctrine-mapping.xsd"> diff --git a/tests/Doctrine/Tests/ORM/Mapping/yaml/Doctrine.Tests.Models.CMS.CmsUser.dcm.yml b/tests/Doctrine/Tests/ORM/Mapping/yaml/Doctrine.Tests.Models.CMS.CmsUser.dcm.yml index 3a03dd6c32e..329e3d061dc 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/yaml/Doctrine.Tests.Models.CMS.CmsUser.dcm.yml +++ b/tests/Doctrine/Tests/ORM/Mapping/yaml/Doctrine.Tests.Models.CMS.CmsUser.dcm.yml @@ -135,7 +135,6 @@ Doctrine\Tests\Models\CMS\CmsUser: name: address_id referencedColumnName: id cascade: [ persist ] - oneToOne: email: targetEntity: CmsEmail orphanRemoval: true @@ -155,4 +154,4 @@ Doctrine\Tests\Models\CMS\CmsUser: inverseJoinColumns: group_id: referencedColumnName: id - cascade: [ persist , detach, merge] \ No newline at end of file + cascade: [ persist , detach, merge] diff --git a/tests/Doctrine/Tests/ORM/Mapping/yaml/Doctrine.Tests.Models.Company.CompanyPerson.dcm.yml b/tests/Doctrine/Tests/ORM/Mapping/yaml/Doctrine.Tests.Models.Company.CompanyPerson.dcm.yml index 26846c5debd..28eec43e391 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/yaml/Doctrine.Tests.Models.Company.CompanyPerson.dcm.yml +++ b/tests/Doctrine/Tests/ORM/Mapping/yaml/Doctrine.Tests.Models.Company.CompanyPerson.dcm.yml @@ -52,7 +52,6 @@ Doctrine\Tests\Models\Company\CompanyPerson: name: address_id referencedColumnName: id cascade: [ persist ] - oneToOne: email: targetEntity: CmsEmail orphanRemoval: true @@ -72,4 +71,4 @@ Doctrine\Tests\Models\Company\CompanyPerson: inverseJoinColumns: group_id: referencedColumnName: id - cascade: [ persist , detach, merge] \ No newline at end of file + cascade: [ persist , detach, merge] diff --git a/tests/Doctrine/Tests/ORM/Mapping/yaml/Doctrine.Tests.Models.DDC5934.DDC5934BaseContract.dcm.yml b/tests/Doctrine/Tests/ORM/Mapping/yaml/Doctrine.Tests.Models.DDC5934.DDC5934BaseContract.dcm.yml new file mode 100644 index 00000000000..2044c9be527 --- /dev/null +++ b/tests/Doctrine/Tests/ORM/Mapping/yaml/Doctrine.Tests.Models.DDC5934.DDC5934BaseContract.dcm.yml @@ -0,0 +1,12 @@ +Doctrine\Tests\Models\DDC5934\DDC5934BaseContract: + type: mappedSuperclass + id: + id: + type: integer + column: id + generator: + strategy: AUTO + manyToMany: + members: + targetEntity: DDC5934Member + inversedBy: contract diff --git a/tests/Doctrine/Tests/ORM/Mapping/yaml/Doctrine.Tests.Models.DDC5934.DDC5934Contract.dcm.yml b/tests/Doctrine/Tests/ORM/Mapping/yaml/Doctrine.Tests.Models.DDC5934.DDC5934Contract.dcm.yml new file mode 100644 index 00000000000..45ba145853e --- /dev/null +++ b/tests/Doctrine/Tests/ORM/Mapping/yaml/Doctrine.Tests.Models.DDC5934.DDC5934Contract.dcm.yml @@ -0,0 +1,5 @@ +Doctrine\Tests\Models\DDC5934\DDC5934Contract: + type: entity + associationOverride: + members: + fetch: EXTRA_LAZY diff --git a/tests/Doctrine/Tests/ORM/Mapping/yaml/Doctrine.Tests.ORM.Mapping.User.dcm.yml b/tests/Doctrine/Tests/ORM/Mapping/yaml/Doctrine.Tests.ORM.Mapping.User.dcm.yml index 457b24eea77..e3a32ce76be 100644 --- a/tests/Doctrine/Tests/ORM/Mapping/yaml/Doctrine.Tests.ORM.Mapping.User.dcm.yml +++ b/tests/Doctrine/Tests/ORM/Mapping/yaml/Doctrine.Tests.ORM.Mapping.User.dcm.yml @@ -18,6 +18,7 @@ Doctrine\Tests\ORM\Mapping\User: initialValue: 1 options: foo: bar + unsigned: false fields: name: type: string @@ -28,6 +29,7 @@ Doctrine\Tests\ORM\Mapping\User: foo: bar baz: key: val + fixed: false email: type: string column: user_email diff --git a/tests/Doctrine/Tests/ORM/ORMInvalidArgumentExceptionTest.php b/tests/Doctrine/Tests/ORM/ORMInvalidArgumentExceptionTest.php new file mode 100644 index 00000000000..dea8d4f7732 --- /dev/null +++ b/tests/Doctrine/Tests/ORM/ORMInvalidArgumentExceptionTest.php @@ -0,0 +1,152 @@ +getMessage()); + } + + /** + * @return string[][] + */ + public function invalidEntityNames() + { + return [ + [null, 'Entity name must be a string, NULL given'], + [true, 'Entity name must be a string, boolean given'], + [123, 'Entity name must be a string, integer given'], + [123.45, 'Entity name must be a string, double given'], + [new \stdClass(), 'Entity name must be a string, object given'], + ]; + } + + /** + * @dataProvider newEntitiesFoundThroughRelationshipsErrorMessages + */ + public function testNewEntitiesFoundThroughRelationships(array $newEntities, string $expectedMessage) : void + { + $exception = ORMInvalidArgumentException::newEntitiesFoundThroughRelationships($newEntities); + + self::assertInstanceOf(ORMInvalidArgumentException::class, $exception); + self::assertSame($expectedMessage, $exception->getMessage()); + } + + public function newEntitiesFoundThroughRelationshipsErrorMessages() : array + { + $stringEntity3 = uniqid('entity3', true); + $entity1 = new \stdClass(); + $entity2 = new \stdClass(); + $entity3 = $this->getMockBuilder(\stdClass::class)->setMethods(['__toString'])->getMock(); + $association1 = [ + 'sourceEntity' => 'foo1', + 'fieldName' => 'bar1', + 'targetEntity' => 'baz1', + ]; + $association2 = [ + 'sourceEntity' => 'foo2', + 'fieldName' => 'bar2', + 'targetEntity' => 'baz2', + ]; + $association3 = [ + 'sourceEntity' => 'foo3', + 'fieldName' => 'bar3', + 'targetEntity' => 'baz3', + ]; + + $entity3->expects(self::any())->method('__toString')->willReturn($stringEntity3); + + return [ + 'one entity found' => [ + [ + [ + $association1, + $entity1, + ], + ], + 'A new entity was found through the relationship \'foo1#bar1\' that was not configured to cascade ' + . 'persist operations for entity: stdClass@' . spl_object_hash($entity1) + . '. To solve this issue: Either explicitly call EntityManager#persist() on this unknown entity ' + . 'or configure cascade persist this association in the mapping for example ' + . '@ManyToOne(..,cascade={"persist"}). If you cannot find out which entity causes the problem ' + . 'implement \'baz1#__toString()\' to get a clue.', + ], + 'two entities found' => [ + [ + [ + $association1, + $entity1, + ], + [ + $association2, + $entity2, + ], + ], + 'Multiple non-persisted new entities were found through the given association graph:' . "\n\n" + . ' * A new entity was found through the relationship \'foo1#bar1\' that was not configured to ' + . 'cascade persist operations for entity: stdClass@' . spl_object_hash($entity1) . '. ' + . 'To solve this issue: Either explicitly call EntityManager#persist() on this unknown entity ' + . 'or configure cascade persist this association in the mapping for example ' + . '@ManyToOne(..,cascade={"persist"}). If you cannot find out which entity causes the problem ' + . 'implement \'baz1#__toString()\' to get a clue.' . "\n" + . ' * A new entity was found through the relationship \'foo2#bar2\' that was not configured to ' + . 'cascade persist operations for entity: stdClass@' . spl_object_hash($entity2) . '. To solve ' + . 'this issue: Either explicitly call EntityManager#persist() on this unknown entity or ' + . 'configure cascade persist this association in the mapping for example ' + . '@ManyToOne(..,cascade={"persist"}). If you cannot find out which entity causes the problem ' + . 'implement \'baz2#__toString()\' to get a clue.' + ], + 'two entities found, one is stringable' => [ + [ + [ + $association3, + $entity3, + ], + ], + 'A new entity was found through the relationship \'foo3#bar3\' that was not configured to cascade ' + . 'persist operations for entity: ' . $stringEntity3 + . '. To solve this issue: Either explicitly call EntityManager#persist() on this unknown entity ' + . 'or configure cascade persist this association in the mapping for example ' + . '@ManyToOne(..,cascade={"persist"}).', + ], + ]; + } +} diff --git a/tests/Doctrine/Tests/ORM/Performance/HydrationPerformanceTest.php b/tests/Doctrine/Tests/ORM/Performance/HydrationPerformanceTest.php deleted file mode 100644 index e4d65e1e72d..00000000000 --- a/tests/Doctrine/Tests/ORM/Performance/HydrationPerformanceTest.php +++ /dev/null @@ -1,463 +0,0 @@ - 0.7 seconds] - * - * MAXIMUM TIME: 1 second - */ - public function testSimpleQueryScalarHydrationPerformance10000Rows() - { - $rsm = new ResultSetMapping; - $rsm->addEntityResult('Doctrine\Tests\Models\CMS\CmsUser', 'u'); - $rsm->addFieldResult('u', 'u__id', 'id'); - $rsm->addFieldResult('u', 'u__status', 'status'); - $rsm->addFieldResult('u', 'u__username', 'username'); - $rsm->addFieldResult('u', 'u__name', 'name'); - - // Faked result set - $resultSet = array( - //row1 - array( - 'u__id' => '1', - 'u__status' => 'developer', - 'u__username' => 'romanb', - 'u__name' => 'Roman', - ), - array( - 'u__id' => '1', - 'u__status' => 'developer', - 'u__username' => 'romanb', - 'u__name' => 'Roman', - ), - array( - 'u__id' => '2', - 'u__status' => 'developer', - 'u__username' => 'romanb', - 'u__name' => 'Roman', - ) - ); - - for ($i = 4; $i < 10000; ++$i) { - $resultSet[] = array( - 'u__id' => $i, - 'u__status' => 'developer', - 'u__username' => 'jwage', - 'u__name' => 'Jonathan', - ); - } - - $stmt = new HydratorMockStatement($resultSet); - $hydrator = new ScalarHydrator($this->_em); - - $this->setMaxRunningTime(1); - $s = microtime(true); - $result = $hydrator->hydrateAll($stmt, $rsm); - $e = microtime(true); - echo __FUNCTION__ . " - " . ($e - $s) . " seconds" . PHP_EOL; - } - - /** - * Times for comparison: - * - * [romanb: 10000 rows => 1 second] - * - * MAXIMUM TIME: 2 seconds - */ - public function testSimpleQueryArrayHydrationPerformance10000Rows() - { - $rsm = new ResultSetMapping; - $rsm->addEntityResult('Doctrine\Tests\Models\CMS\CmsUser', 'u'); - $rsm->addFieldResult('u', 'u__id', 'id'); - $rsm->addFieldResult('u', 'u__status', 'status'); - $rsm->addFieldResult('u', 'u__username', 'username'); - $rsm->addFieldResult('u', 'u__name', 'name'); - - // Faked result set - $resultSet = array( - //row1 - array( - 'u__id' => '1', - 'u__status' => 'developer', - 'u__username' => 'romanb', - 'u__name' => 'Roman', - ), - array( - 'u__id' => '1', - 'u__status' => 'developer', - 'u__username' => 'romanb', - 'u__name' => 'Roman', - ), - array( - 'u__id' => '2', - 'u__status' => 'developer', - 'u__username' => 'romanb', - 'u__name' => 'Roman', - ) - ); - - for ($i = 4; $i < 10000; ++$i) { - $resultSet[] = array( - 'u__id' => $i, - 'u__status' => 'developer', - 'u__username' => 'jwage', - 'u__name' => 'Jonathan', - ); - } - - $stmt = new HydratorMockStatement($resultSet); - $hydrator = new ArrayHydrator($this->_em); - - $this->setMaxRunningTime(2); - $s = microtime(true); - $result = $hydrator->hydrateAll($stmt, $rsm); - $e = microtime(true); - echo __FUNCTION__ . " - " . ($e - $s) . " seconds" . PHP_EOL; - } - - /** - * Times for comparison: - * - * [romanb: 10000 rows => 1.4 seconds] - * - * MAXIMUM TIME: 3 seconds - */ - public function testMixedQueryFetchJoinArrayHydrationPerformance10000Rows() - { - $rsm = new ResultSetMapping; - $rsm->addEntityResult('Doctrine\Tests\Models\CMS\CmsUser', 'u'); - $rsm->addJoinedEntityResult( - 'Doctrine\Tests\Models\CMS\CmsPhonenumber', - 'p', - 'u', - 'phonenumbers' - ); - $rsm->addFieldResult('u', 'u__id', 'id'); - $rsm->addFieldResult('u', 'u__status', 'status'); - $rsm->addFieldResult('u', 'u__username', 'username'); - $rsm->addFieldResult('u', 'u__name', 'name'); - $rsm->addScalarResult('sclr0', 'nameUpper'); - $rsm->addFieldResult('p', 'p__phonenumber', 'phonenumber'); - - // Faked result set - $resultSet = array( - //row1 - array( - 'u__id' => '1', - 'u__status' => 'developer', - 'u__username' => 'romanb', - 'u__name' => 'Roman', - 'sclr0' => 'ROMANB', - 'p__phonenumber' => '42', - ), - array( - 'u__id' => '1', - 'u__status' => 'developer', - 'u__username' => 'romanb', - 'u__name' => 'Roman', - 'sclr0' => 'ROMANB', - 'p__phonenumber' => '43', - ), - array( - 'u__id' => '2', - 'u__status' => 'developer', - 'u__username' => 'romanb', - 'u__name' => 'Roman', - 'sclr0' => 'JWAGE', - 'p__phonenumber' => '91' - ) - ); - - for ($i = 4; $i < 10000; ++$i) { - $resultSet[] = array( - 'u__id' => $i, - 'u__status' => 'developer', - 'u__username' => 'jwage', - 'u__name' => 'Jonathan', - 'sclr0' => 'JWAGE' . $i, - 'p__phonenumber' => '91' - ); - } - - $stmt = new HydratorMockStatement($resultSet); - $hydrator = new ArrayHydrator($this->_em); - - $this->setMaxRunningTime(3); - $s = microtime(true); - $result = $hydrator->hydrateAll($stmt, $rsm); - $e = microtime(true); - echo __FUNCTION__ . " - " . ($e - $s) . " seconds" . PHP_EOL; - } - - /** - * [romanb: 10000 rows => 1.5 seconds] - * - * MAXIMUM TIME: 3 seconds - */ - public function testSimpleQueryPartialObjectHydrationPerformance10000Rows() - { - $rsm = new ResultSetMapping; - $rsm->addEntityResult('Doctrine\Tests\Models\CMS\CmsUser', 'u'); - $rsm->addFieldResult('u', 'u__id', 'id'); - $rsm->addFieldResult('u', 'u__status', 'status'); - $rsm->addFieldResult('u', 'u__username', 'username'); - $rsm->addFieldResult('u', 'u__name', 'name'); - - // Faked result set - $resultSet = array( - //row1 - array( - 'u__id' => '1', - 'u__status' => 'developer', - 'u__username' => 'romanb', - 'u__name' => 'Roman', - ), - array( - 'u__id' => '1', - 'u__status' => 'developer', - 'u__username' => 'romanb', - 'u__name' => 'Roman', - ), - array( - 'u__id' => '2', - 'u__status' => 'developer', - 'u__username' => 'romanb', - 'u__name' => 'Roman', - ) - ); - - for ($i = 4; $i < 10000; ++$i) { - $resultSet[] = array( - 'u__id' => $i, - 'u__status' => 'developer', - 'u__username' => 'jwage', - 'u__name' => 'Jonathan', - ); - } - - $stmt = new HydratorMockStatement($resultSet); - $hydrator = new ObjectHydrator($this->_em); - - $this->setMaxRunningTime(3); - $s = microtime(true); - $result = $hydrator->hydrateAll($stmt, $rsm, array(Query::HINT_FORCE_PARTIAL_LOAD => true)); - $e = microtime(true); - echo __FUNCTION__ . " - " . ($e - $s) . " seconds" . PHP_EOL; - } - - /** - * [romanb: 10000 rows => 3 seconds] - * - * MAXIMUM TIME: 4.5 seconds - */ - public function testSimpleQueryFullObjectHydrationPerformance10000Rows() - { - $rsm = new ResultSetMapping; - $rsm->addEntityResult('Doctrine\Tests\Models\CMS\CmsUser', 'u'); - $rsm->addFieldResult('u', 'u__id', 'id'); - $rsm->addFieldResult('u', 'u__status', 'status'); - $rsm->addFieldResult('u', 'u__username', 'username'); - $rsm->addFieldResult('u', 'u__name', 'name'); - $rsm->addJoinedEntityResult( - 'Doctrine\Tests\Models\CMS\CmsAddress', - 'a', - 'u', - 'address' - ); - $rsm->addFieldResult('a', 'a__id', 'id'); - //$rsm->addFieldResult('a', 'a__country', 'country'); - //$rsm->addFieldResult('a', 'a__zip', 'zip'); - //$rsm->addFieldResult('a', 'a__city', 'city'); - - // Faked result set - $resultSet = array( - //row1 - array( - 'u__id' => '1', - 'u__status' => 'developer', - 'u__username' => 'romanb', - 'u__name' => 'Roman', - 'a__id' => '1' - ) - ); - - for ($i = 2; $i < 10000; ++$i) { - $resultSet[] = array( - 'u__id' => $i, - 'u__status' => 'developer', - 'u__username' => 'jwage', - 'u__name' => 'Jonathan', - 'a__id' => $i - ); - } - - $stmt = new HydratorMockStatement($resultSet); - $hydrator = new ObjectHydrator($this->_em); - - $this->setMaxRunningTime(5); - $s = microtime(true); - $result = $hydrator->hydrateAll($stmt, $rsm); - $e = microtime(true); - echo __FUNCTION__ . " - " . ($e - $s) . " seconds" . PHP_EOL; - } - - /** - * [romanb: 2000 rows => 0.4 seconds] - * - * MAXIMUM TIME: 1 second - */ - public function testMixedQueryFetchJoinPartialObjectHydrationPerformance2000Rows() - { - $rsm = new ResultSetMapping; - $rsm->addEntityResult('Doctrine\Tests\Models\CMS\CmsUser', 'u'); - $rsm->addJoinedEntityResult( - 'Doctrine\Tests\Models\CMS\CmsPhonenumber', - 'p', - 'u', - 'phonenumbers' - ); - $rsm->addFieldResult('u', 'u__id', 'id'); - $rsm->addFieldResult('u', 'u__status', 'status'); - $rsm->addFieldResult('u', 'u__username', 'username'); - $rsm->addFieldResult('u', 'u__name', 'name'); - $rsm->addScalarResult('sclr0', 'nameUpper'); - $rsm->addFieldResult('p', 'p__phonenumber', 'phonenumber'); - - // Faked result set - $resultSet = array( - //row1 - array( - 'u__id' => '1', - 'u__status' => 'developer', - 'u__username' => 'romanb', - 'u__name' => 'Roman', - 'sclr0' => 'ROMANB', - 'p__phonenumber' => '42', - ), - array( - 'u__id' => '1', - 'u__status' => 'developer', - 'u__username' => 'romanb', - 'u__name' => 'Roman', - 'sclr0' => 'ROMANB', - 'p__phonenumber' => '43', - ), - array( - 'u__id' => '2', - 'u__status' => 'developer', - 'u__username' => 'romanb', - 'u__name' => 'Roman', - 'sclr0' => 'JWAGE', - 'p__phonenumber' => '91' - ) - ); - - for ($i = 4; $i < 2000; ++$i) { - $resultSet[] = array( - 'u__id' => $i, - 'u__status' => 'developer', - 'u__username' => 'jwage', - 'u__name' => 'Jonathan', - 'sclr0' => 'JWAGE' . $i, - 'p__phonenumber' => '91' - ); - } - - $stmt = new HydratorMockStatement($resultSet); - $hydrator = new ObjectHydrator($this->_em); - - $this->setMaxRunningTime(1); - $s = microtime(true); - $result = $hydrator->hydrateAll($stmt, $rsm, array(Query::HINT_FORCE_PARTIAL_LOAD => true)); - $e = microtime(true); - echo __FUNCTION__ . " - " . ($e - $s) . " seconds" . PHP_EOL; - } - - /** - * [romanb: 2000 rows => 0.6 seconds] - * - * MAXIMUM TIME: 1 second - */ - public function testMixedQueryFetchJoinFullObjectHydrationPerformance2000Rows() - { - $rsm = new ResultSetMapping; - $rsm->addEntityResult('Doctrine\Tests\Models\CMS\CmsUser', 'u'); - $rsm->addJoinedEntityResult( - 'Doctrine\Tests\Models\CMS\CmsPhonenumber', - 'p', - 'u', - 'phonenumbers' - ); - $rsm->addFieldResult('u', 'u__id', 'id'); - $rsm->addFieldResult('u', 'u__status', 'status'); - $rsm->addFieldResult('u', 'u__username', 'username'); - $rsm->addFieldResult('u', 'u__name', 'name'); - $rsm->addScalarResult('sclr0', 'nameUpper'); - $rsm->addFieldResult('p', 'p__phonenumber', 'phonenumber'); - $rsm->addJoinedEntityResult( - 'Doctrine\Tests\Models\CMS\CmsAddress', - 'a', - 'u', - 'address' - ); - $rsm->addFieldResult('a', 'a__id', 'id'); - - // Faked result set - $resultSet = array( - //row1 - array( - 'u__id' => '1', - 'u__status' => 'developer', - 'u__username' => 'romanb', - 'u__name' => 'Roman', - 'sclr0' => 'ROMANB', - 'p__phonenumber' => '42', - 'a__id' => '1' - ) - ); - - for ($i = 2; $i < 2000; ++$i) { - $resultSet[] = array( - 'u__id' => $i, - 'u__status' => 'developer', - 'u__username' => 'jwage', - 'u__name' => 'Jonathan', - 'sclr0' => 'JWAGE' . $i, - 'p__phonenumber' => '91', - 'a__id' => $i - ); - } - - $stmt = new HydratorMockStatement($resultSet); - $hydrator = new ObjectHydrator($this->_em); - - $this->setMaxRunningTime(1); - $s = microtime(true); - $result = $hydrator->hydrateAll($stmt, $rsm); - $e = microtime(true); - echo __FUNCTION__ . " - " . ($e - $s) . " seconds" . PHP_EOL; - } -} - diff --git a/tests/Doctrine/Tests/ORM/Performance/InheritancePersisterPerformanceTest.php b/tests/Doctrine/Tests/ORM/Performance/InheritancePersisterPerformanceTest.php deleted file mode 100644 index 2104587aea4..00000000000 --- a/tests/Doctrine/Tests/ORM/Performance/InheritancePersisterPerformanceTest.php +++ /dev/null @@ -1,68 +0,0 @@ -useModelSet('company'); - parent::setUp(); - } - - public function testCompanyContract() - { - $person = new CompanyEmployee(); - $person->setName('Poor Sales Guy'); - $person->setDepartment('Sales'); - $person->setSalary(100); - $this->_em->persist($person); - - for ($i = 0; $i < 33; $i++) { - $fix = new CompanyFixContract(); - $fix->setFixPrice(1000); - $fix->setSalesPerson($person); - $fix->markCompleted(); - $this->_em->persist($fix); - - $flex = new CompanyFlexContract(); - $flex->setSalesPerson($person); - $flex->setHoursWorked(100); - $flex->setPricePerHour(100); - $flex->markCompleted(); - $this->_em->persist($flex); - - $ultra = new CompanyFlexUltraContract(); - $ultra->setSalesPerson($person); - $ultra->setHoursWorked(150); - $ultra->setPricePerHour(150); - $ultra->setMaxPrice(7000); - $this->_em->persist($ultra); - } - - $this->_em->flush(); - $this->_em->clear(); - - $start = microtime(true); - $contracts = $this->_em->getRepository('Doctrine\Tests\Models\Company\CompanyContract')->findAll(); - echo "99 CompanyContract: " . number_format(microtime(true) - $start, 6) . "\n"; - $this->assertEquals(99, count($contracts)); - - $this->_em->clear(); - - $start = microtime(true); - $contracts = $this->_em->getRepository('Doctrine\Tests\Models\Company\CompanyContract')->findAll(); - echo "99 CompanyContract: " . number_format(microtime(true) - $start, 6) . "\n"; - $this->assertEquals(99, count($contracts)); - } -} diff --git a/tests/Doctrine/Tests/ORM/Performance/InsertPerformanceTest.php b/tests/Doctrine/Tests/ORM/Performance/InsertPerformanceTest.php deleted file mode 100644 index db5455b062d..00000000000 --- a/tests/Doctrine/Tests/ORM/Performance/InsertPerformanceTest.php +++ /dev/null @@ -1,56 +0,0 @@ -useModelSet('cms'); - parent::setUp(); - } - - /** - * [romanb: 10000 objects in ~8 seconds] - */ - public function testInsertPerformance() - { - $s = microtime(true); - - $conn = $this->_em->getConnection(); - - $this->setMaxRunningTime(10); - - //echo "Memory usage before: " . (memory_get_usage() / 1024) . " KB" . PHP_EOL; - - $batchSize = 20; - for ($i=1; $i<=10000; ++$i) { - $user = new CmsUser; - $user->status = 'user'; - $user->username = 'user' . $i; - $user->name = 'Mr.Smith-' . $i; - $this->_em->persist($user); - if (($i % $batchSize) == 0) { - $this->_em->flush(); - $this->_em->clear(); - } - } - - //gc_collect_cycles(); - //echo "Memory usage after: " . (memory_get_usage() / 1024) . " KB" . PHP_EOL; - - $e = microtime(true); - - echo ' Inserted 10000 objects in ' . ($e - $s) . ' seconds' . PHP_EOL; - } -} - diff --git a/tests/Doctrine/Tests/ORM/Performance/PersisterPerformanceTest.php b/tests/Doctrine/Tests/ORM/Performance/PersisterPerformanceTest.php deleted file mode 100644 index db5d0f8ef60..00000000000 --- a/tests/Doctrine/Tests/ORM/Performance/PersisterPerformanceTest.php +++ /dev/null @@ -1,113 +0,0 @@ -useModelSet('cms'); - parent::setUp(); - } - - public function testFindCmsArticle() - { - $author = new CmsUser(); - $author->name = "beberlei"; - $author->status = "active"; - $author->username = "beberlei"; - $this->_em->persist($author); - - $ids = array(); - for ($i = 0; $i < 100; $i++) { - $article = new CmsArticle(); - $article->text = "foo"; - $article->topic = "bar"; - $article->user = $author; - $this->_em->persist($article); - $ids[] = $article; - } - $this->_em->flush(); - $this->_em->clear(); - - $start = microtime(true); - $articles = $this->_em->getRepository('Doctrine\Tests\Models\CMS\CmsArticle')->findAll(); - echo "100 CmsArticle findAll(): " . number_format(microtime(true) - $start, 6) . "\n"; - - $this->_em->clear(); - - $start = microtime(true); - $articles = $this->_em->getRepository('Doctrine\Tests\Models\CMS\CmsArticle')->findAll(); - echo "100 CmsArticle findAll(): " . number_format(microtime(true) - $start, 6) . "\n"; - - $this->_em->clear(); - - $start = microtime(true); - for ($i = 0; $i < 100; $i++) { - $articles = $this->_em->getRepository('Doctrine\Tests\Models\CMS\CmsArticle')->find($ids[$i]->id); - } - echo "100 CmsArticle find(): " . number_format(microtime(true) - $start, 6) . "\n"; - - $this->_em->clear(); - - $start = microtime(true); - for ($i = 0; $i < 100; $i++) { - $articles = $this->_em->getRepository('Doctrine\Tests\Models\CMS\CmsArticle')->find($ids[$i]->id); - } - echo "100 CmsArticle find(): " . number_format(microtime(true) - $start, 6) . "\n"; - } - - public function testFindCmsGroup() - { - for ($i = 0; $i < 100; $i++) { - $group = new CmsGroup(); - $group->name = "foo" . $i; - $this->_em->persist($group); - } - $this->_em->flush(); - $this->_em->clear(); - - $start = microtime(true); - $articles = $this->_em->getRepository('Doctrine\Tests\Models\CMS\CmsGroup')->findAll(); - echo "100 CmsGroup: " . number_format(microtime(true) - $start, 6) . "\n"; - - $this->_em->clear(); - - $start = microtime(true); - $articles = $this->_em->getRepository('Doctrine\Tests\Models\CMS\CmsGroup')->findAll(); - echo "100 CmsGroup: " . number_format(microtime(true) - $start, 6) . "\n"; - } - - public function testFindCmsUser() - { - for ($i = 0; $i < 100; $i++) { - $user = new CmsUser(); - $user->name = "beberlei"; - $user->status = "active"; - $user->username = "beberlei".$i; - $this->_em->persist($user); - } - - $this->_em->flush(); - $this->_em->clear(); - - $start = microtime(true); - $articles = $this->_em->getRepository('Doctrine\Tests\Models\CMS\CmsUser')->findAll(); - echo "100 CmsUser: " . number_format(microtime(true) - $start, 6) . "\n"; - - $this->_em->clear(); - - $start = microtime(true); - $articles = $this->_em->getRepository('Doctrine\Tests\Models\CMS\CmsUser')->findAll(); - echo "100 CmsUser: " . number_format(microtime(true) - $start, 6) . "\n"; - } -} diff --git a/tests/Doctrine/Tests/ORM/Performance/ProxyPerformanceTest.php b/tests/Doctrine/Tests/ORM/Performance/ProxyPerformanceTest.php deleted file mode 100644 index ffe621eefd3..00000000000 --- a/tests/Doctrine/Tests/ORM/Performance/ProxyPerformanceTest.php +++ /dev/null @@ -1,170 +0,0 @@ -. - */ - -namespace Doctrine\Tests\ORM\Performance; - -use Doctrine\Tests\OrmPerformanceTestCase; -use Doctrine\ORM\EntityManager; -use Doctrine\ORM\UnitOfWork; -use Doctrine\ORM\Proxy\ProxyFactory; -use Doctrine\ORM\Persisters\Entity\BasicEntityPersister; - -/** - * Performance test used to measure performance of proxy instantiation - * - * @author Marco Pivetta - * @group performance - */ -class ProxyPerformanceTest extends OrmPerformanceTestCase -{ - /** - * @return array - */ - public function entitiesProvider() - { - return array( - array('Doctrine\Tests\Models\CMS\CmsEmployee'), - array('Doctrine\Tests\Models\CMS\CmsUser'), - ); - } - - /** - * @dataProvider entitiesProvider - */ - public function testProxyInstantiationPerformance($entityName) - { - $proxyFactory = $this->_getEntityManager()->getProxyFactory(); - $this->setMaxRunningTime(5); - $start = microtime(true); - - for ($i = 0; $i < 100000; $i += 1) { - $user = $proxyFactory->getProxy($entityName, array('id' => $i)); - } - - echo __FUNCTION__ . " - " . (microtime(true) - $start) . " seconds with " . $entityName . PHP_EOL; - } - - /** - * @dataProvider entitiesProvider - */ - public function testProxyForcedInitializationPerformance($entityName) - { - $em = new MockEntityManager($this->_getEntityManager()); - $proxyFactory = $em->getProxyFactory(); - /* @var $user \Doctrine\Common\Proxy\Proxy */ - $user = $proxyFactory->getProxy($entityName, array('id' => 1)); - $initializer = $user->__getInitializer(); - - $this->setMaxRunningTime(5); - $start = microtime(true); - - for ($i = 0; $i < 100000; $i += 1) { - $user->__setInitialized(false); - $user->__setInitializer($initializer); - $user->__load(); - $user->__load(); - } - - echo __FUNCTION__ . " - " . (microtime(true) - $start) . " seconds with " . $entityName . PHP_EOL; - } -} - -/** - * Mock entity manager to fake `getPersister()` - */ -class MockEntityManager extends EntityManager -{ - /** @var EntityManager */ - private $em; - - /** @param EntityManager $em */ - public function __construct(EntityManager $em) - { - $this->em = $em; - } - - /** {@inheritDoc} */ - public function getProxyFactory() - { - $config = $this->em->getConfiguration(); - - return new ProxyFactory( - $this, - $config->getProxyDir(), - $config->getProxyNamespace(), - $config->getAutoGenerateProxyClasses() - ); - } - - /** {@inheritDoc} */ - public function getMetadataFactory() - { - return $this->em->getMetadataFactory(); - } - - /** {@inheritDoc} */ - public function getClassMetadata($className) - { - return $this->em->getClassMetadata($className); - } - - /** {@inheritDoc} */ - public function getUnitOfWork() - { - return new MockUnitOfWork(); - } -} - -/** - * Mock UnitOfWork manager to fake `getPersister()` - */ -class MockUnitOfWork extends UnitOfWork -{ - /** @var PersisterMock */ - private $entityPersister; - - /** */ - public function __construct() - { - $this->entityPersister = new PersisterMock(); - } - - /** {@inheritDoc} */ - public function getEntityPersister($entityName) - { - return $this->entityPersister; - } -} - -/** - * Mock persister (we don't want PHPUnit comparator API to play a role in here) - */ -class PersisterMock extends BasicEntityPersister -{ - /** */ - public function __construct() - { - } - - /** {@inheritDoc} */ - public function load(array $criteria, $entity = null, $assoc = null, array $hints = array(), $lockMode = 0, $limit = null, array $orderBy = null) - { - return $entity; - } -} diff --git a/tests/Doctrine/Tests/ORM/Performance/SecondLevelCacheTest.php b/tests/Doctrine/Tests/ORM/Performance/SecondLevelCacheTest.php index 61b9c7ce77e..f954d4f4791 100644 --- a/tests/Doctrine/Tests/ORM/Performance/SecondLevelCacheTest.php +++ b/tests/Doctrine/Tests/ORM/Performance/SecondLevelCacheTest.php @@ -101,7 +101,7 @@ public function testFindEntityOneToManyWithCache() $this->findEntityOneToMany($em, __FUNCTION__); - $this->assertEquals(487, $this->countQuery($em)); + $this->assertEquals(472, $this->countQuery($em)); } public function testQueryEntityWithoutCache() @@ -159,8 +159,8 @@ public function findEntityOneToMany(EntityManagerInterface $em, $label) { $times = 50; $size = 30; - $states = array(); - $cities = array(); + $states = []; + $cities = []; $startPersist = microtime(true); $country = new Country("Country"); @@ -202,7 +202,7 @@ public function findEntityOneToMany(EntityManagerInterface $em, $label) foreach ($states as $state) { - $state = $em->find(State::CLASSNAME, $state->getId()); + $state = $em->find(State::class, $state->getId()); foreach ($state->getCities() as $city) { $city->getName(); @@ -218,7 +218,7 @@ private function findEntity(EntityManagerInterface $em, $label) { $times = 10; $size = 500; - $countries = array(); + $countries = []; $startPersist = microtime(true); echo PHP_EOL . $label; @@ -240,7 +240,7 @@ private function findEntity(EntityManagerInterface $em, $label) for ($i = 0; $i <= $times; $i++) { foreach ($countries as $country) { - $em->find(Country::CLASSNAME, $country->getId()); + $em->find(Country::class, $country->getId()); $em->clear(); } } @@ -254,7 +254,7 @@ private function findAllEntity(EntityManagerInterface $em, $label) $times = 100; $size = 50; $startPersist = microtime(true); - $rep = $em->getRepository(Country::CLASSNAME); + $rep = $em->getRepository(Country::class); echo PHP_EOL . $label; @@ -279,4 +279,4 @@ private function findAllEntity(EntityManagerInterface $em, $label) printf("\n[%s] find %s countries (%s times)", number_format(microtime(true) - $startFind, 6), $size, $times); printf("\n%s\n", str_repeat('-', 50)); } -} \ No newline at end of file +} diff --git a/tests/Doctrine/Tests/ORM/Performance/UnitOfWorkPerformanceTest.php b/tests/Doctrine/Tests/ORM/Performance/UnitOfWorkPerformanceTest.php deleted file mode 100644 index 93493363598..00000000000 --- a/tests/Doctrine/Tests/ORM/Performance/UnitOfWorkPerformanceTest.php +++ /dev/null @@ -1,50 +0,0 @@ -useModelSet('cms'); - parent::setUp(); - } - - public function testComputeChanges() - { - $n = 100; - - $users = array(); - for ($i=1; $i<=$n; ++$i) { - $user = new CmsUser; - $user->status = 'user'; - $user->username = 'user' . $i; - $user->name = 'Mr.Smith-' . $i; - $this->_em->persist($user); - $users[] = $user; - } - $this->_em->flush(); - - - foreach ($users AS $user) { - $user->status = 'other'; - $user->username = $user->username . '++'; - $user->name = str_replace('Mr.', 'Mrs.', $user->name); - } - - $s = microtime(true); - $this->_em->flush(); - $e = microtime(true); - - echo ' Compute ChangeSet '.$n.' objects in ' . ($e - $s) . ' seconds' . PHP_EOL; - } -} diff --git a/tests/Doctrine/Tests/ORM/PersistentCollectionTest.php b/tests/Doctrine/Tests/ORM/PersistentCollectionTest.php index 4956e5648c9..bfee130f0b5 100644 --- a/tests/Doctrine/Tests/ORM/PersistentCollectionTest.php +++ b/tests/Doctrine/Tests/ORM/PersistentCollectionTest.php @@ -3,7 +3,9 @@ namespace Doctrine\Tests\ORM; use Doctrine\Common\Collections\ArrayCollection; +use Doctrine\ORM\Mapping\ClassMetadataInfo; use Doctrine\ORM\PersistentCollection; +use Doctrine\ORM\UnitOfWork; use Doctrine\Tests\Mocks\ConnectionMock; use Doctrine\Tests\Mocks\DriverMock; use Doctrine\Tests\Mocks\EntityManagerMock; @@ -24,7 +26,7 @@ class PersistentCollectionTest extends OrmTestCase protected $collection; /** - * @var \Doctrine\ORM\EntityManagerInterface + * @var EntityManagerMock */ private $_emMock; @@ -33,6 +35,8 @@ protected function setUp() parent::setUp(); $this->_emMock = EntityManagerMock::create(new ConnectionMock([], new DriverMock())); + + $this->setUpPersistentCollection(); } /** @@ -40,7 +44,7 @@ protected function setUp() */ public function setUpPersistentCollection() { - $classMetaData = $this->_emMock->getClassMetadata('Doctrine\Tests\Models\ECommerce\ECommerceCart'); + $classMetaData = $this->_emMock->getClassMetadata(ECommerceCart::class); $this->collection = new PersistentCollection($this->_emMock, $classMetaData, new ArrayCollection); $this->collection->setInitialized(false); $this->collection->setOwner(new ECommerceCart(), $classMetaData->getAssociationMapping('products')); @@ -48,7 +52,7 @@ public function setUpPersistentCollection() public function testCanBePutInLazyLoadingMode() { - $class = $this->_emMock->getClassMetadata('Doctrine\Tests\Models\ECommerce\ECommerceProduct'); + $class = $this->_emMock->getClassMetadata(ECommerceProduct::class); $collection = new PersistentCollection($this->_emMock, $class, new ArrayCollection); $collection->setInitialized(false); $this->assertFalse($collection->isInitialized()); @@ -59,7 +63,6 @@ public function testCanBePutInLazyLoadingMode() */ public function testCurrentInitializesCollection() { - $this->setUpPersistentCollection(); $this->collection->current(); $this->assertTrue($this->collection->isInitialized()); } @@ -69,7 +72,6 @@ public function testCurrentInitializesCollection() */ public function testKeyInitializesCollection() { - $this->setUpPersistentCollection(); $this->collection->key(); $this->assertTrue($this->collection->isInitialized()); } @@ -79,7 +81,6 @@ public function testKeyInitializesCollection() */ public function testNextInitializesCollection() { - $this->setUpPersistentCollection(); $this->collection->next(); $this->assertTrue($this->collection->isInitialized()); } @@ -89,8 +90,6 @@ public function testNextInitializesCollection() */ public function testNonObjects() { - $this->setUpPersistentCollection(); - $this->assertEmpty($this->collection); $this->collection->add("dummy"); @@ -107,4 +106,172 @@ public function testNonObjects() $this->assertSame("dummy", $this->collection->get(2)); $this->assertSame(null, $this->collection->get(3)); } + + /** + * @group 6110 + */ + public function testRemovingElementsAlsoRemovesKeys() + { + $dummy = new \stdClass(); + + $this->collection->add($dummy); + $this->assertEquals([0], array_keys($this->collection->toArray())); + + $this->collection->removeElement($dummy); + $this->assertEquals([], array_keys($this->collection->toArray())); + } + + /** + * @group 6110 + */ + public function testClearWillAlsoClearKeys() + { + $this->collection->add(new \stdClass()); + $this->collection->clear(); + $this->assertEquals([], array_keys($this->collection->toArray())); + } + + /** + * @group 6110 + */ + public function testClearWillAlsoResetKeyPositions() + { + $dummy = new \stdClass(); + + $this->collection->add($dummy); + $this->collection->removeElement($dummy); + $this->collection->clear(); + $this->collection->add($dummy); + $this->assertEquals([0], array_keys($this->collection->toArray())); + } + + /** + * @group 6613 + * @group 6614 + * @group 6616 + */ + public function testWillKeepNewItemsInDirtyCollectionAfterInitialization() : void + { + /* @var $unitOfWork UnitOfWork|\PHPUnit_Framework_MockObject_MockObject */ + $unitOfWork = $this->createMock(UnitOfWork::class); + + $this->_emMock->setUnitOfWork($unitOfWork); + + $newElement = new \stdClass(); + $persistedElement = new \stdClass(); + + $this->collection->add($newElement); + + self::assertFalse($this->collection->isInitialized()); + self::assertTrue($this->collection->isDirty()); + + $unitOfWork + ->expects(self::once()) + ->method('loadCollection') + ->with($this->collection) + ->willReturnCallback(function (PersistentCollection $persistentCollection) use ($persistedElement) : void { + $persistentCollection->unwrap()->add($persistedElement); + }); + + $this->collection->initialize(); + + self::assertSame([$persistedElement, $newElement], $this->collection->toArray()); + self::assertTrue($this->collection->isInitialized()); + self::assertTrue($this->collection->isDirty()); + } + + /** + * @group 6613 + * @group 6614 + * @group 6616 + */ + public function testWillDeDuplicateNewItemsThatWerePreviouslyPersistedInDirtyCollectionAfterInitialization() : void + { + /* @var $unitOfWork UnitOfWork|\PHPUnit_Framework_MockObject_MockObject */ + $unitOfWork = $this->createMock(UnitOfWork::class); + + $this->_emMock->setUnitOfWork($unitOfWork); + + $newElement = new \stdClass(); + $newElementThatIsAlsoPersisted = new \stdClass(); + $persistedElement = new \stdClass(); + + $this->collection->add($newElementThatIsAlsoPersisted); + $this->collection->add($newElement); + + self::assertFalse($this->collection->isInitialized()); + self::assertTrue($this->collection->isDirty()); + + $unitOfWork + ->expects(self::once()) + ->method('loadCollection') + ->with($this->collection) + ->willReturnCallback(function (PersistentCollection $persistentCollection) use ( + $persistedElement, + $newElementThatIsAlsoPersisted + ) : void { + $persistentCollection->unwrap()->add($newElementThatIsAlsoPersisted); + $persistentCollection->unwrap()->add($persistedElement); + }); + + $this->collection->initialize(); + + self::assertSame( + [$newElementThatIsAlsoPersisted, $persistedElement, $newElement], + $this->collection->toArray() + ); + self::assertTrue($this->collection->isInitialized()); + self::assertTrue($this->collection->isDirty()); + } + + /** + * @group 6613 + * @group 6614 + * @group 6616 + */ + public function testWillNotMarkCollectionAsDirtyAfterInitializationIfNoElementsWereAdded() : void + { + /* @var $unitOfWork UnitOfWork|\PHPUnit_Framework_MockObject_MockObject */ + $unitOfWork = $this->createMock(UnitOfWork::class); + + $this->_emMock->setUnitOfWork($unitOfWork); + + $newElementThatIsAlsoPersisted = new \stdClass(); + $persistedElement = new \stdClass(); + + $this->collection->add($newElementThatIsAlsoPersisted); + + self::assertFalse($this->collection->isInitialized()); + self::assertTrue($this->collection->isDirty()); + + $unitOfWork + ->expects(self::once()) + ->method('loadCollection') + ->with($this->collection) + ->willReturnCallback(function (PersistentCollection $persistentCollection) use ( + $persistedElement, + $newElementThatIsAlsoPersisted + ) : void { + $persistentCollection->unwrap()->add($newElementThatIsAlsoPersisted); + $persistentCollection->unwrap()->add($persistedElement); + }); + + $this->collection->initialize(); + + self::assertSame( + [$newElementThatIsAlsoPersisted, $persistedElement], + $this->collection->toArray() + ); + self::assertTrue($this->collection->isInitialized()); + self::assertFalse($this->collection->isDirty()); + } + + public function testModifyUOWForDeferredImplicitOwnerOnClear() : void + { + $unitOfWork = $this->createMock(UnitOfWork::class); + $unitOfWork->expects(self::once())->method('scheduleCollectionDeletion'); + $this->_emMock->setUnitOfWork($unitOfWork); + + $this->collection->clear(); + } } diff --git a/tests/Doctrine/Tests/ORM/Persisters/BasicEntityPersisterCompositeTypeParametersTest.php b/tests/Doctrine/Tests/ORM/Persisters/BasicEntityPersisterCompositeTypeParametersTest.php index 74d72856ec1..1694d97ce8f 100644 --- a/tests/Doctrine/Tests/ORM/Persisters/BasicEntityPersisterCompositeTypeParametersTest.php +++ b/tests/Doctrine/Tests/ORM/Persisters/BasicEntityPersisterCompositeTypeParametersTest.php @@ -5,6 +5,7 @@ use Doctrine\Common\Collections\Criteria; use Doctrine\ORM\Persisters\Entity\BasicEntityPersister; use Doctrine\Tests\Models\GeoNames\Admin1; +use Doctrine\Tests\Models\GeoNames\Admin1AlternateName; use Doctrine\Tests\Models\GeoNames\Country; use Doctrine\Tests\OrmTestCase; @@ -29,11 +30,11 @@ protected function setUp() $this->_em = $this->_getTestEntityManager(); - $this->_em->getClassMetadata('Doctrine\Tests\Models\GeoNames\Country'); - $this->_em->getClassMetadata('Doctrine\Tests\Models\GeoNames\Admin1'); - $this->_em->getClassMetadata('Doctrine\Tests\Models\GeoNames\Admin1AlternateName'); + $this->_em->getClassMetadata(Country::class); + $this->_em->getClassMetadata(Admin1::class); + $this->_em->getClassMetadata(Admin1AlternateName::class); - $this->_persister = new BasicEntityPersister($this->_em, $this->_em->getClassMetadata('Doctrine\Tests\Models\GeoNames\Admin1AlternateName')); + $this->_persister = new BasicEntityPersister($this->_em, $this->_em->getClassMetadata(Admin1AlternateName::class)); } @@ -42,13 +43,10 @@ public function testExpandParametersWillExpandCompositeEntityKeys() $country = new Country("IT", "Italy"); $admin1 = new Admin1(10, "Rome", $country); + list ($values, $types) = $this->_persister->expandParameters(['admin1' => $admin1]); - list ($values, $types) = $this->_persister->expandParameters(array( - 'admin1' => $admin1 - )); - - $this->assertEquals(array('integer', 'string'), $types); - $this->assertEquals(array(10, 'IT'), $values); + $this->assertEquals(['integer', 'string'], $types); + $this->assertEquals([10, 'IT'], $values); } public function testExpandCriteriaParametersWillExpandCompositeEntityKeys() @@ -57,12 +55,11 @@ public function testExpandCriteriaParametersWillExpandCompositeEntityKeys() $admin1 = new Admin1(10, "Rome", $country); $criteria = Criteria::create(); - $criteria->andWhere(Criteria::expr()->eq("admin1", $admin1)); list ($values, $types) = $this->_persister->expandCriteriaParameters($criteria); - $this->assertEquals(array('integer', 'string'), $types); - $this->assertEquals(array(10, 'IT'), $values); + $this->assertEquals(['integer', 'string'], $types); + $this->assertEquals([10, 'IT'], $values); } } diff --git a/tests/Doctrine/Tests/ORM/Persisters/BasicEntityPersisterCompositeTypeSqlTest.php b/tests/Doctrine/Tests/ORM/Persisters/BasicEntityPersisterCompositeTypeSqlTest.php index e788826d481..9392b8ee507 100644 --- a/tests/Doctrine/Tests/ORM/Persisters/BasicEntityPersisterCompositeTypeSqlTest.php +++ b/tests/Doctrine/Tests/ORM/Persisters/BasicEntityPersisterCompositeTypeSqlTest.php @@ -4,6 +4,7 @@ use Doctrine\ORM\Persisters\Entity\BasicEntityPersister; use Doctrine\Common\Collections\Expr\Comparison; +use Doctrine\Tests\Models\GeoNames\Admin1AlternateName; use Doctrine\Tests\OrmTestCase; class BasicEntityPersisterCompositeTypeSqlTest extends OrmTestCase @@ -26,25 +27,24 @@ protected function setUp() parent::setUp(); $this->_em = $this->_getTestEntityManager(); - - $this->_persister = new BasicEntityPersister($this->_em, $this->_em->getClassMetadata('Doctrine\Tests\Models\GeoNames\Admin1AlternateName')); + $this->_persister = new BasicEntityPersister($this->_em, $this->_em->getClassMetadata(Admin1AlternateName::class)); } public function testSelectConditionStatementEq() { - $statement = $this->_persister->getSelectConditionStatementSQL('admin1', 1, array(), Comparison::EQ); + $statement = $this->_persister->getSelectConditionStatementSQL('admin1', 1, [], Comparison::EQ); $this->assertEquals('t0.admin1 = ? AND t0.country = ?', $statement); } public function testSelectConditionStatementEqNull() { - $statement = $this->_persister->getSelectConditionStatementSQL('admin1', null, array(), Comparison::IS); + $statement = $this->_persister->getSelectConditionStatementSQL('admin1', null, [], Comparison::IS); $this->assertEquals('t0.admin1 IS NULL AND t0.country IS NULL', $statement); } public function testSelectConditionStatementNeqNull() { - $statement = $this->_persister->getSelectConditionStatementSQL('admin1', null, array(), Comparison::NEQ); + $statement = $this->_persister->getSelectConditionStatementSQL('admin1', null, [], Comparison::NEQ); $this->assertEquals('t0.admin1 IS NOT NULL AND t0.country IS NOT NULL', $statement); } @@ -53,6 +53,6 @@ public function testSelectConditionStatementNeqNull() */ public function testSelectConditionStatementIn() { - $this->_persister->getSelectConditionStatementSQL('admin1', array(), array(), Comparison::IN); + $this->_persister->getSelectConditionStatementSQL('admin1', [], [], Comparison::IN); } } diff --git a/tests/Doctrine/Tests/ORM/Persisters/BasicEntityPersisterTypeValueSqlTest.php b/tests/Doctrine/Tests/ORM/Persisters/BasicEntityPersisterTypeValueSqlTest.php index b617d14da73..ba1d18051e1 100644 --- a/tests/Doctrine/Tests/ORM/Persisters/BasicEntityPersisterTypeValueSqlTest.php +++ b/tests/Doctrine/Tests/ORM/Persisters/BasicEntityPersisterTypeValueSqlTest.php @@ -3,12 +3,13 @@ namespace Doctrine\Tests\ORM\Persisters; use Doctrine\Common\Collections\Criteria; +use Doctrine\Common\Collections\Expr\Comparison; use Doctrine\DBAL\Types\Type as DBALType; use Doctrine\ORM\Persisters\Entity\BasicEntityPersister; -use Doctrine\Tests\Models\CustomType\CustomTypeParent; use Doctrine\Tests\Models\CustomType\CustomTypeChild; use Doctrine\Tests\Models\CustomType\CustomTypeFriend; -use Doctrine\Common\Collections\Expr\Comparison; +use Doctrine\Tests\Models\CustomType\CustomTypeParent; +use Doctrine\Tests\Models\Generic\NonAlphaColumnsEntity; use Doctrine\Tests\OrmTestCase; class BasicEntityPersisterTypeValueSqlTest extends OrmTestCase @@ -44,7 +45,7 @@ protected function setUp() $this->_em = $this->_getTestEntityManager(); - $this->_persister = new BasicEntityPersister($this->_em, $this->_em->getClassMetadata("Doctrine\Tests\Models\CustomType\CustomTypeParent")); + $this->_persister = new BasicEntityPersister($this->_em, $this->_em->getClassMetadata(CustomTypeParent::class)); } public function testGetInsertSQLUsesTypeValuesSQL() @@ -65,8 +66,8 @@ public function testUpdateUsesTypeValuesSQL() $parent->customInteger = 1; $parent->child = $child; - $this->_em->getUnitOfWork()->registerManaged($parent, array('id' => 1), array('customInteger' => 0, 'child' => null)); - $this->_em->getUnitOfWork()->registerManaged($child, array('id' => 1), array()); + $this->_em->getUnitOfWork()->registerManaged($parent, ['id' => 1], ['customInteger' => 0, 'child' => null]); + $this->_em->getUnitOfWork()->registerManaged($child, ['id' => 1], []); $this->_em->getUnitOfWork()->propertyChanged($parent, 'customInteger', 0, 1); $this->_em->getUnitOfWork()->propertyChanged($parent, 'child', null, $child); @@ -83,7 +84,7 @@ public function testGetSelectConditionSQLUsesTypeValuesSQL() $method = new \ReflectionMethod($this->_persister, 'getSelectConditionSQL'); $method->setAccessible(true); - $sql = $method->invoke($this->_persister, array('customInteger' => 1, 'child' => 1)); + $sql = $method->invoke($this->_persister, ['customInteger' => 1, 'child' => 1]); $this->assertEquals('t0.customInteger = ABS(?) AND t0.child_id = ?', $sql); } @@ -93,7 +94,7 @@ public function testGetSelectConditionSQLUsesTypeValuesSQL() */ public function testStripNonAlphanumericCharactersFromSelectColumnListSQL() { - $persister = new BasicEntityPersister($this->_em, $this->_em->getClassMetadata('Doctrine\Tests\Models\Generic\NonAlphaColumnsEntity')); + $persister = new BasicEntityPersister($this->_em, $this->_em->getClassMetadata(NonAlphaColumnsEntity::class)); $method = new \ReflectionMethod($persister, 'getSelectColumnsSQL'); $method->setAccessible(true); @@ -105,19 +106,19 @@ public function testStripNonAlphanumericCharactersFromSelectColumnListSQL() */ public function testSelectConditionStatementIsNull() { - $statement = $this->_persister->getSelectConditionStatementSQL('test', null, array(), Comparison::IS); + $statement = $this->_persister->getSelectConditionStatementSQL('test', null, [], Comparison::IS); $this->assertEquals('test IS NULL', $statement); } public function testSelectConditionStatementEqNull() { - $statement = $this->_persister->getSelectConditionStatementSQL('test', null, array(), Comparison::EQ); + $statement = $this->_persister->getSelectConditionStatementSQL('test', null, [], Comparison::EQ); $this->assertEquals('test IS NULL', $statement); } public function testSelectConditionStatementNeqNull() { - $statement = $this->_persister->getSelectConditionStatementSQL('test', null, array(), Comparison::NEQ); + $statement = $this->_persister->getSelectConditionStatementSQL('test', null, [], Comparison::NEQ); $this->assertEquals('test IS NOT NULL', $statement); } @@ -128,26 +129,26 @@ public function testSelectConditionStatementWithMultipleValuesContainingNull() { $this->assertEquals( '(t0.id IN (?) OR t0.id IS NULL)', - $this->_persister->getSelectConditionStatementSQL('id', array(null)) + $this->_persister->getSelectConditionStatementSQL('id', [null]) ); $this->assertEquals( '(t0.id IN (?) OR t0.id IS NULL)', - $this->_persister->getSelectConditionStatementSQL('id', array(null, 123)) + $this->_persister->getSelectConditionStatementSQL('id', [null, 123]) ); $this->assertEquals( '(t0.id IN (?) OR t0.id IS NULL)', - $this->_persister->getSelectConditionStatementSQL('id', array(123, null)) + $this->_persister->getSelectConditionStatementSQL('id', [123, null]) ); } public function testCountCondition() { - $persister = new BasicEntityPersister($this->_em, $this->_em->getClassMetadata('Doctrine\Tests\Models\Generic\NonAlphaColumnsEntity')); + $persister = new BasicEntityPersister($this->_em, $this->_em->getClassMetadata(NonAlphaColumnsEntity::class)); // Using a criteria as array - $statement = $persister->getCountSQL(array('value' => 'bar')); + $statement = $persister->getCountSQL(['value' => 'bar']); $this->assertEquals('SELECT COUNT(*) FROM "not-a-simple-entity" t0 WHERE t0."simple-entity-value" = ?', $statement); // Using a criteria object diff --git a/tests/Doctrine/Tests/ORM/Persisters/JoinedSubclassPersisterTest.php b/tests/Doctrine/Tests/ORM/Persisters/JoinedSubclassPersisterTest.php index 18145070fbe..4a4cec244a4 100644 --- a/tests/Doctrine/Tests/ORM/Persisters/JoinedSubclassPersisterTest.php +++ b/tests/Doctrine/Tests/ORM/Persisters/JoinedSubclassPersisterTest.php @@ -1,25 +1,9 @@ . - */ namespace Doctrine\Tests\ORM\Persisters; use Doctrine\ORM\Persisters\Entity\JoinedSubclassPersister; +use Doctrine\Tests\Models\JoinedInheritanceType\RootClass; use Doctrine\Tests\OrmTestCase; /** @@ -47,11 +31,7 @@ protected function setUp() parent::setUp(); $this->em = $this->_getTestEntityManager(); - - $this->persister = new JoinedSubclassPersister( - $this->em, - $this->em->getClassMetadata('Doctrine\Tests\Models\JoinedInheritanceType\RootClass') - ); + $this->persister = new JoinedSubclassPersister($this->em, $this->em->getClassMetadata(RootClass::class)); } /** @@ -59,6 +39,6 @@ protected function setUp() */ public function testExecuteInsertsWillReturnEmptySetWithNoQueuedInserts() { - $this->assertSame(array(), $this->persister->executeInserts()); + $this->assertSame([], $this->persister->executeInserts()); } } diff --git a/tests/Doctrine/Tests/ORM/Persisters/ManyToManyPersisterTest.php b/tests/Doctrine/Tests/ORM/Persisters/ManyToManyPersisterTest.php new file mode 100644 index 00000000000..989fc849346 --- /dev/null +++ b/tests/Doctrine/Tests/ORM/Persisters/ManyToManyPersisterTest.php @@ -0,0 +1,53 @@ +children->add($child); + $child->parents->add($parent); + + $em = $this->_getTestEntityManager(); + $em->persist($parent); + $em->flush(); + + /** @var ChildClass|null $childReloaded */ + $childReloaded = $em->find(ChildClass::class, ['id1' => 1, 'otherParent' => $otherParent]); + + self::assertNotNull($childReloaded); + + $persister = new ManyToManyPersister($em); + $persister->delete($childReloaded->parents); + + /** @var ConnectionMock $conn */ + $conn = $em->getConnection(); + + $updates = $conn->getExecuteUpdates(); + $lastUpdate = array_pop($updates); + + self::assertEquals('DELETE FROM parent_child WHERE child_id1 = ? AND child_id2 = ?', $lastUpdate['query']); + self::assertEquals([1, 42], $lastUpdate['params']); + } +} diff --git a/tests/Doctrine/Tests/ORM/Proxy/ProxyFactoryTest.php b/tests/Doctrine/Tests/ORM/Proxy/ProxyFactoryTest.php index dd5b730f67c..d66326faf2f 100644 --- a/tests/Doctrine/Tests/ORM/Proxy/ProxyFactoryTest.php +++ b/tests/Doctrine/Tests/ORM/Proxy/ProxyFactoryTest.php @@ -3,15 +3,18 @@ namespace Doctrine\Tests\ORM\Proxy; use Doctrine\Common\Persistence\Mapping\RuntimeReflectionService; +use Doctrine\Common\Proxy\AbstractProxyFactory; use Doctrine\ORM\EntityNotFoundException; use Doctrine\ORM\Mapping\ClassMetadata; use Doctrine\ORM\Persisters\Entity\BasicEntityPersister; use Doctrine\ORM\Proxy\ProxyFactory; use Doctrine\Tests\Mocks\ConnectionMock; +use Doctrine\Tests\Mocks\DriverMock; use Doctrine\Tests\Mocks\EntityManagerMock; use Doctrine\Tests\Mocks\UnitOfWorkMock; -use Doctrine\Tests\Mocks\DriverMock; -use Doctrine\Common\Proxy\AbstractProxyFactory; +use Doctrine\Tests\Models\Company\CompanyEmployee; +use Doctrine\Tests\Models\Company\CompanyPerson; +use Doctrine\Tests\Models\ECommerce\ECommerceFeature; use Doctrine\Tests\OrmTestCase; /** @@ -46,7 +49,7 @@ class ProxyFactoryTest extends OrmTestCase protected function setUp() { parent::setUp(); - $this->connectionMock = new ConnectionMock(array(), new DriverMock()); + $this->connectionMock = new ConnectionMock([], new DriverMock()); $this->emMock = EntityManagerMock::create($this->connectionMock); $this->uowMock = new UnitOfWorkMock($this->emMock); $this->emMock->setUnitOfWork($this->uowMock); @@ -55,33 +58,60 @@ protected function setUp() public function testReferenceProxyDelegatesLoadingToThePersister() { - $identifier = array('id' => 42); + $identifier = ['id' => 42]; $proxyClass = 'Proxies\__CG__\Doctrine\Tests\Models\ECommerce\ECommerceFeature'; - $persister = $this->getMockBuilder(BasicEntityPersister::class)->setMethods(array('load'))->disableOriginalConstructor()->getMock(); + $persister = $this->getMockBuilder(BasicEntityPersister::class)->setMethods(['load'])->disableOriginalConstructor()->getMock(); - $this->uowMock->setEntityPersister('Doctrine\Tests\Models\ECommerce\ECommerceFeature', $persister); + $this->uowMock->setEntityPersister(ECommerceFeature::class, $persister); - $proxy = $this->proxyFactory->getProxy('Doctrine\Tests\Models\ECommerce\ECommerceFeature', $identifier); + $proxy = $this->proxyFactory->getProxy(ECommerceFeature::class, $identifier); $persister ->expects($this->atLeastOnce()) - ->method('load') - ->with($this->equalTo($identifier), $this->isInstanceOf($proxyClass)) - ->will($this->returnValue(new \stdClass())); + ->method('load') + ->with($this->equalTo($identifier), $this->isInstanceOf($proxyClass)) + ->will($this->returnValue(new \stdClass())); $proxy->getDescription(); } + public function testSkipMappedSuperClassesOnGeneration(): void + { + $cm = new ClassMetadata(\stdClass::class); + $cm->isMappedSuperclass = true; + + self::assertSame( + 0, + $this->proxyFactory->generateProxyClasses([$cm]), + 'No proxies generated.' + ); + } + + /** + * @group 6625 + */ + public function testSkipEmbeddableClassesOnGeneration(): void + { + $cm = new ClassMetadata(\stdClass::class); + $cm->isEmbeddedClass = true; + + self::assertSame( + 0, + $this->proxyFactory->generateProxyClasses([$cm]), + 'No proxies generated.' + ); + } + /** * @group DDC-1771 */ public function testSkipAbstractClassesOnGeneration() { - $cm = new ClassMetadata(__NAMESPACE__ . '\\AbstractClass'); + $cm = new ClassMetadata(AbstractClass::class); $cm->initializeReflection(new RuntimeReflectionService()); $this->assertNotNull($cm->reflClass); - $num = $this->proxyFactory->generateProxyClasses(array($cm)); + $num = $this->proxyFactory->generateProxyClasses([$cm]); $this->assertEquals(0, $num, "No proxies generated."); } @@ -91,11 +121,11 @@ public function testSkipAbstractClassesOnGeneration() */ public function testFailedProxyLoadingDoesNotMarkTheProxyAsInitialized() { - $persister = $this->getMockBuilder(BasicEntityPersister::class)->setMethods(array('load'))->disableOriginalConstructor()->getMock(); - $this->uowMock->setEntityPersister('Doctrine\Tests\Models\ECommerce\ECommerceFeature', $persister); + $persister = $this->getMockBuilder(BasicEntityPersister::class)->setMethods(['load'])->disableOriginalConstructor()->getMock(); + $this->uowMock->setEntityPersister(ECommerceFeature::class, $persister); /* @var $proxy \Doctrine\Common\Proxy\Proxy */ - $proxy = $this->proxyFactory->getProxy('Doctrine\Tests\Models\ECommerce\ECommerceFeature', array('id' => 42)); + $proxy = $this->proxyFactory->getProxy(ECommerceFeature::class, ['id' => 42]); $persister ->expects($this->atLeastOnce()) @@ -118,11 +148,11 @@ public function testFailedProxyLoadingDoesNotMarkTheProxyAsInitialized() */ public function testFailedProxyCloningDoesNotMarkTheProxyAsInitialized() { - $persister = $this->getMockBuilder(BasicEntityPersister::class)->setMethods(array('load'))->disableOriginalConstructor()->getMock(); - $this->uowMock->setEntityPersister('Doctrine\Tests\Models\ECommerce\ECommerceFeature', $persister); + $persister = $this->getMockBuilder(BasicEntityPersister::class)->setMethods(['load'])->disableOriginalConstructor()->getMock(); + $this->uowMock->setEntityPersister(ECommerceFeature::class, $persister); /* @var $proxy \Doctrine\Common\Proxy\Proxy */ - $proxy = $this->proxyFactory->getProxy('Doctrine\Tests\Models\ECommerce\ECommerceFeature', array('id' => 42)); + $proxy = $this->proxyFactory->getProxy(ECommerceFeature::class, ['id' => 42]); $persister ->expects($this->atLeastOnce()) @@ -139,6 +169,48 @@ public function testFailedProxyCloningDoesNotMarkTheProxyAsInitialized() $this->assertInstanceOf('Closure', $proxy->__getInitializer(), 'The initializer wasn\'t removed'); $this->assertInstanceOf('Closure', $proxy->__getCloner(), 'The cloner wasn\'t removed'); } + + public function testProxyClonesParentFields() + { + $companyEmployee = new CompanyEmployee(); + $companyEmployee->setSalary(1000); // A property on the CompanyEmployee + $companyEmployee->setName('Bob'); // A property on the parent class, CompanyPerson + + // Set the id of the CompanyEmployee (which is in the parent CompanyPerson) + $property = new \ReflectionProperty(CompanyPerson::class, 'id'); + + $property->setAccessible(true); + $property->setValue($companyEmployee, 42); + + $classMetaData = $this->emMock->getClassMetadata(CompanyEmployee::class); + + $persister = $this + ->getMockBuilder(BasicEntityPersister::class) + ->setMethods(['load', 'getClassMetadata']) + ->disableOriginalConstructor() + ->getMock(); + $this->uowMock->setEntityPersister(CompanyEmployee::class, $persister); + + /* @var $proxy \Doctrine\Common\Proxy\Proxy */ + $proxy = $this->proxyFactory->getProxy(CompanyEmployee::class, ['id' => 42]); + + $persister + ->expects(self::atLeastOnce()) + ->method('load') + ->willReturn($companyEmployee); + + $persister + ->expects(self::atLeastOnce()) + ->method('getClassMetadata') + ->willReturn($classMetaData); + + /* @var $cloned CompanyEmployee */ + $cloned = clone $proxy; + + self::assertSame(42, $cloned->getId(), 'Expected the Id to be cloned'); + self::assertSame(1000, $cloned->getSalary(), 'Expect properties on the CompanyEmployee class to be cloned'); + self::assertSame('Bob', $cloned->getName(), 'Expect properties on the CompanyPerson class to be cloned'); + } } abstract class AbstractClass diff --git a/tests/Doctrine/Tests/ORM/Query/CustomTreeWalkersJoinTest.php b/tests/Doctrine/Tests/ORM/Query/CustomTreeWalkersJoinTest.php index 284cc1adcab..9bc5bf5a0dc 100644 --- a/tests/Doctrine/Tests/ORM/Query/CustomTreeWalkersJoinTest.php +++ b/tests/Doctrine/Tests/ORM/Query/CustomTreeWalkersJoinTest.php @@ -1,25 +1,10 @@ . - */ namespace Doctrine\Tests\ORM\Query; use Doctrine\ORM\Query; +use Doctrine\Tests\Models\CMS\CmsAddress; +use Doctrine\Tests\Models\CMS\CmsUser; use Doctrine\Tests\OrmTestCase; /** @@ -42,7 +27,7 @@ public function assertSqlGeneration($dqlToBeTested, $sqlToBeConfirmed) { try { $query = $this->em->createQuery($dqlToBeTested); - $query->setHint(Query::HINT_CUSTOM_TREE_WALKERS, array('Doctrine\Tests\ORM\Query\CustomTreeWalkerJoin')) + $query->setHint(Query::HINT_CUSTOM_TREE_WALKERS, [CustomTreeWalkerJoin::class]) ->useQueryCache(false); $this->assertEquals($sqlToBeConfirmed, $query->getSql()); @@ -76,15 +61,15 @@ public function walkSelectStatement(Query\AST\SelectStatement $selectStatement) { foreach ($selectStatement->fromClause->identificationVariableDeclarations as $identificationVariableDeclaration) { $rangeVariableDecl = $identificationVariableDeclaration->rangeVariableDeclaration; - - if ($rangeVariableDecl->abstractSchemaName !== 'Doctrine\Tests\Models\CMS\CmsUser') { + + if ($rangeVariableDecl->abstractSchemaName !== CmsUser::class) { continue; } - + $this->modifySelectStatement($selectStatement, $identificationVariableDeclaration); } } - + private function modifySelectStatement(Query\AST\SelectStatement $selectStatement, $identificationVariableDecl) { $rangeVariableDecl = $identificationVariableDecl->rangeVariableDeclaration; @@ -92,23 +77,23 @@ private function modifySelectStatement(Query\AST\SelectStatement $selectStatemen $joinAssocDeclaration = new Query\AST\JoinAssociationDeclaration($joinAssocPathExpression, $rangeVariableDecl->aliasIdentificationVariable . 'a', null); $join = new Query\AST\Join(Query\AST\Join::JOIN_TYPE_LEFT, $joinAssocDeclaration); $selectExpression = new Query\AST\SelectExpression($rangeVariableDecl->aliasIdentificationVariable . 'a', null, false); - + $identificationVariableDecl->joins[] = $join; $selectStatement->selectClause->selectExpressions[] = $selectExpression; $entityManager = $this->_getQuery()->getEntityManager(); - $userMetadata = $entityManager->getClassMetadata('Doctrine\Tests\Models\CMS\CmsUser'); - $addressMetadata = $entityManager->getClassMetadata('Doctrine\Tests\Models\CMS\CmsAddress'); + $userMetadata = $entityManager->getClassMetadata(CmsUser::class); + $addressMetadata = $entityManager->getClassMetadata(CmsAddress::class); $this->setQueryComponent($rangeVariableDecl->aliasIdentificationVariable . 'a', - array( + [ 'metadata' => $addressMetadata, 'parent' => $rangeVariableDecl->aliasIdentificationVariable, 'relation' => $userMetadata->getAssociationMapping('address'), 'map' => null, 'nestingLevel' => 0, 'token' => null, - ) + ] ); } } diff --git a/tests/Doctrine/Tests/ORM/Query/CustomTreeWalkersTest.php b/tests/Doctrine/Tests/ORM/Query/CustomTreeWalkersTest.php index af7d2bf55d0..4c2898141a7 100644 --- a/tests/Doctrine/Tests/ORM/Query/CustomTreeWalkersTest.php +++ b/tests/Doctrine/Tests/ORM/Query/CustomTreeWalkersTest.php @@ -1,26 +1,11 @@ . - */ namespace Doctrine\Tests\ORM\Functional; use Doctrine\ORM\Query; use Doctrine\ORM\Query\QueryException; +use Doctrine\Tests\Models\CMS\CmsAddress; +use Doctrine\Tests\Models\CMS\CmsUser; use Doctrine\Tests\OrmTestCase; /** @@ -53,7 +38,7 @@ public function generateSql($dqlToBeTested, $treeWalkers, $outputWalker) return $query->getSql(); } - public function assertSqlGeneration($dqlToBeTested, $sqlToBeConfirmed, $treeWalkers = array(), $outputWalker = null) + public function assertSqlGeneration($dqlToBeTested, $sqlToBeConfirmed, $treeWalkers = [], $outputWalker = null) { try { $this->assertEquals($sqlToBeConfirmed, $this->generateSql($dqlToBeTested, $treeWalkers, $outputWalker)); @@ -67,7 +52,7 @@ public function testSupportsQueriesWithoutWhere() $this->assertSqlGeneration( 'select u from Doctrine\Tests\Models\CMS\CmsUser u', "SELECT c0_.id AS id_0, c0_.status AS status_1, c0_.username AS username_2, c0_.name AS name_3, c0_.email_id AS email_id_4 FROM cms_users c0_ WHERE c0_.id = 1", - array('Doctrine\Tests\ORM\Functional\CustomTreeWalker') + [CustomTreeWalker::class] ); } @@ -76,7 +61,7 @@ public function testSupportsQueriesWithMultipleConditionalExpressions() $this->assertSqlGeneration( 'select u from Doctrine\Tests\Models\CMS\CmsUser u where u.name = :name or u.name = :otherName', "SELECT c0_.id AS id_0, c0_.status AS status_1, c0_.username AS username_2, c0_.name AS name_3, c0_.email_id AS email_id_4 FROM cms_users c0_ WHERE (c0_.name = ? OR c0_.name = ?) AND c0_.id = 1", - array('Doctrine\Tests\ORM\Functional\CustomTreeWalker') + [CustomTreeWalker::class] ); } @@ -85,7 +70,7 @@ public function testSupportsQueriesWithSimpleConditionalExpression() $this->assertSqlGeneration( 'select u from Doctrine\Tests\Models\CMS\CmsUser u where u.name = :name', "SELECT c0_.id AS id_0, c0_.status AS status_1, c0_.username AS username_2, c0_.name AS name_3, c0_.email_id AS email_id_4 FROM cms_users c0_ WHERE c0_.name = ? AND c0_.id = 1", - array('Doctrine\Tests\ORM\Functional\CustomTreeWalker') + [CustomTreeWalker::class] ); } @@ -96,8 +81,8 @@ public function testSetUnknownQueryComponentThrowsException() $this->generateSql( 'select u from Doctrine\Tests\Models\CMS\CmsUser u', - array(), - __NAMESPACE__ . '\\AddUnknownQueryComponentWalker' + [], + AddUnknownQueryComponentWalker::class ); } @@ -106,7 +91,7 @@ public function testSupportsSeveralHintsQueries() $this->assertSqlGeneration( 'select u from Doctrine\Tests\Models\CMS\CmsUser u', "SELECT c0_.id AS id_0, c0_.status AS status_1, c0_.username AS username_2, c0_.name AS name_3, c1_.id AS id_4, c1_.country AS country_5, c1_.zip AS zip_6, c1_.city AS city_7, c0_.email_id AS email_id_8, c1_.user_id AS user_id_9 FROM cms_users c0_ LEFT JOIN cms_addresses c1_ ON c0_.id = c1_.user_id WHERE c0_.id = 1", - array('Doctrine\Tests\ORM\Functional\CustomTreeWalkerJoin', 'Doctrine\Tests\ORM\Functional\CustomTreeWalker') + [CustomTreeWalkerJoin::class, CustomTreeWalker::class] ); } } @@ -117,7 +102,7 @@ public function walkSelectStatement(Query\AST\SelectStatement $selectStatement) { parent::walkSelectStatement($selectStatement); - $this->setQueryComponent('x', array()); + $this->setQueryComponent('x', []); } } @@ -126,18 +111,18 @@ class CustomTreeWalker extends Query\TreeWalkerAdapter public function walkSelectStatement(Query\AST\SelectStatement $selectStatement) { // Get the DQL aliases of all the classes we want to modify - $dqlAliases = array(); + $dqlAliases = []; foreach ($this->_getQueryComponents() as $dqlAlias => $comp) { // Hard-coded check just for demonstration: We want to modify the query if // it involves the CmsUser class. - if ($comp['metadata']->name == 'Doctrine\Tests\Models\CMS\CmsUser') { + if ($comp['metadata']->name == CmsUser::class) { $dqlAliases[] = $dqlAlias; } } // Create our conditions for all involved classes - $factors = array(); + $factors = []; foreach ($dqlAliases as $alias) { $pathExpr = new Query\AST\PathExpression(Query\AST\PathExpression::TYPE_STATE_FIELD, $alias, 'id'); $pathExpr->type = Query\AST\PathExpression::TYPE_STATE_FIELD; @@ -156,7 +141,7 @@ public function walkSelectStatement(Query\AST\SelectStatement $selectStatement) // Since Phase 1 AST optimizations were included, we need to re-add the ConditionalExpression if ( ! ($condExpr instanceof Query\AST\ConditionalExpression)) { - $condExpr = new Query\AST\ConditionalExpression(array($condExpr)); + $condExpr = new Query\AST\ConditionalExpression([$condExpr]); $whereClause->conditionalExpression = $condExpr; } @@ -170,27 +155,27 @@ public function walkSelectStatement(Query\AST\SelectStatement $selectStatement) $primary = new Query\AST\ConditionalPrimary; $primary->conditionalExpression = new Query\AST\ConditionalExpression($existingTerms); $existingFactor = new Query\AST\ConditionalFactor($primary); - $term = new Query\AST\ConditionalTerm(array_merge(array($existingFactor), $factors)); + $term = new Query\AST\ConditionalTerm(array_merge([$existingFactor], $factors)); - $selectStatement->whereClause->conditionalExpression->conditionalTerms = array($term); + $selectStatement->whereClause->conditionalExpression->conditionalTerms = [$term]; } else { // Just one term so we can simply append our factors to that term $singleTerm = $selectStatement->whereClause->conditionalExpression->conditionalTerms[0]; // Since Phase 1 AST optimizations were included, we need to re-add the ConditionalExpression if ( ! ($singleTerm instanceof Query\AST\ConditionalTerm)) { - $singleTerm = new Query\AST\ConditionalTerm(array($singleTerm)); + $singleTerm = new Query\AST\ConditionalTerm([$singleTerm]); $selectStatement->whereClause->conditionalExpression->conditionalTerms[0] = $singleTerm; } $singleTerm->conditionalFactors = array_merge($singleTerm->conditionalFactors, $factors); - $selectStatement->whereClause->conditionalExpression->conditionalTerms = array($singleTerm); + $selectStatement->whereClause->conditionalExpression->conditionalTerms = [$singleTerm]; } } else { // Create a new WHERE clause with our factors $term = new Query\AST\ConditionalTerm($factors); - $condExpr = new Query\AST\ConditionalExpression(array($term)); + $condExpr = new Query\AST\ConditionalExpression([$term]); $whereClause = new Query\AST\WhereClause($condExpr); $selectStatement->whereClause = $whereClause; } @@ -203,15 +188,15 @@ public function walkSelectStatement(Query\AST\SelectStatement $selectStatement) { foreach ($selectStatement->fromClause->identificationVariableDeclarations as $identificationVariableDeclaration) { $rangeVariableDecl = $identificationVariableDeclaration->rangeVariableDeclaration; - - if ($rangeVariableDecl->abstractSchemaName !== 'Doctrine\Tests\Models\CMS\CmsUser') { + + if ($rangeVariableDecl->abstractSchemaName !== CmsUser::class) { continue; } - + $this->modifySelectStatement($selectStatement, $identificationVariableDeclaration); } } - + private function modifySelectStatement(Query\AST\SelectStatement $selectStatement, $identificationVariableDecl) { $rangeVariableDecl = $identificationVariableDecl->rangeVariableDeclaration; @@ -219,23 +204,23 @@ private function modifySelectStatement(Query\AST\SelectStatement $selectStatemen $joinAssocDeclaration = new Query\AST\JoinAssociationDeclaration($joinAssocPathExpression, $rangeVariableDecl->aliasIdentificationVariable . 'a', null); $join = new Query\AST\Join(Query\AST\Join::JOIN_TYPE_LEFT, $joinAssocDeclaration); $selectExpression = new Query\AST\SelectExpression($rangeVariableDecl->aliasIdentificationVariable . 'a', null, false); - + $identificationVariableDecl->joins[] = $join; $selectStatement->selectClause->selectExpressions[] = $selectExpression; $entityManager = $this->_getQuery()->getEntityManager(); - $userMetadata = $entityManager->getClassMetadata('Doctrine\Tests\Models\CMS\CmsUser'); - $addressMetadata = $entityManager->getClassMetadata('Doctrine\Tests\Models\CMS\CmsAddress'); + $userMetadata = $entityManager->getClassMetadata(CmsUser::class); + $addressMetadata = $entityManager->getClassMetadata(CmsAddress::class); $this->setQueryComponent($rangeVariableDecl->aliasIdentificationVariable . 'a', - array( + [ 'metadata' => $addressMetadata, 'parent' => $rangeVariableDecl->aliasIdentificationVariable, 'relation' => $userMetadata->getAssociationMapping('address'), 'map' => null, 'nestingLevel' => 0, 'token' => null, - ) + ] ); } -} \ No newline at end of file +} diff --git a/tests/Doctrine/Tests/ORM/Query/DeleteSqlGenerationTest.php b/tests/Doctrine/Tests/ORM/Query/DeleteSqlGenerationTest.php index 0bae052d808..ee5f98ac524 100644 --- a/tests/Doctrine/Tests/ORM/Query/DeleteSqlGenerationTest.php +++ b/tests/Doctrine/Tests/ORM/Query/DeleteSqlGenerationTest.php @@ -1,23 +1,4 @@ . - */ namespace Doctrine\Tests\ORM\Query; use Doctrine\Tests\OrmTestCase; @@ -55,6 +36,17 @@ public function assertSqlGeneration($dqlToBeTested, $sqlToBeConfirmed) } } + /** + * @group 6939 + */ + public function testSupportsDeleteWithoutWhereAndAlias() : void + { + $this->assertSqlGeneration( + 'DELETE FROM Doctrine\Tests\Models\CMS\CmsUser', + 'DELETE FROM cms_users' + ); + } + public function testSupportsDeleteWithoutWhereAndFrom() { $this->assertSqlGeneration( diff --git a/tests/Doctrine/Tests/ORM/Query/ExprTest.php b/tests/Doctrine/Tests/ORM/Query/ExprTest.php index 01e82ce6580..37a4b70a657 100644 --- a/tests/Doctrine/Tests/ORM/Query/ExprTest.php +++ b/tests/Doctrine/Tests/ORM/Query/ExprTest.php @@ -1,26 +1,9 @@ . - */ namespace Doctrine\Tests\ORM\Query; use Doctrine\ORM\Query\Expr; -use Doctrine\ORM\Query; +use Doctrine\Tests\Models\Company\CompanyEmployee; use Doctrine\Tests\OrmTestCase; /** @@ -72,7 +55,7 @@ public function testCountDistinctExpr() { $this->assertEquals('COUNT(DISTINCT u.id)', (string) $this->_expr->countDistinct('u.id')); } - + public function testCountDistinctExprMulti() { $this->assertEquals('COUNT(DISTINCT u.id, u.name)', (string) $this->_expr->countDistinct('u.id', 'u.name')); @@ -282,7 +265,7 @@ public function testIsNotNullExpr() } public function testIsInstanceOfExpr() { - $this->assertEquals('u INSTANCE OF Doctrine\Tests\Models\Company\CompanyEmployee', (string) $this->_expr->isInstanceOf('u', 'Doctrine\Tests\Models\Company\CompanyEmployee')); + $this->assertEquals('u INSTANCE OF Doctrine\Tests\Models\Company\CompanyEmployee', (string) $this->_expr->isInstanceOf('u', CompanyEmployee::class)); } public function testIsMemberOfExpr() { @@ -291,22 +274,22 @@ public function testIsMemberOfExpr() { public function testInExpr() { - $this->assertEquals('u.id IN(1, 2, 3)', (string) $this->_expr->in('u.id', array(1, 2, 3))); + $this->assertEquals('u.id IN(1, 2, 3)', (string) $this->_expr->in('u.id', [1, 2, 3])); } public function testInLiteralExpr() { - $this->assertEquals("u.type IN('foo', 'bar')", (string) $this->_expr->in('u.type', array('foo', 'bar'))); + $this->assertEquals("u.type IN('foo', 'bar')", (string) $this->_expr->in('u.type', ['foo', 'bar'])); } public function testNotInExpr() { - $this->assertEquals('u.id NOT IN(1, 2, 3)', (string) $this->_expr->notIn('u.id', array(1, 2, 3))); + $this->assertEquals('u.id NOT IN(1, 2, 3)', (string) $this->_expr->notIn('u.id', [1, 2, 3])); } public function testNotInLiteralExpr() { - $this->assertEquals("u.type NOT IN('foo', 'bar')", (string) $this->_expr->notIn('u.type', array('foo', 'bar'))); + $this->assertEquals("u.type NOT IN('foo', 'bar')", (string) $this->_expr->notIn('u.type', ['foo', 'bar'])); } public function testAndxOrxExpr() @@ -377,8 +360,8 @@ public function testExpressionGetter() { // Andx - $andx = new Expr\Andx(array('1 = 1', '2 = 2')); - $this->assertEquals(array('1 = 1', '2 = 2'), $andx->getParts()); + $andx = new Expr\Andx(['1 = 1', '2 = 2']); + $this->assertEquals(['1 = 1', '2 = 2'], $andx->getParts()); // Comparison $comparison = new Expr\Comparison('foo', Expr\Comparison::EQ, 'bar'); @@ -393,13 +376,13 @@ public function testExpressionGetter() $this->assertEquals('f.id', $from->getIndexBy()); // Func - $func = new Expr\Func('MAX', array('f.id')); + $func = new Expr\Func('MAX', ['f.id']); $this->assertEquals('MAX', $func->getName()); - $this->assertEquals(array('f.id'), $func->getArguments()); + $this->assertEquals(['f.id'], $func->getArguments()); // GroupBy - $group = new Expr\GroupBy(array('foo DESC', 'bar ASC')); - $this->assertEquals(array('foo DESC', 'bar ASC'), $group->getParts()); + $group = new Expr\GroupBy(['foo DESC', 'bar ASC']); + $this->assertEquals(['foo DESC', 'bar ASC'], $group->getParts()); // Join $join = new Expr\Join(Expr\Join::INNER_JOIN, 'f.bar', 'b', Expr\Join::ON, 'b.bar_id = 1', 'b.bar_id'); @@ -411,8 +394,8 @@ public function testExpressionGetter() $this->assertEquals('b', $join->getAlias()); // Literal - $literal = new Expr\Literal(array('foo')); - $this->assertEquals(array('foo'), $literal->getParts()); + $literal = new Expr\Literal(['foo']); + $this->assertEquals(['foo'], $literal->getParts()); // Math $math = new Expr\Math(10, '+', 20); @@ -422,22 +405,22 @@ public function testExpressionGetter() // OrderBy $order = new Expr\OrderBy('foo', 'DESC'); - $this->assertEquals(array('foo DESC'), $order->getParts()); + $this->assertEquals(['foo DESC'], $order->getParts()); // Andx - $orx = new Expr\Orx(array('foo = 1', 'bar = 2')); - $this->assertEquals(array('foo = 1', 'bar = 2'), $orx->getParts()); + $orx = new Expr\Orx(['foo = 1', 'bar = 2']); + $this->assertEquals(['foo = 1', 'bar = 2'], $orx->getParts()); // Select - $select = new Expr\Select(array('foo', 'bar')); - $this->assertEquals(array('foo', 'bar'), $select->getParts()); + $select = new Expr\Select(['foo', 'bar']); + $this->assertEquals(['foo', 'bar'], $select->getParts()); } public function testAddEmpty() { $andExpr = $this->_expr->andX(); $andExpr->add($this->_expr->andX()); - + $this->assertEquals(0, $andExpr->count()); } @@ -445,7 +428,7 @@ public function testAddNull() { $andExpr = $this->_expr->andX(); $andExpr->add(null); - + $this->assertEquals(0, $andExpr->count()); } } diff --git a/tests/Doctrine/Tests/ORM/Query/FilterCollectionTest.php b/tests/Doctrine/Tests/ORM/Query/FilterCollectionTest.php index 7a50516a793..0e47f6e82d6 100644 --- a/tests/Doctrine/Tests/ORM/Query/FilterCollectionTest.php +++ b/tests/Doctrine/Tests/ORM/Query/FilterCollectionTest.php @@ -2,8 +2,8 @@ namespace Doctrine\Tests\ORM\Query; -use Doctrine\ORM\Mapping\ClassMetadata, - Doctrine\ORM\Query\Filter\SQLFilter; +use Doctrine\ORM\Mapping\ClassMetadata; +use Doctrine\ORM\Query\Filter\SQLFilter; use Doctrine\Tests\OrmTestCase; /** @@ -21,8 +21,7 @@ class FilterCollectionTest extends OrmTestCase protected function setUp() { $this->em = $this->_getTestEntityManager(); - - $this->em->getConfiguration()->addFilter('testFilter', 'Doctrine\Tests\ORM\Query\MyFilter'); + $this->em->getConfiguration()->addFilter('testFilter', MyFilter::class); } public function testEnable() @@ -36,7 +35,7 @@ public function testEnable() $enabledFilters = $filterCollection->getEnabledFilters(); $this->assertCount(1, $enabledFilters); - $this->assertContainsOnly('Doctrine\Tests\ORM\Query\MyFilter', $enabledFilters); + $this->assertContainsOnly(MyFilter::class, $enabledFilters); $filterCollection->disable('testFilter'); $this->assertCount(0, $filterCollection->getEnabledFilters()); @@ -70,17 +69,15 @@ public function testIsEnabled() public function testGetFilterInvalidArgument() { $filterCollection = $this->em->getFilters(); - $filterCollection->getFilter('testFilter'); } public function testGetFilter() { $filterCollection = $this->em->getFilters(); - $filterCollection->enable('testFilter'); - $this->assertInstanceOf('Doctrine\Tests\ORM\Query\MyFilter', $filterCollection->getFilter('testFilter')); + $this->assertInstanceOf(MyFilter::class, $filterCollection->getFilter('testFilter')); } } diff --git a/tests/Doctrine/Tests/ORM/Query/LanguageRecognitionTest.php b/tests/Doctrine/Tests/ORM/Query/LanguageRecognitionTest.php index fe12b3989d4..fe3b298cbf9 100644 --- a/tests/Doctrine/Tests/ORM/Query/LanguageRecognitionTest.php +++ b/tests/Doctrine/Tests/ORM/Query/LanguageRecognitionTest.php @@ -5,6 +5,7 @@ use Doctrine\ORM\EntityManagerInterface; use Doctrine\ORM\Query, Doctrine\ORM\Query\QueryException; +use Doctrine\Tests\Mocks\MockTreeWalker; use Doctrine\Tests\OrmTestCase; class LanguageRecognitionTest extends OrmTestCase @@ -23,6 +24,7 @@ public function assertValidDQL($dql, $debug = false) { try { $parserResult = $this->parseDql($dql); + $this->addToAssertionCount(1); } catch (QueryException $e) { if ($debug) { echo $e->getTraceAsString() . PHP_EOL; @@ -43,10 +45,11 @@ public function assertInvalidDQL($dql, $debug = false) echo $e->getMessage() . PHP_EOL; echo $e->getTraceAsString() . PHP_EOL; } + $this->addToAssertionCount(1); } } - public function parseDql($dql, $hints = array()) + public function parseDql($dql, $hints = []) { $query = $this->_em->createQuery($dql); $query->setHint(Query::HINT_FORCE_PARTIAL_LOAD, true); @@ -59,7 +62,7 @@ public function parseDql($dql, $hints = array()) $parser = new Query\Parser($query); // We do NOT test SQL output here. That only unnecessarily slows down the tests! - $parser->setCustomOutputTreeWalker('Doctrine\Tests\Mocks\MockTreeWalker'); + $parser->setCustomOutputTreeWalker(MockTreeWalker::class); return $parser->parse(); } @@ -86,50 +89,52 @@ public function testRejectsInvalidDQL($dql) { $this->expectException(QueryException::class); - $this->_em->getConfiguration()->setEntityNamespaces(array( + $this->_em->getConfiguration()->setEntityNamespaces( + [ 'Unknown' => 'Unknown', 'CMS' => 'Doctrine\Tests\Models\CMS' - )); + ] + ); $this->parseDql($dql); } public function invalidDQL() { - return array( + return [ - array('SELECT \'foo\' AS foo\bar FROM Doctrine\Tests\Models\CMS\CmsUser u'), + ['SELECT \'foo\' AS foo\bar FROM Doctrine\Tests\Models\CMS\CmsUser u'], /* Checks for invalid IdentificationVariables and AliasIdentificationVariables */ - array('SELECT \foo FROM Doctrine\Tests\Models\CMS\CmsUser \foo'), - array('SELECT foo\ FROM Doctrine\Tests\Models\CMS\CmsUser foo\\'), - array('SELECT foo\bar FROM Doctrine\Tests\Models\CMS\CmsUser foo\bar'), - array('SELECT foo:bar FROM Doctrine\Tests\Models\CMS\CmsUser foo:bar'), - array('SELECT foo: FROM Doctrine\Tests\Models\CMS\CmsUser foo:'), + ['SELECT \foo FROM Doctrine\Tests\Models\CMS\CmsUser \foo'], + ['SELECT foo\ FROM Doctrine\Tests\Models\CMS\CmsUser foo\\'], + ['SELECT foo\bar FROM Doctrine\Tests\Models\CMS\CmsUser foo\bar'], + ['SELECT foo:bar FROM Doctrine\Tests\Models\CMS\CmsUser foo:bar'], + ['SELECT foo: FROM Doctrine\Tests\Models\CMS\CmsUser foo:'], /* Checks for invalid AbstractSchemaName */ - array('SELECT u FROM UnknownClass u'), // unknown - array('SELECT u FROM Unknown\Class u'), // unknown with namespace - array('SELECT u FROM \Unknown\Class u'), // unknown, leading backslash - array('SELECT u FROM Unknown\\\\Class u'), // unknown, syntactically bogus (duplicate \\) - array('SELECT u FROM Unknown\Class\ u'), // unknown, syntactically bogus (trailing \) - array('SELECT u FROM Unknown:Class u'), // unknown, with namespace alias - array('SELECT u FROM Unknown::Class u'), // unknown, with PAAMAYIM_NEKUDOTAYIM - array('SELECT u FROM Unknown:Class:Name u'), // unknown, with invalid namespace alias - array('SELECT u FROM UnknownClass: u'), // unknown, with invalid namespace alias - array('SELECT u FROM Unknown:Class: u'), // unknown, with invalid namespace alias - array('SELECT u FROM Doctrine\Tests\Models\CMS\\\\CmsUser u'), // syntactically bogus (duplicate \\)array('SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser\ u'), // syntactically bogus (trailing \) - array('SELECT u FROM CMS::User u'), - array('SELECT u FROM CMS:User: u'), - array('SELECT u FROM CMS:User:Foo u'), + ['SELECT u FROM UnknownClass u'], // unknown + ['SELECT u FROM Unknown\Class u'], // unknown with namespace + ['SELECT u FROM \Unknown\Class u'], // unknown, leading backslash + ['SELECT u FROM Unknown\\\\Class u'], // unknown, syntactically bogus (duplicate \\) + ['SELECT u FROM Unknown\Class\ u'], // unknown, syntactically bogus (trailing \) + ['SELECT u FROM Unknown:Class u'], // unknown, with namespace alias + ['SELECT u FROM Unknown::Class u'], // unknown, with PAAMAYIM_NEKUDOTAYIM + ['SELECT u FROM Unknown:Class:Name u'], // unknown, with invalid namespace alias + ['SELECT u FROM UnknownClass: u'], // unknown, with invalid namespace alias + ['SELECT u FROM Unknown:Class: u'], // unknown, with invalid namespace alias + ['SELECT u FROM Doctrine\Tests\Models\CMS\\\\CmsUser u'], // syntactically bogus (duplicate \\)array('SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser\ u'), // syntactically bogus (trailing \) + ['SELECT u FROM CMS::User u'], + ['SELECT u FROM CMS:User: u'], + ['SELECT u FROM CMS:User:Foo u'], /* Checks for invalid AliasResultVariable */ - array('SELECT \'foo\' AS \foo FROM Doctrine\Tests\Models\CMS\CmsUser u'), - array('SELECT \'foo\' AS \foo\bar FROM Doctrine\Tests\Models\CMS\CmsUser u'), - array('SELECT \'foo\' AS foo\ FROM Doctrine\Tests\Models\CMS\CmsUser u'), - array('SELECT \'foo\' AS foo\\\\bar FROM Doctrine\Tests\Models\CMS\CmsUser u'), - array('SELECT \'foo\' AS foo: FROM Doctrine\Tests\Models\CMS\CmsUser u'), - array('SELECT \'foo\' AS foo:bar FROM Doctrine\Tests\Models\CMS\CmsUser u'), - ); + ['SELECT \'foo\' AS \foo FROM Doctrine\Tests\Models\CMS\CmsUser u'], + ['SELECT \'foo\' AS \foo\bar FROM Doctrine\Tests\Models\CMS\CmsUser u'], + ['SELECT \'foo\' AS foo\ FROM Doctrine\Tests\Models\CMS\CmsUser u'], + ['SELECT \'foo\' AS foo\\\\bar FROM Doctrine\Tests\Models\CMS\CmsUser u'], + ['SELECT \'foo\' AS foo: FROM Doctrine\Tests\Models\CMS\CmsUser u'], + ['SELECT \'foo\' AS foo:bar FROM Doctrine\Tests\Models\CMS\CmsUser u'], + ]; } public function testSelectSingleComponentWithMultipleColumns() @@ -570,7 +575,7 @@ public function testInputParameterInSelect() */ public function testCustomFunctionsReturningStringInStringPrimary() { - $this->_em->getConfiguration()->addCustomStringFunction('CC', 'Doctrine\ORM\Query\AST\Functions\ConcatFunction'); + $this->_em->getConfiguration()->addCustomStringFunction('CC', Query\AST\Functions\ConcatFunction::class); $this->assertValidDQL("SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE CC('%', u.name) LIKE '%foo%'", true); } @@ -671,7 +676,7 @@ public function testHavingSupportIsNullExpression() { $this->assertValidDQL("SELECT u.name FROM Doctrine\Tests\Models\CMS\CmsUser u HAVING u.username IS NULL"); } - + /** * @group DDC-3085 */ @@ -703,6 +708,13 @@ public function testNewLiteralWithSubselectExpression() { $this->assertValidDQL("SELECT new " . __NAMESPACE__ . "\\DummyStruct(u.id, 'foo', (SELECT 1 FROM Doctrine\Tests\Models\CMS\CmsUser su), true) FROM Doctrine\Tests\Models\CMS\CmsUser u"); } + + public function testStringPrimaryAcceptsAggregateExpression() : void + { + $this->assertValidDQL( + 'SELECT CONCAT(a.topic, MAX(a.version)) last FROM Doctrine\Tests\Models\CMS\CmsArticle a GROUP BY a' + ); + } } /** @Entity */ diff --git a/tests/Doctrine/Tests/ORM/Query/LexerTest.php b/tests/Doctrine/Tests/ORM/Query/LexerTest.php index 9c4a889f04b..904b8978786 100644 --- a/tests/Doctrine/Tests/ORM/Query/LexerTest.php +++ b/tests/Doctrine/Tests/ORM/Query/LexerTest.php @@ -161,63 +161,63 @@ public function testScannerTokenizesASimpleQueryCorrectly() $dql = "SELECT u FROM My\Namespace\User u WHERE u.name = 'Jack O''Neil'"; $lexer = new Lexer($dql); - $tokens = array( - array( + $tokens = [ + [ 'value' => 'SELECT', 'type' => Lexer::T_SELECT, 'position' => 0 - ), - array( + ], + [ 'value' => 'u', 'type' => Lexer::T_IDENTIFIER, 'position' => 7 - ), - array( + ], + [ 'value' => 'FROM', 'type' => Lexer::T_FROM, 'position' => 9 - ), - array( + ], + [ 'value' => 'My\Namespace\User', 'type' => Lexer::T_FULLY_QUALIFIED_NAME, 'position' => 14 - ), - array( + ], + [ 'value' => 'u', 'type' => Lexer::T_IDENTIFIER, 'position' => 32 - ), - array( + ], + [ 'value' => 'WHERE', 'type' => Lexer::T_WHERE, 'position' => 34 - ), - array( + ], + [ 'value' => 'u', 'type' => Lexer::T_IDENTIFIER, 'position' => 40 - ), - array( + ], + [ 'value' => '.', 'type' => Lexer::T_DOT, 'position' => 41 - ), - array( + ], + [ 'value' => 'name', 'type' => Lexer::T_IDENTIFIER, 'position' => 42 - ), - array( + ], + [ 'value' => '=', 'type' => Lexer::T_EQUALS, 'position' => 47 - ), - array( + ], + [ 'value' => "Jack O'Neil", 'type' => Lexer::T_STRING, 'position' => 49 - ) - ); + ] + ]; foreach ($tokens as $expected) { $lexer->moveNext(); @@ -232,16 +232,16 @@ public function testScannerTokenizesASimpleQueryCorrectly() public function provideTokens() { - return array( - array(Lexer::T_IDENTIFIER, 'u'), // one char - array(Lexer::T_IDENTIFIER, 'someIdentifier'), - array(Lexer::T_IDENTIFIER, 's0m31d3nt1f13r'), // including digits - array(Lexer::T_IDENTIFIER, 'some_identifier'), // including underscore - array(Lexer::T_IDENTIFIER, '_some_identifier'), // starts with underscore - array(Lexer::T_IDENTIFIER, 'comma'), // name of a token class with value < 100 (whitebox test) - array(Lexer::T_FULLY_QUALIFIED_NAME, 'Some\Class'), // DQL class reference - array(Lexer::T_ALIASED_NAME, 'Some:Name'), - array(Lexer::T_ALIASED_NAME, 'Some:Subclassed\Name') - ); + return [ + [Lexer::T_IDENTIFIER, 'u'], // one char + [Lexer::T_IDENTIFIER, 'someIdentifier'], + [Lexer::T_IDENTIFIER, 's0m31d3nt1f13r'], // including digits + [Lexer::T_IDENTIFIER, 'some_identifier'], // including underscore + [Lexer::T_IDENTIFIER, '_some_identifier'], // starts with underscore + [Lexer::T_IDENTIFIER, 'comma'], // name of a token class with value < 100 (whitebox test) + [Lexer::T_FULLY_QUALIFIED_NAME, 'Some\Class'], // DQL class reference + [Lexer::T_ALIASED_NAME, 'Some:Name'], + [Lexer::T_ALIASED_NAME, 'Some:Subclassed\Name'] + ]; } } diff --git a/tests/Doctrine/Tests/ORM/Query/ParameterTypeInfererTest.php b/tests/Doctrine/Tests/ORM/Query/ParameterTypeInfererTest.php index d10c78c9c49..35e9bf2f57e 100644 --- a/tests/Doctrine/Tests/ORM/Query/ParameterTypeInfererTest.php +++ b/tests/Doctrine/Tests/ORM/Query/ParameterTypeInfererTest.php @@ -1,21 +1,5 @@ . - */ + namespace Doctrine\Tests\ORM\Query; use Doctrine\ORM\Query\ParameterTypeInferer; @@ -29,20 +13,21 @@ class ParameterTypeInfererTest extends OrmTestCase public function providerParameterTypeInferer() { - $data = array( - array(1, Type::INTEGER), - array("bar", PDO::PARAM_STR), - array("1", PDO::PARAM_STR), - array(new \DateTime, Type::DATETIME), - array(array(2), Connection::PARAM_INT_ARRAY), - array(array("foo"), Connection::PARAM_STR_ARRAY), - array(array("1","2"), Connection::PARAM_STR_ARRAY), - array(array(), Connection::PARAM_STR_ARRAY), - array(true, Type::BOOLEAN), - ); + $data = [ + [1, Type::INTEGER], + ["bar", PDO::PARAM_STR], + ["1", PDO::PARAM_STR], + [new \DateTime, Type::DATETIME], + [new \DateInterval('P1D'), Type::DATEINTERVAL], + [[2], Connection::PARAM_INT_ARRAY], + [["foo"], Connection::PARAM_STR_ARRAY], + [["1","2"], Connection::PARAM_STR_ARRAY], + [[], Connection::PARAM_STR_ARRAY], + [true, Type::BOOLEAN], + ]; if (PHP_VERSION_ID >= 50500) { - $data[] = array(new \DateTimeImmutable(), Type::DATETIME); + $data[] = [new \DateTimeImmutable(), Type::DATETIME]; } return $data; diff --git a/tests/Doctrine/Tests/ORM/Query/ParserResultTest.php b/tests/Doctrine/Tests/ORM/Query/ParserResultTest.php index 086e1d43e2a..1b74654430e 100644 --- a/tests/Doctrine/Tests/ORM/Query/ParserResultTest.php +++ b/tests/Doctrine/Tests/ORM/Query/ParserResultTest.php @@ -4,8 +4,10 @@ use Doctrine\ORM\Query\Exec\AbstractSqlExecutor; use Doctrine\ORM\Query\ParserResult; +use Doctrine\ORM\Query\ResultSetMapping; +use PHPUnit\Framework\TestCase; -class ParserResultTest extends \PHPUnit_Framework_TestCase +class ParserResultTest extends TestCase { public $parserResult; @@ -16,17 +18,14 @@ public function setUp() public function testGetRsm() { - $this->assertInstanceOf( - 'Doctrine\ORM\Query\ResultSetMapping', - $this->parserResult->getResultSetMapping() - ); + $this->assertInstanceOf(ResultSetMapping::class, $this->parserResult->getResultSetMapping()); } public function testSetGetSqlExecutor() { $this->assertNull($this->parserResult->getSqlExecutor()); - $executor = $this->getMockBuilder(AbstractSqlExecutor::class)->setMethods(array('execute'))->getMock(); + $executor = $this->getMockBuilder(AbstractSqlExecutor::class)->setMethods(['execute'])->getMock(); $this->parserResult->setSqlExecutor($executor); $this->assertSame($executor, $this->parserResult->getSqlExecutor()); } @@ -35,7 +34,7 @@ public function testGetSqlParameterPosition() { $this->parserResult->addParameterMapping(1, 1); $this->parserResult->addParameterMapping(1, 2); - $this->assertEquals(array(1, 2), $this->parserResult->getSqlParameterPositions(1)); + $this->assertEquals([1, 2], $this->parserResult->getSqlParameterPositions(1)); } public function testGetParameterMappings() @@ -44,6 +43,6 @@ public function testGetParameterMappings() $this->parserResult->addParameterMapping(1, 1); $this->parserResult->addParameterMapping(1, 2); - $this->assertEquals(array(1 => array(1, 2)), $this->parserResult->getParameterMappings()); + $this->assertEquals([1 => [1, 2]], $this->parserResult->getParameterMappings()); } -} \ No newline at end of file +} diff --git a/tests/Doctrine/Tests/ORM/Query/ParserTest.php b/tests/Doctrine/Tests/ORM/Query/ParserTest.php index fb320773eb5..b290812fc85 100644 --- a/tests/Doctrine/Tests/ORM/Query/ParserTest.php +++ b/tests/Doctrine/Tests/ORM/Query/ParserTest.php @@ -6,6 +6,7 @@ use Doctrine\ORM\Query\Lexer; use Doctrine\ORM\Query\Parser; use Doctrine\ORM\Query\QueryException; +use Doctrine\Tests\Models\CMS\CmsUser; use Doctrine\Tests\OrmTestCase; class ParserTest extends OrmTestCase @@ -17,9 +18,9 @@ class ParserTest extends OrmTestCase */ public function testAbstractSchemaNameSupportsFQCN() { - $parser = $this->createParser('Doctrine\Tests\Models\CMS\CmsUser'); + $parser = $this->createParser(CmsUser::class); - $this->assertEquals('Doctrine\Tests\Models\CMS\CmsUser', $parser->AbstractSchemaName()); + $this->assertEquals(CmsUser::class, $parser->AbstractSchemaName()); } /** @@ -28,9 +29,9 @@ public function testAbstractSchemaNameSupportsFQCN() */ public function testAbstractSchemaNameSupportsClassnamesWithLeadingBackslash() { - $parser = $this->createParser('\Doctrine\Tests\Models\CMS\CmsUser'); + $parser = $this->createParser('\\' . CmsUser::class); - $this->assertEquals('\Doctrine\Tests\Models\CMS\CmsUser', $parser->AbstractSchemaName()); + $this->assertEquals('\\' . CmsUser::class, $parser->AbstractSchemaName()); } /** @@ -39,9 +40,9 @@ public function testAbstractSchemaNameSupportsClassnamesWithLeadingBackslash() */ public function testAbstractSchemaNameSupportsIdentifier() { - $parser = $this->createParser('stdClass'); + $parser = $this->createParser(\stdClass::class); - $this->assertEquals('stdClass', $parser->AbstractSchemaName()); + $this->assertEquals(\stdClass::class, $parser->AbstractSchemaName()); } /** @@ -54,7 +55,7 @@ public function testAbstractSchemaNameSupportsNamespaceAlias() $parser->getEntityManager()->getConfiguration()->addEntityNamespace('CMS', 'Doctrine\Tests\Models\CMS'); - $this->assertEquals('Doctrine\Tests\Models\CMS\CmsUser', $parser->AbstractSchemaName()); + $this->assertEquals(CmsUser::class, $parser->AbstractSchemaName()); } /** @@ -67,7 +68,7 @@ public function testAbstractSchemaNameSupportsNamespaceAliasWithRelativeClassnam $parser->getEntityManager()->getConfiguration()->addEntityNamespace('Model', 'Doctrine\Tests\Models'); - $this->assertEquals('Doctrine\Tests\Models\CMS\CmsUser', $parser->AbstractSchemaName()); + $this->assertEquals(CmsUser::class, $parser->AbstractSchemaName()); } /** @@ -108,28 +109,29 @@ public function validMatches() * The basic checks that tokens are classified correctly do not belong here * but in LexerTest. */ - return array( - array(Lexer::T_WHERE, 'where'), // keyword - array(Lexer::T_DOT, '.'), // token that cannot be an identifier - array(Lexer::T_IDENTIFIER, 'someIdentifier'), - array(Lexer::T_IDENTIFIER, 'from'), // also a terminal string (the "FROM" keyword) as in DDC-505 - array(Lexer::T_IDENTIFIER, 'comma') // not even a terminal string, but the name of a constant in the Lexer (whitebox test) - ); + return [ + [Lexer::T_WHERE, 'where'], // keyword + [Lexer::T_DOT, '.'], // token that cannot be an identifier + [Lexer::T_IDENTIFIER, 'someIdentifier'], + [Lexer::T_IDENTIFIER, 'from'], // also a terminal string (the "FROM" keyword) as in DDC-505 + [Lexer::T_IDENTIFIER, 'comma'] + // not even a terminal string, but the name of a constant in the Lexer (whitebox test) + ]; } public function invalidMatches() { - return array( - array(Lexer::T_DOT, 'ALL'), // ALL is a terminal string (reserved keyword) and also possibly an identifier - array(Lexer::T_DOT, ','), // "," is a token on its own, but cannot be used as identifier - array(Lexer::T_WHERE, 'WITH'), // as in DDC-3697 - array(Lexer::T_WHERE, '.'), + return [ + [Lexer::T_DOT, 'ALL'], // ALL is a terminal string (reserved keyword) and also possibly an identifier + [Lexer::T_DOT, ','], // "," is a token on its own, but cannot be used as identifier + [Lexer::T_WHERE, 'WITH'], // as in DDC-3697 + [Lexer::T_WHERE, '.'], // The following are qualified or aliased names and must not be accepted where only an Identifier is expected - array(Lexer::T_IDENTIFIER, '\\Some\\Class'), - array(Lexer::T_IDENTIFIER, 'Some\\Class'), - array(Lexer::T_IDENTIFIER, 'Some:Name'), - ); + [Lexer::T_IDENTIFIER, '\\Some\\Class'], + [Lexer::T_IDENTIFIER, 'Some\\Class'], + [Lexer::T_IDENTIFIER, 'Some:Name'], + ]; } private function createParser($dql) diff --git a/tests/Doctrine/Tests/ORM/Query/QueryExpressionVisitorTest.php b/tests/Doctrine/Tests/ORM/Query/QueryExpressionVisitorTest.php index 2b9fc2304b1..27dce7d6d95 100644 --- a/tests/Doctrine/Tests/ORM/Query/QueryExpressionVisitorTest.php +++ b/tests/Doctrine/Tests/ORM/Query/QueryExpressionVisitorTest.php @@ -1,41 +1,22 @@ . - */ namespace Doctrine\Tests\ORM\Query; use Doctrine\Common\Collections\ArrayCollection; - -use Doctrine\Common\Collections\Expr\Value; use Doctrine\Common\Collections\Expr\Comparison as CriteriaComparison; -use Doctrine\ORM\Query\Expr\Comparison as QueryComparison; +use Doctrine\Common\Collections\Expr\Value; use Doctrine\Common\Collections\ExpressionBuilder as CriteriaBuilder; use Doctrine\ORM\Query\Expr as QueryBuilder; - use Doctrine\ORM\Query\Parameter; use Doctrine\ORM\Query\QueryExpressionVisitor; +use PHPUnit\Framework\TestCase; /** * Test for QueryExpressionVisitor * * @author Kirill chEbba Chebunin */ -class QueryExpressionVisitorTest extends \PHPUnit_Framework_TestCase +class QueryExpressionVisitorTest extends TestCase { /** * @var QueryExpressionVisitor @@ -47,12 +28,12 @@ class QueryExpressionVisitorTest extends \PHPUnit_Framework_TestCase */ protected function setUp() { - $this->visitor = new QueryExpressionVisitor(array('o','p')); + $this->visitor = new QueryExpressionVisitor(['o','p']); } /** * @param CriteriaComparison $criteriaExpr - * @param QueryComparison|string $queryExpr + * @param QueryBuilder\Comparison|string $queryExpr * @param Parameter $parameter * * @dataProvider comparisonData @@ -61,7 +42,7 @@ public function testWalkComparison(CriteriaComparison $criteriaExpr, $queryExpr, { $this->assertEquals($queryExpr, $this->visitor->walkComparison($criteriaExpr)); if ($parameter) { - $this->assertEquals(new ArrayCollection(array($parameter)), $this->visitor->getParameters()); + $this->assertEquals(new ArrayCollection([$parameter]), $this->visitor->getParameters()); } } @@ -70,30 +51,34 @@ public function comparisonData() $cb = new CriteriaBuilder(); $qb = new QueryBuilder(); - return array( - array($cb->eq('field', 'value'), $qb->eq('o.field', ':field'), new Parameter('field', 'value')), - array($cb->neq('field', 'value'), $qb->neq('o.field', ':field'), new Parameter('field', 'value')), - array($cb->eq('field', null), $qb->isNull('o.field')), - array($cb->neq('field', null), $qb->isNotNull('o.field')), - array($cb->isNull('field'), $qb->isNull('o.field')), + return [ + [$cb->eq('field', 'value'), $qb->eq('o.field', ':field'), new Parameter('field', 'value')], + [$cb->neq('field', 'value'), $qb->neq('o.field', ':field'), new Parameter('field', 'value')], + [$cb->eq('field', null), $qb->isNull('o.field')], + [$cb->neq('field', null), $qb->isNotNull('o.field')], + [$cb->isNull('field'), $qb->isNull('o.field')], - array($cb->gt('field', 'value'), $qb->gt('o.field', ':field'), new Parameter('field', 'value')), - array($cb->gte('field', 'value'), $qb->gte('o.field', ':field'), new Parameter('field', 'value')), - array($cb->lt('field', 'value'), $qb->lt('o.field', ':field'), new Parameter('field', 'value')), - array($cb->lte('field', 'value'), $qb->lte('o.field', ':field'), new Parameter('field', 'value')), + [$cb->gt('field', 'value'), $qb->gt('o.field', ':field'), new Parameter('field', 'value')], + [$cb->gte('field', 'value'), $qb->gte('o.field', ':field'), new Parameter('field', 'value')], + [$cb->lt('field', 'value'), $qb->lt('o.field', ':field'), new Parameter('field', 'value')], + [$cb->lte('field', 'value'), $qb->lte('o.field', ':field'), new Parameter('field', 'value')], - array($cb->in('field', array('value')), $qb->in('o.field', ':field'), new Parameter('field', array('value'))), - array($cb->notIn('field', array('value')), $qb->notIn('o.field', ':field'), new Parameter('field', array('value'))), + [$cb->in('field', ['value']), $qb->in('o.field', ':field'), new Parameter('field', ['value'])], + [$cb->notIn('field', ['value']), $qb->notIn('o.field', ':field'), new Parameter('field', ['value'])], - array($cb->contains('field', 'value'), $qb->like('o.field', ':field'), new Parameter('field', '%value%')), + [$cb->contains('field', 'value'), $qb->like('o.field', ':field'), new Parameter('field', '%value%')], + [$cb->memberOf(':field', 'o.field'), $qb->isMemberOf(':field', 'o.field')], + + [$cb->startsWith('field', 'value'), $qb->like('o.field', ':field'), new Parameter('field', 'value%')], + [$cb->endsWith('field', 'value'), $qb->like('o.field', ':field'), new Parameter('field', '%value')], // Test parameter conversion - array($cb->eq('object.field', 'value'), $qb->eq('o.object.field', ':object_field'), new Parameter('object_field', 'value')), + [$cb->eq('object.field', 'value'), $qb->eq('o.object.field', ':object_field'), new Parameter('object_field', 'value')], // Test alternative rootAlias - array($cb->eq('p.field', 'value'), $qb->eq('p.field', ':p_field'), new Parameter('p_field', 'value')), - array($cb->eq('p.object.field', 'value'), $qb->eq('p.object.field', ':p_object_field'), new Parameter('p_object_field', 'value')), - ); + [$cb->eq('p.field', 'value'), $qb->eq('p.field', ':p_field'), new Parameter('p_field', 'value')], + [$cb->eq('p.object.field', 'value'), $qb->eq('p.object.field', ':p_object_field'), new Parameter('p_object_field', 'value')], + ]; } public function testWalkAndCompositeExpression() @@ -106,7 +91,7 @@ public function testWalkAndCompositeExpression() ) ); - $this->assertInstanceOf('Doctrine\ORM\Query\Expr\Andx', $expr); + $this->assertInstanceOf(QueryBuilder\Andx::class, $expr); $this->assertCount(2, $expr->getParts()); } @@ -120,7 +105,7 @@ public function testWalkOrCompositeExpression() ) ); - $this->assertInstanceOf('Doctrine\ORM\Query\Expr\Orx', $expr); + $this->assertInstanceOf(QueryBuilder\Orx::class, $expr); $this->assertCount(2, $expr->getParts()); } diff --git a/tests/Doctrine/Tests/ORM/Query/QueryTest.php b/tests/Doctrine/Tests/ORM/Query/QueryTest.php index 7a3687c5216..71422e641ad 100644 --- a/tests/Doctrine/Tests/ORM/Query/QueryTest.php +++ b/tests/Doctrine/Tests/ORM/Query/QueryTest.php @@ -2,19 +2,26 @@ namespace Doctrine\Tests\ORM\Query; +use DateTime; use Doctrine\Common\Cache\ArrayCache; use Doctrine\Common\Collections\ArrayCollection; - -use Doctrine\ORM\EntityManager; +use Doctrine\DBAL\Types\Type; +use Doctrine\ORM\Internal\Hydration\IterableResult; use Doctrine\ORM\Query\Parameter; +use Doctrine\ORM\Query\QueryException; +use Doctrine\ORM\UnitOfWork; use Doctrine\Tests\Mocks\DriverConnectionMock; +use Doctrine\Tests\Mocks\EntityManagerMock; use Doctrine\Tests\Mocks\StatementArrayMock; +use Doctrine\Tests\Models\CMS\CmsAddress; +use Doctrine\Tests\Models\CMS\CmsUser; +use Doctrine\Tests\Models\Generic\DateTimeModel; use Doctrine\Tests\OrmTestCase; class QueryTest extends OrmTestCase { - /** @var EntityManager */ - protected $_em = null; + /** @var EntityManagerMock */ + protected $_em; protected function setUp() { @@ -89,7 +96,7 @@ public function testFluentQueryInterface() ->setHint('foo', 'bar') ->setHint('bar', 'baz') ->setParameter(1, 'bar') - ->setParameters(new ArrayCollection(array(new Parameter(2, 'baz')))) + ->setParameters(new ArrayCollection([new Parameter(2, 'baz')])) ->setResultCacheDriver(null) ->setResultCacheId('foo') ->setDQL('foo') @@ -109,7 +116,7 @@ public function testHints() $this->assertEquals('bar', $q->getHint('foo')); $this->assertEquals('baz', $q->getHint('bar')); - $this->assertEquals(array('foo' => 'bar', 'bar' => 'baz'), $q->getHints()); + $this->assertEquals(['foo' => 'bar', 'bar' => 'baz'], $q->getHints()); $this->assertTrue($q->hasHint('foo')); $this->assertFalse($q->hasHint('barFooBaz')); } @@ -121,7 +128,7 @@ public function testQueryDefaultResultCache() { $this->_em->getConfiguration()->setResultCacheImpl(new ArrayCache()); $q = $this->_em->createQuery("select a from Doctrine\Tests\Models\CMS\CmsArticle a"); - $q->useResultCache(true); + $q->enableResultCache(); $this->assertSame($this->_em->getConfiguration()->getResultCacheImpl(), $q->getQueryCacheProfile()->getResultCacheDriver()); } @@ -146,7 +153,8 @@ public function testIterateWithNoDistinctAndWithValidSelectClause() public function testIterateWithDistinct() { $q = $this->_em->createQuery("SELECT DISTINCT u from Doctrine\Tests\Models\CMS\CmsUser u LEFT JOIN u.articles a"); - $q->iterate(); + + self::assertInstanceOf(IterableResult::class, $q->iterate()); } /** @@ -154,11 +162,11 @@ public function testIterateWithDistinct() */ public function testCollectionParameters() { - $cities = array( + $cities = [ 0 => "Paris", 3 => "Canne", 9 => "St Julien" - ); + ]; $query = $this->_em ->createQuery("SELECT a FROM Doctrine\Tests\Models\CMS\CmsAddress a WHERE a.city IN (:cities)") @@ -178,19 +186,38 @@ public function testProcessParameterValueClassMetadata() { $query = $this->_em->createQuery("SELECT a FROM Doctrine\Tests\Models\CMS\CmsAddress a WHERE a.city IN (:cities)"); $this->assertEquals( - 'Doctrine\Tests\Models\CMS\CmsAddress', - $query->processParameterValue($this->_em->getClassMetadata('Doctrine\Tests\Models\CMS\CmsAddress')) + CmsAddress::class, + $query->processParameterValue($this->_em->getClassMetadata(CmsAddress::class)) ); } + public function testProcessParameterValueObject() : void + { + $query = $this->_em->createQuery('SELECT a FROM Doctrine\Tests\Models\CMS\CmsAddress a WHERE a.user = :user'); + $user = new CmsUser(); + $user->id = 12345; + + self::assertSame( + 12345, + $query->processParameterValue($user) + ); + } + + public function testProcessParameterValueNull() : void + { + $query = $this->_em->createQuery('SELECT a FROM Doctrine\Tests\Models\CMS\CmsAddress a WHERE a.user = :user'); + + self::assertNull($query->processParameterValue(null)); + } + public function testDefaultQueryHints() { $config = $this->_em->getConfiguration(); - $defaultHints = array( + $defaultHints = [ 'hint_name_1' => 'hint_value_1', 'hint_name_2' => 'hint_value_2', 'hint_name_3' => 'hint_value_3', - ); + ]; $config->setDefaultQueryHints($defaultHints); $query = $this->_em->createQuery(); @@ -218,7 +245,7 @@ public function testResultCacheCaching() $driverConnectionMock->setStatementMock($stmt); $res = $this->_em->createQuery("select u from Doctrine\Tests\Models\CMS\CmsUser u") ->useQueryCache(true) - ->useResultCache(true, 60) + ->enableResultCache(60) //let it cache ->getResult(); @@ -228,7 +255,7 @@ public function testResultCacheCaching() $res = $this->_em->createQuery("select u from Doctrine\Tests\Models\CMS\CmsUser u") ->useQueryCache(true) - ->useResultCache(false) + ->disableResultCache() ->getResult(); $this->assertCount(0, $res); } @@ -242,4 +269,155 @@ public function testSetHydrationCacheProfileNull() $query->setHydrationCacheProfile(null); $this->assertNull($query->getHydrationCacheProfile()); } + + /** + * @group 2947 + */ + public function testResultCacheEviction() + { + $this->_em->getConfiguration()->setResultCacheImpl(new ArrayCache()); + + $query = $this->_em->createQuery("SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u") + ->enableResultCache(); + + /** @var DriverConnectionMock $driverConnectionMock */ + $driverConnectionMock = $this->_em->getConnection() + ->getWrappedConnection(); + + $driverConnectionMock->setStatementMock(new StatementArrayMock([['id_0' => 1]])); + + // Performs the query and sets up the initial cache + self::assertCount(1, $query->getResult()); + + $driverConnectionMock->setStatementMock(new StatementArrayMock([['id_0' => 1], ['id_0' => 2]])); + + // Retrieves cached data since expire flag is false and we have a cached result set + self::assertCount(1, $query->getResult()); + + // Performs the query and caches the result set since expire flag is true + self::assertCount(2, $query->expireResultCache(true)->getResult()); + + $driverConnectionMock->setStatementMock(new StatementArrayMock([['id_0' => 1]])); + + // Retrieves cached data since expire flag is false and we have a cached result set + self::assertCount(2, $query->expireResultCache(false)->getResult()); + } + + /** + * @group #6162 + */ + public function testSelectJoinSubquery() + { + $query = $this->_em->createQuery("select u from Doctrine\Tests\Models\CMS\CmsUser u JOIN (SELECT )"); + + $this->expectException(QueryException::class); + $this->expectExceptionMessage('Subquery'); + $query->getSQL(); + } + + /** + * @group #6162 + */ + public function testSelectFromSubquery() + { + $query = $this->_em->createQuery("select u from (select Doctrine\Tests\Models\CMS\CmsUser c) as u"); + + $this->expectException(QueryException::class); + $this->expectExceptionMessage('Subquery'); + $query->getSQL(); + } + + /** + * @group 6699 + */ + public function testGetParameterTypeJuggling() : void + { + $query = $this->_em->createQuery('select u from ' . CmsUser::class . ' u where u.id = ?0'); + + $query->setParameter(0, 0); + + self::assertCount(1, $query->getParameters()); + self::assertSame(0, $query->getParameter(0)->getValue()); + self::assertSame(0, $query->getParameter('0')->getValue()); + } + + /** + * @group 6699 + */ + public function testSetParameterWithNameZeroIsNotOverridden() : void + { + $query = $this->_em->createQuery('select u from ' . CmsUser::class . ' u where u.id != ?0 and u.username = :name'); + + $query->setParameter(0, 0); + $query->setParameter('name', 'Doctrine'); + + self::assertCount(2, $query->getParameters()); + self::assertSame(0, $query->getParameter('0')->getValue()); + self::assertSame('Doctrine', $query->getParameter('name')->getValue()); + } + + /** + * @group 6699 + */ + public function testSetParameterWithNameZeroDoesNotOverrideAnotherParameter() : void + { + $query = $this->_em->createQuery('select u from ' . CmsUser::class . ' u where u.id != ?0 and u.username = :name'); + + $query->setParameter('name', 'Doctrine'); + $query->setParameter(0, 0); + + self::assertCount(2, $query->getParameters()); + self::assertSame(0, $query->getParameter(0)->getValue()); + self::assertSame('Doctrine', $query->getParameter('name')->getValue()); + } + + /** + * @group 6699 + */ + public function testSetParameterWithTypeJugglingWorks() : void + { + $query = $this->_em->createQuery('select u from ' . CmsUser::class . ' u where u.id != ?0 and u.username = :name'); + + $query->setParameter('0', 1); + $query->setParameter('name', 'Doctrine'); + $query->setParameter(0, 2); + $query->setParameter('0', 3); + + self::assertCount(2, $query->getParameters()); + self::assertSame(3, $query->getParameter(0)->getValue()); + self::assertSame(3, $query->getParameter('0')->getValue()); + self::assertSame('Doctrine', $query->getParameter('name')->getValue()); + } + + /** + * @group 6748 + */ + public function testResultCacheProfileCanBeRemovedViaSetter() : void + { + $this->_em->getConfiguration()->setResultCacheImpl(new ArrayCache()); + + $query = $this->_em->createQuery('SELECT u FROM ' . CmsUser::class . ' u'); + $query->enableResultCache(); + $query->setResultCacheProfile(); + + self::assertAttributeSame(null, '_queryCacheProfile', $query); + } + + /** @group 7527 */ + public function testValuesAreNotBeingResolvedForSpecifiedParameterTypes() : void + { + $unitOfWork = $this->createMock(UnitOfWork::class); + + $this->_em->setUnitOfWork($unitOfWork); + + $unitOfWork + ->expects(self::never()) + ->method('getSingleIdentifierValue'); + + $query = $this->_em->createQuery('SELECT d FROM ' . DateTimeModel::class . ' d WHERE d.datetime = :value'); + + $query->setParameter('value', new DateTime(), Type::DATETIME); + + self::assertEmpty($query->getResult()); + } } diff --git a/tests/Doctrine/Tests/ORM/Query/SelectSqlGenerationTest.php b/tests/Doctrine/Tests/ORM/Query/SelectSqlGenerationTest.php index 707973495a2..2c3435fdbdc 100644 --- a/tests/Doctrine/Tests/ORM/Query/SelectSqlGenerationTest.php +++ b/tests/Doctrine/Tests/ORM/Query/SelectSqlGenerationTest.php @@ -15,8 +15,10 @@ use Doctrine\ORM\Query\Parser; use Doctrine\ORM\Query\QueryException; use Doctrine\ORM\Query\SqlWalker; +use Doctrine\Tests\DbalTypes\NegativeToPositiveType; use Doctrine\Tests\Models\CMS\CmsGroup; use Doctrine\Tests\Models\CMS\CmsPhonenumber; +use Doctrine\Tests\Models\Company\CompanyEmployee; use Doctrine\Tests\Models\Company\CompanyPerson; use Doctrine\Tests\OrmTestCase; @@ -37,7 +39,7 @@ protected function setUp() * @param array $queryHints * @param array $queryParams */ - public function assertSqlGeneration($dqlToBeTested, $sqlToBeConfirmed, array $queryHints = array(), array $queryParams = array()) + public function assertSqlGeneration($dqlToBeTested, $sqlToBeConfirmed, array $queryHints = [], array $queryParams = []) { try { $query = $this->_em->createQuery($dqlToBeTested); @@ -75,7 +77,7 @@ public function assertSqlGeneration($dqlToBeTested, $sqlToBeConfirmed, array $qu * @param array $queryHints * @param array $queryParams */ - public function assertInvalidSqlGeneration($dqlToBeTested, $expectedException, array $queryHints = array(), array $queryParams = array()) + public function assertInvalidSqlGeneration($dqlToBeTested, $expectedException, array $queryHints = [], array $queryParams = []) { $this->expectException($expectedException); @@ -107,7 +109,7 @@ public function testJoinWithRangeVariablePutsConditionIntoSqlWhereClause() $this->assertSqlGeneration( 'SELECT c.id FROM Doctrine\Tests\Models\Company\CompanyPerson c JOIN Doctrine\Tests\Models\Company\CompanyPerson r WHERE c.spouse = r AND r.id = 42', 'SELECT c0_.id AS id_0 FROM company_persons c0_ INNER JOIN company_persons c1_ WHERE c0_.spouse_id = c1_.id AND c1_.id = 42', - array(ORMQuery::HINT_FORCE_PARTIAL_LOAD => true) + [ORMQuery::HINT_FORCE_PARTIAL_LOAD => true] ); } @@ -124,7 +126,7 @@ public function testJoinWithRangeVariableAndInheritancePutsConditionIntoSqlWhere $this->assertSqlGeneration( 'SELECT c.id FROM Doctrine\Tests\Models\Company\CompanyPerson c JOIN Doctrine\Tests\Models\Company\CompanyPerson r WHERE c.spouse = r AND r.id = 42', 'SELECT c0_.id AS id_0 FROM company_persons c0_ LEFT JOIN company_managers c1_ ON c0_.id = c1_.id LEFT JOIN company_employees c2_ ON c0_.id = c2_.id INNER JOIN company_persons c3_ LEFT JOIN company_managers c4_ ON c3_.id = c4_.id LEFT JOIN company_employees c5_ ON c3_.id = c5_.id WHERE c0_.spouse_id = c3_.id AND c3_.id = 42', - array(ORMQuery::HINT_FORCE_PARTIAL_LOAD => false) + [ORMQuery::HINT_FORCE_PARTIAL_LOAD => false] ); } @@ -196,12 +198,17 @@ public function testSupportsJoinOnMultipleComponentsWithJoinedInheritanceType() { $this->assertSqlGeneration( 'SELECT e FROM Doctrine\Tests\Models\Company\CompanyEmployee e JOIN Doctrine\Tests\Models\Company\CompanyManager m WITH e.id = m.id', - 'SELECT c0_.id AS id_0, c0_.name AS name_1, c1_.salary AS salary_2, c1_.department AS department_3, c1_.startDate AS startDate_4, c0_.discr AS discr_5 FROM company_employees c1_ INNER JOIN company_persons c0_ ON c1_.id = c0_.id INNER JOIN company_managers c2_ INNER JOIN company_employees c4_ ON c2_.id = c4_.id INNER JOIN company_persons c3_ ON c2_.id = c3_.id AND (c0_.id = c3_.id)' + 'SELECT c0_.id AS id_0, c0_.name AS name_1, c1_.salary AS salary_2, c1_.department AS department_3, c1_.startDate AS startDate_4, c0_.discr AS discr_5 FROM company_employees c1_ INNER JOIN company_persons c0_ ON c1_.id = c0_.id INNER JOIN (company_managers c2_ INNER JOIN company_employees c4_ ON c2_.id = c4_.id INNER JOIN company_persons c3_ ON c2_.id = c3_.id) ON (c0_.id = c3_.id)' ); $this->assertSqlGeneration( 'SELECT e FROM Doctrine\Tests\Models\Company\CompanyEmployee e LEFT JOIN Doctrine\Tests\Models\Company\CompanyManager m WITH e.id = m.id', - 'SELECT c0_.id AS id_0, c0_.name AS name_1, c1_.salary AS salary_2, c1_.department AS department_3, c1_.startDate AS startDate_4, c0_.discr AS discr_5 FROM company_employees c1_ INNER JOIN company_persons c0_ ON c1_.id = c0_.id LEFT JOIN company_managers c2_ INNER JOIN company_employees c4_ ON c2_.id = c4_.id INNER JOIN company_persons c3_ ON c2_.id = c3_.id ON (c0_.id = c3_.id)' + 'SELECT c0_.id AS id_0, c0_.name AS name_1, c1_.salary AS salary_2, c1_.department AS department_3, c1_.startDate AS startDate_4, c0_.discr AS discr_5 FROM company_employees c1_ INNER JOIN company_persons c0_ ON c1_.id = c0_.id LEFT JOIN (company_managers c2_ INNER JOIN company_employees c4_ ON c2_.id = c4_.id INNER JOIN company_persons c3_ ON c2_.id = c3_.id) ON (c0_.id = c3_.id)' + ); + + $this->assertSqlGeneration( + 'SELECT c FROM Doctrine\Tests\Models\Company\CompanyContract c JOIN c.salesPerson s LEFT JOIN Doctrine\Tests\Models\Company\CompanyEvent e WITH s.id = e.id', + 'SELECT c0_.id AS id_0, c0_.completed AS completed_1, c0_.fixPrice AS fixPrice_2, c0_.hoursWorked AS hoursWorked_3, c0_.pricePerHour AS pricePerHour_4, c0_.maxPrice AS maxPrice_5, c0_.discr AS discr_6 FROM company_contracts c0_ INNER JOIN company_employees c1_ ON c0_.salesPerson_id = c1_.id LEFT JOIN company_persons c2_ ON c1_.id = c2_.id LEFT JOIN company_events c3_ ON (c2_.id = c3_.id) WHERE c0_.discr IN (\'fix\', \'flexible\', \'flexultra\')' ); } @@ -498,7 +505,7 @@ public function testSupportsInstanceOfExpressionsInWherePart() { $this->assertSqlGeneration( "SELECT u FROM Doctrine\Tests\Models\Company\CompanyPerson u WHERE u INSTANCE OF Doctrine\Tests\Models\Company\CompanyEmployee", - "SELECT c0_.id AS id_0, c0_.name AS name_1, c0_.discr AS discr_2 FROM company_persons c0_ WHERE c0_.discr IN ('employee')" + "SELECT c0_.id AS id_0, c0_.name AS name_1, c0_.discr AS discr_2 FROM company_persons c0_ WHERE c0_.discr IN ('manager', 'employee')" ); } @@ -507,7 +514,7 @@ public function testSupportsInstanceOfExpressionInWherePartWithMultipleValues() // This also uses FQCNs starting with or without a backslash in the INSTANCE OF parameter $this->assertSqlGeneration( "SELECT u FROM Doctrine\Tests\Models\Company\CompanyPerson u WHERE u INSTANCE OF (Doctrine\Tests\Models\Company\CompanyEmployee, \Doctrine\Tests\Models\Company\CompanyManager)", - "SELECT c0_.id AS id_0, c0_.name AS name_1, c0_.discr AS discr_2 FROM company_persons c0_ WHERE c0_.discr IN ('employee', 'manager')" + "SELECT c0_.id AS id_0, c0_.name AS name_1, c0_.discr AS discr_2 FROM company_persons c0_ WHERE c0_.discr IN ('manager', 'employee')" ); } @@ -518,7 +525,7 @@ public function testSupportsInstanceOfExpressionsInWherePartPrefixedSlash() { $this->assertSqlGeneration( "SELECT u FROM Doctrine\Tests\Models\Company\CompanyPerson u WHERE u INSTANCE OF \Doctrine\Tests\Models\Company\CompanyEmployee", - "SELECT c0_.id AS id_0, c0_.name AS name_1, c0_.discr AS discr_2 FROM company_persons c0_ WHERE c0_.discr IN ('employee')" + "SELECT c0_.id AS id_0, c0_.name AS name_1, c0_.discr AS discr_2 FROM company_persons c0_ WHERE c0_.discr IN ('manager', 'employee')" ); } @@ -529,7 +536,7 @@ public function testSupportsInstanceOfExpressionsInWherePartWithUnrelatedClass() { $this->assertInvalidSqlGeneration( "SELECT u FROM Doctrine\Tests\Models\Company\CompanyPerson u WHERE u INSTANCE OF \Doctrine\Tests\Models\CMS\CmsUser", - "Doctrine\\ORM\\Query\\QueryException" + QueryException::class ); } @@ -554,7 +561,7 @@ public function testSupportsInstanceOfExpressionsUsingInputParameterInWherePart( $this->assertSqlGeneration( "SELECT u FROM Doctrine\Tests\Models\Company\CompanyPerson u WHERE u INSTANCE OF ?1", "SELECT c0_.id AS id_0, c0_.name AS name_1, c0_.discr AS discr_2 FROM company_persons c0_ WHERE c0_.discr IN (?)", - array(), array(1 => $this->_em->getClassMetadata('Doctrine\Tests\Models\Company\CompanyEmployee')) + [], [1 => $this->_em->getClassMetadata(CompanyEmployee::class)] ); } @@ -607,7 +614,7 @@ public function testInvalidInExpressionWithSingleValuedAssociationPathExpression // We do not support SingleValuedAssociationPathExpression on inverse side $this->assertInvalidSqlGeneration( "SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.address IN (?1, ?2)", - "Doctrine\ORM\Query\QueryException" + QueryException::class ); } @@ -699,7 +706,7 @@ public function testSupportsMemberOfExpressionManyToManyParameterArray() $group->id = 101; $group2 = new CmsGroup(); $group2->id = 105; - $q->setParameter('param', array($group, $group2)); + $q->setParameter('param', [$group, $group2]); $this->assertEquals( 'SELECT c0_.id AS id_0 FROM cms_users c0_ WHERE EXISTS (SELECT 1 FROM cms_users_groups c1_ INNER JOIN cms_groups c2_ ON c1_.group_id = c2_.id WHERE c1_.user_id = c0_.id AND c2_.id IN (?))', @@ -713,7 +720,7 @@ public function testSupportsMemberOfExpressionSelfReferencing() // Tough one: Many-many self-referencing ("friends") with class table inheritance $q = $this->_em->createQuery('SELECT p FROM Doctrine\Tests\Models\Company\CompanyPerson p WHERE :param MEMBER OF p.friends'); $person = new CompanyPerson(); - $this->_em->getClassMetadata(get_class($person))->setIdentifierValues($person, array('id' => 101)); + $this->_em->getClassMetadata(get_class($person))->setIdentifierValues($person, ['id' => 101]); $q->setParameter('param', $person); $this->assertEquals( 'SELECT c0_.id AS id_0, c0_.name AS name_1, c1_.title AS title_2, c2_.salary AS salary_3, c2_.department AS department_4, c2_.startDate AS startDate_5, c0_.discr AS discr_6, c0_.spouse_id AS spouse_id_7, c1_.car_id AS car_id_8 FROM company_persons c0_ LEFT JOIN company_managers c1_ ON c0_.id = c1_.id LEFT JOIN company_employees c2_ ON c0_.id = c2_.id WHERE EXISTS (SELECT 1 FROM company_persons_friends c3_ INNER JOIN company_persons c4_ ON c3_.friend_id = c4_.id WHERE c3_.person_id = c0_.id AND c4_.id IN (?))', @@ -816,7 +823,14 @@ public function testLimitAndOffsetFromQueryClass() ->setMaxResults(10) ->setFirstResult(0); - $this->assertEquals('SELECT c0_.id AS id_0, c0_.status AS status_1, c0_.username AS username_2, c0_.name AS name_3, c0_.email_id AS email_id_4 FROM cms_users c0_ LIMIT 10 OFFSET 0', $q->getSql()); + // DBAL 2.8+ doesn't add OFFSET part when offset is 0 + self::assertThat( + $q->getSql(), + self::logicalOr( + self::identicalTo('SELECT c0_.id AS id_0, c0_.status AS status_1, c0_.username AS username_2, c0_.name AS name_3, c0_.email_id AS email_id_4 FROM cms_users c0_ LIMIT 10'), + self::identicalTo('SELECT c0_.id AS id_0, c0_.status AS status_1, c0_.username AS username_2, c0_.name AS name_3, c0_.email_id AS email_id_4 FROM cms_users c0_ LIMIT 10 OFFSET 0') + ) + ); } public function testSizeFunction() @@ -888,7 +902,7 @@ public function testOrderBySupportsSingleValuedPathExpressionOwningSide() } /** - * @expectedException Doctrine\ORM\Query\QueryException + * @expectedException \Doctrine\ORM\Query\QueryException */ public function testOrderBySupportsSingleValuedPathExpressionInverseSide() { @@ -1029,7 +1043,7 @@ public function testSubselectInSelect() { $this->assertSqlGeneration( "SELECT u.name, (SELECT COUNT(p.phonenumber) FROM Doctrine\Tests\Models\CMS\CmsPhonenumber p WHERE p.phonenumber = 1234) pcount FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.name = 'jon'", - "SELECT c0_.name AS name_0, (SELECT COUNT(c1_.phonenumber) AS dctrn__1 FROM cms_phonenumbers c1_ WHERE c1_.phonenumber = 1234) AS sclr_1 FROM cms_users c0_ WHERE c0_.name = 'jon'" + "SELECT c0_.name AS name_0, (SELECT COUNT(c1_.phonenumber) AS sclr_2 FROM cms_phonenumbers c1_ WHERE c1_.phonenumber = 1234) AS sclr_1 FROM cms_users c0_ WHERE c0_.name = 'jon'" ); } @@ -1047,7 +1061,7 @@ public function testPessimisticWriteLockQueryHint() "SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.username = 'gblanco'", "SELECT c0_.id AS id_0, c0_.status AS status_1, c0_.username AS username_2, c0_.name AS name_3 ". "FROM cms_users c0_ WHERE c0_.username = 'gblanco' FOR UPDATE", - array(ORMQuery::HINT_LOCK_MODE => LockMode::PESSIMISTIC_WRITE) + [ORMQuery::HINT_LOCK_MODE => LockMode::PESSIMISTIC_WRITE] ); } @@ -1063,7 +1077,7 @@ public function testPessimisticReadLockQueryHintPostgreSql() "SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.username = 'gblanco'", "SELECT c0_.id AS id_0, c0_.status AS status_1, c0_.username AS username_2, c0_.name AS name_3 ". "FROM cms_users c0_ WHERE c0_.username = 'gblanco' FOR SHARE", - array(ORMQuery::HINT_LOCK_MODE => LockMode::PESSIMISTIC_READ) + [ORMQuery::HINT_LOCK_MODE => LockMode::PESSIMISTIC_READ] ); } @@ -1077,7 +1091,7 @@ public function testLockModeNoneQueryHint() "SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.username = 'gblanco'", "SELECT c0_.id AS id_0, c0_.status AS status_1, c0_.username AS username_2, c0_.name AS name_3 ". "FROM cms_users c0_ WHERE c0_.username = 'gblanco'", - array(ORMQuery::HINT_LOCK_MODE => LockMode::NONE) + [ORMQuery::HINT_LOCK_MODE => LockMode::NONE] ); } @@ -1104,7 +1118,7 @@ public function testPessimisticReadLockQueryHintMySql() "SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.username = 'gblanco'", "SELECT c0_.id AS id_0, c0_.status AS status_1, c0_.username AS username_2, c0_.name AS name_3 ". "FROM cms_users c0_ WHERE c0_.username = 'gblanco' LOCK IN SHARE MODE", - array(ORMQuery::HINT_LOCK_MODE => LockMode::PESSIMISTIC_READ) + [ORMQuery::HINT_LOCK_MODE => LockMode::PESSIMISTIC_READ] ); } @@ -1120,7 +1134,7 @@ public function testPessimisticReadLockQueryHintOracle() "SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.username = 'gblanco'", "SELECT c0_.id AS ID_0, c0_.status AS STATUS_1, c0_.username AS USERNAME_2, c0_.name AS NAME_3 ". "FROM cms_users c0_ WHERE c0_.username = 'gblanco' FOR UPDATE", - array(ORMQuery::HINT_LOCK_MODE => LockMode::PESSIMISTIC_READ) + [ORMQuery::HINT_LOCK_MODE => LockMode::PESSIMISTIC_READ] ); } @@ -1130,14 +1144,14 @@ public function testPessimisticReadLockQueryHintOracle() public function testSupportToCustomDQLFunctions() { $config = $this->_em->getConfiguration(); - $config->addCustomNumericFunction('MYABS', 'Doctrine\Tests\ORM\Query\MyAbsFunction'); + $config->addCustomNumericFunction('MYABS', MyAbsFunction::class); $this->assertSqlGeneration( 'SELECT MYABS(p.phonenumber) FROM Doctrine\Tests\Models\CMS\CmsPhonenumber p', 'SELECT ABS(c0_.phonenumber) AS sclr_0 FROM cms_phonenumbers c0_' ); - $config->setCustomNumericFunctions(array()); + $config->setCustomNumericFunctions([]); } /** @@ -1196,7 +1210,7 @@ public function testSubSelectDiscriminator() { $this->assertSqlGeneration( "SELECT u.name, (SELECT COUNT(cfc.id) total FROM Doctrine\Tests\Models\Company\CompanyFixContract cfc) as cfc_count FROM Doctrine\Tests\Models\CMS\CmsUser u", - "SELECT c0_.name AS name_0, (SELECT COUNT(c1_.id) AS dctrn__total FROM company_contracts c1_ WHERE c1_.discr IN ('fix')) AS sclr_1 FROM cms_users c0_" + "SELECT c0_.name AS name_0, (SELECT COUNT(c1_.id) AS sclr_2 FROM company_contracts c1_ WHERE c1_.discr IN ('fix')) AS sclr_1 FROM cms_users c0_" ); } @@ -1376,7 +1390,7 @@ public function testIdentityFunctionWithCompositePrimaryKey() $this->assertInvalidSqlGeneration( "SELECT IDENTITY(p.poi, 'invalid') AS invalid FROM Doctrine\Tests\Models\Navigation\NavPhotos p", - "Doctrine\ORM\Query\QueryException" + QueryException::class ); } @@ -1429,7 +1443,7 @@ public function testIdentityFunctionDoesNotAcceptStateField() { $this->assertInvalidSqlGeneration( "SELECT IDENTITY(u.name) as name FROM Doctrine\Tests\Models\CMS\CmsUser u", - "Doctrine\ORM\Query\QueryException" + QueryException::class ); } @@ -1441,7 +1455,7 @@ public function testInheritanceTypeJoinInRootClassWithDisabledForcePartialLoad() $this->assertSqlGeneration( 'SELECT p FROM Doctrine\Tests\Models\Company\CompanyPerson p', 'SELECT c0_.id AS id_0, c0_.name AS name_1, c1_.title AS title_2, c2_.salary AS salary_3, c2_.department AS department_4, c2_.startDate AS startDate_5, c0_.discr AS discr_6, c0_.spouse_id AS spouse_id_7, c1_.car_id AS car_id_8 FROM company_persons c0_ LEFT JOIN company_managers c1_ ON c0_.id = c1_.id LEFT JOIN company_employees c2_ ON c0_.id = c2_.id', - array(ORMQuery::HINT_FORCE_PARTIAL_LOAD => false) + [ORMQuery::HINT_FORCE_PARTIAL_LOAD => false] ); } @@ -1453,7 +1467,7 @@ public function testInheritanceTypeJoinInRootClassWithEnabledForcePartialLoad() $this->assertSqlGeneration( 'SELECT p FROM Doctrine\Tests\Models\Company\CompanyPerson p', 'SELECT c0_.id AS id_0, c0_.name AS name_1, c0_.discr AS discr_2 FROM company_persons c0_', - array(ORMQuery::HINT_FORCE_PARTIAL_LOAD => true) + [ORMQuery::HINT_FORCE_PARTIAL_LOAD => true] ); } @@ -1465,7 +1479,7 @@ public function testInheritanceTypeJoinInChildClassWithDisabledForcePartialLoad( $this->assertSqlGeneration( 'SELECT e FROM Doctrine\Tests\Models\Company\CompanyEmployee e', 'SELECT c0_.id AS id_0, c0_.name AS name_1, c1_.salary AS salary_2, c1_.department AS department_3, c1_.startDate AS startDate_4, c2_.title AS title_5, c0_.discr AS discr_6, c0_.spouse_id AS spouse_id_7, c2_.car_id AS car_id_8 FROM company_employees c1_ INNER JOIN company_persons c0_ ON c1_.id = c0_.id LEFT JOIN company_managers c2_ ON c1_.id = c2_.id', - array(ORMQuery::HINT_FORCE_PARTIAL_LOAD => false) + [ORMQuery::HINT_FORCE_PARTIAL_LOAD => false] ); } @@ -1477,7 +1491,7 @@ public function testInheritanceTypeJoinInChildClassWithEnabledForcePartialLoad() $this->assertSqlGeneration( 'SELECT e FROM Doctrine\Tests\Models\Company\CompanyEmployee e', 'SELECT c0_.id AS id_0, c0_.name AS name_1, c1_.salary AS salary_2, c1_.department AS department_3, c1_.startDate AS startDate_4, c0_.discr AS discr_5 FROM company_employees c1_ INNER JOIN company_persons c0_ ON c1_.id = c0_.id', - array(ORMQuery::HINT_FORCE_PARTIAL_LOAD => true) + [ORMQuery::HINT_FORCE_PARTIAL_LOAD => true] ); } @@ -1489,7 +1503,7 @@ public function testInheritanceTypeJoinInLeafClassWithDisabledForcePartialLoad() $this->assertSqlGeneration( 'SELECT m FROM Doctrine\Tests\Models\Company\CompanyManager m', 'SELECT c0_.id AS id_0, c0_.name AS name_1, c1_.salary AS salary_2, c1_.department AS department_3, c1_.startDate AS startDate_4, c2_.title AS title_5, c0_.discr AS discr_6, c0_.spouse_id AS spouse_id_7, c2_.car_id AS car_id_8 FROM company_managers c2_ INNER JOIN company_employees c1_ ON c2_.id = c1_.id INNER JOIN company_persons c0_ ON c2_.id = c0_.id', - array(ORMQuery::HINT_FORCE_PARTIAL_LOAD => false) + [ORMQuery::HINT_FORCE_PARTIAL_LOAD => false] ); } @@ -1501,7 +1515,7 @@ public function testInheritanceTypeJoinInLeafClassWithEnabledForcePartialLoad() $this->assertSqlGeneration( 'SELECT m FROM Doctrine\Tests\Models\Company\CompanyManager m', 'SELECT c0_.id AS id_0, c0_.name AS name_1, c1_.salary AS salary_2, c1_.department AS department_3, c1_.startDate AS startDate_4, c2_.title AS title_5, c0_.discr AS discr_6 FROM company_managers c2_ INNER JOIN company_employees c1_ ON c2_.id = c1_.id INNER JOIN company_persons c0_ ON c2_.id = c0_.id', - array(ORMQuery::HINT_FORCE_PARTIAL_LOAD => true) + [ORMQuery::HINT_FORCE_PARTIAL_LOAD => true] ); } @@ -1513,7 +1527,7 @@ public function testInheritanceTypeSingleTableInRootClassWithDisabledForcePartia $this->assertSqlGeneration( 'SELECT c FROM Doctrine\Tests\Models\Company\CompanyContract c', "SELECT c0_.id AS id_0, c0_.completed AS completed_1, c0_.fixPrice AS fixPrice_2, c0_.hoursWorked AS hoursWorked_3, c0_.pricePerHour AS pricePerHour_4, c0_.maxPrice AS maxPrice_5, c0_.discr AS discr_6, c0_.salesPerson_id AS salesPerson_id_7 FROM company_contracts c0_ WHERE c0_.discr IN ('fix', 'flexible', 'flexultra')", - array(ORMQuery::HINT_FORCE_PARTIAL_LOAD => false) + [ORMQuery::HINT_FORCE_PARTIAL_LOAD => false] ); } @@ -1525,7 +1539,7 @@ public function testInheritanceTypeSingleTableInRootClassWithEnabledForcePartial $this->assertSqlGeneration( 'SELECT c FROM Doctrine\Tests\Models\Company\CompanyContract c', "SELECT c0_.id AS id_0, c0_.completed AS completed_1, c0_.fixPrice AS fixPrice_2, c0_.hoursWorked AS hoursWorked_3, c0_.pricePerHour AS pricePerHour_4, c0_.maxPrice AS maxPrice_5, c0_.discr AS discr_6 FROM company_contracts c0_ WHERE c0_.discr IN ('fix', 'flexible', 'flexultra')", - array(ORMQuery::HINT_FORCE_PARTIAL_LOAD => true) + [ORMQuery::HINT_FORCE_PARTIAL_LOAD => true] ); } @@ -1537,7 +1551,7 @@ public function testInheritanceTypeSingleTableInChildClassWithDisabledForceParti $this->assertSqlGeneration( 'SELECT fc FROM Doctrine\Tests\Models\Company\CompanyFlexContract fc', "SELECT c0_.id AS id_0, c0_.completed AS completed_1, c0_.hoursWorked AS hoursWorked_2, c0_.pricePerHour AS pricePerHour_3, c0_.maxPrice AS maxPrice_4, c0_.discr AS discr_5, c0_.salesPerson_id AS salesPerson_id_6 FROM company_contracts c0_ WHERE c0_.discr IN ('flexible', 'flexultra')", - array(ORMQuery::HINT_FORCE_PARTIAL_LOAD => false) + [ORMQuery::HINT_FORCE_PARTIAL_LOAD => false] ); } @@ -1549,7 +1563,7 @@ public function testInheritanceTypeSingleTableInChildClassWithEnabledForcePartia $this->assertSqlGeneration( 'SELECT fc FROM Doctrine\Tests\Models\Company\CompanyFlexContract fc', "SELECT c0_.id AS id_0, c0_.completed AS completed_1, c0_.hoursWorked AS hoursWorked_2, c0_.pricePerHour AS pricePerHour_3, c0_.maxPrice AS maxPrice_4, c0_.discr AS discr_5 FROM company_contracts c0_ WHERE c0_.discr IN ('flexible', 'flexultra')", - array(ORMQuery::HINT_FORCE_PARTIAL_LOAD => true) + [ORMQuery::HINT_FORCE_PARTIAL_LOAD => true] ); } @@ -1561,7 +1575,7 @@ public function testInheritanceTypeSingleTableInLeafClassWithDisabledForcePartia $this->assertSqlGeneration( 'SELECT fuc FROM Doctrine\Tests\Models\Company\CompanyFlexUltraContract fuc', "SELECT c0_.id AS id_0, c0_.completed AS completed_1, c0_.hoursWorked AS hoursWorked_2, c0_.pricePerHour AS pricePerHour_3, c0_.maxPrice AS maxPrice_4, c0_.discr AS discr_5, c0_.salesPerson_id AS salesPerson_id_6 FROM company_contracts c0_ WHERE c0_.discr IN ('flexultra')", - array(ORMQuery::HINT_FORCE_PARTIAL_LOAD => false) + [ORMQuery::HINT_FORCE_PARTIAL_LOAD => false] ); } @@ -1573,7 +1587,7 @@ public function testInheritanceTypeSingleTableInLeafClassWithEnabledForcePartial $this->assertSqlGeneration( 'SELECT fuc FROM Doctrine\Tests\Models\Company\CompanyFlexUltraContract fuc', "SELECT c0_.id AS id_0, c0_.completed AS completed_1, c0_.hoursWorked AS hoursWorked_2, c0_.pricePerHour AS pricePerHour_3, c0_.maxPrice AS maxPrice_4, c0_.discr AS discr_5 FROM company_contracts c0_ WHERE c0_.discr IN ('flexultra')", - array(ORMQuery::HINT_FORCE_PARTIAL_LOAD => true) + [ORMQuery::HINT_FORCE_PARTIAL_LOAD => true] ); } @@ -1585,7 +1599,7 @@ public function testSelfReferenceWithOneToOneDoesNotDuplicateAlias() $this->assertSqlGeneration( 'SELECT p, pp FROM Doctrine\Tests\Models\Company\CompanyPerson p JOIN p.spouse pp', "SELECT c0_.id AS id_0, c0_.name AS name_1, c1_.title AS title_2, c2_.salary AS salary_3, c2_.department AS department_4, c2_.startDate AS startDate_5, c3_.id AS id_6, c3_.name AS name_7, c4_.title AS title_8, c5_.salary AS salary_9, c5_.department AS department_10, c5_.startDate AS startDate_11, c0_.discr AS discr_12, c0_.spouse_id AS spouse_id_13, c1_.car_id AS car_id_14, c3_.discr AS discr_15, c3_.spouse_id AS spouse_id_16, c4_.car_id AS car_id_17 FROM company_persons c0_ LEFT JOIN company_managers c1_ ON c0_.id = c1_.id LEFT JOIN company_employees c2_ ON c0_.id = c2_.id INNER JOIN company_persons c3_ ON c0_.spouse_id = c3_.id LEFT JOIN company_managers c4_ ON c3_.id = c4_.id LEFT JOIN company_employees c5_ ON c3_.id = c5_.id", - array(ORMQuery::HINT_FORCE_PARTIAL_LOAD => false) + [ORMQuery::HINT_FORCE_PARTIAL_LOAD => false] ); } @@ -1748,7 +1762,7 @@ public function testSupportsSubSqlFunction() ); $this->assertSqlGeneration( 'SELECT u1 FROM Doctrine\Tests\Models\CMS\CmsUser u1 WHERE COUNT(u1.id) = ( SELECT SUM(u2.id) FROM Doctrine\Tests\Models\CMS\CmsUser u2 )', - 'SELECT c0_.id AS id_0, c0_.status AS status_1, c0_.username AS username_2, c0_.name AS name_3 FROM cms_users c0_ WHERE COUNT(c0_.id) = (SELECT SUM(c1_.id) AS dctrn__1 FROM cms_users c1_)' + 'SELECT c0_.id AS id_0, c0_.status AS status_1, c0_.username AS username_2, c0_.name AS name_3 FROM cms_users c0_ WHERE COUNT(c0_.id) = (SELECT SUM(c1_.id) AS sclr_4 FROM cms_users c1_)' ); $this->assertSqlGeneration( 'SELECT u1 FROM Doctrine\Tests\Models\CMS\CmsUser u1 WHERE COUNT(u1.id) <= ( SELECT SUM(u2.id) + COUNT(u2.email) FROM Doctrine\Tests\Models\CMS\CmsUser u2 )', @@ -1836,9 +1850,9 @@ public function testWhereFunctionIsNullComparisonExpression() public function testCustomTypeValueSql() { if (DBALType::hasType('negative_to_positive')) { - DBALType::overrideType('negative_to_positive', 'Doctrine\Tests\DbalTypes\NegativeToPositiveType'); + DBALType::overrideType('negative_to_positive', NegativeToPositiveType::class); } else { - DBALType::addType('negative_to_positive', 'Doctrine\Tests\DbalTypes\NegativeToPositiveType'); + DBALType::addType('negative_to_positive', NegativeToPositiveType::class); } $this->assertSqlGeneration( @@ -1850,9 +1864,9 @@ public function testCustomTypeValueSql() public function testCustomTypeValueSqlIgnoresIdentifierColumn() { if (DBALType::hasType('negative_to_positive')) { - DBALType::overrideType('negative_to_positive', 'Doctrine\Tests\DbalTypes\NegativeToPositiveType'); + DBALType::overrideType('negative_to_positive', NegativeToPositiveType::class); } else { - DBALType::addType('negative_to_positive', 'Doctrine\Tests\DbalTypes\NegativeToPositiveType'); + DBALType::addType('negative_to_positive', NegativeToPositiveType::class); } $this->assertSqlGeneration( @@ -1864,9 +1878,9 @@ public function testCustomTypeValueSqlIgnoresIdentifierColumn() public function testCustomTypeValueSqlForAllFields() { if (DBALType::hasType('negative_to_positive')) { - DBALType::overrideType('negative_to_positive', 'Doctrine\Tests\DbalTypes\NegativeToPositiveType'); + DBALType::overrideType('negative_to_positive', NegativeToPositiveType::class); } else { - DBALType::addType('negative_to_positive', 'Doctrine\Tests\DbalTypes\NegativeToPositiveType'); + DBALType::addType('negative_to_positive', NegativeToPositiveType::class); } $this->assertSqlGeneration( @@ -1878,9 +1892,9 @@ public function testCustomTypeValueSqlForAllFields() public function testCustomTypeValueSqlForPartialObject() { if (DBALType::hasType('negative_to_positive')) { - DBALType::overrideType('negative_to_positive', 'Doctrine\Tests\DbalTypes\NegativeToPositiveType'); + DBALType::overrideType('negative_to_positive', NegativeToPositiveType::class); } else { - DBALType::addType('negative_to_positive', 'Doctrine\Tests\DbalTypes\NegativeToPositiveType'); + DBALType::addType('negative_to_positive', NegativeToPositiveType::class); } $this->assertSqlGeneration( @@ -1987,7 +2001,7 @@ public function testQuotedWalkJoinVariableDeclaration() { $this->assertSqlGeneration( 'SELECT u, a FROM Doctrine\Tests\Models\Quote\User u JOIN u.address a', - 'SELECT q0_."user-id" AS userid_0, q0_."user-name" AS username_1, q1_."address-id" AS addressid_2, q1_."address-zip" AS addresszip_3 FROM "quote-user" q0_ INNER JOIN "quote-address" q1_ ON q0_."address-id" = q1_."address-id"' + 'SELECT q0_."user-id" AS userid_0, q0_."user-name" AS username_1, q1_."address-id" AS addressid_2, q1_."address-zip" AS addresszip_3, q1_.type AS type_4 FROM "quote-user" q0_ INNER JOIN "quote-address" q1_ ON q0_."address-id" = q1_."address-id" AND q1_.type IN (\'simple\', \'full\')' ); $this->assertSqlGeneration( @@ -2002,7 +2016,7 @@ public function testQuotedWalkJoinVariableDeclaration() $this->assertSqlGeneration( 'SELECT a, u FROM Doctrine\Tests\Models\Quote\Address a JOIN a.user u', - 'SELECT q0_."address-id" AS addressid_0, q0_."address-zip" AS addresszip_1, q1_."user-id" AS userid_2, q1_."user-name" AS username_3 FROM "quote-address" q0_ INNER JOIN "quote-user" q1_ ON q0_."user-id" = q1_."user-id"' + 'SELECT q0_."address-id" AS addressid_0, q0_."address-zip" AS addresszip_1, q1_."user-id" AS userid_2, q1_."user-name" AS username_3, q0_.type AS type_4 FROM "quote-address" q0_ INNER JOIN "quote-user" q1_ ON q0_."user-id" = q1_."user-id" WHERE q0_.type IN (\'simple\', \'full\')' ); $this->assertSqlGeneration( @@ -2145,7 +2159,7 @@ public function testHavingSupportIsNullExpression() 'SELECT u.name FROM Doctrine\Tests\Models\CMS\CmsUser u HAVING u.username IS NULL', 'SELECT c0_.name AS name_0 FROM cms_users c0_ HAVING c0_.username IS NULL' ); - + $this->assertSqlGeneration( 'SELECT u.name FROM Doctrine\Tests\Models\CMS\CmsUser u HAVING MAX(u.name) IS NULL', 'SELECT c0_.name AS name_0 FROM cms_users c0_ HAVING MAX(c0_.name) IS NULL' @@ -2160,7 +2174,7 @@ public function testClassTableInheritanceJoinWithConditionAppliesToBaseTable() $this->assertSqlGeneration( 'SELECT e.id FROM Doctrine\Tests\Models\Company\CompanyOrganization o JOIN o.events e WITH e.id = ?1', 'SELECT c0_.id AS id_0 FROM company_organizations c1_ INNER JOIN (company_events c0_ LEFT JOIN company_auctions c2_ ON c0_.id = c2_.id LEFT JOIN company_raffles c3_ ON c0_.id = c3_.id) ON c1_.id = c0_.org_id AND (c0_.id = ?)', - array(ORMQuery::HINT_FORCE_PARTIAL_LOAD => false) + [ORMQuery::HINT_FORCE_PARTIAL_LOAD => false] ); } @@ -2209,7 +2223,7 @@ public function testSingleTableInheritanceLeftJoinNonAssociationWithConditionAnd // the where clause when not joining onto that table $this->assertSqlGeneration( 'SELECT c FROM Doctrine\Tests\Models\Company\CompanyContract c LEFT JOIN Doctrine\Tests\Models\Company\CompanyEmployee e WITH e.id = c.salesPerson WHERE c.completed = true', - "SELECT c0_.id AS id_0, c0_.completed AS completed_1, c0_.fixPrice AS fixPrice_2, c0_.hoursWorked AS hoursWorked_3, c0_.pricePerHour AS pricePerHour_4, c0_.maxPrice AS maxPrice_5, c0_.discr AS discr_6 FROM company_contracts c0_ LEFT JOIN company_employees c1_ INNER JOIN company_persons c2_ ON c1_.id = c2_.id ON (c2_.id = c0_.salesPerson_id) WHERE (c0_.completed = 1) AND c0_.discr IN ('fix', 'flexible', 'flexultra')" + "SELECT c0_.id AS id_0, c0_.completed AS completed_1, c0_.fixPrice AS fixPrice_2, c0_.hoursWorked AS hoursWorked_3, c0_.pricePerHour AS pricePerHour_4, c0_.maxPrice AS maxPrice_5, c0_.discr AS discr_6 FROM company_contracts c0_ LEFT JOIN (company_employees c1_ INNER JOIN company_persons c2_ ON c1_.id = c2_.id) ON (c2_.id = c0_.salesPerson_id) WHERE (c0_.completed = 1) AND c0_.discr IN ('fix', 'flexible', 'flexultra')" ); } @@ -2238,8 +2252,8 @@ public function testSingleTableInheritanceCreatesOnConditionAndWhere() $this->assertSqlGeneration( 'SELECT e, COUNT(c) FROM Doctrine\Tests\Models\Company\CompanyEmployee e JOIN e.contracts c WHERE e.department = :department', "SELECT c0_.id AS id_0, c0_.name AS name_1, c1_.salary AS salary_2, c1_.department AS department_3, c1_.startDate AS startDate_4, COUNT(c2_.id) AS sclr_5, c0_.discr AS discr_6 FROM company_employees c1_ INNER JOIN company_persons c0_ ON c1_.id = c0_.id INNER JOIN company_contract_employees c3_ ON c1_.id = c3_.employee_id INNER JOIN company_contracts c2_ ON c2_.id = c3_.contract_id AND c2_.discr IN ('fix', 'flexible', 'flexultra') WHERE c1_.department = ?", - array(), - array('department' => 'foobar') + [], + ['department' => 'foobar'] ); } @@ -2264,7 +2278,7 @@ public function testHavingSupportResultVariableLikeExpression() "SELECT c0_.name AS name_0 FROM cms_users c0_ HAVING name_0 LIKE '3'" ); } - + /** * @group DDC-3085 */ @@ -2288,7 +2302,7 @@ public function testHavingSupportResultVariableInAggregateFunction() } /** - * GitHub issue #4764: https://github.com/doctrine/doctrine2/issues/4764 + * GitHub issue #4764: https://github.com/doctrine/orm/issues/4764 * @group DDC-3907 * @dataProvider mathematicOperatorsProvider */ diff --git a/tests/Doctrine/Tests/ORM/Query/SqlWalkerTest.php b/tests/Doctrine/Tests/ORM/Query/SqlWalkerTest.php index 263cffc567f..e23ee0117f8 100644 --- a/tests/Doctrine/Tests/ORM/Query/SqlWalkerTest.php +++ b/tests/Doctrine/Tests/ORM/Query/SqlWalkerTest.php @@ -24,7 +24,7 @@ class SqlWalkerTest extends OrmTestCase */ protected function setUp() { - $this->sqlWalker = new SqlWalker(new Query($this->_getTestEntityManager()), new ParserResult(), array()); + $this->sqlWalker = new SqlWalker(new Query($this->_getTestEntityManager()), new ParserResult(), []); } /** @@ -53,10 +53,10 @@ public function testGetSQLTableAliasIsSameForMultipleCalls($tableName) */ public function getColumnNamesAndSqlAliases() { - return array( - array('aaaaa', 'a0_'), - array('table', 't0_'), - array('çtable', 't0_'), - ); + return [ + ['aaaaa', 'a0_'], + ['table', 't0_'], + ['çtable', 't0_'], + ]; } } diff --git a/tests/Doctrine/Tests/ORM/Query/UpdateSqlGenerationTest.php b/tests/Doctrine/Tests/ORM/Query/UpdateSqlGenerationTest.php index 5dae79b3d57..7044929e940 100644 --- a/tests/Doctrine/Tests/ORM/Query/UpdateSqlGenerationTest.php +++ b/tests/Doctrine/Tests/ORM/Query/UpdateSqlGenerationTest.php @@ -1,27 +1,9 @@ . - */ namespace Doctrine\Tests\ORM\Query; use Doctrine\DBAL\Types\Type as DBALType; +use Doctrine\Tests\DbalTypes\NegativeToPositiveType; use Doctrine\Tests\OrmTestCase; /** @@ -44,9 +26,9 @@ class UpdateSqlGenerationTest extends OrmTestCase protected function setUp() { if (DBALType::hasType('negative_to_positive')) { - DBALType::overrideType('negative_to_positive', 'Doctrine\Tests\DbalTypes\NegativeToPositiveType'); + DBALType::overrideType('negative_to_positive', NegativeToPositiveType::class); } else { - DBALType::addType('negative_to_positive', 'Doctrine\Tests\DbalTypes\NegativeToPositiveType'); + DBALType::addType('negative_to_positive', NegativeToPositiveType::class); } $this->_em = $this->_getTestEntityManager(); diff --git a/tests/Doctrine/Tests/ORM/QueryBuilderTest.php b/tests/Doctrine/Tests/ORM/QueryBuilderTest.php index 7b1e38c307b..17d10f4b2dc 100644 --- a/tests/Doctrine/Tests/ORM/QueryBuilderTest.php +++ b/tests/Doctrine/Tests/ORM/QueryBuilderTest.php @@ -1,32 +1,18 @@ . - */ namespace Doctrine\Tests\ORM; use Doctrine\Common\Collections\ArrayCollection; use Doctrine\Common\Collections\Criteria; use Doctrine\ORM\Cache; - -use Doctrine\ORM\QueryBuilder; -use Doctrine\ORM\Query\Expr; +use Doctrine\ORM\Query; use Doctrine\ORM\Query\Parameter; use Doctrine\ORM\Query\ParameterTypeInferer; +use Doctrine\ORM\QueryBuilder; +use Doctrine\Tests\Models\Cache\State; +use Doctrine\Tests\Models\CMS\CmsArticle; +use Doctrine\Tests\Models\CMS\CmsGroup; +use Doctrine\Tests\Models\CMS\CmsUser; use Doctrine\Tests\OrmTestCase; /** @@ -60,7 +46,7 @@ protected function assertValidQueryBuilder(QueryBuilder $qb, $expectedDql) public function testSelectSetsType() { $qb = $this->_em->createQueryBuilder() - ->delete('Doctrine\Tests\Models\CMS\CmsUser', 'u') + ->delete(CmsUser::class, 'u') ->select('u.id', 'u.username'); $this->assertEquals($qb->getType(), QueryBuilder::SELECT); @@ -69,7 +55,7 @@ public function testSelectSetsType() public function testEmptySelectSetsType() { $qb = $this->_em->createQueryBuilder() - ->delete('Doctrine\Tests\Models\CMS\CmsUser', 'u') + ->delete(CmsUser::class, 'u') ->select(); $this->assertEquals($qb->getType(), QueryBuilder::SELECT); @@ -78,7 +64,7 @@ public function testEmptySelectSetsType() public function testDeleteSetsType() { $qb = $this->_em->createQueryBuilder() - ->from('Doctrine\Tests\Models\CMS\CmsUser', 'u') + ->from(CmsUser::class, 'u') ->delete(); $this->assertEquals($qb->getType(), QueryBuilder::DELETE); @@ -87,7 +73,7 @@ public function testDeleteSetsType() public function testUpdateSetsType() { $qb = $this->_em->createQueryBuilder() - ->from('Doctrine\Tests\Models\CMS\CmsUser', 'u') + ->from(CmsUser::class, 'u') ->update(); $this->assertEquals($qb->getType(), QueryBuilder::UPDATE); @@ -96,7 +82,7 @@ public function testUpdateSetsType() public function testSimpleSelect() { $qb = $this->_em->createQueryBuilder() - ->from('Doctrine\Tests\Models\CMS\CmsUser', 'u') + ->from(CmsUser::class, 'u') ->select('u.id', 'u.username'); $this->assertValidQueryBuilder($qb, 'SELECT u.id, u.username FROM Doctrine\Tests\Models\CMS\CmsUser u'); @@ -105,7 +91,7 @@ public function testSimpleSelect() public function testSimpleDelete() { $qb = $this->_em->createQueryBuilder() - ->delete('Doctrine\Tests\Models\CMS\CmsUser', 'u'); + ->delete(CmsUser::class, 'u'); $this->assertValidQueryBuilder($qb, 'DELETE Doctrine\Tests\Models\CMS\CmsUser u'); } @@ -113,7 +99,7 @@ public function testSimpleDelete() public function testSimpleSelectWithFromIndexBy() { $qb = $this->_em->createQueryBuilder() - ->from('Doctrine\Tests\Models\CMS\CmsUser', 'u', 'u.id') + ->from(CmsUser::class, 'u', 'u.id') ->select('u.id', 'u.username'); $this->assertValidQueryBuilder($qb, 'SELECT u.id, u.username FROM Doctrine\Tests\Models\CMS\CmsUser u INDEX BY u.id'); @@ -122,7 +108,7 @@ public function testSimpleSelectWithFromIndexBy() public function testSimpleSelectWithIndexBy() { $qb = $this->_em->createQueryBuilder() - ->from('Doctrine\Tests\Models\CMS\CmsUser', 'u') + ->from(CmsUser::class, 'u') ->indexBy('u', 'u.id') ->select('u.id', 'u.username'); @@ -132,7 +118,7 @@ public function testSimpleSelectWithIndexBy() public function testSimpleUpdate() { $qb = $this->_em->createQueryBuilder() - ->update('Doctrine\Tests\Models\CMS\CmsUser', 'u') + ->update(CmsUser::class, 'u') ->set('u.username', ':username'); $this->assertValidQueryBuilder($qb, 'UPDATE Doctrine\Tests\Models\CMS\CmsUser u SET u.username = :username'); @@ -142,7 +128,7 @@ public function testInnerJoin() { $qb = $this->_em->createQueryBuilder() ->select('u', 'a') - ->from('Doctrine\Tests\Models\CMS\CmsUser', 'u') + ->from(CmsUser::class, 'u') ->innerJoin('u.articles', 'a'); $this->assertValidQueryBuilder($qb, 'SELECT u, a FROM Doctrine\Tests\Models\CMS\CmsUser u INNER JOIN u.articles a'); @@ -152,7 +138,7 @@ public function testComplexInnerJoin() { $qb = $this->_em->createQueryBuilder() ->select('u', 'a') - ->from('Doctrine\Tests\Models\CMS\CmsUser', 'u') + ->from(CmsUser::class, 'u') ->innerJoin('u.articles', 'a', 'ON', 'u.id = a.author_id'); $this->assertValidQueryBuilder( @@ -165,7 +151,7 @@ public function testComplexInnerJoinWithIndexBy() { $qb = $this->_em->createQueryBuilder() ->select('u', 'a') - ->from('Doctrine\Tests\Models\CMS\CmsUser', 'u') + ->from(CmsUser::class, 'u') ->innerJoin('u.articles', 'a', 'ON', 'u.id = a.author_id', 'a.name'); $this->assertValidQueryBuilder( @@ -178,7 +164,7 @@ public function testLeftJoin() { $qb = $this->_em->createQueryBuilder() ->select('u', 'a') - ->from('Doctrine\Tests\Models\CMS\CmsUser', 'u') + ->from(CmsUser::class, 'u') ->leftJoin('u.articles', 'a'); $this->assertValidQueryBuilder($qb, 'SELECT u, a FROM Doctrine\Tests\Models\CMS\CmsUser u LEFT JOIN u.articles a'); @@ -188,7 +174,7 @@ public function testLeftJoinWithIndexBy() { $qb = $this->_em->createQueryBuilder() ->select('u', 'a') - ->from('Doctrine\Tests\Models\CMS\CmsUser', 'u') + ->from(CmsUser::class, 'u') ->leftJoin('u.articles', 'a', null, null, 'a.name'); $this->assertValidQueryBuilder($qb, 'SELECT u, a FROM Doctrine\Tests\Models\CMS\CmsUser u LEFT JOIN u.articles a INDEX BY a.name'); @@ -198,8 +184,8 @@ public function testMultipleFrom() { $qb = $this->_em->createQueryBuilder() ->select('u', 'g') - ->from('Doctrine\Tests\Models\CMS\CmsUser', 'u') - ->from('Doctrine\Tests\Models\CMS\CmsGroup', 'g'); + ->from(CmsUser::class, 'u') + ->from(CmsGroup::class, 'g'); $this->assertValidQueryBuilder($qb, 'SELECT u, g FROM Doctrine\Tests\Models\CMS\CmsUser u, Doctrine\Tests\Models\CMS\CmsGroup g'); } @@ -208,8 +194,8 @@ public function testMultipleFromWithIndexBy() { $qb = $this->_em->createQueryBuilder() ->select('u', 'g') - ->from('Doctrine\Tests\Models\CMS\CmsUser', 'u') - ->from('Doctrine\Tests\Models\CMS\CmsGroup', 'g') + ->from(CmsUser::class, 'u') + ->from(CmsGroup::class, 'g') ->indexBy('g', 'g.id'); $this->assertValidQueryBuilder($qb, 'SELECT u, g FROM Doctrine\Tests\Models\CMS\CmsUser u, Doctrine\Tests\Models\CMS\CmsGroup g INDEX BY g.id'); @@ -219,8 +205,8 @@ public function testMultipleFromWithJoin() { $qb = $this->_em->createQueryBuilder() ->select('u', 'g') - ->from('Doctrine\Tests\Models\CMS\CmsUser', 'u') - ->from('Doctrine\Tests\Models\CMS\CmsGroup', 'g') + ->from(CmsUser::class, 'u') + ->from(CmsGroup::class, 'g') ->innerJoin('u.articles', 'a', 'ON', 'u.id = a.author_id'); $this->assertValidQueryBuilder($qb, 'SELECT u, g FROM Doctrine\Tests\Models\CMS\CmsUser u INNER JOIN u.articles a ON u.id = a.author_id, Doctrine\Tests\Models\CMS\CmsGroup g'); @@ -230,8 +216,8 @@ public function testMultipleFromWithMultipleJoin() { $qb = $this->_em->createQueryBuilder() ->select('u', 'g') - ->from('Doctrine\Tests\Models\CMS\CmsUser', 'u') - ->from('Doctrine\Tests\Models\CMS\CmsArticle', 'a') + ->from(CmsUser::class, 'u') + ->from(CmsArticle::class, 'a') ->innerJoin('u.groups', 'g') ->leftJoin('u.address', 'ad') ->innerJoin('a.comments', 'c'); @@ -243,7 +229,7 @@ public function testWhere() { $qb = $this->_em->createQueryBuilder() ->select('u') - ->from('Doctrine\Tests\Models\CMS\CmsUser', 'u') + ->from(CmsUser::class, 'u') ->where('u.id = :uid'); $this->assertValidQueryBuilder($qb, 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.id = :uid'); @@ -253,7 +239,7 @@ public function testComplexAndWhere() { $qb = $this->_em->createQueryBuilder() ->select('u') - ->from('Doctrine\Tests\Models\CMS\CmsUser', 'u') + ->from(CmsUser::class, 'u') ->where('u.id = :uid OR u.id = :uid2 OR u.id = :uid3') ->andWhere('u.name = :name'); @@ -264,7 +250,7 @@ public function testAndWhere() { $qb = $this->_em->createQueryBuilder() ->select('u') - ->from('Doctrine\Tests\Models\CMS\CmsUser', 'u') + ->from(CmsUser::class, 'u') ->where('u.id = :uid') ->andWhere('u.id = :uid2'); @@ -275,7 +261,7 @@ public function testOrWhere() { $qb = $this->_em->createQueryBuilder() ->select('u') - ->from('Doctrine\Tests\Models\CMS\CmsUser', 'u') + ->from(CmsUser::class, 'u') ->where('u.id = :uid') ->orWhere('u.id = :uid2'); @@ -286,7 +272,7 @@ public function testComplexAndWhereOrWhereNesting() { $qb = $this->_em->createQueryBuilder(); $qb->select('u') - ->from('Doctrine\Tests\Models\CMS\CmsUser', 'u') + ->from(CmsUser::class, 'u') ->where('u.id = :uid') ->orWhere('u.id = :uid2') ->andWhere('u.id = :uid3') @@ -300,9 +286,9 @@ public function testAndWhereIn() { $qb = $this->_em->createQueryBuilder(); $qb->select('u') - ->from('Doctrine\Tests\Models\CMS\CmsUser', 'u') + ->from(CmsUser::class, 'u') ->where('u.id = :uid') - ->andWhere($qb->expr()->in('u.id', array(1, 2, 3))); + ->andWhere($qb->expr()->in('u.id', [1, 2, 3])); $this->assertValidQueryBuilder($qb, 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.id = :uid AND u.id IN(1, 2, 3)'); } @@ -311,9 +297,9 @@ public function testOrWhereIn() { $qb = $this->_em->createQueryBuilder(); $qb->select('u') - ->from('Doctrine\Tests\Models\CMS\CmsUser', 'u') + ->from(CmsUser::class, 'u') ->where('u.id = :uid') - ->orWhere($qb->expr()->in('u.id', array(1, 2, 3))); + ->orWhere($qb->expr()->in('u.id', [1, 2, 3])); $this->assertValidQueryBuilder($qb, 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.id = :uid OR u.id IN(1, 2, 3)'); } @@ -322,9 +308,9 @@ public function testAndWhereNotIn() { $qb = $this->_em->createQueryBuilder(); $qb->select('u') - ->from('Doctrine\Tests\Models\CMS\CmsUser', 'u') + ->from(CmsUser::class, 'u') ->where('u.id = :uid') - ->andWhere($qb->expr()->notIn('u.id', array(1, 2, 3))); + ->andWhere($qb->expr()->notIn('u.id', [1, 2, 3])); $this->assertValidQueryBuilder($qb, 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.id = :uid AND u.id NOT IN(1, 2, 3)'); } @@ -333,9 +319,9 @@ public function testOrWhereNotIn() { $qb = $this->_em->createQueryBuilder(); $qb->select('u') - ->from('Doctrine\Tests\Models\CMS\CmsUser', 'u') + ->from(CmsUser::class, 'u') ->where('u.id = :uid') - ->orWhere($qb->expr()->notIn('u.id', array(1, 2, 3))); + ->orWhere($qb->expr()->notIn('u.id', [1, 2, 3])); $this->assertValidQueryBuilder($qb, 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.id = :uid OR u.id NOT IN(1, 2, 3)'); } @@ -344,7 +330,7 @@ public function testGroupBy() { $qb = $this->_em->createQueryBuilder() ->select('u') - ->from('Doctrine\Tests\Models\CMS\CmsUser', 'u') + ->from(CmsUser::class, 'u') ->groupBy('u.id') ->addGroupBy('u.username'); @@ -355,7 +341,7 @@ public function testHaving() { $qb = $this->_em->createQueryBuilder() ->select('u') - ->from('Doctrine\Tests\Models\CMS\CmsUser', 'u') + ->from(CmsUser::class, 'u') ->groupBy('u.id') ->having('COUNT(u.id) > 1'); @@ -366,7 +352,7 @@ public function testAndHaving() { $qb = $this->_em->createQueryBuilder() ->select('u') - ->from('Doctrine\Tests\Models\CMS\CmsUser', 'u') + ->from(CmsUser::class, 'u') ->groupBy('u.id') ->having('COUNT(u.id) > 1') ->andHaving('COUNT(u.id) < 1'); @@ -378,7 +364,7 @@ public function testOrHaving() { $qb = $this->_em->createQueryBuilder() ->select('u') - ->from('Doctrine\Tests\Models\CMS\CmsUser', 'u') + ->from(CmsUser::class, 'u') ->groupBy('u.id') ->having('COUNT(u.id) > 1') ->andHaving('COUNT(u.id) < 1') @@ -391,7 +377,7 @@ public function testOrderBy() { $qb = $this->_em->createQueryBuilder() ->select('u') - ->from('Doctrine\Tests\Models\CMS\CmsUser', 'u') + ->from(CmsUser::class, 'u') ->orderBy('u.username', 'ASC'); $this->assertValidQueryBuilder($qb, 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u ORDER BY u.username ASC'); @@ -401,7 +387,7 @@ public function testOrderByWithExpression() { $qb = $this->_em->createQueryBuilder(); $qb->select('u') - ->from('Doctrine\Tests\Models\CMS\CmsUser', 'u') + ->from(CmsUser::class, 'u') ->orderBy($qb->expr()->asc('u.username')); $this->assertValidQueryBuilder($qb, 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u ORDER BY u.username ASC'); @@ -411,7 +397,7 @@ public function testAddOrderBy() { $qb = $this->_em->createQueryBuilder() ->select('u') - ->from('Doctrine\Tests\Models\CMS\CmsUser', 'u') + ->from(CmsUser::class, 'u') ->orderBy('u.username', 'ASC') ->addOrderBy('u.username', 'DESC'); @@ -422,7 +408,7 @@ public function testAddOrderByWithExpression() { $qb = $this->_em->createQueryBuilder(); $qb->select('u') - ->from('Doctrine\Tests\Models\CMS\CmsUser', 'u') + ->from(CmsUser::class, 'u') ->orderBy('u.username', 'ASC') ->addOrderBy($qb->expr()->desc('u.username')); @@ -433,7 +419,7 @@ public function testAddCriteriaWhere() { $qb = $this->_em->createQueryBuilder(); $qb->select('u') - ->from('Doctrine\Tests\Models\CMS\CmsUser', 'u'); + ->from(CmsUser::class, 'u'); $criteria = new Criteria(); $criteria->where($criteria->expr()->eq('field', 'value')); @@ -447,7 +433,7 @@ public function testAddCriteriaWhere() public function testAddMultipleSameCriteriaWhere() { $qb = $this->_em->createQueryBuilder(); - $qb->select('alias1')->from('Doctrine\Tests\Models\CMS\CmsUser', 'alias1'); + $qb->select('alias1')->from(CmsUser::class, 'alias1'); $criteria = new Criteria(); $criteria->where($criteria->expr()->andX( @@ -468,7 +454,7 @@ public function testAddMultipleSameCriteriaWhere() public function testAddCriteriaWhereWithMultipleParametersWithSameField() { $qb = $this->_em->createQueryBuilder(); - $qb->select('alias1')->from('Doctrine\Tests\Models\CMS\CmsUser', 'alias1'); + $qb->select('alias1')->from(CmsUser::class, 'alias1'); $criteria = new Criteria(); $criteria->where($criteria->expr()->eq('field', 'value1')); @@ -487,7 +473,7 @@ public function testAddCriteriaWhereWithMultipleParametersWithSameField() public function testAddCriteriaWhereWithMultipleParametersWithDifferentFields() { $qb = $this->_em->createQueryBuilder(); - $qb->select('alias1')->from('Doctrine\Tests\Models\CMS\CmsUser', 'alias1'); + $qb->select('alias1')->from(CmsUser::class, 'alias1'); $criteria = new Criteria(); $criteria->where($criteria->expr()->eq('field1', 'value1')); @@ -506,7 +492,7 @@ public function testAddCriteriaWhereWithMultipleParametersWithDifferentFields() public function testAddCriteriaWhereWithMultipleParametersWithSubpathsAndDifferentProperties() { $qb = $this->_em->createQueryBuilder(); - $qb->select('alias1')->from('Doctrine\Tests\Models\CMS\CmsUser', 'alias1'); + $qb->select('alias1')->from(CmsUser::class, 'alias1'); $criteria = new Criteria(); $criteria->where($criteria->expr()->eq('field1', 'value1')); @@ -525,7 +511,7 @@ public function testAddCriteriaWhereWithMultipleParametersWithSubpathsAndDiffere public function testAddCriteriaWhereWithMultipleParametersWithSubpathsAndSameProperty() { $qb = $this->_em->createQueryBuilder(); - $qb->select('alias1')->from('Doctrine\Tests\Models\CMS\CmsUser', 'alias1'); + $qb->select('alias1')->from(CmsUser::class, 'alias1'); $criteria = new Criteria(); $criteria->where($criteria->expr()->eq('field1', 'value1')); @@ -542,10 +528,10 @@ public function testAddCriteriaOrder() { $qb = $this->_em->createQueryBuilder(); $qb->select('u') - ->from('Doctrine\Tests\Models\CMS\CmsUser', 'u'); + ->from(CmsUser::class, 'u'); $criteria = new Criteria(); - $criteria->orderBy(array('field' => Criteria::DESC)); + $criteria->orderBy(['field' => Criteria::DESC]); $qb->addCriteria($criteria); @@ -560,11 +546,11 @@ public function testAddCriteriaOrderOnJoinAlias() { $qb = $this->_em->createQueryBuilder(); $qb->select('u') - ->from('Doctrine\Tests\Models\CMS\CmsUser', 'u') + ->from(CmsUser::class, 'u') ->join('u.article','a'); $criteria = new Criteria(); - $criteria->orderBy(array('a.field' => Criteria::DESC)); + $criteria->orderBy(['a.field' => Criteria::DESC]); $qb->addCriteria($criteria); @@ -576,7 +562,7 @@ public function testAddCriteriaLimit() { $qb = $this->_em->createQueryBuilder(); $qb->select('u') - ->from('Doctrine\Tests\Models\CMS\CmsUser', 'u'); + ->from(CmsUser::class, 'u'); $criteria = new Criteria(); $criteria->setFirstResult(2); @@ -592,7 +578,7 @@ public function testAddCriteriaUndefinedLimit() { $qb = $this->_em->createQueryBuilder(); $qb->select('u') - ->from('Doctrine\Tests\Models\CMS\CmsUser', 'u') + ->from(CmsUser::class, 'u') ->setFirstResult(2) ->setMaxResults(10); @@ -608,30 +594,33 @@ public function testGetQuery() { $qb = $this->_em->createQueryBuilder() ->select('u') - ->from('Doctrine\Tests\Models\CMS\CmsUser', 'u'); + ->from(CmsUser::class, 'u'); $q = $qb->getQuery(); - $this->assertEquals('Doctrine\ORM\Query', get_class($q)); + $this->assertEquals(Query::class, get_class($q)); } public function testSetParameter() { $qb = $this->_em->createQueryBuilder() ->select('u') - ->from('Doctrine\Tests\Models\CMS\CmsUser', 'u') + ->from(CmsUser::class, 'u') ->where('u.id = :id') ->setParameter('id', 1); $parameter = new Parameter('id', 1, ParameterTypeInferer::inferType(1)); + $inferred = $qb->getParameter('id'); - $this->assertEquals($parameter, $qb->getParameter('id')); + self::assertSame($parameter->getValue(), $inferred->getValue()); + self::assertSame($parameter->getType(), $inferred->getType()); + self::assertFalse($inferred->typeWasSpecified()); } public function testSetParameters() { $qb = $this->_em->createQueryBuilder(); $qb->select('u') - ->from('Doctrine\Tests\Models\CMS\CmsUser', 'u') + ->from(CmsUser::class, 'u') ->where($qb->expr()->orX('u.username = :username', 'u.username = :username2')); $parameters = new ArrayCollection(); @@ -648,7 +637,7 @@ public function testGetParameters() { $qb = $this->_em->createQueryBuilder(); $qb->select('u') - ->from('Doctrine\Tests\Models\CMS\CmsUser', 'u') + ->from(CmsUser::class, 'u') ->where('u.id = :id'); $parameters = new ArrayCollection(); @@ -663,7 +652,7 @@ public function testGetParameter() { $qb = $this->_em->createQueryBuilder() ->select('u') - ->from('Doctrine\Tests\Models\CMS\CmsUser', 'u') + ->from(CmsUser::class, 'u') ->where('u.id = :id'); $parameters = new ArrayCollection(); @@ -678,7 +667,7 @@ public function testMultipleWhere() { $qb = $this->_em->createQueryBuilder() ->select('u') - ->from('Doctrine\Tests\Models\CMS\CmsUser', 'u') + ->from(CmsUser::class, 'u') ->where('u.id = :uid', 'u.id = :uid2'); $this->assertValidQueryBuilder($qb, 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.id = :uid AND u.id = :uid2'); @@ -688,7 +677,7 @@ public function testMultipleAndWhere() { $qb = $this->_em->createQueryBuilder() ->select('u') - ->from('Doctrine\Tests\Models\CMS\CmsUser', 'u') + ->from(CmsUser::class, 'u') ->andWhere('u.id = :uid', 'u.id = :uid2'); $this->assertValidQueryBuilder($qb, 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.id = :uid AND u.id = :uid2'); @@ -698,7 +687,7 @@ public function testMultipleOrWhere() { $qb = $this->_em->createQueryBuilder(); $qb->select('u') - ->from('Doctrine\Tests\Models\CMS\CmsUser', 'u') + ->from(CmsUser::class, 'u') ->orWhere('u.id = :uid', $qb->expr()->eq('u.id', ':uid2')); $this->assertValidQueryBuilder($qb, 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.id = :uid OR u.id = :uid2'); @@ -709,10 +698,10 @@ public function testComplexWhere() $qb = $this->_em->createQueryBuilder(); $orExpr = $qb->expr()->orX(); $orExpr->add($qb->expr()->eq('u.id', ':uid3')); - $orExpr->add($qb->expr()->in('u.id', array(1))); + $orExpr->add($qb->expr()->in('u.id', [1])); $qb->select('u') - ->from('Doctrine\Tests\Models\CMS\CmsUser', 'u') + ->from(CmsUser::class, 'u') ->where($orExpr); $this->assertValidQueryBuilder($qb, 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.id = :uid3 OR u.id IN(1)'); @@ -722,12 +711,12 @@ public function testWhereInWithStringLiterals() { $qb = $this->_em->createQueryBuilder(); $qb->select('u') - ->from('Doctrine\Tests\Models\CMS\CmsUser', 'u') - ->where($qb->expr()->in('u.name', array('one', 'two', 'three'))); + ->from(CmsUser::class, 'u') + ->where($qb->expr()->in('u.name', ['one', 'two', 'three'])); $this->assertValidQueryBuilder($qb, "SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.name IN('one', 'two', 'three')"); - $qb->where($qb->expr()->in('u.name', array("O'Reilly", "O'Neil", 'Smith'))); + $qb->where($qb->expr()->in('u.name', ["O'Reilly", "O'Neil", 'Smith'])); $this->assertValidQueryBuilder($qb, "SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.name IN('O''Reilly', 'O''Neil', 'Smith')"); } @@ -737,12 +726,12 @@ public function testWhereInWithObjectLiterals() $qb = $this->_em->createQueryBuilder(); $expr = $this->_em->getExpressionBuilder(); $qb->select('u') - ->from('Doctrine\Tests\Models\CMS\CmsUser', 'u') - ->where($expr->in('u.name', array($expr->literal('one'), $expr->literal('two'), $expr->literal('three')))); + ->from(CmsUser::class, 'u') + ->where($expr->in('u.name', [$expr->literal('one'), $expr->literal('two'), $expr->literal('three')])); $this->assertValidQueryBuilder($qb, "SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.name IN('one', 'two', 'three')"); - $qb->where($expr->in('u.name', array($expr->literal("O'Reilly"), $expr->literal("O'Neil"), $expr->literal('Smith')))); + $qb->where($expr->in('u.name', [$expr->literal("O'Reilly"), $expr->literal("O'Neil"), $expr->literal('Smith')])); $this->assertValidQueryBuilder($qb, "SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.name IN('O''Reilly', 'O''Neil', 'Smith')"); } @@ -752,11 +741,11 @@ public function testNegation() $expr = $this->_em->getExpressionBuilder(); $orExpr = $expr->orX(); $orExpr->add($expr->eq('u.id', ':uid3')); - $orExpr->add($expr->not($expr->in('u.id', array(1)))); + $orExpr->add($expr->not($expr->in('u.id', [1]))); $qb = $this->_em->createQueryBuilder(); $qb->select('u') - ->from('Doctrine\Tests\Models\CMS\CmsUser', 'u') + ->from(CmsUser::class, 'u') ->where($orExpr); $this->assertValidQueryBuilder($qb, 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.id = :uid3 OR NOT(u.id IN(1))'); @@ -767,10 +756,8 @@ public function testSomeAllAny() $qb = $this->_em->createQueryBuilder(); $expr = $this->_em->getExpressionBuilder(); - //$subquery = $qb->subquery('Doctrine\Tests\Models\CMS\CmsArticle', 'a')->select('a.id'); - $qb->select('u') - ->from('Doctrine\Tests\Models\CMS\CmsUser', 'u') + ->from(CmsUser::class, 'u') ->where($expr->gt('u.id', $expr->all('select a.id from Doctrine\Tests\Models\CMS\CmsArticle a'))); $this->assertValidQueryBuilder($qb, 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.id > ALL(select a.id from Doctrine\Tests\Models\CMS\CmsArticle a)'); @@ -782,7 +769,7 @@ public function testMultipleIsolatedQueryConstruction() $qb = $this->_em->createQueryBuilder(); $expr = $this->_em->getExpressionBuilder(); - $qb->select('u')->from('Doctrine\Tests\Models\CMS\CmsUser', 'u'); + $qb->select('u')->from(CmsUser::class, 'u'); $qb->where($expr->eq('u.name', ':name')); $qb->setParameter('name', 'romanb'); @@ -819,7 +806,7 @@ public function testAlteringQueryChangesStateToDirty() { $qb = $this->_em->createQueryBuilder() ->select('u') - ->from('Doctrine\Tests\Models\CMS\CmsUser', 'u'); + ->from(CmsUser::class, 'u'); $this->assertEquals(QueryBuilder::STATE_DIRTY, $qb->getState()); } @@ -837,7 +824,7 @@ public function testResetDQLPart() { $qb = $this->_em->createQueryBuilder() ->select('u') - ->from('Doctrine\Tests\Models\CMS\CmsUser', 'u') + ->from(CmsUser::class, 'u') ->where('u.username = ?1')->orderBy('u.username'); $this->assertEquals('u.username = ?1', (string)$qb->getDQLPart('where')); @@ -853,10 +840,10 @@ public function testResetDQLParts() { $qb = $this->_em->createQueryBuilder() ->select('u') - ->from('Doctrine\Tests\Models\CMS\CmsUser', 'u') + ->from(CmsUser::class, 'u') ->where('u.username = ?1')->orderBy('u.username'); - $qb->resetDQLParts(array('where', 'orderBy')); + $qb->resetDQLParts(['where', 'orderBy']); $this->assertEquals(1, count($qb->getDQLPart('select'))); $this->assertNull($qb->getDQLPart('where')); @@ -867,7 +854,7 @@ public function testResetAllDQLParts() { $qb = $this->_em->createQueryBuilder() ->select('u') - ->from('Doctrine\Tests\Models\CMS\CmsUser', 'u') + ->from(CmsUser::class, 'u') ->where('u.username = ?1')->orderBy('u.username'); $qb->resetDQLParts(); @@ -884,7 +871,7 @@ public function testDeepClone() { $qb = $this->_em->createQueryBuilder() ->select('u') - ->from('Doctrine\Tests\Models\CMS\CmsUser', 'u') + ->from(CmsUser::class, 'u') ->andWhere('u.username = ?1') ->andWhere('u.status = ?2'); @@ -903,7 +890,7 @@ public function testDeepClone() public function testAddCriteriaWhereWithJoinAlias() { $qb = $this->_em->createQueryBuilder(); - $qb->select('alias1')->from('Doctrine\Tests\Models\CMS\CmsUser', 'alias1'); + $qb->select('alias1')->from(CmsUser::class, 'alias1'); $qb->join('alias1.articles','alias2'); $criteria = new Criteria(); @@ -923,7 +910,7 @@ public function testAddCriteriaWhereWithJoinAlias() public function testAddCriteriaWhereWithDefaultAndJoinAlias() { $qb = $this->_em->createQueryBuilder(); - $qb->select('alias1')->from('Doctrine\Tests\Models\CMS\CmsUser', 'alias1'); + $qb->select('alias1')->from(CmsUser::class, 'alias1'); $qb->join('alias1.articles','alias2'); $criteria = new Criteria(); @@ -943,7 +930,7 @@ public function testAddCriteriaWhereWithDefaultAndJoinAlias() public function testAddCriteriaWhereOnJoinAliasWithDuplicateFields() { $qb = $this->_em->createQueryBuilder(); - $qb->select('alias1')->from('Doctrine\Tests\Models\CMS\CmsUser', 'alias1'); + $qb->select('alias1')->from(CmsUser::class, 'alias1'); $qb->join('alias1.articles','alias2'); $criteria = new Criteria(); @@ -981,7 +968,7 @@ public function testGetRootAlias() { $qb = $this->_em->createQueryBuilder() ->select('u') - ->from('Doctrine\Tests\Models\CMS\CmsUser', 'u'); + ->from(CmsUser::class, 'u'); $this->assertEquals('u', $qb->getRootAlias()); } @@ -990,28 +977,28 @@ public function testGetRootAliases() { $qb = $this->_em->createQueryBuilder() ->select('u') - ->from('Doctrine\Tests\Models\CMS\CmsUser', 'u'); + ->from(CmsUser::class, 'u'); - $this->assertEquals(array('u'), $qb->getRootAliases()); + $this->assertEquals(['u'], $qb->getRootAliases()); } public function testGetRootEntities() { $qb = $this->_em->createQueryBuilder() ->select('u') - ->from('Doctrine\Tests\Models\CMS\CmsUser', 'u'); + ->from(CmsUser::class, 'u'); - $this->assertEquals(array('Doctrine\Tests\Models\CMS\CmsUser'), $qb->getRootEntities()); + $this->assertEquals([CmsUser::class], $qb->getRootEntities()); } public function testGetSeveralRootAliases() { $qb = $this->_em->createQueryBuilder() ->select('u') - ->from('Doctrine\Tests\Models\CMS\CmsUser', 'u') - ->from('Doctrine\Tests\Models\CMS\CmsUser', 'u2'); + ->from(CmsUser::class, 'u') + ->from(CmsUser::class, 'u2'); - $this->assertEquals(array('u', 'u2'), $qb->getRootAliases()); + $this->assertEquals(['u', 'u2'], $qb->getRootAliases()); $this->assertEquals('u', $qb->getRootAlias()); } @@ -1019,8 +1006,8 @@ public function testBCAddJoinWithoutRootAlias() { $qb = $this->_em->createQueryBuilder() ->select('u') - ->from('Doctrine\Tests\Models\CMS\CmsUser', 'u') - ->add('join', array('INNER JOIN u.groups g'), true); + ->from(CmsUser::class, 'u') + ->add('join', ['INNER JOIN u.groups g'], true); $this->assertEquals('SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u INNER JOIN u.groups g', $qb->getDQL()); } @@ -1033,7 +1020,7 @@ public function testEmptyStringLiteral() $expr = $this->_em->getExpressionBuilder(); $qb = $this->_em->createQueryBuilder() ->select('u') - ->from('Doctrine\Tests\Models\CMS\CmsUser', 'u') + ->from(CmsUser::class, 'u') ->where($expr->eq('u.username', $expr->literal(""))); $this->assertEquals("SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.username = ''", $qb->getDQL()); @@ -1047,7 +1034,7 @@ public function testEmptyNumericLiteral() $expr = $this->_em->getExpressionBuilder(); $qb = $this->_em->createQueryBuilder() ->select('u') - ->from('Doctrine\Tests\Models\CMS\CmsUser', 'u') + ->from(CmsUser::class, 'u') ->where($expr->eq('u.username', $expr->literal(0))); $this->assertEquals('SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.username = 0', $qb->getDQL()); @@ -1060,7 +1047,7 @@ public function testAddFromString() { $qb = $this->_em->createQueryBuilder() ->add('select', 'u') - ->add('from', 'Doctrine\Tests\Models\CMS\CmsUser u'); + ->add('from', CmsUser::class . ' u'); $this->assertEquals('SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u', $qb->getDQL()); } @@ -1073,7 +1060,7 @@ public function testAddDistinct() $qb = $this->_em->createQueryBuilder() ->select('u') ->distinct() - ->from('Doctrine\Tests\Models\CMS\CmsUser', 'u'); + ->from(CmsUser::class, 'u'); $this->assertEquals('SELECT DISTINCT u FROM Doctrine\Tests\Models\CMS\CmsUser u', $qb->getDQL()); } @@ -1096,7 +1083,7 @@ public function testSecondLevelCacheQueryBuilderOptions() { $defaultQueryBuilder = $this->_em->createQueryBuilder() ->select('s') - ->from('Doctrine\Tests\Models\Cache\State', 's'); + ->from(State::class, 's'); $this->assertFalse($defaultQueryBuilder->isCacheable()); $this->assertEquals(0, $defaultQueryBuilder->getLifetime()); @@ -1116,7 +1103,7 @@ public function testSecondLevelCacheQueryBuilderOptions() ->setCacheable(true) ->setCacheRegion('foo_reg') ->setCacheMode(Cache::MODE_REFRESH) - ->from('Doctrine\Tests\Models\Cache\State', 's'); + ->from(State::class, 's'); $this->assertTrue($builder->isCacheable()); $this->assertEquals(123, $builder->getLifetime()); @@ -1138,7 +1125,7 @@ public function testRebuildsFromParts() { $qb = $this->_em->createQueryBuilder() ->select('u') - ->from('Doctrine\Tests\Models\CMS\CmsUser', 'u') + ->from(CmsUser::class, 'u') ->join('u.article', 'a'); $dqlParts = $qb->getDQLParts(); @@ -1156,7 +1143,7 @@ public function testRebuildsFromParts() public function testGetAllAliasesWithNoJoins() { $qb = $this->_em->createQueryBuilder(); - $qb->select('u')->from('Doctrine\Tests\Models\CMS\CmsUser', 'u'); + $qb->select('u')->from(CmsUser::class, 'u'); $aliases = $qb->getAllAliases(); @@ -1167,11 +1154,88 @@ public function testGetAllAliasesWithJoins() { $qb = $this->_em->createQueryBuilder() ->select('u') - ->from('Doctrine\Tests\Models\CMS\CmsUser', 'u') + ->from(CmsUser::class, 'u') ->join('u.groups', 'g'); $aliases = $qb->getAllAliases(); $this->assertEquals(['u', 'g'], $aliases); } + + /** + * @group 6699 + */ + public function testGetParameterTypeJuggling() : void + { + $builder = $this->_em->createQueryBuilder() + ->select('u') + ->from(CmsUser::class, 'u') + ->where('u.id = ?0'); + + $builder->setParameter(0, 0); + + self::assertCount(1, $builder->getParameters()); + self::assertSame(0, $builder->getParameter(0)->getValue()); + self::assertSame(0, $builder->getParameter('0')->getValue()); + } + + /** + * @group 6699 + */ + public function testSetParameterWithNameZeroIsNotOverridden() : void + { + $builder = $this->_em->createQueryBuilder() + ->select('u') + ->from(CmsUser::class, 'u') + ->where('u.id != ?0') + ->andWhere('u.username = :name'); + + $builder->setParameter(0, 0); + $builder->setParameter('name', 'Doctrine'); + + self::assertCount(2, $builder->getParameters()); + self::assertSame(0, $builder->getParameter('0')->getValue()); + self::assertSame('Doctrine', $builder->getParameter('name')->getValue()); + } + + /** + * @group 6699 + */ + public function testSetParameterWithNameZeroDoesNotOverrideAnotherParameter() : void + { + $builder = $this->_em->createQueryBuilder() + ->select('u') + ->from(CmsUser::class, 'u') + ->where('u.id != ?0') + ->andWhere('u.username = :name'); + + $builder->setParameter('name', 'Doctrine'); + $builder->setParameter(0, 0); + + self::assertCount(2, $builder->getParameters()); + self::assertSame(0, $builder->getParameter(0)->getValue()); + self::assertSame('Doctrine', $builder->getParameter('name')->getValue()); + } + + /** + * @group 6699 + */ + public function testSetParameterWithTypeJugglingWorks() : void + { + $builder = $this->_em->createQueryBuilder() + ->select('u') + ->from(CmsUser::class, 'u') + ->where('u.id != ?0') + ->andWhere('u.username = :name'); + + $builder->setParameter('0', 1); + $builder->setParameter('name', 'Doctrine'); + $builder->setParameter(0, 2); + $builder->setParameter('0', 3); + + self::assertCount(2, $builder->getParameters()); + self::assertSame(3, $builder->getParameter(0)->getValue()); + self::assertSame(3, $builder->getParameter('0')->getValue()); + self::assertSame('Doctrine', $builder->getParameter('name')->getValue()); + } } diff --git a/tests/Doctrine/Tests/ORM/Repository/DefaultRepositoryFactoryTest.php b/tests/Doctrine/Tests/ORM/Repository/DefaultRepositoryFactoryTest.php index bdccb4d7efd..85a63404618 100644 --- a/tests/Doctrine/Tests/ORM/Repository/DefaultRepositoryFactoryTest.php +++ b/tests/Doctrine/Tests/ORM/Repository/DefaultRepositoryFactoryTest.php @@ -6,14 +6,16 @@ use Doctrine\ORM\EntityManagerInterface; use Doctrine\ORM\Mapping\ClassMetadata; use Doctrine\ORM\Repository\DefaultRepositoryFactory; -use PHPUnit_Framework_TestCase; +use Doctrine\Tests\Models\DDC753\DDC753DefaultRepository; +use Doctrine\Tests\Models\DDC869\DDC869PaymentRepository; +use PHPUnit\Framework\TestCase; /** * Tests for {@see \Doctrine\ORM\Repository\DefaultRepositoryFactory} * * @covers \Doctrine\ORM\Repository\DefaultRepositoryFactory */ -class DefaultRepositoryFactoryTest extends PHPUnit_Framework_TestCase +class DefaultRepositoryFactoryTest extends TestCase { /** * @var \Doctrine\ORM\EntityManagerInterface|\PHPUnit_Framework_MockObject_MockObject @@ -39,34 +41,31 @@ protected function setUp() $this->entityManager = $this->createEntityManager(); $this->repositoryFactory = new DefaultRepositoryFactory(); - $this - ->configuration + $this->configuration ->expects($this->any()) ->method('getDefaultRepositoryClassName') - ->will($this->returnValue('Doctrine\\Tests\\Models\\DDC869\\DDC869PaymentRepository')); + ->will($this->returnValue(DDC869PaymentRepository::class)); } public function testCreatesRepositoryFromDefaultRepositoryClass() { - $this - ->entityManager + $this->entityManager ->expects($this->any()) ->method('getClassMetadata') - ->will($this->returnCallback(array($this, 'buildClassMetadata'))); + ->will($this->returnCallback([$this, 'buildClassMetadata'])); $this->assertInstanceOf( - 'Doctrine\\Tests\\Models\\DDC869\\DDC869PaymentRepository', + DDC869PaymentRepository::class, $this->repositoryFactory->getRepository($this->entityManager, __CLASS__) ); } public function testCreatedRepositoriesAreCached() { - $this - ->entityManager + $this->entityManager ->expects($this->any()) ->method('getClassMetadata') - ->will($this->returnCallback(array($this, 'buildClassMetadata'))); + ->will($this->returnCallback([$this, 'buildClassMetadata'])); $this->assertSame( $this->repositoryFactory->getRepository($this->entityManager, __CLASS__), @@ -77,17 +76,15 @@ public function testCreatedRepositoriesAreCached() public function testCreatesRepositoryFromCustomClassMetadata() { $customMetadata = $this->buildClassMetadata(__DIR__); + $customMetadata->customRepositoryClassName = DDC753DefaultRepository::class; - $customMetadata->customRepositoryClassName = 'Doctrine\\Tests\\Models\\DDC753\\DDC753DefaultRepository'; - - $this - ->entityManager + $this->entityManager ->expects($this->any()) ->method('getClassMetadata') ->will($this->returnValue($customMetadata)); $this->assertInstanceOf( - 'Doctrine\\Tests\\Models\\DDC753\\DDC753DefaultRepository', + DDC753DefaultRepository::class, $this->repositoryFactory->getRepository($this->entityManager, __CLASS__) ); } @@ -97,14 +94,13 @@ public function testCachesDistinctRepositoriesPerDistinctEntityManager() $em1 = $this->createEntityManager(); $em2 = $this->createEntityManager(); - $em1 - ->expects($this->any()) + $em1->expects($this->any()) ->method('getClassMetadata') - ->will($this->returnCallback(array($this, 'buildClassMetadata'))); - $em2 - ->expects($this->any()) + ->will($this->returnCallback([$this, 'buildClassMetadata'])); + + $em2->expects($this->any()) ->method('getClassMetadata') - ->will($this->returnCallback(array($this, 'buildClassMetadata'))); + ->will($this->returnCallback([$this, 'buildClassMetadata'])); $repo1 = $this->repositoryFactory->getRepository($em1, __CLASS__); $repo2 = $this->repositoryFactory->getRepository($em2, __CLASS__); @@ -141,8 +137,7 @@ private function createEntityManager() { $entityManager = $this->createMock(EntityManagerInterface::class); - $entityManager - ->expects($this->any()) + $entityManager->expects($this->any()) ->method('getConfiguration') ->will($this->returnValue($this->configuration)); diff --git a/tests/Doctrine/Tests/ORM/Tools/AttachEntityListenersListenerTest.php b/tests/Doctrine/Tests/ORM/Tools/AttachEntityListenersListenerTest.php index 8c0a7a75bcd..db4da0b5d88 100644 --- a/tests/Doctrine/Tests/ORM/Tools/AttachEntityListenersListenerTest.php +++ b/tests/Doctrine/Tests/ORM/Tools/AttachEntityListenersListenerTest.php @@ -40,36 +40,36 @@ public function setUp() public function testAttachEntityListeners() { $this->listener->addEntityListener( - AttachEntityListenersListenerTestFooEntity::CLASSNAME, - AttachEntityListenersListenerTestListener::CLASSNAME, + AttachEntityListenersListenerTestFooEntity::class, + AttachEntityListenersListenerTestListener::class, Events::postLoad, 'postLoadHandler' ); - $metadata = $this->factory->getMetadataFor(AttachEntityListenersListenerTestFooEntity::CLASSNAME); + $metadata = $this->factory->getMetadataFor(AttachEntityListenersListenerTestFooEntity::class); $this->assertArrayHasKey('postLoad', $metadata->entityListeners); $this->assertCount(1, $metadata->entityListeners['postLoad']); $this->assertEquals('postLoadHandler', $metadata->entityListeners['postLoad'][0]['method']); - $this->assertEquals(AttachEntityListenersListenerTestListener::CLASSNAME, $metadata->entityListeners['postLoad'][0]['class']); + $this->assertEquals(AttachEntityListenersListenerTestListener::class, $metadata->entityListeners['postLoad'][0]['class']); } public function testAttachToExistingEntityListeners() { $this->listener->addEntityListener( - AttachEntityListenersListenerTestBarEntity::CLASSNAME, - AttachEntityListenersListenerTestListener2::CLASSNAME, + AttachEntityListenersListenerTestBarEntity::class, + AttachEntityListenersListenerTestListener2::class, Events::prePersist ); $this->listener->addEntityListener( - AttachEntityListenersListenerTestBarEntity::CLASSNAME, - AttachEntityListenersListenerTestListener2::CLASSNAME, + AttachEntityListenersListenerTestBarEntity::class, + AttachEntityListenersListenerTestListener2::class, Events::postPersist, 'postPersistHandler' ); - $metadata = $this->factory->getMetadataFor(AttachEntityListenersListenerTestBarEntity::CLASSNAME); + $metadata = $this->factory->getMetadataFor(AttachEntityListenersListenerTestBarEntity::class); $this->assertArrayHasKey('postPersist', $metadata->entityListeners); $this->assertArrayHasKey('prePersist', $metadata->entityListeners); @@ -78,16 +78,16 @@ public function testAttachToExistingEntityListeners() $this->assertCount(2, $metadata->entityListeners['postPersist']); $this->assertEquals('prePersist', $metadata->entityListeners['prePersist'][0]['method']); - $this->assertEquals(AttachEntityListenersListenerTestListener::CLASSNAME, $metadata->entityListeners['prePersist'][0]['class']); + $this->assertEquals(AttachEntityListenersListenerTestListener::class, $metadata->entityListeners['prePersist'][0]['class']); $this->assertEquals('prePersist', $metadata->entityListeners['prePersist'][1]['method']); - $this->assertEquals(AttachEntityListenersListenerTestListener2::CLASSNAME, $metadata->entityListeners['prePersist'][1]['class']); + $this->assertEquals(AttachEntityListenersListenerTestListener2::class, $metadata->entityListeners['prePersist'][1]['class']); $this->assertEquals('postPersist', $metadata->entityListeners['postPersist'][0]['method']); - $this->assertEquals(AttachEntityListenersListenerTestListener::CLASSNAME, $metadata->entityListeners['postPersist'][0]['class']); + $this->assertEquals(AttachEntityListenersListenerTestListener::class, $metadata->entityListeners['postPersist'][0]['class']); $this->assertEquals('postPersistHandler', $metadata->entityListeners['postPersist'][1]['method']); - $this->assertEquals(AttachEntityListenersListenerTestListener2::CLASSNAME, $metadata->entityListeners['postPersist'][1]['class']); + $this->assertEquals(AttachEntityListenersListenerTestListener2::class, $metadata->entityListeners['postPersist'][1]['class']); } /** @@ -97,18 +97,18 @@ public function testAttachToExistingEntityListeners() public function testDuplicateEntityListenerException() { $this->listener->addEntityListener( - AttachEntityListenersListenerTestFooEntity::CLASSNAME, - AttachEntityListenersListenerTestListener::CLASSNAME, + AttachEntityListenersListenerTestFooEntity::class, + AttachEntityListenersListenerTestListener::class, Events::postPersist ); $this->listener->addEntityListener( - AttachEntityListenersListenerTestFooEntity::CLASSNAME, - AttachEntityListenersListenerTestListener::CLASSNAME, + AttachEntityListenersListenerTestFooEntity::class, + AttachEntityListenersListenerTestListener::class, Events::postPersist ); - $this->factory->getMetadataFor(AttachEntityListenersListenerTestFooEntity::CLASSNAME); + $this->factory->getMetadataFor(AttachEntityListenersListenerTestFooEntity::class); } } @@ -117,8 +117,6 @@ public function testDuplicateEntityListenerException() */ class AttachEntityListenersListenerTestFooEntity { - const CLASSNAME = __CLASS__; - /** * @Id * @Column(type="integer") @@ -133,8 +131,6 @@ class AttachEntityListenersListenerTestFooEntity */ class AttachEntityListenersListenerTestBarEntity { - const CLASSNAME = __CLASS__; - /** * @Id * @Column(type="integer") @@ -145,8 +141,6 @@ class AttachEntityListenersListenerTestBarEntity class AttachEntityListenersListenerTestListener { - const CLASSNAME = __CLASS__; - public $calls; public function prePersist() @@ -167,8 +161,6 @@ public function postPersist() class AttachEntityListenersListenerTestListener2 { - const CLASSNAME = __CLASS__; - public $calls; public function prePersist() diff --git a/tests/Doctrine/Tests/ORM/Tools/Console/Command/ClearCacheCollectionRegionCommandTest.php b/tests/Doctrine/Tests/ORM/Tools/Console/Command/ClearCacheCollectionRegionCommandTest.php index 298ca23a9fb..f8c17b318bf 100644 --- a/tests/Doctrine/Tests/ORM/Tools/Console/Command/ClearCacheCollectionRegionCommandTest.php +++ b/tests/Doctrine/Tests/ORM/Tools/Console/Command/ClearCacheCollectionRegionCommandTest.php @@ -4,10 +4,11 @@ use Doctrine\ORM\Tools\Console\Command\ClearCache\CollectionRegionCommand; use Doctrine\ORM\Tools\Console\Helper\EntityManagerHelper; -use Symfony\Component\Console\Tester\CommandTester; -use Symfony\Component\Console\Helper\HelperSet; -use Symfony\Component\Console\Application; +use Doctrine\Tests\Models\Cache\State; use Doctrine\Tests\OrmFunctionalTestCase; +use Symfony\Component\Console\Application; +use Symfony\Component\Console\Helper\HelperSet; +use Symfony\Component\Console\Tester\CommandTester; /** * @group DDC-2183 @@ -29,66 +30,90 @@ protected function setUp() $this->enableSecondLevelCache(); parent::setUp(); - $this->application = new Application(); - $this->command = new CollectionRegionCommand(); - - $this->application->setHelperSet(new HelperSet(array( - 'em' => new EntityManagerHelper($this->_em) - ))); + $this->command = new CollectionRegionCommand(); + $this->application = new Application(); + $this->application->setHelperSet(new HelperSet(['em' => new EntityManagerHelper($this->_em)])); $this->application->add($this->command); } public function testClearAllRegion() { - $command = $this->application->find('orm:clear-cache:region:collection'); - $tester = new CommandTester($command); - $tester->execute(array( - 'command' => $command->getName(), - '--all' => true, - ), array('decorated' => false)); - - $this->assertEquals('Clearing all second-level cache collection regions' . PHP_EOL, $tester->getDisplay()); + $command = $this->application->find('orm:clear-cache:region:collection'); + $tester = new CommandTester($command); + + $tester->execute( + [ + 'command' => $command->getName(), + '--all' => true, + ], + ['decorated' => false] + ); + + self::assertContains(' // Clearing all second-level cache collection regions', $tester->getDisplay()); } public function testClearByOwnerEntityClassName() { - $command = $this->application->find('orm:clear-cache:region:collection'); - $tester = new CommandTester($command); - $tester->execute(array( - 'command' => $command->getName(), - 'owner-class' => 'Doctrine\Tests\Models\Cache\State', - 'association' => 'cities', - ), array('decorated' => false)); - - $this->assertEquals('Clearing second-level cache for collection "Doctrine\Tests\Models\Cache\State#cities"' . PHP_EOL, $tester->getDisplay()); + $command = $this->application->find('orm:clear-cache:region:collection'); + $tester = new CommandTester($command); + + $tester->execute( + [ + 'command' => $command->getName(), + 'owner-class' => State::class, + 'association' => 'cities', + ], + ['decorated' => false] + ); + + self::assertContains( + ' // Clearing second-level cache for collection "Doctrine\Tests\Models\Cache\State#cities"', + $tester->getDisplay() + ); } public function testClearCacheEntryName() { - $command = $this->application->find('orm:clear-cache:region:collection'); - $tester = new CommandTester($command); - $tester->execute(array( - 'command' => $command->getName(), - 'owner-class' => 'Doctrine\Tests\Models\Cache\State', - 'association' => 'cities', - 'owner-id' => 1, - ), array('decorated' => false)); - - $this->assertEquals('Clearing second-level cache entry for collection "Doctrine\Tests\Models\Cache\State#cities" owner entity identified by "1"' . PHP_EOL, $tester->getDisplay()); + $command = $this->application->find('orm:clear-cache:region:collection'); + $tester = new CommandTester($command); + + $tester->execute( + [ + 'command' => $command->getName(), + 'owner-class' => State::class, + 'association' => 'cities', + 'owner-id' => 1, + ], + ['decorated' => false] + ); + + self::assertContains( + ' // Clearing second-level cache entry for collection "Doctrine\Tests\Models\Cache\State#cities" owner', + $tester->getDisplay() + ); + + self::assertContains(' // entity identified by "1"', $tester->getDisplay()); } public function testFlushRegionName() { - $command = $this->application->find('orm:clear-cache:region:collection'); - $tester = new CommandTester($command); - $tester->execute(array( - 'command' => $command->getName(), - 'owner-class' => 'Doctrine\Tests\Models\Cache\State', - 'association' => 'cities', - '--flush' => true, - ), array('decorated' => false)); - - $this->assertEquals('Flushing cache provider configured for "Doctrine\Tests\Models\Cache\State#cities"' . PHP_EOL, $tester->getDisplay()); + $command = $this->application->find('orm:clear-cache:region:collection'); + $tester = new CommandTester($command); + + $tester->execute( + [ + 'command' => $command->getName(), + 'owner-class' => State::class, + 'association' => 'cities', + '--flush' => true, + ], + ['decorated' => false] + ); + + self::assertContains( + ' // Flushing cache provider configured for "Doctrine\Tests\Models\Cache\State#cities"', + $tester->getDisplay() + ); } } diff --git a/tests/Doctrine/Tests/ORM/Tools/Console/Command/ClearCacheEntityRegionCommandTest.php b/tests/Doctrine/Tests/ORM/Tools/Console/Command/ClearCacheEntityRegionCommandTest.php index d16fa2e7fa2..b1d8d386b2f 100644 --- a/tests/Doctrine/Tests/ORM/Tools/Console/Command/ClearCacheEntityRegionCommandTest.php +++ b/tests/Doctrine/Tests/ORM/Tools/Console/Command/ClearCacheEntityRegionCommandTest.php @@ -4,10 +4,11 @@ use Doctrine\ORM\Tools\Console\Command\ClearCache\EntityRegionCommand; use Doctrine\ORM\Tools\Console\Helper\EntityManagerHelper; -use Symfony\Component\Console\Tester\CommandTester; -use Symfony\Component\Console\Helper\HelperSet; -use Symfony\Component\Console\Application; +use Doctrine\Tests\Models\Cache\Country; use Doctrine\Tests\OrmFunctionalTestCase; +use Symfony\Component\Console\Application; +use Symfony\Component\Console\Helper\HelperSet; +use Symfony\Component\Console\Tester\CommandTester; /** * @group DDC-2183 @@ -29,63 +30,87 @@ protected function setUp() $this->enableSecondLevelCache(); parent::setUp(); - $this->application = new Application(); - $this->command = new EntityRegionCommand(); - - $this->application->setHelperSet(new HelperSet(array( - 'em' => new EntityManagerHelper($this->_em) - ))); + $this->command = new EntityRegionCommand(); + $this->application = new Application(); + $this->application->setHelperSet(new HelperSet(['em' => new EntityManagerHelper($this->_em)])); $this->application->add($this->command); } public function testClearAllRegion() { - $command = $this->application->find('orm:clear-cache:region:entity'); - $tester = new CommandTester($command); - $tester->execute(array( - 'command' => $command->getName(), - '--all' => true, - ), array('decorated' => false)); - - $this->assertEquals('Clearing all second-level cache entity regions' . PHP_EOL, $tester->getDisplay()); + $command = $this->application->find('orm:clear-cache:region:entity'); + $tester = new CommandTester($command); + + $tester->execute( + [ + 'command' => $command->getName(), + '--all' => true, + ], + ['decorated' => false] + ); + + self::assertContains(' // Clearing all second-level cache entity regions', $tester->getDisplay()); } public function testClearByEntityClassName() { - $command = $this->application->find('orm:clear-cache:region:entity'); - $tester = new CommandTester($command); - $tester->execute(array( - 'command' => $command->getName(), - 'entity-class' => 'Doctrine\Tests\Models\Cache\Country', - ), array('decorated' => false)); - - $this->assertEquals('Clearing second-level cache for entity "Doctrine\Tests\Models\Cache\Country"' . PHP_EOL, $tester->getDisplay()); + $command = $this->application->find('orm:clear-cache:region:entity'); + $tester = new CommandTester($command); + + $tester->execute( + [ + 'command' => $command->getName(), + 'entity-class' => Country::class, + ], + ['decorated' => false] + ); + + self::assertContains( + ' // Clearing second-level cache for entity "Doctrine\Tests\Models\Cache\Country"', + $tester->getDisplay() + ); } public function testClearCacheEntryName() { - $command = $this->application->find('orm:clear-cache:region:entity'); - $tester = new CommandTester($command); - $tester->execute(array( - 'command' => $command->getName(), - 'entity-class' => 'Doctrine\Tests\Models\Cache\Country', - 'entity-id' => 1, - ), array('decorated' => false)); - - $this->assertEquals('Clearing second-level cache entry for entity "Doctrine\Tests\Models\Cache\Country" identified by "1"' . PHP_EOL, $tester->getDisplay()); + $command = $this->application->find('orm:clear-cache:region:entity'); + $tester = new CommandTester($command); + + $tester->execute( + [ + 'command' => $command->getName(), + 'entity-class' => Country::class, + 'entity-id' => 1, + ], + ['decorated' => false] + ); + + self::assertContains( + ' // Clearing second-level cache entry for entity "Doctrine\Tests\Models\Cache\Country" identified by', + $tester->getDisplay() + ); + + self::assertContains(' // "1"', $tester->getDisplay()); } public function testFlushRegionName() { - $command = $this->application->find('orm:clear-cache:region:entity'); - $tester = new CommandTester($command); - $tester->execute(array( - 'command' => $command->getName(), - 'entity-class' => 'Doctrine\Tests\Models\Cache\Country', - '--flush' => true, - ), array('decorated' => false)); - - $this->assertEquals('Flushing cache provider configured for entity named "Doctrine\Tests\Models\Cache\Country"' . PHP_EOL, $tester->getDisplay()); + $command = $this->application->find('orm:clear-cache:region:entity'); + $tester = new CommandTester($command); + + $tester->execute( + [ + 'command' => $command->getName(), + 'entity-class' => Country::class, + '--flush' => true, + ], + ['decorated' => false] + ); + + self::assertContains( + ' // Flushing cache provider configured for entity named "Doctrine\Tests\Models\Cache\Country"', + $tester->getDisplay() + ); } } diff --git a/tests/Doctrine/Tests/ORM/Tools/Console/Command/ClearCacheQueryRegionCommandTest.php b/tests/Doctrine/Tests/ORM/Tools/Console/Command/ClearCacheQueryRegionCommandTest.php index 4468faf9638..1d761260cb7 100644 --- a/tests/Doctrine/Tests/ORM/Tools/Console/Command/ClearCacheQueryRegionCommandTest.php +++ b/tests/Doctrine/Tests/ORM/Tools/Console/Command/ClearCacheQueryRegionCommandTest.php @@ -4,10 +4,10 @@ use Doctrine\ORM\Tools\Console\Command\ClearCache\QueryRegionCommand; use Doctrine\ORM\Tools\Console\Helper\EntityManagerHelper; -use Symfony\Component\Console\Tester\CommandTester; -use Symfony\Component\Console\Helper\HelperSet; -use Symfony\Component\Console\Application; use Doctrine\Tests\OrmFunctionalTestCase; +use Symfony\Component\Console\Application; +use Symfony\Component\Console\Helper\HelperSet; +use Symfony\Component\Console\Tester\CommandTester; /** * @group DDC-2183 @@ -29,62 +29,84 @@ protected function setUp() $this->enableSecondLevelCache(); parent::setUp(); - $this->application = new Application(); - $this->command = new QueryRegionCommand(); - - $this->application->setHelperSet(new HelperSet(array( - 'em' => new EntityManagerHelper($this->_em) - ))); + $this->command = new QueryRegionCommand(); + $this->application = new Application(); + $this->application->setHelperSet(new HelperSet(['em' => new EntityManagerHelper($this->_em)])); $this->application->add($this->command); } public function testClearAllRegion() { - $command = $this->application->find('orm:clear-cache:region:query'); - $tester = new CommandTester($command); - $tester->execute(array( - 'command' => $command->getName(), - '--all' => true, - ), array('decorated' => false)); - - $this->assertEquals('Clearing all second-level cache query regions' . PHP_EOL, $tester->getDisplay()); + $command = $this->application->find('orm:clear-cache:region:query'); + $tester = new CommandTester($command); + + $tester->execute( + [ + 'command' => $command->getName(), + '--all' => true, + ], + ['decorated' => false] + ); + + self::assertContains(' // Clearing all second-level cache query regions', $tester->getDisplay()); } public function testClearDefaultRegionName() { - $command = $this->application->find('orm:clear-cache:region:query'); - $tester = new CommandTester($command); - $tester->execute(array( - 'command' => $command->getName(), - 'region-name' => null, - ), array('decorated' => false)); - - $this->assertEquals('Clearing second-level cache query region named "query_cache_region"' . PHP_EOL, $tester->getDisplay()); + $command = $this->application->find('orm:clear-cache:region:query'); + $tester = new CommandTester($command); + + $tester->execute( + [ + 'command' => $command->getName(), + 'region-name' => null, + ], + ['decorated' => false] + ); + + self::assertContains( + ' // Clearing second-level cache query region named "query_cache_region"', + $tester->getDisplay() + ); } public function testClearByRegionName() { - $command = $this->application->find('orm:clear-cache:region:query'); - $tester = new CommandTester($command); - $tester->execute(array( - 'command' => $command->getName(), - 'region-name' => 'my_region', - ), array('decorated' => false)); - - $this->assertEquals('Clearing second-level cache query region named "my_region"' . PHP_EOL, $tester->getDisplay()); + $command = $this->application->find('orm:clear-cache:region:query'); + $tester = new CommandTester($command); + + $tester->execute( + [ + 'command' => $command->getName(), + 'region-name' => 'my_region', + ], + ['decorated' => false] + ); + + self::assertContains( + ' // Clearing second-level cache query region named "my_region"', + $tester->getDisplay() + ); } public function testFlushRegionName() { - $command = $this->application->find('orm:clear-cache:region:query'); - $tester = new CommandTester($command); - $tester->execute(array( - 'command' => $command->getName(), - 'region-name' => 'my_region', - '--flush' => true, - ), array('decorated' => false)); - - $this->assertEquals('Flushing cache provider configured for second-level cache query region named "my_region"' . PHP_EOL, $tester->getDisplay()); + $command = $this->application->find('orm:clear-cache:region:query'); + $tester = new CommandTester($command); + + $tester->execute( + [ + 'command' => $command->getName(), + 'region-name' => 'my_region', + '--flush' => true, + ], + ['decorated' => false] + ); + + self::assertContains( + ' // Flushing cache provider configured for second-level cache query region named "my_region"', + $tester->getDisplay() + ); } } diff --git a/tests/Doctrine/Tests/ORM/Tools/Console/Command/ConvertDoctrine1SchemaCommandTest.php b/tests/Doctrine/Tests/ORM/Tools/Console/Command/ConvertDoctrine1SchemaCommandTest.php index af89c866dbf..f21a9a64d3a 100644 --- a/tests/Doctrine/Tests/ORM/Tools/Console/Command/ConvertDoctrine1SchemaCommandTest.php +++ b/tests/Doctrine/Tests/ORM/Tools/Console/Command/ConvertDoctrine1SchemaCommandTest.php @@ -5,10 +5,19 @@ use Doctrine\ORM\Tools\Console\Command\ConvertDoctrine1SchemaCommand; use Doctrine\ORM\Tools\EntityGenerator; use Doctrine\Tests\OrmTestCase; +use Doctrine\Tests\VerifyDeprecations; use Symfony\Component\Console\Output\OutputInterface; class ConvertDoctrine1SchemaCommandTest extends OrmTestCase { + use VerifyDeprecations; + + /** @after */ + public function ensureTestGeneratedDeprecationMessages() : void + { + $this->assertHasDeprecationMessages(); + } + public function testExecution() { $entityGenerator = $this->createMock(EntityGenerator::class); @@ -20,6 +29,6 @@ public function testExecution() ->method('writeln') ->with($this->equalTo('No Metadata Classes to process.')); - $command->convertDoctrine1Schema(array(), sys_get_temp_dir(), 'annotation', 4, null, $output); + $command->convertDoctrine1Schema([], sys_get_temp_dir(), 'annotation', 4, null, $output); } } diff --git a/tests/Doctrine/Tests/ORM/Tools/Console/Command/GenerateRepositoriesCommandTest.php b/tests/Doctrine/Tests/ORM/Tools/Console/Command/GenerateRepositoriesCommandTest.php index 08ade299929..c155b9aa7e3 100644 --- a/tests/Doctrine/Tests/ORM/Tools/Console/Command/GenerateRepositoriesCommandTest.php +++ b/tests/Doctrine/Tests/ORM/Tools/Console/Command/GenerateRepositoriesCommandTest.php @@ -2,18 +2,22 @@ namespace Doctrine\Tests\ORM\Tools\Console\Command; +use Doctrine\Common\Persistence\Mapping\ClassMetadataFactory; +use Doctrine\ORM\Configuration; +use Doctrine\ORM\EntityManagerInterface; +use Doctrine\ORM\EntityRepository; use Doctrine\ORM\Tools\Console\Command\GenerateRepositoriesCommand; use Doctrine\ORM\Tools\Console\Helper\EntityManagerHelper; -use Symfony\Component\Console\Tester\CommandTester; -use Symfony\Component\Console\Helper\HelperSet; -use Symfony\Component\Console\Application; +use Doctrine\Tests\Models\DDC3231\DDC3231EntityRepository; use Doctrine\Tests\OrmFunctionalTestCase; +use Doctrine\Tests\VerifyDeprecations; +use Symfony\Component\Console\Application; +use Symfony\Component\Console\Helper\HelperSet; +use Symfony\Component\Console\Tester\CommandTester; -/** - * GenerateRepositoriesCommandTest - */ class GenerateRepositoriesCommandTest extends OrmFunctionalTestCase { + use VerifyDeprecations; /** * @var \Symfony\Component\Console\Application */ @@ -32,21 +36,12 @@ protected function setUp() \mkdir($this->path); - $metadataDriver = $this->_em->getConfiguration()->getMetadataDriverImpl(); + $metadataDriver->addPaths([__DIR__ . '/../../../../Models/DDC3231/']); - $metadataDriver->addPaths(array( - __DIR__ . '/../../../../Models/DDC3231/' - )); - $this->application = new Application(); - - $this->application->setHelperSet(new HelperSet(array( - 'em' => new EntityManagerHelper($this->_em) - ))); - + $this->application->setHelperSet(new HelperSet(['em' => new EntityManagerHelper($this->_em)])); $this->application->add(new GenerateRepositoriesCommand()); - } /** @@ -54,7 +49,7 @@ protected function setUp() */ public function tearDown() { - $dirs = array(); + $dirs = []; $ri = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($this->path)); foreach ($ri AS $file) { @@ -82,43 +77,45 @@ public function testGenerateRepositories() $cname = 'Doctrine\Tests\Models\DDC3231\DDC3231User1Repository'; $fname = str_replace('\\', DIRECTORY_SEPARATOR, $cname) . '.php'; - $this->assertFileExists($this->path . DIRECTORY_SEPARATOR . $fname); - $this->assertFileExists($this->path . DIRECTORY_SEPARATOR . 'DDC3231User1NoNamespaceRepository.php'); + self::assertFileExists($this->path . DIRECTORY_SEPARATOR . $fname); + self::assertFileExists($this->path . DIRECTORY_SEPARATOR . 'DDC3231User1NoNamespaceRepository.php'); require $this->path . DIRECTORY_SEPARATOR . $fname; require $this->path . DIRECTORY_SEPARATOR . 'DDC3231User1NoNamespaceRepository.php'; - $this->assertTrue(class_exists($cname)); - $this->assertTrue(class_exists('DDC3231User1NoNamespaceRepository')); + self::assertTrue(class_exists($cname)); + self::assertTrue(class_exists('DDC3231User1NoNamespaceRepository')); $repo1 = new \ReflectionClass($cname); $repo2 = new \ReflectionClass('DDC3231User1NoNamespaceRepository'); - $this->assertSame('Doctrine\ORM\EntityRepository', $repo1->getParentClass()->getName()); - $this->assertSame('Doctrine\ORM\EntityRepository', $repo2->getParentClass()->getName()); + self::assertSame(EntityRepository::class, $repo1->getParentClass()->getName()); + self::assertSame(EntityRepository::class, $repo2->getParentClass()->getName()); + $this->assertHasDeprecationMessages(); } public function testGenerateRepositoriesCustomDefaultRepository() { - $this->generateRepositories('DDC3231User2', 'Doctrine\Tests\Models\DDC3231\DDC3231EntityRepository'); + $this->generateRepositories('DDC3231User2', DDC3231EntityRepository::class); $cname = 'Doctrine\Tests\Models\DDC3231\DDC3231User2Repository'; $fname = str_replace('\\', DIRECTORY_SEPARATOR, $cname) . '.php'; - $this->assertFileExists($this->path . DIRECTORY_SEPARATOR . $fname); - $this->assertFileExists($this->path . DIRECTORY_SEPARATOR . 'DDC3231User2NoNamespaceRepository.php'); + self::assertFileExists($this->path . DIRECTORY_SEPARATOR . $fname); + self::assertFileExists($this->path . DIRECTORY_SEPARATOR . 'DDC3231User2NoNamespaceRepository.php'); require $this->path . DIRECTORY_SEPARATOR . $fname; require $this->path . DIRECTORY_SEPARATOR . 'DDC3231User2NoNamespaceRepository.php'; - $this->assertTrue(class_exists($cname)); - $this->assertTrue(class_exists('DDC3231User2NoNamespaceRepository')); + self::assertTrue(class_exists($cname)); + self::assertTrue(class_exists('DDC3231User2NoNamespaceRepository')); $repo1 = new \ReflectionClass($cname); $repo2 = new \ReflectionClass('DDC3231User2NoNamespaceRepository'); - $this->assertSame('Doctrine\Tests\Models\DDC3231\DDC3231EntityRepository', $repo1->getParentClass()->getName()); - $this->assertSame('Doctrine\Tests\Models\DDC3231\DDC3231EntityRepository', $repo2->getParentClass()->getName()); + self::assertSame(DDC3231EntityRepository::class, $repo1->getParentClass()->getName()); + self::assertSame(DDC3231EntityRepository::class, $repo2->getParentClass()->getName()); + $this->assertHasDeprecationMessages(); } /** @@ -131,13 +128,51 @@ private function generateRepositories($filter, $defaultRepository = null) $this->_em->getConfiguration()->setDefaultRepositoryClassName($defaultRepository); } - $command = $this->application->find('orm:generate-repositories'); - $tester = new CommandTester($command); - $tester->execute(array( - 'command' => $command->getName(), - 'dest-path' => $this->path, - '--filter' => $filter, - )); + $command = $this->application->find('orm:generate-repositories'); + $tester = new CommandTester($command); + + $tester->execute( + [ + 'command' => $command->getName(), + 'dest-path' => $this->path, + '--filter' => $filter, + ] + ); } + public function testNoMetadataClassesToProcess() : void + { + $configuration = $this->createMock(Configuration::class); + $metadataFactory = $this->createMock(ClassMetadataFactory::class); + $em = $this->createMock(EntityManagerInterface::class); + + $configuration->method('getDefaultRepositoryClassName') + ->willReturn('fooRepository'); + + $metadataFactory->method('getAllMetadata') + ->willReturn([]); + + $em->method('getMetadataFactory') + ->willReturn($metadataFactory); + + $em->method('getConfiguration') + ->willReturn($configuration); + + $application = new Application(); + $application->setHelperSet(new HelperSet(['em' => new EntityManagerHelper($em)])); + $application->add(new GenerateRepositoriesCommand()); + + $command = $application->find('orm:generate-repositories'); + $tester = new CommandTester($command); + + $tester->execute( + [ + 'command' => $command->getName(), + 'dest-path' => $this->path, + ] + ); + + self::assertContains('Command orm:generate-repositories is deprecated and will be removed in Doctrine ORM 3.0.', $tester->getDisplay()); + self::assertContains('[OK] No Metadata Classes to process.', $tester->getDisplay()); + } } diff --git a/tests/Doctrine/Tests/ORM/Tools/Console/Command/InfoCommandTest.php b/tests/Doctrine/Tests/ORM/Tools/Console/Command/InfoCommandTest.php index fb63e4f6402..59d5d9532ab 100644 --- a/tests/Doctrine/Tests/ORM/Tools/Console/Command/InfoCommandTest.php +++ b/tests/Doctrine/Tests/ORM/Tools/Console/Command/InfoCommandTest.php @@ -2,7 +2,13 @@ namespace Doctrine\Tests\ORM\Tools\Console\Command; +use Doctrine\Common\Persistence\Mapping\Driver\MappingDriver; +use Doctrine\ORM\Configuration; +use Doctrine\ORM\EntityManagerInterface; +use Doctrine\ORM\Mapping\MappingException; use Doctrine\ORM\Tools\Console\Helper\EntityManagerHelper; +use Doctrine\Tests\Models\Cache\AttractionInfo; +use Doctrine\Tests\Models\Cache\City; use Symfony\Component\Console\Tester\CommandTester; use Symfony\Component\Console\Helper\HelperSet; use Symfony\Component\Console\Application; @@ -31,25 +37,86 @@ protected function setUp() parent::setUp(); $this->application = new Application(); - $command = new InfoCommand(); - $this->application->setHelperSet(new HelperSet(array( - 'em' => new EntityManagerHelper($this->_em) - ))); + $this->application->setHelperSet(new HelperSet(['em' => new EntityManagerHelper($this->_em)])); + $this->application->add(new InfoCommand()); - $this->application->add($command); - - $this->command = $this->application->find('orm:info'); - $this->tester = new CommandTester($command); + $this->command = $this->application->find('orm:info'); + $this->tester = new CommandTester($this->command); } public function testListAllClasses() { - $this->tester->execute(array( - 'command' => $this->command->getName(), - )); + $this->tester->execute(['command' => $this->command->getName()]); + + self::assertContains(AttractionInfo::class, $this->tester->getDisplay()); + self::assertContains(City::class, $this->tester->getDisplay()); + } + + public function testEmptyEntityClassNames() : void + { + $mappingDriver = $this->createMock(MappingDriver::class); + $configuration = $this->createMock(Configuration::class); + $em = $this->createMock(EntityManagerInterface::class); + + $mappingDriver->method('getAllClassNames') + ->willReturn([]); + + $configuration->method('getMetadataDriverImpl') + ->willReturn($mappingDriver); + + $em->method('getConfiguration') + ->willReturn($configuration); + + $application = new Application(); + $application->setHelperSet(new HelperSet(['em' => new EntityManagerHelper($em)])); + $application->add(new InfoCommand()); + + $command = $application->find('orm:info'); + $tester = new CommandTester($command); + + $tester->execute(['command' => $command->getName()]); + + self::assertContains( + ' ! [CAUTION] You do not have any mapped Doctrine ORM entities according to the current configuration', + $tester->getDisplay() + ); + + self::assertContains( + ' ! If you have entities or mapping files you should check your mapping configuration for errors.', + $tester->getDisplay() + ); + } + + public function testInvalidEntityClassMetadata() : void + { + $mappingDriver = $this->createMock(MappingDriver::class); + $configuration = $this->createMock(Configuration::class); + $em = $this->createMock(EntityManagerInterface::class); + + $mappingDriver->method('getAllClassNames') + ->willReturn(['InvalidEntity']); + + $configuration->method('getMetadataDriverImpl') + ->willReturn($mappingDriver); + + $em->method('getConfiguration') + ->willReturn($configuration); + + $em->method('getClassMetadata') + ->with('InvalidEntity') + ->willThrowException(new MappingException('exception message')); + + $application = new Application(); + $application->setHelperSet(new HelperSet(['em' => new EntityManagerHelper($em)])); + $application->add(new InfoCommand()); + + $command = $application->find('orm:info'); + $tester = new CommandTester($command); + + $tester->execute(['command' => $command->getName()]); - $this->assertContains('Doctrine\Tests\Models\Cache\AttractionInfo', $this->tester->getDisplay()); - $this->assertContains('Doctrine\Tests\Models\Cache\City', $this->tester->getDisplay()); + self::assertContains('[FAIL] InvalidEntity', $tester->getDisplay()); + self::assertContains('exception message', $tester->getDisplay()); } } diff --git a/tests/Doctrine/Tests/ORM/Tools/Console/Command/MappingDescribeCommandTest.php b/tests/Doctrine/Tests/ORM/Tools/Console/Command/MappingDescribeCommandTest.php index 017e94aeede..f73456b47ab 100644 --- a/tests/Doctrine/Tests/ORM/Tools/Console/Command/MappingDescribeCommandTest.php +++ b/tests/Doctrine/Tests/ORM/Tools/Console/Command/MappingDescribeCommandTest.php @@ -4,6 +4,7 @@ use Doctrine\ORM\Tools\Console\Command\MappingDescribeCommand; use Doctrine\ORM\Tools\Console\Helper\EntityManagerHelper; +use Doctrine\Tests\Models\Cache\AttractionInfo; use Doctrine\Tests\OrmFunctionalTestCase; use Symfony\Component\Console\Application; use Symfony\Component\Console\Helper\HelperSet; @@ -36,28 +37,26 @@ protected function setUp() parent::setUp(); $this->application = new Application(); - $command = new MappingDescribeCommand(); - - $this->application->setHelperSet(new HelperSet(array( - 'em' => new EntityManagerHelper($this->_em) - ))); - - $this->application->add($command); + $this->application->setHelperSet(new HelperSet(['em' => new EntityManagerHelper($this->_em)])); + $this->application->add(new MappingDescribeCommand()); $this->command = $this->application->find('orm:mapping:describe'); - $this->tester = new CommandTester($command); + $this->tester = new CommandTester($this->command); } public function testShowSpecificFuzzySingle() { - $this->tester->execute(array( - 'command' => $this->command->getName(), - 'entityName' => 'AttractionInfo', - )); + $this->tester->execute( + [ + 'command' => $this->command->getName(), + 'entityName' => 'AttractionInfo', + ] + ); $display = $this->tester->getDisplay(); - $this->assertContains('Doctrine\Tests\Models\Cache\AttractionInfo', $display); - $this->assertContains('Root entity name', $display); + + self::assertContains(AttractionInfo::class, $display); + self::assertContains('Root entity name', $display); } /** @@ -66,10 +65,12 @@ public function testShowSpecificFuzzySingle() */ public function testShowSpecificFuzzyAmbiguous() { - $this->tester->execute(array( - 'command' => $this->command->getName(), - 'entityName' => 'Attraction', - )); + $this->tester->execute( + [ + 'command' => $this->command->getName(), + 'entityName' => 'Attraction', + ] + ); } /** @@ -78,10 +79,12 @@ public function testShowSpecificFuzzyAmbiguous() */ public function testShowSpecificNotFound() { - $this->tester->execute(array( - 'command' => $this->command->getName(), - 'entityName' => 'AttractionFooBar' - )); + $this->tester->execute( + [ + 'command' => $this->command->getName(), + 'entityName' => 'AttractionFooBar', + ] + ); } } diff --git a/tests/Doctrine/Tests/ORM/Tools/Console/Command/RunDqlCommandTest.php b/tests/Doctrine/Tests/ORM/Tools/Console/Command/RunDqlCommandTest.php index 8a78e497035..552c678739c 100644 --- a/tests/Doctrine/Tests/ORM/Tools/Console/Command/RunDqlCommandTest.php +++ b/tests/Doctrine/Tests/ORM/Tools/Console/Command/RunDqlCommandTest.php @@ -38,13 +38,10 @@ protected function setUp() parent::setUp(); - $this->application = new Application(); - $this->command = new RunDqlCommand(); - - $this->application->setHelperSet(new HelperSet(array( - 'em' => new EntityManagerHelper($this->_em) - ))); + $this->command = new RunDqlCommand(); + $this->application = new Application(); + $this->application->setHelperSet(new HelperSet(['em' => new EntityManagerHelper($this->_em)])); $this->application->add($this->command); $this->tester = new CommandTester($this->command); @@ -52,7 +49,7 @@ protected function setUp() public function testCommandName() { - $this->assertSame($this->command, $this->application->get('orm:run-dql')); + self::assertSame($this->command, $this->application->get('orm:run-dql')); } public function testWillRunQuery() @@ -60,15 +57,17 @@ public function testWillRunQuery() $this->_em->persist(new DateTimeModel()); $this->_em->flush(); - $this->assertSame( + self::assertSame( 0, - $this->tester->execute(array( - 'command' => $this->command->getName(), - 'dql' => 'SELECT e FROM ' . DateTimeModel::CLASSNAME . ' e', - )) + $this->tester->execute( + [ + 'command' => $this->command->getName(), + 'dql' => 'SELECT e FROM ' . DateTimeModel::class . ' e', + ] + ) ); - $this->assertContains(DateTimeModel::CLASSNAME, $this->tester->getDisplay()); + self::assertContains(DateTimeModel::class, $this->tester->getDisplay()); } public function testWillShowQuery() @@ -76,15 +75,17 @@ public function testWillShowQuery() $this->_em->persist(new DateTimeModel()); $this->_em->flush(); - $this->assertSame( + self::assertSame( 0, - $this->tester->execute(array( - 'command' => $this->command->getName(), - 'dql' => 'SELECT e FROM ' . DateTimeModel::CLASSNAME . ' e', - '--show-sql' => 'true' - )) + $this->tester->execute( + [ + 'command' => $this->command->getName(), + 'dql' => 'SELECT e FROM ' . DateTimeModel::class . ' e', + '--show-sql' => 'true', + ] + ) ); - $this->assertStringMatchesFormat('%Astring%sSELECT %a', $this->tester->getDisplay()); + self::assertStringMatchesFormat('SELECT %a', trim($this->tester->getDisplay())); } } diff --git a/tests/Doctrine/Tests/ORM/Tools/Console/ConsoleRunnerTest.php b/tests/Doctrine/Tests/ORM/Tools/Console/ConsoleRunnerTest.php index 9d19665344d..a53ba514dd9 100644 --- a/tests/Doctrine/Tests/ORM/Tools/Console/ConsoleRunnerTest.php +++ b/tests/Doctrine/Tests/ORM/Tools/Console/ConsoleRunnerTest.php @@ -5,6 +5,7 @@ use Doctrine\ORM\Tools\Console\ConsoleRunner; use Doctrine\ORM\Version; use Doctrine\Tests\DoctrineTestCase; +use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Helper\HelperSet; /** @@ -12,15 +13,50 @@ * * @covers \Doctrine\ORM\Tools\Console\ConsoleRunner */ -class ConsoleRunnerTest extends DoctrineTestCase +final class ConsoleRunnerTest extends DoctrineTestCase { - public function testCreateApplication() + public function testCreateApplicationShouldReturnAnApplicationWithTheCorrectCommands() : void { $helperSet = new HelperSet(); $app = ConsoleRunner::createApplication($helperSet); - $this->assertInstanceOf('Symfony\Component\Console\Application', $app); - $this->assertSame($helperSet, $app->getHelperSet()); - $this->assertEquals(Version::VERSION, $app->getVersion()); + self::assertSame($helperSet, $app->getHelperSet()); + self::assertEquals(Version::VERSION, $app->getVersion()); + + self::assertTrue($app->has('dbal:import')); + self::assertTrue($app->has('dbal:reserved-words')); + self::assertTrue($app->has('dbal:run-sql')); + self::assertTrue($app->has('orm:clear-cache:region:collection')); + self::assertTrue($app->has('orm:clear-cache:region:entity')); + self::assertTrue($app->has('orm:clear-cache:region:query')); + self::assertTrue($app->has('orm:clear-cache:metadata')); + self::assertTrue($app->has('orm:clear-cache:query')); + self::assertTrue($app->has('orm:clear-cache:result')); + self::assertTrue($app->has('orm:convert-d1-schema')); + self::assertTrue($app->has('orm:convert-mapping')); + self::assertTrue($app->has('orm:convert:d1-schema')); + self::assertTrue($app->has('orm:convert:mapping')); + self::assertTrue($app->has('orm:ensure-production-settings')); + self::assertTrue($app->has('orm:generate-entities')); + self::assertTrue($app->has('orm:generate-proxies')); + self::assertTrue($app->has('orm:generate-repositories')); + self::assertTrue($app->has('orm:generate:entities')); + self::assertTrue($app->has('orm:generate:proxies')); + self::assertTrue($app->has('orm:generate:repositories')); + self::assertTrue($app->has('orm:info')); + self::assertTrue($app->has('orm:mapping:describe')); + self::assertTrue($app->has('orm:run-dql')); + self::assertTrue($app->has('orm:schema-tool:create')); + self::assertTrue($app->has('orm:schema-tool:drop')); + self::assertTrue($app->has('orm:schema-tool:update')); + self::assertTrue($app->has('orm:validate-schema')); + } + + public function testCreateApplicationShouldAppendGivenCommands() : void + { + $command = 'my:lovely-command'; + $app = ConsoleRunner::createApplication(new HelperSet(), [new Command($command)]); + + self::assertTrue($app->has($command)); } } diff --git a/tests/Doctrine/Tests/ORM/Tools/Console/MetadataFilterTest.php b/tests/Doctrine/Tests/ORM/Tools/Console/MetadataFilterTest.php new file mode 100644 index 00000000000..24f3b54a3a8 --- /dev/null +++ b/tests/Doctrine/Tests/ORM/Tools/Console/MetadataFilterTest.php @@ -0,0 +1,184 @@ +createAnnotationDriver(); + $em = $this->_getTestEntityManager(); + + $em->getConfiguration()->setMetadataDriverImpl($driver); + + $this->cmf = new DisconnectedClassMetadataFactory(); + $this->cmf->setEntityManager($em); + } + + public function testFilterWithEmptyArray() : void + { + $originalMetadatas = [ + $metadataAaa = $this->cmf->getMetadataFor(MetadataFilterTestEntityAaa::class), + $metadataBbb = $this->cmf->getMetadataFor(MetadataFilterTestEntityBbb::class), + ]; + + $metadatas = $originalMetadatas; + $metadatas = MetadataFilter::filter($metadatas, []); + + $this->assertContains($metadataAaa, $metadatas); + $this->assertContains($metadataBbb, $metadatas); + $this->assertCount(count($originalMetadatas), $metadatas); + } + + public function testFilterWithString() : void + { + $originalMetadatas = [ + $metadataAaa = $this->cmf->getMetadataFor(MetadataFilterTestEntityAaa::class), + $metadataBbb = $this->cmf->getMetadataFor(MetadataFilterTestEntityBbb::class), + $metadataCcc = $this->cmf->getMetadataFor(MetadataFilterTestEntityCcc::class), + ]; + + $metadatas = $originalMetadatas; + $metadatas = MetadataFilter::filter($metadatas, 'MetadataFilterTestEntityAaa'); + + $this->assertContains($metadataAaa, $metadatas); + $this->assertNotContains($metadataBbb, $metadatas); + $this->assertNotContains($metadataCcc, $metadatas); + $this->assertCount(1, $metadatas); + + $metadatas = $originalMetadatas; + $metadatas = MetadataFilter::filter($metadatas, 'MetadataFilterTestEntityBbb'); + + $this->assertNotContains($metadataAaa, $metadatas); + $this->assertContains($metadataBbb, $metadatas); + $this->assertNotContains($metadataCcc, $metadatas); + $this->assertCount(1, $metadatas); + + $metadatas = $originalMetadatas; + $metadatas = MetadataFilter::filter($metadatas, 'MetadataFilterTestEntityCcc'); + + $this->assertNotContains($metadataAaa, $metadatas); + $this->assertNotContains($metadataBbb, $metadatas); + $this->assertContains($metadataCcc, $metadatas); + $this->assertCount(1, $metadatas); + } + + public function testFilterWithString2() : void + { + $originalMetadatas = [ + $metadataFoo = $this->cmf->getMetadataFor(MetadataFilterTestEntityFoo::class), + $metadataFooBar = $this->cmf->getMetadataFor(MetadataFilterTestEntityFooBar::class), + $metadataBar = $this->cmf->getMetadataFor(MetadataFilterTestEntityBar::class), + ]; + + $metadatas = $originalMetadatas; + $metadatas = MetadataFilter::filter($metadatas, 'MetadataFilterTestEntityFoo'); + + $this->assertContains($metadataFoo, $metadatas); + $this->assertContains($metadataFooBar, $metadatas); + $this->assertNotContains($metadataBar, $metadatas); + $this->assertCount(2, $metadatas); + } + + public function testFilterWithArray() : void + { + $originalMetadatas = [ + $metadataAaa = $this->cmf->getMetadataFor(MetadataFilterTestEntityAaa::class), + $metadataBbb = $this->cmf->getMetadataFor(MetadataFilterTestEntityBbb::class), + $metadataCcc = $this->cmf->getMetadataFor(MetadataFilterTestEntityCcc::class), + ]; + + $metadatas = $originalMetadatas; + $metadatas = MetadataFilter::filter($metadatas, [ + 'MetadataFilterTestEntityAaa', + 'MetadataFilterTestEntityCcc', + ]); + + $this->assertContains($metadataAaa, $metadatas); + $this->assertNotContains($metadataBbb, $metadatas); + $this->assertContains($metadataCcc, $metadatas); + $this->assertCount(2, $metadatas); + } + + public function testFilterWithRegex() : void + { + $originalMetadatas = [ + $metadataFoo = $this->cmf->getMetadataFor(MetadataFilterTestEntityFoo::class), + $metadataFooBar = $this->cmf->getMetadataFor(MetadataFilterTestEntityFooBar::class), + $metadataBar = $this->cmf->getMetadataFor(MetadataFilterTestEntityBar::class), + ]; + + $metadatas = $originalMetadatas; + $metadatas = MetadataFilter::filter($metadatas, 'Foo$'); + + $this->assertContains($metadataFoo, $metadatas); + $this->assertNotContains($metadataFooBar, $metadatas); + $this->assertNotContains($metadataBar, $metadatas); + $this->assertCount(1, $metadatas); + + $metadatas = $originalMetadatas; + $metadatas = MetadataFilter::filter($metadatas, 'Bar$'); + + $this->assertNotContains($metadataFoo, $metadatas); + $this->assertContains($metadataFooBar, $metadatas); + $this->assertContains($metadataBar, $metadatas); + $this->assertCount(2, $metadatas); + } +} + +/** @Entity */ +class MetadataFilterTestEntityAaa +{ + /** @Id @Column */ + protected $id; +} + +/** @Entity */ +class MetadataFilterTestEntityBbb +{ + /** @Id @Column */ + protected $id; +} + +/** @Entity */ +class MetadataFilterTestEntityCcc +{ + /** @Id @Column */ + protected $id; +} + +/** @Entity */ +class MetadataFilterTestEntityFoo +{ + /** @Id @Column */ + protected $id; +} + +/** @Entity */ +class MetadataFilterTestEntityBar +{ + /** @Id @Column */ + protected $id; +} + +/** @Entity */ +class MetadataFilterTestEntityFooBar +{ + /** @Id @Column */ + protected $id; +} diff --git a/tests/Doctrine/Tests/ORM/Tools/ConvertDoctrine1SchemaTest.php b/tests/Doctrine/Tests/ORM/Tools/ConvertDoctrine1SchemaTest.php index b0a07270da9..291228687fb 100644 --- a/tests/Doctrine/Tests/ORM/Tools/ConvertDoctrine1SchemaTest.php +++ b/tests/Doctrine/Tests/ORM/Tools/ConvertDoctrine1SchemaTest.php @@ -1,23 +1,4 @@ . - */ namespace Doctrine\Tests\ORM\Tools; @@ -32,6 +13,7 @@ use Doctrine\Common\EventManager; use Doctrine\ORM\Tools\DisconnectedClassMetadataFactory; use Doctrine\Tests\OrmTestCase; +use Doctrine\Tests\VerifyDeprecations; /** * Test case for converting a Doctrine 1 style schema to Doctrine 2 mapping files @@ -45,6 +27,8 @@ */ class ConvertDoctrine1SchemaTest extends OrmTestCase { + use VerifyDeprecations; + protected function _createEntityManager($metadataDriver) { $driverMock = new DriverMock(); @@ -52,7 +36,7 @@ protected function _createEntityManager($metadataDriver) $config->setProxyDir(__DIR__ . '/../../Proxies'); $config->setProxyNamespace('Doctrine\Tests\Proxies'); $eventManager = new EventManager(); - $conn = new ConnectionMock(array(), $driverMock, $config, $eventManager); + $conn = new ConnectionMock([], $driverMock, $config, $eventManager); $config->setMetadataDriverImpl($metadataDriver); return EntityManagerMock::create($conn, $config, $eventManager); @@ -96,6 +80,7 @@ public function testTest() $this->assertEquals('User', $profileClass->associationMappings['User']['targetEntity']); $this->assertEquals('username', $userClass->table['uniqueConstraints']['username']['columns'][0]); + $this->assertHasDeprecationMessages(); } public function tearDown() diff --git a/tests/Doctrine/Tests/ORM/Tools/EntityGeneratorTest.php b/tests/Doctrine/Tests/ORM/Tools/EntityGeneratorTest.php index 0cbae94d7a3..25518691538 100644 --- a/tests/Doctrine/Tests/ORM/Tools/EntityGeneratorTest.php +++ b/tests/Doctrine/Tests/ORM/Tools/EntityGeneratorTest.php @@ -12,9 +12,11 @@ use Doctrine\Tests\Models\DDC2372\DDC2372Admin; use Doctrine\Tests\Models\DDC2372\DDC2372User; use Doctrine\Tests\OrmTestCase; +use Doctrine\Tests\VerifyDeprecations; class EntityGeneratorTest extends OrmTestCase { + use VerifyDeprecations; /** * @var EntityGenerator @@ -49,37 +51,47 @@ public function tearDown() rmdir($this->_tmpDir . '/' . $this->_namespace); } + /** @after */ + public function ensureTestGeneratedDeprecationMessages() : void + { + $this->assertHasDeprecationMessages(); + } + /** * @param ClassMetadataInfo[] $embeddedClasses * * @return ClassMetadataInfo */ - public function generateBookEntityFixture(array $embeddedClasses = array()) + public function generateBookEntityFixture(array $embeddedClasses = []) { $metadata = new ClassMetadataInfo($this->_namespace . '\EntityGeneratorBook'); $metadata->namespace = $this->_namespace; $metadata->customRepositoryClassName = $this->_namespace . '\EntityGeneratorBookRepository'; $metadata->table['name'] = 'book'; - $metadata->table['uniqueConstraints']['name_uniq'] = array('columns' => array('name')); - $metadata->table['indexes']['status_idx'] = array('columns' => array('status')); - $metadata->mapField(array('fieldName' => 'name', 'type' => 'string')); - $metadata->mapField(array('fieldName' => 'status', 'type' => 'string', 'options' => array('default' => 'published'))); - $metadata->mapField(array('fieldName' => 'id', 'type' => 'integer', 'id' => true)); - $metadata->mapOneToOne(array('fieldName' => 'author', 'targetEntity' => 'Doctrine\Tests\ORM\Tools\EntityGeneratorAuthor', 'mappedBy' => 'book')); - $joinColumns = array( - array('name' => 'author_id', 'referencedColumnName' => 'id') + $metadata->table['uniqueConstraints']['name_uniq'] = ['columns' => ['name']]; + $metadata->table['indexes']['status_idx'] = ['columns' => ['status']]; + $metadata->mapField(['fieldName' => 'name', 'type' => 'string']); + $metadata->mapField(['fieldName' => 'status', 'type' => 'string', 'options' => ['default' => 'published']]); + $metadata->mapField(['fieldName' => 'id', 'type' => 'integer', 'id' => true]); + $metadata->mapOneToOne( + ['fieldName' => 'author', 'targetEntity' => EntityGeneratorAuthor::class, 'mappedBy' => 'book'] ); - $metadata->mapManyToMany(array( + $joinColumns = [ + ['name' => 'author_id', 'referencedColumnName' => 'id'] + ]; + $metadata->mapManyToMany( + [ 'fieldName' => 'comments', - 'targetEntity' => 'Doctrine\Tests\ORM\Tools\EntityGeneratorComment', + 'targetEntity' => EntityGeneratorComment::class, 'fetch' => ClassMetadataInfo::FETCH_EXTRA_LAZY, - 'joinTable' => array( + 'joinTable' => [ 'name' => 'book_comment', - 'joinColumns' => array(array('name' => 'book_id', 'referencedColumnName' => 'id')), - 'inverseJoinColumns' => array(array('name' => 'comment_id', 'referencedColumnName' => 'id')), - ), - )); + 'joinColumns' => [['name' => 'book_id', 'referencedColumnName' => 'id']], + 'inverseJoinColumns' => [['name' => 'comment_id', 'referencedColumnName' => 'id']], + ], + ] + ); $metadata->addLifecycleCallback('loading', 'postLoad'); $metadata->addLifecycleCallback('willBeRemoved', 'preRemove'); $metadata->setIdGeneratorType(ClassMetadataInfo::GENERATOR_TYPE_AUTO); @@ -100,12 +112,12 @@ private function generateEntityTypeFixture(array $field) $metadata->namespace = $this->_namespace; $metadata->table['name'] = 'entity_type'; - $metadata->mapField(array('fieldName' => 'id', 'type' => 'integer', 'id' => true)); + $metadata->mapField(['fieldName' => 'id', 'type' => 'integer', 'id' => true]); $metadata->setIdGeneratorType(ClassMetadataInfo::GENERATOR_TYPE_AUTO); $name = $field['fieldName']; $type = $field['dbType']; - $metadata->mapField(array('fieldName' => $name, 'type' => $type)); + $metadata->mapField(['fieldName' => $name, 'type' => $type]); $this->_generator->writeEntityClass($metadata, $this->_tmpDir); @@ -115,19 +127,19 @@ private function generateEntityTypeFixture(array $field) /** * @return ClassMetadataInfo */ - private function generateIsbnEmbeddableFixture(array $embeddedClasses = array()) + private function generateIsbnEmbeddableFixture(array $embeddedClasses = [], $columnPrefix = null) { $metadata = new ClassMetadataInfo($this->_namespace . '\EntityGeneratorIsbn'); $metadata->namespace = $this->_namespace; $metadata->isEmbeddedClass = true; - $metadata->mapField(array('fieldName' => 'prefix', 'type' => 'integer')); - $metadata->mapField(array('fieldName' => 'groupNumber', 'type' => 'integer')); - $metadata->mapField(array('fieldName' => 'publisherNumber', 'type' => 'integer')); - $metadata->mapField(array('fieldName' => 'titleNumber', 'type' => 'integer')); - $metadata->mapField(array('fieldName' => 'checkDigit', 'type' => 'integer')); + $metadata->mapField(['fieldName' => 'prefix', 'type' => 'integer']); + $metadata->mapField(['fieldName' => 'groupNumber', 'type' => 'integer']); + $metadata->mapField(['fieldName' => 'publisherNumber', 'type' => 'integer']); + $metadata->mapField(['fieldName' => 'titleNumber', 'type' => 'integer']); + $metadata->mapField(['fieldName' => 'checkDigit', 'type' => 'integer']); foreach ($embeddedClasses as $fieldName => $embeddedClass) { - $this->mapEmbedded($fieldName, $metadata, $embeddedClass); + $this->mapEmbedded($fieldName, $metadata, $embeddedClass, $columnPrefix); } $this->_generator->writeEntityClass($metadata, $this->_tmpDir); @@ -143,10 +155,10 @@ private function generateTestEmbeddableFixture() $metadata = new ClassMetadataInfo($this->_namespace . '\EntityGeneratorTestEmbeddable'); $metadata->namespace = $this->_namespace; $metadata->isEmbeddedClass = true; - $metadata->mapField(array('fieldName' => 'field1', 'type' => 'integer')); - $metadata->mapField(array('fieldName' => 'field2', 'type' => 'integer', 'nullable' => true)); - $metadata->mapField(array('fieldName' => 'field3', 'type' => 'datetime')); - $metadata->mapField(array('fieldName' => 'field4', 'type' => 'datetime', 'nullable' => true)); + $metadata->mapField(['fieldName' => 'field1', 'type' => 'integer']); + $metadata->mapField(['fieldName' => 'field2', 'type' => 'integer', 'nullable' => true]); + $metadata->mapField(['fieldName' => 'field3', 'type' => 'datetime']); + $metadata->mapField(['fieldName' => 'field4', 'type' => 'datetime', 'nullable' => true]); $this->_generator->writeEntityClass($metadata, $this->_tmpDir); @@ -166,7 +178,7 @@ private function mapEmbedded( $columnPrefix = false ) { $classMetadata->mapEmbedded( - array('fieldName' => $fieldName, 'class' => $embeddableMetadata->name, 'columnPrefix' => $columnPrefix) + ['fieldName' => $fieldName, 'class' => $embeddableMetadata->name, 'columnPrefix' => $columnPrefix] ); } @@ -181,7 +193,8 @@ private function mapNestedEmbedded( ClassMetadataInfo $embeddableMetadata ) { foreach ($embeddableMetadata->embeddedClasses as $property => $embeddableClass) { - $classMetadata->mapEmbedded(array( + $classMetadata->mapEmbedded( + [ 'fieldName' => $fieldName . '.' . $property, 'class' => $embeddableClass['class'], 'columnPrefix' => $embeddableClass['columnPrefix'], @@ -189,7 +202,8 @@ private function mapNestedEmbedded( ? $fieldName . '.' . $embeddableClass['declaredField'] : $fieldName, 'originalField' => $embeddableClass['originalField'] ?: $property, - )); + ] + ); } } @@ -218,11 +232,44 @@ public function newInstance($metadata) return new $metadata->name; } + /** + * @group GH-6314 + */ + public function testEmbeddedEntityWithNamedColumnPrefix() + { + $columnPrefix = 'GH6314Prefix_'; + $testMetadata = $this->generateTestEmbeddableFixture(); + $isbnMetadata = $this->generateIsbnEmbeddableFixture(['testEmbedded' => $testMetadata], $columnPrefix); + $isbnEntity = $this->newInstance($isbnMetadata); + $refClass = new \ReflectionClass($isbnEntity); + self::assertTrue($refClass->hasProperty('testEmbedded')); + + $docComment = $refClass->getProperty('testEmbedded')->getDocComment(); + $needle = sprintf('@Embedded(class="%s", columnPrefix="%s")', $testMetadata->name, $columnPrefix); + self::assertContains($needle, $docComment); + } + + /** + * @group GH-6314 + */ + public function testEmbeddedEntityWithoutColumnPrefix() + { + $testMetadata = $this->generateTestEmbeddableFixture(); + $isbnMetadata = $this->generateIsbnEmbeddableFixture(['testEmbedded' => $testMetadata], false); + $isbnEntity = $this->newInstance($isbnMetadata); + $refClass = new \ReflectionClass($isbnEntity); + self::assertTrue($refClass->hasProperty('testEmbedded')); + + $docComment = $refClass->getProperty('testEmbedded')->getDocComment(); + $needle = sprintf('@Embedded(class="%s", columnPrefix=false)', $testMetadata->name); + self::assertContains($needle, $docComment); + } + public function testGeneratedEntityClass() { $testMetadata = $this->generateTestEmbeddableFixture(); - $isbnMetadata = $this->generateIsbnEmbeddableFixture(array('test' => $testMetadata)); - $metadata = $this->generateBookEntityFixture(array('isbn' => $isbnMetadata)); + $isbnMetadata = $this->generateIsbnEmbeddableFixture(['test' => $testMetadata]); + $metadata = $this->generateBookEntityFixture(['isbn' => $isbnMetadata]); $book = $this->newInstance($metadata); $this->assertTrue(class_exists($metadata->name), "Class does not exist."); @@ -264,10 +311,10 @@ public function testGeneratedEntityClass() $comment = new EntityGeneratorComment(); $this->assertInstanceOf($metadata->name, $book->addComment($comment)); - $this->assertInstanceOf('Doctrine\Common\Collections\ArrayCollection', $book->getComments()); - $this->assertEquals(new ArrayCollection(array($comment)), $book->getComments()); + $this->assertInstanceOf(ArrayCollection::class, $book->getComments()); + $this->assertEquals(new ArrayCollection([$comment]), $book->getComments()); $this->assertInternalType('boolean', $book->removeComment($comment)); - $this->assertEquals(new ArrayCollection(array()), $book->getComments()); + $this->assertEquals(new ArrayCollection([]), $book->getComments()); $this->newInstance($isbnMetadata); $isbn = new $isbnMetadata->name(); @@ -282,9 +329,9 @@ public function testGeneratedEntityClass() public function testEntityUpdatingWorks() { - $metadata = $this->generateBookEntityFixture(array('isbn' => $this->generateIsbnEmbeddableFixture())); + $metadata = $this->generateBookEntityFixture(['isbn' => $this->generateIsbnEmbeddableFixture()]); - $metadata->mapField(array('fieldName' => 'test', 'type' => 'string')); + $metadata->mapField(['fieldName' => 'test', 'type' => 'string']); $testEmbeddableMetadata = $this->generateTestEmbeddableFixture(); $this->mapEmbedded('testEmbedded', $metadata, $testEmbeddableMetadata); @@ -326,7 +373,7 @@ public function testEntityUpdatingWorks() */ public function testDoesNotRegenerateExistingMethodsWithDifferentCase() { - $metadata = $this->generateBookEntityFixture(array('isbn' => $this->generateIsbnEmbeddableFixture())); + $metadata = $this->generateBookEntityFixture(['isbn' => $this->generateIsbnEmbeddableFixture()]); // Workaround to change existing fields case (just to simulate the use case) $metadata->fieldMappings['status']['fieldName'] = 'STATUS'; @@ -357,7 +404,7 @@ public function testDoesNotRegenerateExistingMethodsWithDifferentCase() public function testMethodDocBlockShouldStartWithBackSlash() { $embeddedMetadata = $this->generateIsbnEmbeddableFixture(); - $metadata = $this->generateBookEntityFixture(array('isbn' => $embeddedMetadata)); + $metadata = $this->generateBookEntityFixture(['isbn' => $embeddedMetadata]); $book = $this->newInstance($metadata); $this->assertPhpDocVarType('\Doctrine\Common\Collections\Collection', new \ReflectionProperty($book, 'comments')); @@ -368,8 +415,8 @@ public function testMethodDocBlockShouldStartWithBackSlash() $this->assertPhpDocReturnType('boolean', new \ReflectionMethod($book, 'removeComment')); $this->assertPhpDocVarType('\Doctrine\Tests\ORM\Tools\EntityGeneratorAuthor', new \ReflectionProperty($book, 'author')); - $this->assertPhpDocReturnType('\Doctrine\Tests\ORM\Tools\EntityGeneratorAuthor', new \ReflectionMethod($book, 'getAuthor')); - $this->assertPhpDocParamType('\Doctrine\Tests\ORM\Tools\EntityGeneratorAuthor', new \ReflectionMethod($book, 'setAuthor')); + $this->assertPhpDocReturnType('\Doctrine\Tests\ORM\Tools\EntityGeneratorAuthor|null', new \ReflectionMethod($book, 'getAuthor')); + $this->assertPhpDocParamType('\Doctrine\Tests\ORM\Tools\EntityGeneratorAuthor|null', new \ReflectionMethod($book, 'setAuthor')); $expectedClassName = '\\' . $embeddedMetadata->name; $this->assertPhpDocVarType($expectedClassName, new \ReflectionProperty($book, 'isbn')); @@ -404,7 +451,7 @@ public function testLifecycleCallbacks() public function testLoadMetadata() { $embeddedMetadata = $this->generateIsbnEmbeddableFixture(); - $metadata = $this->generateBookEntityFixture(array('isbn' => $embeddedMetadata)); + $metadata = $this->generateBookEntityFixture(['isbn' => $embeddedMetadata]); $book = $this->newInstance($metadata); @@ -443,10 +490,10 @@ public function testLoadPrefixedMetadata() { $this->_generator->setAnnotationPrefix('ORM\\'); $embeddedMetadata = $this->generateIsbnEmbeddableFixture(); - $metadata = $this->generateBookEntityFixture(array('isbn' => $embeddedMetadata)); + $metadata = $this->generateBookEntityFixture(['isbn' => $embeddedMetadata]); $reader = new AnnotationReader(); - $driver = new AnnotationDriver($reader, array()); + $driver = new AnnotationDriver($reader, []); $book = $this->newInstance($metadata); @@ -489,7 +536,7 @@ public function testMappedSuperclassAnnotationGeneration() $this->_generator->writeEntityClass($metadata, $this->_tmpDir); $this->newInstance($metadata); // force instantiation (causes autoloading to kick in) - $driver = new AnnotationDriver(new AnnotationReader(), array()); + $driver = new AnnotationDriver(new AnnotationReader(), []); $cm = new ClassMetadataInfo($metadata->name); $cm->initializeReflection(new RuntimeReflectionService); @@ -521,13 +568,15 @@ public function testGenerateEntityWithSequenceGenerator() { $metadata = new ClassMetadataInfo($this->_namespace . '\DDC1784Entity'); $metadata->namespace = $this->_namespace; - $metadata->mapField(array('fieldName' => 'id', 'type' => 'integer', 'id' => true)); + $metadata->mapField(['fieldName' => 'id', 'type' => 'integer', 'id' => true]); $metadata->setIdGeneratorType(ClassMetadataInfo::GENERATOR_TYPE_SEQUENCE); - $metadata->setSequenceGeneratorDefinition(array( + $metadata->setSequenceGeneratorDefinition( + [ 'sequenceName' => 'DDC1784_ID_SEQ', 'allocationSize' => 1, 'initialValue' => 2 - )); + ] + ); $this->_generator->writeEntityClass($metadata, $this->_tmpDir); $filename = $this->_tmpDir . DIRECTORY_SEPARATOR @@ -553,23 +602,25 @@ public function testGenerateEntityWithMultipleInverseJoinColumns() { $metadata = new ClassMetadataInfo($this->_namespace . '\DDC2079Entity'); $metadata->namespace = $this->_namespace; - $metadata->mapField(array('fieldName' => 'id', 'type' => 'integer', 'id' => true)); + $metadata->mapField(['fieldName' => 'id', 'type' => 'integer', 'id' => true]); $metadata->setIdGeneratorType(ClassMetadataInfo::GENERATOR_TYPE_SEQUENCE); - $metadata->mapManyToMany(array( + $metadata->mapManyToMany( + [ 'fieldName' => 'centroCustos', 'targetEntity' => 'DDC2079CentroCusto', - 'joinTable' => array( + 'joinTable' => [ 'name' => 'unidade_centro_custo', - 'joinColumns' => array( - array('name' => 'idorcamento', 'referencedColumnName' => 'idorcamento'), - array('name' => 'idunidade', 'referencedColumnName' => 'idunidade') - ), - 'inverseJoinColumns' => array( - array('name' => 'idcentrocusto', 'referencedColumnName' => 'idcentrocusto'), - array('name' => 'idpais', 'referencedColumnName' => 'idpais'), - ), - ), - )); + 'joinColumns' => [ + ['name' => 'idorcamento', 'referencedColumnName' => 'idorcamento'], + ['name' => 'idunidade', 'referencedColumnName' => 'idunidade'] + ], + 'inverseJoinColumns' => [ + ['name' => 'idcentrocusto', 'referencedColumnName' => 'idcentrocusto'], + ['name' => 'idpais', 'referencedColumnName' => 'idpais'], + ], + ], + ] + ); $this->_generator->writeEntityClass($metadata, $this->_tmpDir); $filename = $this->_tmpDir . DIRECTORY_SEPARATOR @@ -838,7 +889,7 @@ public function testMethodsAndPropertiesAreNotDuplicatedInChildClasses() public function testGeneratedMutableEmbeddablesClass() { $embeddedMetadata = $this->generateTestEmbeddableFixture(); - $metadata = $this->generateIsbnEmbeddableFixture(array('test' => $embeddedMetadata)); + $metadata = $this->generateIsbnEmbeddableFixture(['test' => $embeddedMetadata]); $isbn = $this->newInstance($metadata); @@ -878,7 +929,7 @@ public function testGeneratedImmutableEmbeddablesClass() { $this->_generator->setEmbeddablesImmutable(true); $embeddedMetadata = $this->generateTestEmbeddableFixture(); - $metadata = $this->generateIsbnEmbeddableFixture(array('test' => $embeddedMetadata)); + $metadata = $this->generateIsbnEmbeddableFixture(['test' => $embeddedMetadata]); $this->loadEntityClass($embeddedMetadata); $this->loadEntityClass($metadata); @@ -968,86 +1019,114 @@ public function testRegenerateEntityClass() */ public function getEntityTypeAliasDataProvider() { - return array( - array(array( + return [ + [ + [ 'fieldName' => 'datetimetz', 'phpType' => '\\DateTime', 'dbType' => 'datetimetz', 'value' => new \DateTime - )), - array(array( + ] + ], + [ + [ 'fieldName' => 'datetime', 'phpType' => '\\DateTime', 'dbType' => 'datetime', 'value' => new \DateTime - )), - array(array( + ] + ], + [ + [ 'fieldName' => 'date', 'phpType' => '\\DateTime', 'dbType' => 'date', 'value' => new \DateTime - )), - array(array( + ] + ], + [ + [ 'fieldName' => 'time', 'phpType' => '\DateTime', 'dbType' => 'time', 'value' => new \DateTime - )), - array(array( + ] + ], + [ + [ 'fieldName' => 'object', 'phpType' => '\stdClass', 'dbType' => 'object', 'value' => new \stdClass() - )), - array(array( + ] + ], + [ + [ 'fieldName' => 'bigint', 'phpType' => 'int', 'dbType' => 'bigint', 'value' => 11 - )), - array(array( + ] + ], + [ + [ 'fieldName' => 'smallint', 'phpType' => 'int', 'dbType' => 'smallint', 'value' => 22 - )), - array(array( + ] + ], + [ + [ 'fieldName' => 'text', 'phpType' => 'string', 'dbType' => 'text', 'value' => 'text' - )), - array(array( + ] + ], + [ + [ 'fieldName' => 'blob', 'phpType' => 'string', 'dbType' => 'blob', 'value' => 'blob' - )), - array(array( + ] + ], + [ + [ + 'fieldName' => 'guid', + 'phpType' => 'string', + 'dbType' => 'guid', + 'value' => '00000000-0000-0000-0000-000000000001' + ] + ], + [ + [ 'fieldName' => 'decimal', 'phpType' => 'string', 'dbType' => 'decimal', 'value' => '12.34' - ), - )); + ], + ] + ]; } public function getParseTokensInEntityFileData() { - return array( - array( + return [ + [ 'assertEquals(1, preg_match('/@var\s+([^\s]+)/',$property->getDocComment(), $matches)); + $docComment = $property->getDocComment(); + $regex = '/@var\s+([\S]+)$/m'; + + $this->assertRegExp($regex, $docComment); + $this->assertEquals(1, preg_match($regex, $docComment, $matches)); $this->assertEquals($type, $matches[1]); } /** * @param string $type - * @param \ReflectionProperty $method + * @param \ReflectionMethod $method */ private function assertPhpDocReturnType($type, \ReflectionMethod $method) { - $this->assertEquals(1, preg_match('/@return\s+([^\s]+)/', $method->getDocComment(), $matches)); + $docComment = $method->getDocComment(); + $regex = '/@return\s+([\S]+)(\s+.*)$/m'; + + $this->assertRegExp($regex, $docComment); + $this->assertEquals(1, preg_match($regex, $docComment, $matches)); $this->assertEquals($type, $matches[1]); } @@ -1103,6 +1190,103 @@ private function assertPhpDocParamType($type, \ReflectionMethod $method) $this->assertEquals(1, preg_match('/@param\s+([^\s]+)/', $method->getDocComment(), $matches)); $this->assertEquals($type, $matches[1]); } + + /** + * @group 6703 + * + * @dataProvider columnOptionsProvider + */ + public function testOptionsAreGeneratedProperly(string $expectedAnnotation, array $fieldConfiguration) : void + { + $metadata = new ClassMetadataInfo($this->_namespace . '\GH6703Options'); + $metadata->namespace = $this->_namespace; + $metadata->mapField(['fieldName' => 'id', 'type' => 'integer', 'id' => true]); + $metadata->mapField(['fieldName' => 'test'] + $fieldConfiguration); + $metadata->setIdGeneratorType(ClassMetadataInfo::GENERATOR_TYPE_SEQUENCE); + $this->_generator->writeEntityClass($metadata, $this->_tmpDir); + + $filename = $this->_tmpDir . DIRECTORY_SEPARATOR . $this->_namespace . DIRECTORY_SEPARATOR . 'GH6703Options.php'; + + self::assertFileExists($filename); + require_once $filename; + + $property = new \ReflectionProperty($metadata->name, 'test'); + $docComment = $property->getDocComment(); + + self::assertContains($expectedAnnotation, $docComment); + } + + public function columnOptionsProvider() : array + { + return [ + 'string-default' => [ + '@Column(name="test", type="string", length=10, options={"default"="testing"})', + ['type' => 'string', 'length' => 10, 'options' => ['default' => 'testing']], + ], + 'string-fixed' => [ + '@Column(name="test", type="string", length=10, options={"fixed"=true})', + ['type' => 'string', 'length' => 10, 'options' => ['fixed' => true]], + ], + 'string-comment' => [ + '@Column(name="test", type="string", length=10, options={"comment"="testing"})', + ['type' => 'string', 'length' => 10, 'options' => ['comment' => 'testing']], + ], + 'string-comment-quote' => [ + '@Column(name="test", type="string", length=10, options={"comment"="testing ""quotes"""})', + ['type' => 'string', 'length' => 10, 'options' => ['comment' => 'testing "quotes"']], + ], + 'string-collation' => [ + '@Column(name="test", type="string", length=10, options={"collation"="utf8mb4_general_ci"})', + ['type' => 'string', 'length' => 10, 'options' => ['collation' => 'utf8mb4_general_ci']], + ], + 'string-check' => [ + '@Column(name="test", type="string", length=10, options={"check"="CHECK (test IN (""test""))"})', + ['type' => 'string', 'length' => 10, 'options' => ['check' => 'CHECK (test IN (""test""))']], + ], + 'string-all' => [ + '@Column(name="test", type="string", length=10, options={"default"="testing","fixed"=true,"comment"="testing","collation"="utf8mb4_general_ci","check"="CHECK (test IN (""test""))"})', + [ + 'type' => 'string', + 'length' => 10, + 'options' => [ + 'default' => 'testing', + 'fixed' => true, + 'comment' => 'testing', + 'collation' => 'utf8mb4_general_ci', + 'check' => 'CHECK (test IN (""test""))' + ] + ], + ], + 'int-default' => [ + '@Column(name="test", type="integer", options={"default"="10"})', + ['type' => 'integer', 'options' => ['default' => 10]], + ], + 'int-unsigned' => [ + '@Column(name="test", type="integer", options={"unsigned"=true})', + ['type' => 'integer', 'options' => ['unsigned' => true]], + ], + 'int-comment' => [ + '@Column(name="test", type="integer", options={"comment"="testing"})', + ['type' => 'integer', 'options' => ['comment' => 'testing']], + ], + 'int-check' => [ + '@Column(name="test", type="integer", options={"check"="CHECK (test > 5)"})', + ['type' => 'integer', 'options' => ['check' => 'CHECK (test > 5)']], + ], + 'int-all' => [ + '@Column(name="test", type="integer", options={"default"="10","unsigned"=true,"comment"="testing","check"="CHECK (test > 5)"})', + [ + 'type' => 'integer', + 'options' => [ + 'default' => 10, + 'unsigned' => true, + 'comment' => 'testing', + 'check' => 'CHECK (test > 5)', + ] + ], + ], + ]; + } } class EntityGeneratorAuthor {} diff --git a/tests/Doctrine/Tests/ORM/Tools/EntityRepositoryGeneratorTest.php b/tests/Doctrine/Tests/ORM/Tools/EntityRepositoryGeneratorTest.php index bcb16a3d6e2..d020cc6e07c 100644 --- a/tests/Doctrine/Tests/ORM/Tools/EntityRepositoryGeneratorTest.php +++ b/tests/Doctrine/Tests/ORM/Tools/EntityRepositoryGeneratorTest.php @@ -2,13 +2,20 @@ namespace Doctrine\Tests\ORM\Tools; +use Doctrine\ORM\EntityRepository; +use Doctrine\ORM\Mapping\ClassMetadataFactory; use Doctrine\ORM\Tools\EntityGenerator; use Doctrine\ORM\Tools\EntityRepositoryGenerator; -use Doctrine\ORM\Mapping\ClassMetadataFactory; +use Doctrine\Tests\Models\DDC3231\DDC3231EntityRepository; +use Doctrine\Tests\Models\DDC3231\DDC3231User1; +use Doctrine\Tests\Models\DDC3231\DDC3231User2; use Doctrine\Tests\OrmTestCase; +use Doctrine\Tests\VerifyDeprecations; class EntityRepositoryGeneratorTest extends OrmTestCase { + use VerifyDeprecations; + /** * @var EntityGenerator */ @@ -38,7 +45,7 @@ public function setUp() $this->_generator->setRegenerateEntityIfExists(false); $this->_generator->setUpdateEntityIfExists(true); $this->_generator->setFieldVisibility(EntityGenerator::FIELD_VISIBLE_PROTECTED); - + $this->_repositoryGenerator = new EntityRepositoryGenerator(); } @@ -47,7 +54,7 @@ public function setUp() */ public function tearDown() { - $dirs = array(); + $dirs = []; $ri = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($this->_tmpDir)); foreach ($ri AS $file) { @@ -66,6 +73,12 @@ public function tearDown() } } + /** @after */ + public function ensureTestGeneratedDeprecationMessages() : void + { + $this->assertHasDeprecationMessages(); + } + /** * @group DDC-3231 */ @@ -74,11 +87,8 @@ public function testGeneratedEntityRepositoryClass() $em = $this->_getTestEntityManager(); $ns = $this->_namespace; - - require_once __DIR__ . '/../../Models/DDC3231/DDC3231User1.php'; - $className = $ns . '\DDC3231User1Tmp'; - $this->writeEntityClass('Doctrine\Tests\Models\DDC3231\DDC3231User1', $className); + $this->writeEntityClass(DDC3231User1::class, $className); $rpath = $this->writeRepositoryClass($className); @@ -90,13 +100,12 @@ public function testGeneratedEntityRepositoryClass() $this->assertTrue($repo->inNamespace()); $this->assertSame($className . 'Repository', $repo->getName()); - $this->assertSame('Doctrine\ORM\EntityRepository', $repo->getParentClass()->getName()); - + $this->assertSame(EntityRepository::class, $repo->getParentClass()->getName()); require_once __DIR__ . '/../../Models/DDC3231/DDC3231User1NoNamespace.php'; $className2 = 'DDC3231User1NoNamespaceTmp'; - $this->writeEntityClass('DDC3231User1NoNamespace', $className2); + $this->writeEntityClass(\DDC3231User1NoNamespace::class, $className2); $rpath2 = $this->writeRepositoryClass($className2); @@ -108,7 +117,7 @@ public function testGeneratedEntityRepositoryClass() $this->assertFalse($repo2->inNamespace()); $this->assertSame($className2 . 'Repository', $repo2->getName()); - $this->assertSame('Doctrine\ORM\EntityRepository', $repo2->getParentClass()->getName()); + $this->assertSame(EntityRepository::class, $repo2->getParentClass()->getName()); } /** @@ -119,32 +128,29 @@ public function testGeneratedEntityRepositoryClassCustomDefaultRepository() $em = $this->_getTestEntityManager(); $ns = $this->_namespace; - - require_once __DIR__ . '/../../Models/DDC3231/DDC3231User2.php'; - $className = $ns . '\DDC3231User2Tmp'; - $this->writeEntityClass('Doctrine\Tests\Models\DDC3231\DDC3231User2', $className); + $this->writeEntityClass(DDC3231User2::class, $className); - $rpath = $this->writeRepositoryClass($className, 'Doctrine\Tests\Models\DDC3231\DDC3231EntityRepository'); + $rpath = $this->writeRepositoryClass($className, DDC3231EntityRepository::class); $this->assertNotNull($rpath); $this->assertFileExists($rpath); require $rpath; - + $repo = new \ReflectionClass($em->getRepository($className)); $this->assertTrue($repo->inNamespace()); $this->assertSame($className . 'Repository', $repo->getName()); - $this->assertSame('Doctrine\Tests\Models\DDC3231\DDC3231EntityRepository', $repo->getParentClass()->getName()); + $this->assertSame(DDC3231EntityRepository::class, $repo->getParentClass()->getName()); + - require_once __DIR__ . '/../../Models/DDC3231/DDC3231User2NoNamespace.php'; $className2 = 'DDC3231User2NoNamespaceTmp'; $this->writeEntityClass('DDC3231User2NoNamespace', $className2); - $rpath2 = $this->writeRepositoryClass($className2, 'Doctrine\Tests\Models\DDC3231\DDC3231EntityRepository'); + $rpath2 = $this->writeRepositoryClass($className2, DDC3231EntityRepository::class); $this->assertNotNull($rpath2); $this->assertFileExists($rpath2); @@ -155,13 +161,12 @@ public function testGeneratedEntityRepositoryClassCustomDefaultRepository() $this->assertFalse($repo2->inNamespace()); $this->assertSame($className2 . 'Repository', $repo2->getName()); - $this->assertSame('Doctrine\Tests\Models\DDC3231\DDC3231EntityRepository', $repo2->getParentClass()->getName()); + $this->assertSame(DDC3231EntityRepository::class, $repo2->getParentClass()->getName()); } /** * @param string $className * @param string $newClassName - * @return string */ private function writeEntityClass($className, $newClassName) { @@ -188,10 +193,10 @@ private function writeEntityClass($className, $newClassName) private function writeRepositoryClass($className, $defaultRepository = null) { $this->_repositoryGenerator->setDefaultRepositoryName($defaultRepository); - + $this->_repositoryGenerator->writeEntityRepositoryClass($className . 'Repository', $this->_tmpDir); return $this->_tmpDir . DIRECTORY_SEPARATOR . str_replace('\\', DIRECTORY_SEPARATOR, $className) . 'Repository.php'; } - + } diff --git a/tests/Doctrine/Tests/ORM/Tools/Export/AbstractClassMetadataExporterTest.php b/tests/Doctrine/Tests/ORM/Tools/Export/AbstractClassMetadataExporterTest.php index d712730ff00..84ddd011f6a 100644 --- a/tests/Doctrine/Tests/ORM/Tools/Export/AbstractClassMetadataExporterTest.php +++ b/tests/Doctrine/Tests/ORM/Tools/Export/AbstractClassMetadataExporterTest.php @@ -1,38 +1,25 @@ . - */ namespace Doctrine\Tests\ORM\Tools\Export; +use Doctrine\Common\EventManager; +use Doctrine\Common\Persistence\Mapping\Driver\PHPDriver; use Doctrine\ORM\Configuration; -use Doctrine\ORM\Tools\Export\ClassMetadataExporter; +use Doctrine\ORM\Events; +use Doctrine\ORM\Mapping\ClassMetadata; +use Doctrine\ORM\Mapping\ClassMetadataFactory; use Doctrine\ORM\Mapping\ClassMetadataInfo; +use Doctrine\ORM\Mapping\Driver\AnnotationDriver; +use Doctrine\ORM\Mapping\Driver\XmlDriver; +use Doctrine\ORM\Mapping\Driver\YamlDriver; +use Doctrine\ORM\Tools\DisconnectedClassMetadataFactory; use Doctrine\ORM\Tools\EntityGenerator; -use Doctrine\Tests\Mocks\MetadataDriverMock; -use Doctrine\Tests\Mocks\EntityManagerMock; +use Doctrine\ORM\Tools\Export\ClassMetadataExporter; use Doctrine\Tests\Mocks\ConnectionMock; use Doctrine\Tests\Mocks\DriverMock; -use Doctrine\Common\EventManager; -use Doctrine\ORM\Tools\DisconnectedClassMetadataFactory; -use Doctrine\ORM\Mapping\ClassMetadataFactory; +use Doctrine\Tests\Mocks\EntityManagerMock; use Doctrine\Tests\OrmTestCase; +use Doctrine\Tests\VerifyDeprecations; use Symfony\Component\Yaml\Parser; /** @@ -47,6 +34,8 @@ */ abstract class AbstractClassMetadataExporterTest extends OrmTestCase { + use VerifyDeprecations; + protected $_extension; abstract protected function _getType(); @@ -58,7 +47,7 @@ protected function _createEntityManager($metadataDriver) $config->setProxyDir(__DIR__ . '/../../Proxies'); $config->setProxyNamespace('Doctrine\Tests\Proxies'); $eventManager = new EventManager(); - $conn = new ConnectionMock(array(), $driverMock, $config, $eventManager); + $conn = new ConnectionMock([], $driverMock, $config, $eventManager); $config->setMetadataDriverImpl($metadataDriver); return EntityManagerMock::create($conn, $config, $eventManager); @@ -66,18 +55,18 @@ protected function _createEntityManager($metadataDriver) protected function _createMetadataDriver($type, $path) { - $mappingDriver = array( - 'php' => 'Doctrine\Common\Persistence\Mapping\Driver\PHPDriver', - 'annotation' => 'Doctrine\ORM\Mapping\Driver\AnnotationDriver', - 'xml' => 'Doctrine\ORM\Mapping\Driver\XmlDriver', - 'yaml' => 'Doctrine\ORM\Mapping\Driver\YamlDriver', - ); + $mappingDriver = [ + 'php' => PHPDriver::class, + 'annotation' => AnnotationDriver::class, + 'xml' => XmlDriver::class, + 'yaml' => YamlDriver::class, + ]; $this->assertArrayHasKey($type, $mappingDriver, "There is no metadata driver for the type '" . $type . "'."); $class = $mappingDriver[$type]; $driver = ($type === 'annotation') - ? $this->createAnnotationDriver(array($path)) + ? $this->createAnnotationDriver([$path]) : new $class($path); return $driver; @@ -104,9 +93,9 @@ public function testExportDirectoryAndFilesAreCreated() $cmf = $this->_createClassMetadataFactory($em, $type); $metadata = $cmf->getAllMetadata(); - $metadata[0]->name = 'Doctrine\Tests\ORM\Tools\Export\ExportedUser'; + $metadata[0]->name = ExportedUser::class; - $this->assertEquals('Doctrine\Tests\ORM\Tools\Export\ExportedUser', $metadata[0]->name); + $this->assertEquals(ExportedUser::class, $metadata[0]->name); $type = $this->_getType(); $cme = new ClassMetadataExporter(); @@ -125,10 +114,12 @@ public function testExportDirectoryAndFilesAreCreated() $exporter->export(); if ($type == 'annotation') { - $this->assertTrue(file_exists(__DIR__ . '/export/' . $type . '/'.str_replace('\\', '/', 'Doctrine\Tests\ORM\Tools\Export\ExportedUser').$this->_extension)); + $this->assertTrue(file_exists(__DIR__ . '/export/' . $type . '/'.str_replace('\\', '/', ExportedUser::class).$this->_extension)); } else { $this->assertTrue(file_exists(__DIR__ . '/export/' . $type . '/Doctrine.Tests.ORM.Tools.Export.ExportedUser'.$this->_extension)); } + + $this->assertHasDeprecationMessages(); } /** @@ -147,7 +138,7 @@ public function testExportedMetadataCanBeReadBackIn() $class = current($metadata); - $this->assertEquals('Doctrine\Tests\ORM\Tools\Export\ExportedUser', $class->name); + $this->assertEquals(ExportedUser::class, $class->name); return $class; } @@ -159,7 +150,8 @@ public function testExportedMetadataCanBeReadBackIn() public function testTableIsExported($class) { $this->assertEquals('cms_users', $class->table['name']); - $this->assertEquals(array('engine' => 'MyISAM', 'foo' => array('bar' => 'baz')), + $this->assertEquals( + ['engine' => 'MyISAM', 'foo' => ['bar' => 'baz']], $class->table['options']); return $class; @@ -183,7 +175,7 @@ public function testTypeIsExported($class) public function testIdentifierIsExported($class) { $this->assertEquals(ClassMetadataInfo::GENERATOR_TYPE_IDENTITY, $class->generatorType, "Generator Type wrong"); - $this->assertEquals(array('id'), $class->identifier); + $this->assertEquals(['id'], $class->identifier); $this->assertTrue(isset($class->fieldMappings['id']['id']) && $class->fieldMappings['id']['id'] === true); return $class; @@ -243,7 +235,7 @@ public function testFieldsAreProperlySerialized() public function testOneToOneAssociationsAreExported($class) { $this->assertTrue(isset($class->associationMappings['address'])); - $this->assertEquals('Doctrine\Tests\ORM\Tools\Export\Address', $class->associationMappings['address']['targetEntity']); + $this->assertEquals(Address::class, $class->associationMappings['address']['targetEntity']); $this->assertEquals('address_id', $class->associationMappings['address']['joinColumns'][0]['name']); $this->assertEquals('id', $class->associationMappings['address']['joinColumns'][0]['referencedColumnName']); $this->assertEquals('CASCADE', $class->associationMappings['address']['joinColumns'][0]['onDelete']); @@ -265,7 +257,7 @@ public function testOneToOneAssociationsAreExported($class) public function testManyToOneAssociationsAreExported($class) { $this->assertTrue(isset($class->associationMappings['mainGroup'])); - $this->assertEquals('Doctrine\Tests\ORM\Tools\Export\Group', $class->associationMappings['mainGroup']['targetEntity']); + $this->assertEquals(Group::class, $class->associationMappings['mainGroup']['targetEntity']); } /** @@ -275,10 +267,9 @@ public function testManyToOneAssociationsAreExported($class) public function testOneToManyAssociationsAreExported($class) { $this->assertTrue(isset($class->associationMappings['phonenumbers'])); - //$this->assertInstanceOf('Doctrine\ORM\Mapping\OneToManyMapping', $class->associationMappings['phonenumbers']); - $this->assertEquals('Doctrine\Tests\ORM\Tools\Export\Phonenumber', $class->associationMappings['phonenumbers']['targetEntity']); + $this->assertEquals(Phonenumber::class, $class->associationMappings['phonenumbers']['targetEntity']); $this->assertEquals('user', $class->associationMappings['phonenumbers']['mappedBy']); - $this->assertEquals(array('number' => 'ASC'), $class->associationMappings['phonenumbers']['orderBy']); + $this->assertEquals(['number' => 'ASC'], $class->associationMappings['phonenumbers']['orderBy']); $this->assertTrue($class->associationMappings['phonenumbers']['isCascadeRemove']); $this->assertTrue($class->associationMappings['phonenumbers']['isCascadePersist']); @@ -298,8 +289,7 @@ public function testOneToManyAssociationsAreExported($class) public function testManyToManyAssociationsAreExported($class) { $this->assertTrue(isset($class->associationMappings['groups'])); - //$this->assertInstanceOf('Doctrine\ORM\Mapping\ManyToManyMapping', $class->associationMappings['groups']); - $this->assertEquals('Doctrine\Tests\ORM\Tools\Export\Group', $class->associationMappings['groups']['targetEntity']); + $this->assertEquals(Group::class, $class->associationMappings['groups']['targetEntity']); $this->assertEquals('cms_users_groups', $class->associationMappings['groups']['joinTable']['name']); $this->assertEquals('user_id', $class->associationMappings['groups']['joinTable']['joinColumns'][0]['name']); @@ -361,7 +351,7 @@ public function testInversedByIsExported($class) { $this->assertEquals('user', $class->associationMappings['address']['inversedBy']); } - /** + /** * @depends testExportDirectoryAndFilesAreCreated */ public function testCascadeAllCollapsed() @@ -380,14 +370,34 @@ public function testCascadeAllCollapsed() $yaml = new Parser(); $value = $yaml->parse(file_get_contents(__DIR__ . '/export/'.$type.'/Doctrine.Tests.ORM.Tools.Export.ExportedUser.dcm.yml')); - $this->assertTrue(isset($value['Doctrine\Tests\ORM\Tools\Export\ExportedUser']['oneToMany']['interests']['cascade'])); - $this->assertEquals(1, count($value['Doctrine\Tests\ORM\Tools\Export\ExportedUser']['oneToMany']['interests']['cascade'])); - $this->assertEquals('all', $value['Doctrine\Tests\ORM\Tools\Export\ExportedUser']['oneToMany']['interests']['cascade'][0]); + $this->assertTrue(isset($value[ExportedUser::class]['oneToMany']['interests']['cascade'])); + $this->assertEquals(1, count($value[ExportedUser::class]['oneToMany']['interests']['cascade'])); + $this->assertEquals('all', $value[ExportedUser::class]['oneToMany']['interests']['cascade'][0]); } else { $this->markTestSkipped('Test not available for '.$type.' driver'); } } + /** + * @depends testExportedMetadataCanBeReadBackIn + * + * @param ClassMetadata $class + */ + public function testEntityListenersAreExported($class) + { + $this->assertNotEmpty($class->entityListeners); + $this->assertCount(2, $class->entityListeners[Events::prePersist]); + $this->assertCount(2, $class->entityListeners[Events::postPersist]); + $this->assertEquals(UserListener::class, $class->entityListeners[Events::prePersist][0]['class']); + $this->assertEquals('customPrePersist', $class->entityListeners[Events::prePersist][0]['method']); + $this->assertEquals(GroupListener::class, $class->entityListeners[Events::prePersist][1]['class']); + $this->assertEquals('prePersist', $class->entityListeners[Events::prePersist][1]['method']); + $this->assertEquals(UserListener::class, $class->entityListeners[Events::postPersist][0]['class']); + $this->assertEquals('customPostPersist', $class->entityListeners[Events::postPersist][0]['method']); + $this->assertEquals(AddressListener::class, $class->entityListeners[Events::postPersist][1]['class']); + $this->assertEquals('customPostPersist', $class->entityListeners[Events::postPersist][1]['method']); + } + public function __destruct() { # $this->_deleteDirectory(__DIR__ . '/export/'.$this->_getType()); @@ -423,3 +433,28 @@ class Group { } +class UserListener +{ + /** + * @\Doctrine\ORM\Mapping\PrePersist + */ + public function customPrePersist(): void {} + /** + * @\Doctrine\ORM\Mapping\PostPersist + */ + public function customPostPersist(): void {} +} +class GroupListener +{ + /** + * @\Doctrine\ORM\Mapping\PrePersist + */ + public function prePersist(): void {} +} +class AddressListener +{ + /** + * @\Doctrine\ORM\Mapping\PostPersist + */ + public function customPostPersist(): void {} +} diff --git a/tests/Doctrine/Tests/ORM/Tools/Export/AnnotationClassMetadataExporterTest.php b/tests/Doctrine/Tests/ORM/Tools/Export/AnnotationClassMetadataExporterTest.php index 9fa20941cb4..a432ec45187 100644 --- a/tests/Doctrine/Tests/ORM/Tools/Export/AnnotationClassMetadataExporterTest.php +++ b/tests/Doctrine/Tests/ORM/Tools/Export/AnnotationClassMetadataExporterTest.php @@ -1,23 +1,4 @@ . - */ namespace Doctrine\Tests\ORM\Tools\Export; diff --git a/tests/Doctrine/Tests/ORM/Tools/Export/PhpClassMetadataExporterTest.php b/tests/Doctrine/Tests/ORM/Tools/Export/PhpClassMetadataExporterTest.php index 2ad37588f16..6ca3cf94830 100644 --- a/tests/Doctrine/Tests/ORM/Tools/Export/PhpClassMetadataExporterTest.php +++ b/tests/Doctrine/Tests/ORM/Tools/Export/PhpClassMetadataExporterTest.php @@ -1,23 +1,4 @@ . - */ namespace Doctrine\Tests\ORM\Tools\Export; diff --git a/tests/Doctrine/Tests/ORM/Tools/Export/XmlClassMetadataExporterTest.php b/tests/Doctrine/Tests/ORM/Tools/Export/XmlClassMetadataExporterTest.php index 5bec99cfe91..4ee7afa8f80 100644 --- a/tests/Doctrine/Tests/ORM/Tools/Export/XmlClassMetadataExporterTest.php +++ b/tests/Doctrine/Tests/ORM/Tools/Export/XmlClassMetadataExporterTest.php @@ -1,23 +1,4 @@ . - */ namespace Doctrine\Tests\ORM\Tools\Export; use Doctrine\ORM\Mapping\ClassMetadataInfo; @@ -48,26 +29,30 @@ public function testSequenceGenerator() { $exporter = new XmlExporter(); $metadata = new ClassMetadata('entityTest'); - $metadata->mapField(array( + $metadata->mapField( + [ "fieldName" => 'id', "type" => 'integer', "columnName" => 'id', "id" => true, - )); + ] + ); $metadata->setIdGeneratorType(ClassMetadataInfo::GENERATOR_TYPE_SEQUENCE); - $metadata->setSequenceGeneratorDefinition(array( + $metadata->setSequenceGeneratorDefinition( + [ 'sequenceName' => 'seq_entity_test_id', 'allocationSize' => 5, 'initialValue' => 1 - )); + ] + ); $expectedFileContent = <<<'XML' @@ -90,19 +75,21 @@ public function testFieldOptionsExport() { $exporter = new XmlExporter(); $metadata = new ClassMetadata('entityTest'); - $metadata->mapField(array( + $metadata->mapField( + [ "fieldName" => 'myField', "type" => 'string', "columnName" => 'my_field', - "options" => array( + "options" => [ "default" => "default_string", "comment" => "The comment for the field", - ), - )); + ], + ] + ); $expectedFileContent = <<<'XML' - + diff --git a/tests/Doctrine/Tests/ORM/Tools/Export/YamlClassMetadataExporterTest.php b/tests/Doctrine/Tests/ORM/Tools/Export/YamlClassMetadataExporterTest.php index 85c6e1c5ea1..a47c396d2ce 100644 --- a/tests/Doctrine/Tests/ORM/Tools/Export/YamlClassMetadataExporterTest.php +++ b/tests/Doctrine/Tests/ORM/Tools/Export/YamlClassMetadataExporterTest.php @@ -1,23 +1,4 @@ . - */ namespace Doctrine\Tests\ORM\Tools\Export; diff --git a/tests/Doctrine/Tests/ORM/Tools/Export/annotation/Doctrine.Tests.ORM.Tools.Export.User.php b/tests/Doctrine/Tests/ORM/Tools/Export/annotation/Doctrine.Tests.ORM.Tools.Export.User.php index 34470805953..c6a066258f4 100644 --- a/tests/Doctrine/Tests/ORM/Tools/Export/annotation/Doctrine.Tests.ORM.Tools.Export.User.php +++ b/tests/Doctrine/Tests/ORM/Tools/Export/annotation/Doctrine.Tests.ORM.Tools.Export.User.php @@ -5,6 +5,11 @@ /** * @Entity * @HasLifecycleCallbacks + * @EntityListeners({ + * Doctrine\Tests\ORM\Tools\Export\UserListener::class, + * Doctrine\Tests\ORM\Tools\Export\GroupListener::class, + * Doctrine\Tests\ORM\Tools\Export\AddressListener::class + * }) * @Table(name="cms_users",options={"engine"="MyISAM","foo"={"bar"="baz"}}) */ class User @@ -57,21 +62,21 @@ class User /** * @PrePersist */ - public function doStuffOnPrePersist() + public function doStuffOnPrePersist(): void { } /** * @PrePersist */ - public function doOtherStuffOnPrePersistToo() + public function doOtherStuffOnPrePersistToo(): void { } /** * @PostPersist */ - public function doStuffOnPostPersist() + public function doStuffOnPostPersist(): void { } } diff --git a/tests/Doctrine/Tests/ORM/Tools/Export/php/Doctrine.Tests.ORM.Tools.Export.User.php b/tests/Doctrine/Tests/ORM/Tools/Export/php/Doctrine.Tests.ORM.Tools.Export.User.php index 4a379f82e0a..5e54c0b2e7e 100644 --- a/tests/Doctrine/Tests/ORM/Tools/Export/php/Doctrine.Tests.ORM.Tools.Export.User.php +++ b/tests/Doctrine/Tests/ORM/Tools/Export/php/Doctrine.Tests.ORM.Tools.Export.User.php @@ -1,130 +1,159 @@ setInheritanceType(ClassMetadataInfo::INHERITANCE_TYPE_NONE); -$metadata->setPrimaryTable(array( +$metadata->setPrimaryTable( + [ 'name' => 'cms_users', - 'options' => array('engine' => 'MyISAM', 'foo' => array('bar' => 'baz')), - )); + 'options' => ['engine' => 'MyISAM', 'foo' => ['bar' => 'baz']], + ] +); $metadata->setChangeTrackingPolicy(ClassMetadataInfo::CHANGETRACKING_DEFERRED_IMPLICIT); -$metadata->addLifecycleCallback('doStuffOnPrePersist', 'prePersist'); -$metadata->addLifecycleCallback('doOtherStuffOnPrePersistToo', 'prePersist'); -$metadata->addLifecycleCallback('doStuffOnPostPersist', 'postPersist'); -$metadata->mapField(array( +$metadata->addLifecycleCallback('doStuffOnPrePersist', Events::prePersist); +$metadata->addLifecycleCallback('doOtherStuffOnPrePersistToo', Events::prePersist); +$metadata->addLifecycleCallback('doStuffOnPostPersist', Events::postPersist); +$metadata->mapField( + [ 'id' => true, 'fieldName' => 'id', 'type' => 'integer', 'columnName' => 'id', - )); -$metadata->mapField(array( + ] +); +$metadata->mapField( + [ 'fieldName' => 'name', 'type' => 'string', 'length' => 50, 'unique' => true, 'nullable' => true, 'columnName' => 'name', - )); -$metadata->mapField(array( + ] +); +$metadata->mapField( + [ 'fieldName' => 'email', 'type' => 'string', 'columnName' => 'user_email', 'columnDefinition' => 'CHAR(32) NOT NULL', - )); -$metadata->mapField(array( + ] +); +$metadata->mapField( + [ 'fieldName' => 'age', 'type' => 'integer', - 'options' => array("unsigned"=>true), - )); + 'options' => ["unsigned"=>true], + ] +); $metadata->setIdGeneratorType(ClassMetadataInfo::GENERATOR_TYPE_AUTO); -$metadata->mapManyToOne(array( +$metadata->mapManyToOne( + [ 'fieldName' => 'mainGroup', - 'targetEntity' => 'Doctrine\\Tests\\ORM\Tools\\Export\\Group', -)); -$metadata->mapOneToOne(array( + 'targetEntity' => Export\Group::class, + ] +); +$metadata->mapOneToOne( + [ 'fieldName' => 'address', - 'targetEntity' => 'Doctrine\\Tests\\ORM\\Tools\\Export\\Address', + 'targetEntity' => Export\Address::class, 'inversedBy' => 'user', 'cascade' => - array( + [ 0 => 'persist', - ), + ], 'mappedBy' => NULL, 'joinColumns' => - array( + [ 0 => - array( + [ 'name' => 'address_id', 'referencedColumnName' => 'id', 'onDelete' => 'CASCADE', - ), - ), + ], + ], 'orphanRemoval' => true, 'fetch' => ClassMetadataInfo::FETCH_EAGER, - )); -$metadata->mapOneToOne(array( + ] +); +$metadata->mapOneToOne( + [ 'fieldName' => 'cart', - 'targetEntity' => 'Doctrine\\Tests\\ORM\\Tools\\Export\\Cart', + 'targetEntity' => Export\Cart::class, 'mappedBy' => 'user', 'cascade' => - array( + [ 0 => 'persist', - ), + ], 'inversedBy' => NULL, 'orphanRemoval' => false, 'fetch' => ClassMetadataInfo::FETCH_EAGER, -)); -$metadata->mapOneToMany(array( + ] +); +$metadata->mapOneToMany( + [ 'fieldName' => 'phonenumbers', - 'targetEntity' => 'Doctrine\\Tests\\ORM\\Tools\\Export\\Phonenumber', + 'targetEntity' => Export\Phonenumber::class, 'cascade' => - array( + [ 1 => 'persist', 2 => 'merge', - ), + ], 'mappedBy' => 'user', 'orphanRemoval' => true, 'fetch' => ClassMetadataInfo::FETCH_LAZY, 'orderBy' => - array( + [ 'number' => 'ASC', - ), - )); -$metadata->mapManyToMany(array( + ], + ] +); +$metadata->mapManyToMany( + [ 'fieldName' => 'groups', - 'targetEntity' => 'Doctrine\\Tests\\ORM\\Tools\\Export\\Group', + 'targetEntity' => Export\Group::class, 'fetch' => ClassMetadataInfo::FETCH_EXTRA_LAZY, 'cascade' => - array( + [ 0 => 'remove', 1 => 'persist', 2 => 'refresh', 3 => 'merge', 4 => 'detach', - ), + ], 'mappedBy' => NULL, 'joinTable' => - array( + [ 'name' => 'cms_users_groups', 'joinColumns' => - array( + [ 0 => - array( + [ 'name' => 'user_id', 'referencedColumnName' => 'id', 'unique' => false, 'nullable' => false, - ), - ), + ], + ], 'inverseJoinColumns' => - array( + [ 0 => - array( + [ 'name' => 'group_id', 'referencedColumnName' => 'id', 'columnDefinition' => 'INT NULL', - ), - ), - ), + ], + ], + ], 'orderBy' => NULL, - )); + ] +); +$metadata->addEntityListener(Events::prePersist, UserListener::class, 'customPrePersist'); +$metadata->addEntityListener(Events::postPersist, UserListener::class, 'customPostPersist'); +$metadata->addEntityListener(Events::prePersist, GroupListener::class, 'prePersist'); +$metadata->addEntityListener(Events::postPersist, AddressListener::class, 'customPostPersist'); diff --git a/tests/Doctrine/Tests/ORM/Tools/Export/xml/Doctrine.Tests.ORM.Tools.Export.User.dcm.xml b/tests/Doctrine/Tests/ORM/Tools/Export/xml/Doctrine.Tests.ORM.Tools.Export.User.dcm.xml index 8d0c5d217e3..4092c8574c5 100644 --- a/tests/Doctrine/Tests/ORM/Tools/Export/xml/Doctrine.Tests.ORM.Tools.Export.User.dcm.xml +++ b/tests/Doctrine/Tests/ORM/Tools/Export/xml/Doctrine.Tests.ORM.Tools.Export.User.dcm.xml @@ -3,7 +3,7 @@ + https://www.doctrine-project.org/schemas/orm/doctrine-mapping.xsd"> @@ -77,6 +77,18 @@ + + + + + + + + + + + + diff --git a/tests/Doctrine/Tests/ORM/Tools/Export/yaml/Doctrine.Tests.ORM.Tools.Export.User.dcm.yml b/tests/Doctrine/Tests/ORM/Tools/Export/yaml/Doctrine.Tests.ORM.Tools.Export.User.dcm.yml index d52e94601da..df2dae1c558 100644 --- a/tests/Doctrine/Tests/ORM/Tools/Export/yaml/Doctrine.Tests.ORM.Tools.Export.User.dcm.yml +++ b/tests/Doctrine/Tests/ORM/Tools/Export/yaml/Doctrine.Tests.ORM.Tools.Export.User.dcm.yml @@ -75,3 +75,11 @@ Doctrine\Tests\ORM\Tools\Export\User: lifecycleCallbacks: prePersist: [ doStuffOnPrePersist, doOtherStuffOnPrePersistToo ] postPersist: [ doStuffOnPostPersist ] + entityListeners: + Doctrine\Tests\ORM\Tools\Export\UserListener: + prePersist: [customPrePersist] + postPersist: [customPostPersist] + Doctrine\Tests\ORM\Tools\Export\GroupListener: + prePersist: [prePersist] + Doctrine\Tests\ORM\Tools\Export\AddressListener: + postPersist: [customPostPersist] diff --git a/tests/Doctrine/Tests/ORM/Tools/Pagination/CountOutputWalkerTest.php b/tests/Doctrine/Tests/ORM/Tools/Pagination/CountOutputWalkerTest.php index 691b8ef2014..df7f73f7881 100644 --- a/tests/Doctrine/Tests/ORM/Tools/Pagination/CountOutputWalkerTest.php +++ b/tests/Doctrine/Tests/ORM/Tools/Pagination/CountOutputWalkerTest.php @@ -3,6 +3,7 @@ namespace Doctrine\Tests\ORM\Tools\Pagination; use Doctrine\ORM\Query; +use Doctrine\ORM\Tools\Pagination\CountOutputWalker; class CountOutputWalkerTest extends PaginationTestCase { @@ -10,7 +11,7 @@ public function testCountQuery() { $query = $this->entityManager->createQuery( 'SELECT p, c, a FROM Doctrine\Tests\ORM\Tools\Pagination\BlogPost p JOIN p.category c JOIN p.author a'); - $query->setHint(Query::HINT_CUSTOM_OUTPUT_WALKER, 'Doctrine\ORM\Tools\Pagination\CountOutputWalker'); + $query->setHint(Query::HINT_CUSTOM_OUTPUT_WALKER, CountOutputWalker::class); $query->setFirstResult(null)->setMaxResults(null); $this->assertEquals( @@ -22,7 +23,7 @@ public function testCountQuery_MixedResultsWithName() { $query = $this->entityManager->createQuery( 'SELECT a, sum(a.name) as foo FROM Doctrine\Tests\ORM\Tools\Pagination\Author a'); - $query->setHint(Query::HINT_CUSTOM_OUTPUT_WALKER, 'Doctrine\ORM\Tools\Pagination\CountOutputWalker'); + $query->setHint(Query::HINT_CUSTOM_OUTPUT_WALKER, CountOutputWalker::class); $query->setFirstResult(null)->setMaxResults(null); $this->assertEquals( @@ -30,15 +31,27 @@ public function testCountQuery_MixedResultsWithName() ); } - public function testCountQuery_Having() + public function testCountQuery_GroupBy(): void + { + $query = $this->entityManager->createQuery( + 'SELECT p.name FROM Doctrine\Tests\ORM\Tools\Pagination\Person p GROUP BY p.name'); + $query->setHint(Query::HINT_CUSTOM_OUTPUT_WALKER, CountOutputWalker::class); + $query->setFirstResult(null)->setMaxResults(null); + + $this->assertSame( + "SELECT COUNT(*) AS dctrn_count FROM (SELECT p0_.name AS name_0 FROM Person p0_ GROUP BY p0_.name) dctrn_table", $query->getSQL() + ); + } + + public function testCountQuery_Having(): void { $query = $this->entityManager->createQuery( 'SELECT g, u, count(u.id) AS userCount FROM Doctrine\Tests\ORM\Tools\Pagination\Group g LEFT JOIN g.users u GROUP BY g.id HAVING userCount > 0'); - $query->setHint(Query::HINT_CUSTOM_OUTPUT_WALKER, 'Doctrine\ORM\Tools\Pagination\CountOutputWalker'); + $query->setHint(Query::HINT_CUSTOM_OUTPUT_WALKER, CountOutputWalker::class); $query->setFirstResult(null)->setMaxResults(null); - $this->assertEquals( - "SELECT COUNT(*) AS dctrn_count FROM (SELECT DISTINCT id_1 FROM (SELECT count(u0_.id) AS sclr_0, g1_.id AS id_1, u0_.id AS id_2 FROM groups g1_ LEFT JOIN user_group u2_ ON g1_.id = u2_.group_id LEFT JOIN User u0_ ON u0_.id = u2_.user_id GROUP BY g1_.id HAVING sclr_0 > 0) dctrn_result) dctrn_table", $query->getSQL() + $this->assertSame( + "SELECT COUNT(*) AS dctrn_count FROM (SELECT count(u0_.id) AS sclr_0, g1_.id AS id_1, u0_.id AS id_2 FROM groups g1_ LEFT JOIN user_group u2_ ON g1_.id = u2_.group_id LEFT JOIN User u0_ ON u0_.id = u2_.user_id GROUP BY g1_.id HAVING sclr_0 > 0) dctrn_table", $query->getSQL() ); } @@ -50,7 +63,7 @@ public function testCountQueryOrderBySqlServer() $query = $this->entityManager->createQuery( 'SELECT p FROM Doctrine\Tests\ORM\Tools\Pagination\BlogPost p ORDER BY p.id'); - $query->setHint(Query::HINT_CUSTOM_OUTPUT_WALKER, 'Doctrine\ORM\Tools\Pagination\CountOutputWalker'); + $query->setHint(Query::HINT_CUSTOM_OUTPUT_WALKER, CountOutputWalker::class); $query->setFirstResult(null)->setMaxResults(null); $this->assertEquals( diff --git a/tests/Doctrine/Tests/ORM/Tools/Pagination/CountWalkerTest.php b/tests/Doctrine/Tests/ORM/Tools/Pagination/CountWalkerTest.php index a85a5f6f807..2aa398d6fbe 100644 --- a/tests/Doctrine/Tests/ORM/Tools/Pagination/CountWalkerTest.php +++ b/tests/Doctrine/Tests/ORM/Tools/Pagination/CountWalkerTest.php @@ -14,7 +14,7 @@ public function testCountQuery() { $query = $this->entityManager->createQuery( 'SELECT p, c, a FROM Doctrine\Tests\ORM\Tools\Pagination\BlogPost p JOIN p.category c JOIN p.author a'); - $query->setHint(Query::HINT_CUSTOM_TREE_WALKERS, array('Doctrine\ORM\Tools\Pagination\CountWalker')); + $query->setHint(Query::HINT_CUSTOM_TREE_WALKERS, [CountWalker::class]); $query->setHint(CountWalker::HINT_DISTINCT, true); $query->setFirstResult(null)->setMaxResults(null); @@ -27,7 +27,7 @@ public function testCountQuery_MixedResultsWithName() { $query = $this->entityManager->createQuery( 'SELECT a, sum(a.name) as foo FROM Doctrine\Tests\ORM\Tools\Pagination\Author a'); - $query->setHint(Query::HINT_CUSTOM_TREE_WALKERS, array('Doctrine\ORM\Tools\Pagination\CountWalker')); + $query->setHint(Query::HINT_CUSTOM_TREE_WALKERS, [CountWalker::class]); $query->setHint(CountWalker::HINT_DISTINCT, true); $query->setFirstResult(null)->setMaxResults(null); @@ -40,7 +40,7 @@ public function testCountQuery_KeepsGroupBy() { $query = $this->entityManager->createQuery( 'SELECT b FROM Doctrine\Tests\ORM\Tools\Pagination\BlogPost b GROUP BY b.id'); - $query->setHint(Query::HINT_CUSTOM_TREE_WALKERS, array('Doctrine\ORM\Tools\Pagination\CountWalker')); + $query->setHint(Query::HINT_CUSTOM_TREE_WALKERS, [CountWalker::class]); $query->setHint(CountWalker::HINT_DISTINCT, true); $query->setFirstResult(null)->setMaxResults(null); @@ -53,7 +53,7 @@ public function testCountQuery_RemovesOrderBy() { $query = $this->entityManager->createQuery( 'SELECT p, c, a FROM Doctrine\Tests\ORM\Tools\Pagination\BlogPost p JOIN p.category c JOIN p.author a ORDER BY a.name'); - $query->setHint(Query::HINT_CUSTOM_TREE_WALKERS, array('Doctrine\ORM\Tools\Pagination\CountWalker')); + $query->setHint(Query::HINT_CUSTOM_TREE_WALKERS, [CountWalker::class]); $query->setHint(CountWalker::HINT_DISTINCT, true); $query->setFirstResult(null)->setMaxResults(null); @@ -66,7 +66,7 @@ public function testCountQuery_RemovesLimits() { $query = $this->entityManager->createQuery( 'SELECT p, c, a FROM Doctrine\Tests\ORM\Tools\Pagination\BlogPost p JOIN p.category c JOIN p.author a'); - $query->setHint(Query::HINT_CUSTOM_TREE_WALKERS, array('Doctrine\ORM\Tools\Pagination\CountWalker')); + $query->setHint(Query::HINT_CUSTOM_TREE_WALKERS, [CountWalker::class]); $query->setHint(CountWalker::HINT_DISTINCT, true); $query->setFirstResult(null)->setMaxResults(null); @@ -80,7 +80,7 @@ public function testCountQuery_HavingException() $query = $this->entityManager->createQuery( "SELECT g, COUNT(u.id) AS userCount FROM Doctrine\Tests\Models\CMS\CmsGroup g LEFT JOIN g.users u GROUP BY g.id HAVING userCount > 0" ); - $query->setHint(Query::HINT_CUSTOM_TREE_WALKERS, array('Doctrine\ORM\Tools\Pagination\CountWalker')); + $query->setHint(Query::HINT_CUSTOM_TREE_WALKERS, [CountWalker::class]); $query->setFirstResult(null)->setMaxResults(null); $this->expectException(\RuntimeException::class); @@ -88,15 +88,15 @@ public function testCountQuery_HavingException() $query->getSQL(); } - + /** - * Arbitrary Join + * Arbitrary Join */ public function testCountQueryWithArbitraryJoin() { $query = $this->entityManager->createQuery( 'SELECT p FROM Doctrine\Tests\ORM\Tools\Pagination\BlogPost p LEFT JOIN Doctrine\Tests\ORM\Tools\Pagination\Category c WITH p.category = c'); - $query->setHint(Query::HINT_CUSTOM_TREE_WALKERS, array('Doctrine\ORM\Tools\Pagination\CountWalker')); + $query->setHint(Query::HINT_CUSTOM_TREE_WALKERS, [CountWalker::class]); $query->setHint(CountWalker::HINT_DISTINCT, true); $query->setFirstResult(null)->setMaxResults(null); diff --git a/tests/Doctrine/Tests/ORM/Tools/Pagination/LimitSubqueryOutputWalkerTest.php b/tests/Doctrine/Tests/ORM/Tools/Pagination/LimitSubqueryOutputWalkerTest.php index 78fd38e9a39..39ee1360dc9 100644 --- a/tests/Doctrine/Tests/ORM/Tools/Pagination/LimitSubqueryOutputWalkerTest.php +++ b/tests/Doctrine/Tests/ORM/Tools/Pagination/LimitSubqueryOutputWalkerTest.php @@ -6,23 +6,24 @@ use Doctrine\DBAL\Platforms\OraclePlatform; use Doctrine\DBAL\Platforms\PostgreSqlPlatform; use Doctrine\ORM\Query; +use Doctrine\ORM\Tools\Pagination\LimitSubqueryOutputWalker; -class LimitSubqueryOutputWalkerTest extends PaginationTestCase +final class LimitSubqueryOutputWalkerTest extends PaginationTestCase { - public function testLimitSubquery() + public function testLimitSubquery() : void { $query = $this->entityManager->createQuery( 'SELECT p, c, a FROM Doctrine\Tests\ORM\Tools\Pagination\MyBlogPost p JOIN p.category c JOIN p.author a'); $query->expireQueryCache(true); $limitQuery = clone $query; - $limitQuery->setHint(Query::HINT_CUSTOM_OUTPUT_WALKER, 'Doctrine\ORM\Tools\Pagination\LimitSubqueryOutputWalker'); + $limitQuery->setHint(Query::HINT_CUSTOM_OUTPUT_WALKER, LimitSubqueryOutputWalker::class); - $this->assertEquals( + self::assertSame( "SELECT DISTINCT id_0 FROM (SELECT m0_.id AS id_0, m0_.title AS title_1, c1_.id AS id_2, a2_.id AS id_3, a2_.name AS name_4, m0_.author_id AS author_id_5, m0_.category_id AS category_id_6 FROM MyBlogPost m0_ INNER JOIN Category c1_ ON m0_.category_id = c1_.id INNER JOIN Author a2_ ON m0_.author_id = a2_.id) dctrn_result", $limitQuery->getSQL() ); } - public function testLimitSubqueryWithSortPg() + public function testLimitSubqueryWithSortPg() : void { $odp = $this->entityManager->getConnection()->getDatabasePlatform(); $this->entityManager->getConnection()->setDatabasePlatform(new PostgreSqlPlatform); @@ -30,16 +31,16 @@ public function testLimitSubqueryWithSortPg() $query = $this->entityManager->createQuery( 'SELECT p, c, a FROM Doctrine\Tests\ORM\Tools\Pagination\MyBlogPost p JOIN p.category c JOIN p.author a ORDER BY p.title'); $limitQuery = clone $query; - $limitQuery->setHint(Query::HINT_CUSTOM_OUTPUT_WALKER, 'Doctrine\ORM\Tools\Pagination\LimitSubqueryOutputWalker'); + $limitQuery->setHint(Query::HINT_CUSTOM_OUTPUT_WALKER, LimitSubqueryOutputWalker::class); - $this->assertEquals( + self::assertSame( "SELECT DISTINCT id_0, MIN(sclr_5) AS dctrn_minrownum FROM (SELECT m0_.id AS id_0, m0_.title AS title_1, c1_.id AS id_2, a2_.id AS id_3, a2_.name AS name_4, ROW_NUMBER() OVER(ORDER BY m0_.title ASC) AS sclr_5, m0_.author_id AS author_id_6, m0_.category_id AS category_id_7 FROM MyBlogPost m0_ INNER JOIN Category c1_ ON m0_.category_id = c1_.id INNER JOIN Author a2_ ON m0_.author_id = a2_.id) dctrn_result GROUP BY id_0 ORDER BY dctrn_minrownum ASC", $limitQuery->getSQL() ); $this->entityManager->getConnection()->setDatabasePlatform($odp); } - public function testLimitSubqueryWithScalarSortPg() + public function testLimitSubqueryWithScalarSortPg() : void { $odp = $this->entityManager->getConnection()->getDatabasePlatform(); $this->entityManager->getConnection()->setDatabasePlatform(new PostgreSqlPlatform); @@ -48,9 +49,9 @@ public function testLimitSubqueryWithScalarSortPg() 'SELECT u, g, COUNT(g.id) AS g_quantity FROM Doctrine\Tests\ORM\Tools\Pagination\User u JOIN u.groups g ORDER BY g_quantity' ); $limitQuery = clone $query; - $limitQuery->setHint(Query::HINT_CUSTOM_OUTPUT_WALKER, 'Doctrine\ORM\Tools\Pagination\LimitSubqueryOutputWalker'); + $limitQuery->setHint(Query::HINT_CUSTOM_OUTPUT_WALKER, LimitSubqueryOutputWalker::class); - $this->assertEquals( + self::assertSame( "SELECT DISTINCT id_1, MIN(sclr_3) AS dctrn_minrownum FROM (SELECT COUNT(g0_.id) AS sclr_0, u1_.id AS id_1, g0_.id AS id_2, ROW_NUMBER() OVER(ORDER BY COUNT(g0_.id) ASC) AS sclr_3 FROM User u1_ INNER JOIN user_group u2_ ON u1_.id = u2_.user_id INNER JOIN groups g0_ ON g0_.id = u2_.group_id) dctrn_result GROUP BY id_1 ORDER BY dctrn_minrownum ASC", $limitQuery->getSQL() ); @@ -58,7 +59,7 @@ public function testLimitSubqueryWithScalarSortPg() $this->entityManager->getConnection()->setDatabasePlatform($odp); } - public function testLimitSubqueryWithMixedSortPg() + public function testLimitSubqueryWithMixedSortPg() : void { $odp = $this->entityManager->getConnection()->getDatabasePlatform(); $this->entityManager->getConnection()->setDatabasePlatform(new PostgreSqlPlatform); @@ -67,9 +68,9 @@ public function testLimitSubqueryWithMixedSortPg() 'SELECT u, g, COUNT(g.id) AS g_quantity FROM Doctrine\Tests\ORM\Tools\Pagination\User u JOIN u.groups g ORDER BY g_quantity, u.id DESC' ); $limitQuery = clone $query; - $limitQuery->setHint(Query::HINT_CUSTOM_OUTPUT_WALKER, 'Doctrine\ORM\Tools\Pagination\LimitSubqueryOutputWalker'); + $limitQuery->setHint(Query::HINT_CUSTOM_OUTPUT_WALKER, LimitSubqueryOutputWalker::class); - $this->assertEquals( + self::assertSame( "SELECT DISTINCT id_1, MIN(sclr_3) AS dctrn_minrownum FROM (SELECT COUNT(g0_.id) AS sclr_0, u1_.id AS id_1, g0_.id AS id_2, ROW_NUMBER() OVER(ORDER BY COUNT(g0_.id) ASC, u1_.id DESC) AS sclr_3 FROM User u1_ INNER JOIN user_group u2_ ON u1_.id = u2_.user_id INNER JOIN groups g0_ ON g0_.id = u2_.group_id) dctrn_result GROUP BY id_1 ORDER BY dctrn_minrownum ASC", $limitQuery->getSQL() ); @@ -77,7 +78,7 @@ public function testLimitSubqueryWithMixedSortPg() $this->entityManager->getConnection()->setDatabasePlatform($odp); } - public function testLimitSubqueryWithHiddenScalarSortPg() + public function testLimitSubqueryWithHiddenScalarSortPg() : void { $odp = $this->entityManager->getConnection()->getDatabasePlatform(); $this->entityManager->getConnection()->setDatabasePlatform(new PostgreSqlPlatform); @@ -86,9 +87,9 @@ public function testLimitSubqueryWithHiddenScalarSortPg() 'SELECT u, g, COUNT(g.id) AS hidden g_quantity FROM Doctrine\Tests\ORM\Tools\Pagination\User u JOIN u.groups g ORDER BY g_quantity, u.id DESC' ); $limitQuery = clone $query; - $limitQuery->setHint(Query::HINT_CUSTOM_OUTPUT_WALKER, 'Doctrine\ORM\Tools\Pagination\LimitSubqueryOutputWalker'); + $limitQuery->setHint(Query::HINT_CUSTOM_OUTPUT_WALKER, LimitSubqueryOutputWalker::class); - $this->assertEquals( + self::assertSame( "SELECT DISTINCT id_1, MIN(sclr_3) AS dctrn_minrownum FROM (SELECT COUNT(g0_.id) AS sclr_0, u1_.id AS id_1, g0_.id AS id_2, ROW_NUMBER() OVER(ORDER BY COUNT(g0_.id) ASC, u1_.id DESC) AS sclr_3 FROM User u1_ INNER JOIN user_group u2_ ON u1_.id = u2_.user_id INNER JOIN groups g0_ ON g0_.id = u2_.group_id) dctrn_result GROUP BY id_1 ORDER BY dctrn_minrownum ASC", $limitQuery->getSQL() ); @@ -96,7 +97,7 @@ public function testLimitSubqueryWithHiddenScalarSortPg() $this->entityManager->getConnection()->setDatabasePlatform($odp); } - public function testLimitSubqueryPg() + public function testLimitSubqueryPg() : void { $odp = $this->entityManager->getConnection()->getDatabasePlatform(); $this->entityManager->getConnection()->setDatabasePlatform(new PostgreSqlPlatform); @@ -105,8 +106,8 @@ public function testLimitSubqueryPg() $this->entityManager->getConnection()->setDatabasePlatform($odp); } - - public function testLimitSubqueryWithSortOracle() + + public function testLimitSubqueryWithSortOracle() : void { $odp = $this->entityManager->getConnection()->getDatabasePlatform(); $this->entityManager->getConnection()->setDatabasePlatform(new OraclePlatform); @@ -115,16 +116,16 @@ public function testLimitSubqueryWithSortOracle() 'SELECT p, c, a FROM Doctrine\Tests\ORM\Tools\Pagination\MyBlogPost p JOIN p.category c JOIN p.author a ORDER BY p.title'); $query->expireQueryCache(true); $limitQuery = clone $query; - $limitQuery->setHint(Query::HINT_CUSTOM_OUTPUT_WALKER, 'Doctrine\ORM\Tools\Pagination\LimitSubqueryOutputWalker'); + $limitQuery->setHint(Query::HINT_CUSTOM_OUTPUT_WALKER, LimitSubqueryOutputWalker::class); - $this->assertEquals( + self::assertSame( "SELECT DISTINCT ID_0, MIN(SCLR_5) AS dctrn_minrownum FROM (SELECT m0_.id AS ID_0, m0_.title AS TITLE_1, c1_.id AS ID_2, a2_.id AS ID_3, a2_.name AS NAME_4, ROW_NUMBER() OVER(ORDER BY m0_.title ASC) AS SCLR_5, m0_.author_id AS AUTHOR_ID_6, m0_.category_id AS CATEGORY_ID_7 FROM MyBlogPost m0_ INNER JOIN Category c1_ ON m0_.category_id = c1_.id INNER JOIN Author a2_ ON m0_.author_id = a2_.id) dctrn_result GROUP BY ID_0 ORDER BY dctrn_minrownum ASC", $limitQuery->getSQL() ); $this->entityManager->getConnection()->setDatabasePlatform($odp); } - public function testLimitSubqueryWithScalarSortOracle() + public function testLimitSubqueryWithScalarSortOracle() : void { $odp = $this->entityManager->getConnection()->getDatabasePlatform(); $this->entityManager->getConnection()->setDatabasePlatform(new OraclePlatform); @@ -134,9 +135,9 @@ public function testLimitSubqueryWithScalarSortOracle() ); $query->expireQueryCache(true); $limitQuery = clone $query; - $limitQuery->setHint(Query::HINT_CUSTOM_OUTPUT_WALKER, 'Doctrine\ORM\Tools\Pagination\LimitSubqueryOutputWalker'); + $limitQuery->setHint(Query::HINT_CUSTOM_OUTPUT_WALKER, LimitSubqueryOutputWalker::class); - $this->assertEquals( + self::assertSame( "SELECT DISTINCT ID_1, MIN(SCLR_3) AS dctrn_minrownum FROM (SELECT COUNT(g0_.id) AS SCLR_0, u1_.id AS ID_1, g0_.id AS ID_2, ROW_NUMBER() OVER(ORDER BY COUNT(g0_.id) ASC) AS SCLR_3 FROM User u1_ INNER JOIN user_group u2_ ON u1_.id = u2_.user_id INNER JOIN groups g0_ ON g0_.id = u2_.group_id) dctrn_result GROUP BY ID_1 ORDER BY dctrn_minrownum ASC", $limitQuery->getSQL() ); @@ -144,7 +145,7 @@ public function testLimitSubqueryWithScalarSortOracle() $this->entityManager->getConnection()->setDatabasePlatform($odp); } - public function testLimitSubqueryWithMixedSortOracle() + public function testLimitSubqueryWithMixedSortOracle() : void { $odp = $this->entityManager->getConnection()->getDatabasePlatform(); $this->entityManager->getConnection()->setDatabasePlatform(new OraclePlatform); @@ -154,9 +155,9 @@ public function testLimitSubqueryWithMixedSortOracle() ); $query->expireQueryCache(true); $limitQuery = clone $query; - $limitQuery->setHint(Query::HINT_CUSTOM_OUTPUT_WALKER, 'Doctrine\ORM\Tools\Pagination\LimitSubqueryOutputWalker'); + $limitQuery->setHint(Query::HINT_CUSTOM_OUTPUT_WALKER, LimitSubqueryOutputWalker::class); - $this->assertEquals( + self::assertSame( "SELECT DISTINCT ID_1, MIN(SCLR_3) AS dctrn_minrownum FROM (SELECT COUNT(g0_.id) AS SCLR_0, u1_.id AS ID_1, g0_.id AS ID_2, ROW_NUMBER() OVER(ORDER BY COUNT(g0_.id) ASC, u1_.id DESC) AS SCLR_3 FROM User u1_ INNER JOIN user_group u2_ ON u1_.id = u2_.user_id INNER JOIN groups g0_ ON g0_.id = u2_.group_id) dctrn_result GROUP BY ID_1 ORDER BY dctrn_minrownum ASC", $limitQuery->getSQL() ); @@ -164,7 +165,7 @@ public function testLimitSubqueryWithMixedSortOracle() $this->entityManager->getConnection()->setDatabasePlatform($odp); } - public function testLimitSubqueryOracle() + public function testLimitSubqueryOracle() : void { $odp = $this->entityManager->getConnection()->getDatabasePlatform(); $this->entityManager->getConnection()->setDatabasePlatform(new OraclePlatform); @@ -173,23 +174,23 @@ public function testLimitSubqueryOracle() 'SELECT p, c, a FROM Doctrine\Tests\ORM\Tools\Pagination\MyBlogPost p JOIN p.category c JOIN p.author a'); $query->expireQueryCache(true); $limitQuery = clone $query; - $limitQuery->setHint(Query::HINT_CUSTOM_OUTPUT_WALKER, 'Doctrine\ORM\Tools\Pagination\LimitSubqueryOutputWalker'); + $limitQuery->setHint(Query::HINT_CUSTOM_OUTPUT_WALKER, LimitSubqueryOutputWalker::class); - $this->assertEquals( + self::assertSame( "SELECT DISTINCT ID_0 FROM (SELECT m0_.id AS ID_0, m0_.title AS TITLE_1, c1_.id AS ID_2, a2_.id AS ID_3, a2_.name AS NAME_4, m0_.author_id AS AUTHOR_ID_5, m0_.category_id AS CATEGORY_ID_6 FROM MyBlogPost m0_ INNER JOIN Category c1_ ON m0_.category_id = c1_.id INNER JOIN Author a2_ ON m0_.author_id = a2_.id) dctrn_result", $limitQuery->getSQL() ); $this->entityManager->getConnection()->setDatabasePlatform($odp); } - public function testCountQueryMixedResultsWithName() + public function testCountQueryMixedResultsWithName() : void { $query = $this->entityManager->createQuery( 'SELECT a, sum(a.name) as foo FROM Doctrine\Tests\ORM\Tools\Pagination\Author a'); $limitQuery = clone $query; - $limitQuery->setHint(Query::HINT_CUSTOM_OUTPUT_WALKER, 'Doctrine\ORM\Tools\Pagination\LimitSubqueryOutputWalker'); + $limitQuery->setHint(Query::HINT_CUSTOM_OUTPUT_WALKER, LimitSubqueryOutputWalker::class); - $this->assertEquals( + self::assertSame( "SELECT DISTINCT id_0 FROM (SELECT a0_.id AS id_0, a0_.name AS name_1, sum(a0_.name) AS sclr_2 FROM Author a0_) dctrn_result", $limitQuery->getSQL() ); } @@ -197,74 +198,74 @@ public function testCountQueryMixedResultsWithName() /** * @group DDC-3336 */ - public function testCountQueryWithArithmeticOrderByCondition() + public function testCountQueryWithArithmeticOrderByCondition() : void { $query = $this->entityManager->createQuery( 'SELECT a FROM Doctrine\Tests\ORM\Tools\Pagination\Author a ORDER BY (1 - 1000) * 1 DESC' ); $this->entityManager->getConnection()->setDatabasePlatform(new MySqlPlatform()); - $query->setHint(Query::HINT_CUSTOM_OUTPUT_WALKER, 'Doctrine\ORM\Tools\Pagination\LimitSubqueryOutputWalker'); + $query->setHint(Query::HINT_CUSTOM_OUTPUT_WALKER, LimitSubqueryOutputWalker::class); $this->assertSame( - 'SELECT DISTINCT id_0 FROM (SELECT a0_.id AS id_0, a0_.name AS name_1 FROM Author a0_) dctrn_result ORDER BY (1 - 1000) * 1 DESC', + 'SELECT DISTINCT id_0 FROM (SELECT DISTINCT id_0, (1 - 1000) * 1 FROM (SELECT a0_.id AS id_0, a0_.name AS name_1 FROM Author a0_) dctrn_result_inner ORDER BY (1 - 1000) * 1 DESC) dctrn_result', $query->getSQL() ); } - public function testCountQueryWithComplexScalarOrderByItem() + public function testCountQueryWithComplexScalarOrderByItem() : void { $query = $this->entityManager->createQuery( 'SELECT a FROM Doctrine\Tests\ORM\Tools\Pagination\Avatar a ORDER BY a.image_height * a.image_width DESC' ); $this->entityManager->getConnection()->setDatabasePlatform(new MySqlPlatform()); - $query->setHint(Query::HINT_CUSTOM_OUTPUT_WALKER, 'Doctrine\ORM\Tools\Pagination\LimitSubqueryOutputWalker'); + $query->setHint(Query::HINT_CUSTOM_OUTPUT_WALKER, LimitSubqueryOutputWalker::class); $this->assertSame( - 'SELECT DISTINCT id_0 FROM (SELECT a0_.id AS id_0, a0_.image AS image_1, a0_.image_height AS image_height_2, a0_.image_width AS image_width_3, a0_.image_alt_desc AS image_alt_desc_4, a0_.user_id AS user_id_5 FROM Avatar a0_) dctrn_result ORDER BY image_height_2 * image_width_3 DESC', + 'SELECT DISTINCT id_0 FROM (SELECT DISTINCT id_0, image_height_2 * image_width_3 FROM (SELECT a0_.id AS id_0, a0_.image AS image_1, a0_.image_height AS image_height_2, a0_.image_width AS image_width_3, a0_.image_alt_desc AS image_alt_desc_4, a0_.user_id AS user_id_5 FROM Avatar a0_) dctrn_result_inner ORDER BY image_height_2 * image_width_3 DESC) dctrn_result', $query->getSQL() ); } - public function testCountQueryWithComplexScalarOrderByItemJoined() + public function testCountQueryWithComplexScalarOrderByItemJoined() : void { $query = $this->entityManager->createQuery( 'SELECT u FROM Doctrine\Tests\ORM\Tools\Pagination\User u JOIN u.avatar a ORDER BY a.image_height * a.image_width DESC' ); $this->entityManager->getConnection()->setDatabasePlatform(new MySqlPlatform()); - $query->setHint(Query::HINT_CUSTOM_OUTPUT_WALKER, 'Doctrine\ORM\Tools\Pagination\LimitSubqueryOutputWalker'); + $query->setHint(Query::HINT_CUSTOM_OUTPUT_WALKER, LimitSubqueryOutputWalker::class); $this->assertSame( - 'SELECT DISTINCT id_0 FROM (SELECT u0_.id AS id_0, a1_.image_height AS image_height_1, a1_.image_width AS image_width_2, a1_.user_id AS user_id_3 FROM User u0_ INNER JOIN Avatar a1_ ON u0_.id = a1_.user_id) dctrn_result ORDER BY image_height_1 * image_width_2 DESC', + 'SELECT DISTINCT id_0 FROM (SELECT DISTINCT id_0, image_height_1 * image_width_2 FROM (SELECT u0_.id AS id_0, a1_.image_height AS image_height_1, a1_.image_width AS image_width_2, a1_.user_id AS user_id_3 FROM User u0_ INNER JOIN Avatar a1_ ON u0_.id = a1_.user_id) dctrn_result_inner ORDER BY image_height_1 * image_width_2 DESC) dctrn_result', $query->getSQL() ); } - public function testCountQueryWithComplexScalarOrderByItemJoinedWithPartial() + public function testCountQueryWithComplexScalarOrderByItemJoinedWithPartial() : void { $query = $this->entityManager->createQuery( 'SELECT u, partial a.{id, image_alt_desc} FROM Doctrine\Tests\ORM\Tools\Pagination\User u JOIN u.avatar a ORDER BY a.image_height * a.image_width DESC' ); $this->entityManager->getConnection()->setDatabasePlatform(new MySqlPlatform()); - $query->setHint(Query::HINT_CUSTOM_OUTPUT_WALKER, 'Doctrine\ORM\Tools\Pagination\LimitSubqueryOutputWalker'); + $query->setHint(Query::HINT_CUSTOM_OUTPUT_WALKER, LimitSubqueryOutputWalker::class); $this->assertSame( - 'SELECT DISTINCT id_0 FROM (SELECT u0_.id AS id_0, a1_.id AS id_1, a1_.image_alt_desc AS image_alt_desc_2, a1_.image_height AS image_height_3, a1_.image_width AS image_width_4, a1_.user_id AS user_id_5 FROM User u0_ INNER JOIN Avatar a1_ ON u0_.id = a1_.user_id) dctrn_result ORDER BY image_height_3 * image_width_4 DESC', + 'SELECT DISTINCT id_0 FROM (SELECT DISTINCT id_0, image_height_3 * image_width_4 FROM (SELECT u0_.id AS id_0, a1_.id AS id_1, a1_.image_alt_desc AS image_alt_desc_2, a1_.image_height AS image_height_3, a1_.image_width AS image_width_4, a1_.user_id AS user_id_5 FROM User u0_ INNER JOIN Avatar a1_ ON u0_.id = a1_.user_id) dctrn_result_inner ORDER BY image_height_3 * image_width_4 DESC) dctrn_result', $query->getSQL() ); } - public function testCountQueryWithComplexScalarOrderByItemOracle() + public function testCountQueryWithComplexScalarOrderByItemOracle() : void { $query = $this->entityManager->createQuery( 'SELECT a FROM Doctrine\Tests\ORM\Tools\Pagination\Avatar a ORDER BY a.image_height * a.image_width DESC' ); $this->entityManager->getConnection()->setDatabasePlatform(new OraclePlatform()); - $query->setHint(Query::HINT_CUSTOM_OUTPUT_WALKER, 'Doctrine\ORM\Tools\Pagination\LimitSubqueryOutputWalker'); + $query->setHint(Query::HINT_CUSTOM_OUTPUT_WALKER, LimitSubqueryOutputWalker::class); $this->assertSame( 'SELECT DISTINCT ID_0, MIN(SCLR_5) AS dctrn_minrownum FROM (SELECT a0_.id AS ID_0, a0_.image AS IMAGE_1, a0_.image_height AS IMAGE_HEIGHT_2, a0_.image_width AS IMAGE_WIDTH_3, a0_.image_alt_desc AS IMAGE_ALT_DESC_4, ROW_NUMBER() OVER(ORDER BY a0_.image_height * a0_.image_width DESC) AS SCLR_5, a0_.user_id AS USER_ID_6 FROM Avatar a0_) dctrn_result GROUP BY ID_0 ORDER BY dctrn_minrownum ASC', @@ -275,50 +276,50 @@ public function testCountQueryWithComplexScalarOrderByItemOracle() /** * @group DDC-3434 */ - public function testLimitSubqueryWithHiddenSelectionInOrderBy() + public function testLimitSubqueryWithHiddenSelectionInOrderBy() : void { $query = $this->entityManager->createQuery( 'SELECT a, a.name AS HIDDEN ord FROM Doctrine\Tests\ORM\Tools\Pagination\Author a ORDER BY ord DESC' ); - $query->setHint(Query::HINT_CUSTOM_OUTPUT_WALKER, 'Doctrine\ORM\Tools\Pagination\LimitSubqueryOutputWalker'); + $query->setHint(Query::HINT_CUSTOM_OUTPUT_WALKER, LimitSubqueryOutputWalker::class); - $this->assertEquals( - 'SELECT DISTINCT id_0 FROM (SELECT a0_.id AS id_0, a0_.name AS name_1, a0_.name AS name_2 FROM Author a0_) dctrn_result ORDER BY name_2 DESC', + self::assertSame( + 'SELECT DISTINCT id_0 FROM (SELECT DISTINCT id_0, name_2 FROM (SELECT a0_.id AS id_0, a0_.name AS name_1, a0_.name AS name_2 FROM Author a0_) dctrn_result_inner ORDER BY name_2 DESC) dctrn_result', $query->getSQL() ); } - public function testLimitSubqueryWithColumnWithSortDirectionInName() + public function testLimitSubqueryWithColumnWithSortDirectionInName() : void { $query = $this->entityManager->createQuery( 'SELECT a FROM Doctrine\Tests\ORM\Tools\Pagination\Avatar a ORDER BY a.image_alt_desc DESC' ); $this->entityManager->getConnection()->setDatabasePlatform(new MySqlPlatform()); - $query->setHint(Query::HINT_CUSTOM_OUTPUT_WALKER, 'Doctrine\ORM\Tools\Pagination\LimitSubqueryOutputWalker'); + $query->setHint(Query::HINT_CUSTOM_OUTPUT_WALKER, LimitSubqueryOutputWalker::class); $this->assertSame( - 'SELECT DISTINCT id_0 FROM (SELECT a0_.id AS id_0, a0_.image AS image_1, a0_.image_height AS image_height_2, a0_.image_width AS image_width_3, a0_.image_alt_desc AS image_alt_desc_4, a0_.user_id AS user_id_5 FROM Avatar a0_) dctrn_result ORDER BY image_alt_desc_4 DESC', + 'SELECT DISTINCT id_0 FROM (SELECT DISTINCT id_0, image_alt_desc_4 FROM (SELECT a0_.id AS id_0, a0_.image AS image_1, a0_.image_height AS image_height_2, a0_.image_width AS image_width_3, a0_.image_alt_desc AS image_alt_desc_4, a0_.user_id AS user_id_5 FROM Avatar a0_) dctrn_result_inner ORDER BY image_alt_desc_4 DESC) dctrn_result', $query->getSQL() ); } - public function testLimitSubqueryWithOrderByInnerJoined() + public function testLimitSubqueryWithOrderByInnerJoined() : void { $query = $this->entityManager->createQuery( 'SELECT b FROM Doctrine\Tests\ORM\Tools\Pagination\BlogPost b JOIN b.author a ORDER BY a.name ASC' ); - $query->setHint(Query::HINT_CUSTOM_OUTPUT_WALKER, 'Doctrine\ORM\Tools\Pagination\LimitSubqueryOutputWalker'); + $query->setHint(Query::HINT_CUSTOM_OUTPUT_WALKER, LimitSubqueryOutputWalker::class); - $this->assertEquals( - 'SELECT DISTINCT id_0 FROM (SELECT b0_.id AS id_0, a1_.name AS name_1, b0_.author_id AS author_id_2, b0_.category_id AS category_id_3 FROM BlogPost b0_ INNER JOIN Author a1_ ON b0_.author_id = a1_.id) dctrn_result ORDER BY name_1 ASC', + self::assertSame( + 'SELECT DISTINCT id_0 FROM (SELECT DISTINCT id_0, name_1 FROM (SELECT b0_.id AS id_0, a1_.name AS name_1, b0_.author_id AS author_id_2, b0_.category_id AS category_id_3 FROM BlogPost b0_ INNER JOIN Author a1_ ON b0_.author_id = a1_.id) dctrn_result_inner ORDER BY name_1 ASC) dctrn_result', $query->getSQL() ); } - public function testLimitSubqueryWithOrderByAndSubSelectInWhereClauseMySql() + public function testLimitSubqueryWithOrderByAndSubSelectInWhereClauseMySql() : void { $this->entityManager->getConnection()->setDatabasePlatform(new MySqlPlatform()); $query = $this->entityManager->createQuery( @@ -326,15 +327,15 @@ public function testLimitSubqueryWithOrderByAndSubSelectInWhereClauseMySql() WHERE ((SELECT COUNT(simple.id) FROM Doctrine\Tests\ORM\Tools\Pagination\BlogPost simple) = 1) ORDER BY b.id DESC' ); - $query->setHint(Query::HINT_CUSTOM_OUTPUT_WALKER, 'Doctrine\ORM\Tools\Pagination\LimitSubqueryOutputWalker'); + $query->setHint(Query::HINT_CUSTOM_OUTPUT_WALKER, LimitSubqueryOutputWalker::class); - $this->assertEquals( - 'SELECT DISTINCT id_0 FROM (SELECT b0_.id AS id_0, b0_.author_id AS author_id_1, b0_.category_id AS category_id_2 FROM BlogPost b0_ WHERE ((SELECT COUNT(b1_.id) AS dctrn__1 FROM BlogPost b1_) = 1)) dctrn_result ORDER BY id_0 DESC', + self::assertSame( + 'SELECT DISTINCT id_0 FROM (SELECT DISTINCT id_0 FROM (SELECT b0_.id AS id_0, b0_.author_id AS author_id_1, b0_.category_id AS category_id_2 FROM BlogPost b0_ WHERE ((SELECT COUNT(b1_.id) AS sclr_3 FROM BlogPost b1_) = 1)) dctrn_result_inner ORDER BY id_0 DESC) dctrn_result', $query->getSQL() ); } - public function testLimitSubqueryWithOrderByAndSubSelectInWhereClausePgSql() + public function testLimitSubqueryWithOrderByAndSubSelectInWhereClausePgSql() : void { $this->entityManager->getConnection()->setDatabasePlatform(new PostgreSqlPlatform()); $query = $this->entityManager->createQuery( @@ -342,10 +343,10 @@ public function testLimitSubqueryWithOrderByAndSubSelectInWhereClausePgSql() WHERE ((SELECT COUNT(simple.id) FROM Doctrine\Tests\ORM\Tools\Pagination\BlogPost simple) = 1) ORDER BY b.id DESC' ); - $query->setHint(Query::HINT_CUSTOM_OUTPUT_WALKER, 'Doctrine\ORM\Tools\Pagination\LimitSubqueryOutputWalker'); + $query->setHint(Query::HINT_CUSTOM_OUTPUT_WALKER, LimitSubqueryOutputWalker::class); - $this->assertEquals( - 'SELECT DISTINCT id_0, MIN(sclr_1) AS dctrn_minrownum FROM (SELECT b0_.id AS id_0, ROW_NUMBER() OVER(ORDER BY b0_.id DESC) AS sclr_1, b0_.author_id AS author_id_2, b0_.category_id AS category_id_3 FROM BlogPost b0_ WHERE ((SELECT COUNT(b1_.id) AS dctrn__1 FROM BlogPost b1_) = 1)) dctrn_result GROUP BY id_0 ORDER BY dctrn_minrownum ASC', + self::assertSame( + 'SELECT DISTINCT id_0, MIN(sclr_1) AS dctrn_minrownum FROM (SELECT b0_.id AS id_0, ROW_NUMBER() OVER(ORDER BY b0_.id DESC) AS sclr_1, b0_.author_id AS author_id_2, b0_.category_id AS category_id_3 FROM BlogPost b0_ WHERE ((SELECT COUNT(b1_.id) AS sclr_4 FROM BlogPost b1_) = 1)) dctrn_result GROUP BY id_0 ORDER BY dctrn_minrownum ASC', $query->getSQL() ); } @@ -353,7 +354,7 @@ public function testLimitSubqueryWithOrderByAndSubSelectInWhereClausePgSql() /** * This tests ordering by property that has the 'declared' field. */ - public function testLimitSubqueryOrderByFieldFromMappedSuperclass() + public function testLimitSubqueryOrderByFieldFromMappedSuperclass() : void { $this->entityManager->getConnection()->setDatabasePlatform(new MySqlPlatform()); @@ -361,10 +362,10 @@ public function testLimitSubqueryOrderByFieldFromMappedSuperclass() $query = $this->entityManager->createQuery( 'SELECT b FROM Doctrine\Tests\ORM\Tools\Pagination\Banner b ORDER BY b.id DESC' ); - $query->setHint(Query::HINT_CUSTOM_OUTPUT_WALKER, 'Doctrine\ORM\Tools\Pagination\LimitSubqueryOutputWalker'); + $query->setHint(Query::HINT_CUSTOM_OUTPUT_WALKER, LimitSubqueryOutputWalker::class); - $this->assertEquals( - 'SELECT DISTINCT id_0 FROM (SELECT b0_.id AS id_0, b0_.name AS name_1 FROM Banner b0_) dctrn_result ORDER BY id_0 DESC', + self::assertSame( + 'SELECT DISTINCT id_0 FROM (SELECT DISTINCT id_0 FROM (SELECT b0_.id AS id_0, b0_.name AS name_1 FROM Banner b0_) dctrn_result_inner ORDER BY id_0 DESC) dctrn_result', $query->getSQL() ); } @@ -372,7 +373,7 @@ public function testLimitSubqueryOrderByFieldFromMappedSuperclass() /** * Tests order by on a subselect expression (mysql). */ - public function testLimitSubqueryOrderBySubSelectOrderByExpression() + public function testLimitSubqueryOrderBySubSelectOrderByExpression() : void { $this->entityManager->getConnection()->setDatabasePlatform(new MySqlPlatform()); @@ -386,10 +387,10 @@ public function testLimitSubqueryOrderBySubSelectOrderByExpression() FROM Doctrine\Tests\ORM\Tools\Pagination\Author a ORDER BY first_blog_post DESC' ); - $query->setHint(Query::HINT_CUSTOM_OUTPUT_WALKER, 'Doctrine\ORM\Tools\Pagination\LimitSubqueryOutputWalker'); + $query->setHint(Query::HINT_CUSTOM_OUTPUT_WALKER, LimitSubqueryOutputWalker::class); - $this->assertEquals( - 'SELECT DISTINCT id_0 FROM (SELECT a0_.id AS id_0, a0_.name AS name_1, (SELECT MIN(m1_.title) AS dctrn__1 FROM MyBlogPost m1_ WHERE m1_.author_id = a0_.id) AS sclr_2 FROM Author a0_) dctrn_result ORDER BY sclr_2 DESC', + self::assertSame( + 'SELECT DISTINCT id_0 FROM (SELECT DISTINCT id_0, sclr_2 FROM (SELECT a0_.id AS id_0, a0_.name AS name_1, (SELECT MIN(m1_.title) AS sclr_3 FROM MyBlogPost m1_ WHERE m1_.author_id = a0_.id) AS sclr_2 FROM Author a0_) dctrn_result_inner ORDER BY sclr_2 DESC) dctrn_result', $query->getSQL() ); } @@ -397,7 +398,7 @@ public function testLimitSubqueryOrderBySubSelectOrderByExpression() /** * Tests order by on a subselect expression invoking RowNumberOverFunction (postgres). */ - public function testLimitSubqueryOrderBySubSelectOrderByExpressionPg() + public function testLimitSubqueryOrderBySubSelectOrderByExpressionPg() : void { $this->entityManager->getConnection()->setDatabasePlatform(new PostgreSqlPlatform()); @@ -411,10 +412,10 @@ public function testLimitSubqueryOrderBySubSelectOrderByExpressionPg() FROM Doctrine\Tests\ORM\Tools\Pagination\Author a ORDER BY first_blog_post DESC' ); - $query->setHint(Query::HINT_CUSTOM_OUTPUT_WALKER, 'Doctrine\ORM\Tools\Pagination\LimitSubqueryOutputWalker'); + $query->setHint(Query::HINT_CUSTOM_OUTPUT_WALKER, LimitSubqueryOutputWalker::class); - $this->assertEquals( - 'SELECT DISTINCT id_0, MIN(sclr_3) AS dctrn_minrownum FROM (SELECT a0_.id AS id_0, a0_.name AS name_1, (SELECT MIN(m1_.title) AS dctrn__1 FROM MyBlogPost m1_ WHERE m1_.author_id = a0_.id) AS sclr_2, ROW_NUMBER() OVER(ORDER BY (SELECT MIN(m1_.title) AS dctrn__2 FROM MyBlogPost m1_ WHERE m1_.author_id = a0_.id) DESC) AS sclr_3 FROM Author a0_) dctrn_result GROUP BY id_0 ORDER BY dctrn_minrownum ASC', + self::assertSame( + 'SELECT DISTINCT id_0, MIN(sclr_4) AS dctrn_minrownum FROM (SELECT a0_.id AS id_0, a0_.name AS name_1, (SELECT MIN(m1_.title) AS sclr_3 FROM MyBlogPost m1_ WHERE m1_.author_id = a0_.id) AS sclr_2, ROW_NUMBER() OVER(ORDER BY (SELECT MIN(m1_.title) AS sclr_5 FROM MyBlogPost m1_ WHERE m1_.author_id = a0_.id) DESC) AS sclr_4 FROM Author a0_) dctrn_result GROUP BY id_0 ORDER BY dctrn_minrownum ASC', $query->getSQL() ); } @@ -422,7 +423,7 @@ public function testLimitSubqueryOrderBySubSelectOrderByExpressionPg() /** * Tests order by on a subselect expression invoking RowNumberOverFunction (oracle). */ - public function testLimitSubqueryOrderBySubSelectOrderByExpressionOracle() + public function testLimitSubqueryOrderBySubSelectOrderByExpressionOracle() : void { $this->entityManager->getConnection()->setDatabasePlatform(new OraclePlatform()); @@ -436,10 +437,10 @@ public function testLimitSubqueryOrderBySubSelectOrderByExpressionOracle() FROM Doctrine\Tests\ORM\Tools\Pagination\Author a ORDER BY first_blog_post DESC' ); - $query->setHint(Query::HINT_CUSTOM_OUTPUT_WALKER, 'Doctrine\ORM\Tools\Pagination\LimitSubqueryOutputWalker'); + $query->setHint(Query::HINT_CUSTOM_OUTPUT_WALKER, LimitSubqueryOutputWalker::class); - $this->assertEquals( - 'SELECT DISTINCT ID_0, MIN(SCLR_3) AS dctrn_minrownum FROM (SELECT a0_.id AS ID_0, a0_.name AS NAME_1, (SELECT MIN(m1_.title) AS dctrn__1 FROM MyBlogPost m1_ WHERE m1_.author_id = a0_.id) AS SCLR_2, ROW_NUMBER() OVER(ORDER BY (SELECT MIN(m1_.title) AS dctrn__2 FROM MyBlogPost m1_ WHERE m1_.author_id = a0_.id) DESC) AS SCLR_3 FROM Author a0_) dctrn_result GROUP BY ID_0 ORDER BY dctrn_minrownum ASC', + self::assertSame( + 'SELECT DISTINCT ID_0, MIN(SCLR_4) AS dctrn_minrownum FROM (SELECT a0_.id AS ID_0, a0_.name AS NAME_1, (SELECT MIN(m1_.title) AS SCLR_3 FROM MyBlogPost m1_ WHERE m1_.author_id = a0_.id) AS SCLR_2, ROW_NUMBER() OVER(ORDER BY (SELECT MIN(m1_.title) AS SCLR_5 FROM MyBlogPost m1_ WHERE m1_.author_id = a0_.id) DESC) AS SCLR_4 FROM Author a0_) dctrn_result GROUP BY ID_0 ORDER BY dctrn_minrownum ASC', $query->getSQL() ); } diff --git a/tests/Doctrine/Tests/ORM/Tools/Pagination/LimitSubqueryWalkerTest.php b/tests/Doctrine/Tests/ORM/Tools/Pagination/LimitSubqueryWalkerTest.php index 30da257891c..32ad2a354ec 100644 --- a/tests/Doctrine/Tests/ORM/Tools/Pagination/LimitSubqueryWalkerTest.php +++ b/tests/Doctrine/Tests/ORM/Tools/Pagination/LimitSubqueryWalkerTest.php @@ -3,6 +3,7 @@ namespace Doctrine\Tests\ORM\Tools\Pagination; use Doctrine\ORM\Query; +use Doctrine\ORM\Tools\Pagination\LimitSubqueryWalker; /** * @group DDC-1613 @@ -14,11 +15,11 @@ public function testLimitSubquery() $dql = 'SELECT p, c, a FROM Doctrine\Tests\ORM\Tools\Pagination\MyBlogPost p JOIN p.category c JOIN p.author a'; $query = $this->entityManager->createQuery($dql); $limitQuery = clone $query; - - $limitQuery->setHint(Query::HINT_CUSTOM_TREE_WALKERS, array('Doctrine\ORM\Tools\Pagination\LimitSubqueryWalker')); + + $limitQuery->setHint(Query::HINT_CUSTOM_TREE_WALKERS, [LimitSubqueryWalker::class]); $this->assertEquals( - "SELECT DISTINCT m0_.id AS id_0 FROM MyBlogPost m0_ INNER JOIN Category c1_ ON m0_.category_id = c1_.id INNER JOIN Author a2_ ON m0_.author_id = a2_.id", + "SELECT DISTINCT m0_.id AS id_0 FROM MyBlogPost m0_ INNER JOIN Category c1_ ON m0_.category_id = c1_.id INNER JOIN Author a2_ ON m0_.author_id = a2_.id", $limitQuery->getSQL() ); } @@ -28,11 +29,25 @@ public function testLimitSubqueryWithSort() $dql = 'SELECT p, c, a FROM Doctrine\Tests\ORM\Tools\Pagination\MyBlogPost p JOIN p.category c JOIN p.author a ORDER BY p.title'; $query = $this->entityManager->createQuery($dql); $limitQuery = clone $query; - - $limitQuery->setHint(Query::HINT_CUSTOM_TREE_WALKERS, array('Doctrine\ORM\Tools\Pagination\LimitSubqueryWalker')); + + $limitQuery->setHint(Query::HINT_CUSTOM_TREE_WALKERS, [LimitSubqueryWalker::class]); $this->assertEquals( - "SELECT DISTINCT m0_.id AS id_0, m0_.title AS title_1 FROM MyBlogPost m0_ INNER JOIN Category c1_ ON m0_.category_id = c1_.id INNER JOIN Author a2_ ON m0_.author_id = a2_.id ORDER BY m0_.title ASC", + "SELECT DISTINCT m0_.id AS id_0, m0_.title AS title_1 FROM MyBlogPost m0_ INNER JOIN Category c1_ ON m0_.category_id = c1_.id INNER JOIN Author a2_ ON m0_.author_id = a2_.id ORDER BY m0_.title ASC", + $limitQuery->getSQL() + ); + } + + public function testLimitSubqueryWithSortFunction() : void + { + $dql = 'SELECT p FROM Doctrine\Tests\ORM\Tools\Pagination\MyBlogPost p JOIN p.category c GROUP BY p.id ORDER BY COUNT(c.id)'; + $query = $this->entityManager->createQuery($dql); + + $limitQuery = clone $query; + $limitQuery->setHint(Query::HINT_CUSTOM_TREE_WALKERS, [LimitSubqueryWalker::class]); + + self::assertSame( + 'SELECT DISTINCT m0_.id AS id_0 FROM MyBlogPost m0_ INNER JOIN Category c1_ ON m0_.category_id = c1_.id GROUP BY m0_.id ORDER BY COUNT(c1_.id) ASC', $limitQuery->getSQL() ); } @@ -42,11 +57,39 @@ public function testCountQuery_MixedResultsWithName() $dql = 'SELECT a, sum(a.name) as foo FROM Doctrine\Tests\ORM\Tools\Pagination\Author a'; $query = $this->entityManager->createQuery($dql); $limitQuery = clone $query; - - $limitQuery->setHint(Query::HINT_CUSTOM_TREE_WALKERS, array('Doctrine\ORM\Tools\Pagination\LimitSubqueryWalker')); + + $limitQuery->setHint(Query::HINT_CUSTOM_TREE_WALKERS, [LimitSubqueryWalker::class]); $this->assertEquals( - "SELECT DISTINCT a0_.id AS id_0, sum(a0_.name) AS sclr_1 FROM Author a0_", + "SELECT DISTINCT a0_.id AS id_0 FROM Author a0_", + $limitQuery->getSQL() + ); + } + + public function testAggQuery_MixedResultsWithNameAndSort() : void + { + $dql = 'SELECT a, sum(a.name) as foo FROM Doctrine\Tests\ORM\Tools\Pagination\Author a ORDER BY foo DESC'; + $query = $this->entityManager->createQuery($dql); + + $limitQuery = clone $query; + $limitQuery->setHint(Query::HINT_CUSTOM_TREE_WALKERS, [LimitSubqueryWalker::class]); + + self::assertSame( + 'SELECT DISTINCT a0_.id AS id_0, sum(a0_.name) AS sclr_1 FROM Author a0_ ORDER BY sclr_1 DESC', + $limitQuery->getSQL() + ); + } + + public function testAggQuery_MultipleMixedResultsWithSort() : void + { + $dql = 'SELECT a, sum(a.name) as foo, (SELECT count(subA.id) FROM Doctrine\Tests\ORM\Tools\Pagination\Author subA WHERE subA.id = a.id ) as bar FROM Doctrine\Tests\ORM\Tools\Pagination\Author a ORDER BY foo DESC, bar ASC'; + $query = $this->entityManager->createQuery($dql); + + $limitQuery = clone $query; + $limitQuery->setHint(Query::HINT_CUSTOM_TREE_WALKERS, [LimitSubqueryWalker::class]); + + self::assertSame( + 'SELECT DISTINCT a0_.id AS id_0, sum(a0_.name) AS sclr_1, (SELECT count(a1_.id) AS sclr_3 FROM Author a1_ WHERE a1_.id = a0_.id) AS sclr_2 FROM Author a0_ ORDER BY sclr_1 DESC, sclr_2 ASC', $limitQuery->getSQL() ); } @@ -59,28 +102,28 @@ public function testLimitSubqueryWithSortOnAssociation() $dql = 'SELECT p FROM Doctrine\Tests\ORM\Tools\Pagination\MyBlogPost p ORDER BY p.author'; $query = $this->entityManager->createQuery($dql); $limitQuery = clone $query; - - $limitQuery->setHint(Query::HINT_CUSTOM_TREE_WALKERS, array('Doctrine\ORM\Tools\Pagination\LimitSubqueryWalker')); + + $limitQuery->setHint(Query::HINT_CUSTOM_TREE_WALKERS, [LimitSubqueryWalker::class]); $this->assertEquals( - "SELECT DISTINCT m0_.id AS id_0, m0_.author_id AS sclr_1 FROM MyBlogPost m0_ ORDER BY m0_.author_id ASC", + "SELECT DISTINCT m0_.id AS id_0, m0_.author_id AS sclr_1 FROM MyBlogPost m0_ ORDER BY m0_.author_id ASC", $limitQuery->getSQL() ); } - + /** - * Arbitrary Join - */ + * Arbitrary Join + */ public function testLimitSubqueryWithArbitraryJoin() { $dql = 'SELECT p, c FROM Doctrine\Tests\ORM\Tools\Pagination\MyBlogPost p JOIN Doctrine\Tests\ORM\Tools\Pagination\Category c WITH p.category = c'; $query = $this->entityManager->createQuery($dql); $limitQuery = clone $query; - - $limitQuery->setHint(Query::HINT_CUSTOM_TREE_WALKERS, array('Doctrine\ORM\Tools\Pagination\LimitSubqueryWalker')); + + $limitQuery->setHint(Query::HINT_CUSTOM_TREE_WALKERS, [LimitSubqueryWalker::class]); $this->assertEquals( - "SELECT DISTINCT m0_.id AS id_0 FROM MyBlogPost m0_ INNER JOIN Category c1_ ON (m0_.category_id = c1_.id)", + "SELECT DISTINCT m0_.id AS id_0 FROM MyBlogPost m0_ INNER JOIN Category c1_ ON (m0_.category_id = c1_.id)", $limitQuery->getSQL() ); } @@ -90,11 +133,11 @@ public function testLimitSubqueryWithSortWithArbitraryJoin() $dql = 'SELECT p, c FROM Doctrine\Tests\ORM\Tools\Pagination\MyBlogPost p JOIN Doctrine\Tests\ORM\Tools\Pagination\Category c WITH p.category = c ORDER BY p.title'; $query = $this->entityManager->createQuery($dql); $limitQuery = clone $query; - - $limitQuery->setHint(Query::HINT_CUSTOM_TREE_WALKERS, array('Doctrine\ORM\Tools\Pagination\LimitSubqueryWalker')); + + $limitQuery->setHint(Query::HINT_CUSTOM_TREE_WALKERS, [LimitSubqueryWalker::class]); $this->assertEquals( - "SELECT DISTINCT m0_.id AS id_0, m0_.title AS title_1 FROM MyBlogPost m0_ INNER JOIN Category c1_ ON (m0_.category_id = c1_.id) ORDER BY m0_.title ASC", + "SELECT DISTINCT m0_.id AS id_0, m0_.title AS title_1 FROM MyBlogPost m0_ INNER JOIN Category c1_ ON (m0_.category_id = c1_.id) ORDER BY m0_.title ASC", $limitQuery->getSQL() ); } diff --git a/tests/Doctrine/Tests/ORM/Tools/Pagination/PaginationTestCase.php b/tests/Doctrine/Tests/ORM/Tools/Pagination/PaginationTestCase.php index fe8ee0f8252..a4791cd175e 100644 --- a/tests/Doctrine/Tests/ORM/Tools/Pagination/PaginationTestCase.php +++ b/tests/Doctrine/Tests/ORM/Tools/Pagination/PaginationTestCase.php @@ -11,7 +11,7 @@ abstract class PaginationTestCase extends OrmTestCase */ public $entityManager; - public function setUp() + protected function setUp() { $this->entityManager = $this->_getTestEntityManager(); } diff --git a/tests/Doctrine/Tests/ORM/Tools/Pagination/PaginatorTest.php b/tests/Doctrine/Tests/ORM/Tools/Pagination/PaginatorTest.php new file mode 100644 index 00000000000..20b2abdda17 --- /dev/null +++ b/tests/Doctrine/Tests/ORM/Tools/Pagination/PaginatorTest.php @@ -0,0 +1,121 @@ +connection = $this->getMockBuilder(ConnectionMock::class) + ->setConstructorArgs([[], new DriverMock()]) + ->setMethods(['executeQuery']) + ->getMock() + ; + + $this->em = $this->getMockBuilder(EntityManagerDecorator::class) + ->setConstructorArgs([$this->_getTestEntityManager($this->connection)]) + ->setMethods(['newHydrator']) + ->getMock() + ; + + $this->hydrator = $this->createMock(AbstractHydrator::class); + $this->em->method('newHydrator')->willReturn($this->hydrator); + } + + public function testExtraParametersAreStrippedWhenWalkerRemovingOriginalSelectElementsIsUsed() : void + { + $paramInWhere = 1; + $paramInSubSelect = 2; + $returnedIds = [10]; + + $this->hydrator->method('hydrateAll')->willReturn([$returnedIds]); + + $query = new Query($this->em); + $query->setDQL( + 'SELECT u, + ( + SELECT MAX(a.version) + FROM Doctrine\\Tests\\Models\\CMS\\CmsArticle a + WHERE a.user = u AND 1 = :paramInSubSelect + ) AS HIDDEN max_version + FROM Doctrine\\Tests\\Models\\CMS\\CmsUser u + WHERE u.id = :paramInWhere' + ); + $query->setParameters(['paramInWhere' => $paramInWhere, 'paramInSubSelect' => $paramInSubSelect]); + $query->setMaxResults(1); + $paginator = (new Paginator($query, true))->setUseOutputWalkers(false); + + $this->connection->expects($this->exactly(3))->method('executeQuery'); + + $this->connection->expects($this->at(0)) + ->method('executeQuery') + ->with($this->anything(), [$paramInWhere]) + ; + + $this->connection->expects($this->at(1)) + ->method('executeQuery') + ->with($this->anything(), [$paramInWhere]) + ; + + $this->connection->expects($this->at(2)) + ->method('executeQuery') + ->with($this->anything(), [$paramInSubSelect, $paramInWhere, $returnedIds]) + ; + + $paginator->count(); + $paginator->getIterator(); + } + + public function testPaginatorNotCaringAboutExtraParametersWithoutOutputWalkers() : void + { + $this->connection->expects($this->exactly(3))->method('executeQuery'); + + $this->createPaginatorWithExtraParametersWithoutOutputWalkers([])->count(); + $this->createPaginatorWithExtraParametersWithoutOutputWalkers([[10]])->count(); + $this->createPaginatorWithExtraParametersWithoutOutputWalkers([])->getIterator(); + } + + public function testgetIteratorDoesCareAboutExtraParametersWithoutOutputWalkersWhenResultIsNotEmpty() : void + { + $this->connection->expects($this->exactly(1))->method('executeQuery'); + $this->expectException(Query\QueryException::class); + $this->expectExceptionMessage('Too many parameters: the query defines 1 parameters and you bound 2'); + + $this->createPaginatorWithExtraParametersWithoutOutputWalkers([[10]])->getIterator(); + } + + /** + * @param int[][] $willReturnRows + */ + private function createPaginatorWithExtraParametersWithoutOutputWalkers(array $willReturnRows) : Paginator + { + $this->hydrator->method('hydrateAll')->willReturn($willReturnRows); + $this->connection->method('executeQuery')->with($this->anything(), []); + + $query = new Query($this->em); + $query->setDQL('SELECT u FROM Doctrine\\Tests\\Models\\CMS\\CmsUser u'); + $query->setParameters(['paramInWhere' => 1]); + $query->setMaxResults(1); + + return (new Paginator($query, true))->setUseOutputWalkers(false); + } +} diff --git a/tests/Doctrine/Tests/ORM/Tools/Pagination/WhereInWalkerTest.php b/tests/Doctrine/Tests/ORM/Tools/Pagination/WhereInWalkerTest.php index f89ea5704d1..647fed17420 100644 --- a/tests/Doctrine/Tests/ORM/Tools/Pagination/WhereInWalkerTest.php +++ b/tests/Doctrine/Tests/ORM/Tools/Pagination/WhereInWalkerTest.php @@ -2,26 +2,45 @@ namespace Doctrine\Tests\ORM\Tools\Pagination; +use Doctrine\DBAL\Types\Type; use Doctrine\ORM\Query; use Doctrine\ORM\Tools\Pagination\WhereInWalker; +use Doctrine\Tests\DbalTypes\Rot13Type; +use Doctrine\Tests\Models\ValueConversionType\AuxiliaryEntity; +use Doctrine\Tests\Models\ValueConversionType\OwningManyToOneIdForeignKeyEntity; /** * @group DDC-1613 */ class WhereInWalkerTest extends PaginationTestCase { + protected function setUp() : void + { + parent::setUp(); + + if (! Type::hasType('rot13')) { + Type::addType('rot13', Rot13Type::class); + } + } + public function testWhereInQuery_NoWhere() { $query = $this->entityManager->createQuery( 'SELECT u, g FROM Doctrine\Tests\ORM\Tools\Pagination\User u JOIN u.groups g' ); $whereInQuery = clone $query; - $whereInQuery->setHint(Query::HINT_CUSTOM_TREE_WALKERS, array('Doctrine\ORM\Tools\Pagination\WhereInWalker')); + $whereInQuery->setHint(Query::HINT_CUSTOM_TREE_WALKERS, [WhereInWalker::class]); $whereInQuery->setHint(WhereInWalker::HINT_PAGINATOR_ID_COUNT, 10); + $whereInQuery->setParameter(WhereInWalker::PAGINATOR_ID_ALIAS, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]); $this->assertEquals( "SELECT u0_.id AS id_0, g1_.id AS id_1 FROM User u0_ INNER JOIN user_group u2_ ON u0_.id = u2_.user_id INNER JOIN groups g1_ ON g1_.id = u2_.group_id WHERE u0_.id IN (?)", $whereInQuery->getSQL() ); + + $this->assertPaginatorWhereInParameterToBe( + $whereInQuery, + [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + ); } public function testCountQuery_MixedResultsWithName() @@ -30,12 +49,18 @@ public function testCountQuery_MixedResultsWithName() 'SELECT a, sum(a.name) as foo FROM Doctrine\Tests\ORM\Tools\Pagination\Author a' ); $whereInQuery = clone $query; - $whereInQuery->setHint(Query::HINT_CUSTOM_TREE_WALKERS, array('Doctrine\ORM\Tools\Pagination\WhereInWalker')); + $whereInQuery->setHint(Query::HINT_CUSTOM_TREE_WALKERS, [WhereInWalker::class]); $whereInQuery->setHint(WhereInWalker::HINT_PAGINATOR_ID_COUNT, 10); + $whereInQuery->setParameter(WhereInWalker::PAGINATOR_ID_ALIAS, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]); $this->assertEquals( "SELECT a0_.id AS id_0, a0_.name AS name_1, sum(a0_.name) AS sclr_2 FROM Author a0_ WHERE a0_.id IN (?)", $whereInQuery->getSQL() ); + + $this->assertPaginatorWhereInParameterToBe( + $whereInQuery, + [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + ); } public function testWhereInQuery_SingleWhere() @@ -44,12 +69,18 @@ public function testWhereInQuery_SingleWhere() 'SELECT u, g FROM Doctrine\Tests\ORM\Tools\Pagination\User u JOIN u.groups g WHERE 1 = 1' ); $whereInQuery = clone $query; - $whereInQuery->setHint(Query::HINT_CUSTOM_TREE_WALKERS, array('Doctrine\ORM\Tools\Pagination\WhereInWalker')); + $whereInQuery->setHint(Query::HINT_CUSTOM_TREE_WALKERS, [WhereInWalker::class]); $whereInQuery->setHint(WhereInWalker::HINT_PAGINATOR_ID_COUNT, 10); + $whereInQuery->setParameter(WhereInWalker::PAGINATOR_ID_ALIAS, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]); $this->assertEquals( "SELECT u0_.id AS id_0, g1_.id AS id_1 FROM User u0_ INNER JOIN user_group u2_ ON u0_.id = u2_.user_id INNER JOIN groups g1_ ON g1_.id = u2_.group_id WHERE 1 = 1 AND u0_.id IN (?)", $whereInQuery->getSQL() ); + + $this->assertPaginatorWhereInParameterToBe( + $whereInQuery, + [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + ); } public function testWhereInQuery_MultipleWhereWithAnd() @@ -58,12 +89,18 @@ public function testWhereInQuery_MultipleWhereWithAnd() 'SELECT u, g FROM Doctrine\Tests\ORM\Tools\Pagination\User u JOIN u.groups g WHERE 1 = 1 AND 2 = 2' ); $whereInQuery = clone $query; - $whereInQuery->setHint(Query::HINT_CUSTOM_TREE_WALKERS, array('Doctrine\ORM\Tools\Pagination\WhereInWalker')); + $whereInQuery->setHint(Query::HINT_CUSTOM_TREE_WALKERS, [WhereInWalker::class]); $whereInQuery->setHint(WhereInWalker::HINT_PAGINATOR_ID_COUNT, 10); + $whereInQuery->setParameter(WhereInWalker::PAGINATOR_ID_ALIAS, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]); $this->assertEquals( "SELECT u0_.id AS id_0, g1_.id AS id_1 FROM User u0_ INNER JOIN user_group u2_ ON u0_.id = u2_.user_id INNER JOIN groups g1_ ON g1_.id = u2_.group_id WHERE 1 = 1 AND 2 = 2 AND u0_.id IN (?)", $whereInQuery->getSQL() ); + + $this->assertPaginatorWhereInParameterToBe( + $whereInQuery, + [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + ); } public function testWhereInQuery_MultipleWhereWithOr() @@ -72,12 +109,18 @@ public function testWhereInQuery_MultipleWhereWithOr() 'SELECT u, g FROM Doctrine\Tests\ORM\Tools\Pagination\User u JOIN u.groups g WHERE 1 = 1 OR 2 = 2' ); $whereInQuery = clone $query; - $whereInQuery->setHint(Query::HINT_CUSTOM_TREE_WALKERS, array('Doctrine\ORM\Tools\Pagination\WhereInWalker')); + $whereInQuery->setHint(Query::HINT_CUSTOM_TREE_WALKERS, [WhereInWalker::class]); $whereInQuery->setHint(WhereInWalker::HINT_PAGINATOR_ID_COUNT, 10); + $whereInQuery->setParameter(WhereInWalker::PAGINATOR_ID_ALIAS, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]); $this->assertEquals( "SELECT u0_.id AS id_0, g1_.id AS id_1 FROM User u0_ INNER JOIN user_group u2_ ON u0_.id = u2_.user_id INNER JOIN groups g1_ ON g1_.id = u2_.group_id WHERE (1 = 1 OR 2 = 2) AND u0_.id IN (?)", $whereInQuery->getSQL() ); + + $this->assertPaginatorWhereInParameterToBe( + $whereInQuery, + [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + ); } public function testWhereInQuery_MultipleWhereWithMixed_1() @@ -86,12 +129,18 @@ public function testWhereInQuery_MultipleWhereWithMixed_1() 'SELECT u, g FROM Doctrine\Tests\ORM\Tools\Pagination\User u JOIN u.groups g WHERE (1 = 1 OR 2 = 2) AND 3 = 3' ); $whereInQuery = clone $query; - $whereInQuery->setHint(Query::HINT_CUSTOM_TREE_WALKERS, array('Doctrine\ORM\Tools\Pagination\WhereInWalker')); + $whereInQuery->setHint(Query::HINT_CUSTOM_TREE_WALKERS, [WhereInWalker::class]); $whereInQuery->setHint(WhereInWalker::HINT_PAGINATOR_ID_COUNT, 10); + $whereInQuery->setParameter(WhereInWalker::PAGINATOR_ID_ALIAS, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]); $this->assertEquals( "SELECT u0_.id AS id_0, g1_.id AS id_1 FROM User u0_ INNER JOIN user_group u2_ ON u0_.id = u2_.user_id INNER JOIN groups g1_ ON g1_.id = u2_.group_id WHERE (1 = 1 OR 2 = 2) AND 3 = 3 AND u0_.id IN (?)", $whereInQuery->getSQL() ); + + $this->assertPaginatorWhereInParameterToBe( + $whereInQuery, + [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + ); } public function testWhereInQuery_MultipleWhereWithMixed_2() @@ -100,12 +149,18 @@ public function testWhereInQuery_MultipleWhereWithMixed_2() 'SELECT u, g FROM Doctrine\Tests\ORM\Tools\Pagination\User u JOIN u.groups g WHERE 1 = 1 AND 2 = 2 OR 3 = 3' ); $whereInQuery = clone $query; - $whereInQuery->setHint(Query::HINT_CUSTOM_TREE_WALKERS, array('Doctrine\ORM\Tools\Pagination\WhereInWalker')); + $whereInQuery->setHint(Query::HINT_CUSTOM_TREE_WALKERS, [WhereInWalker::class]); $whereInQuery->setHint(WhereInWalker::HINT_PAGINATOR_ID_COUNT, 10); + $whereInQuery->setParameter(WhereInWalker::PAGINATOR_ID_ALIAS, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]); $this->assertEquals( "SELECT u0_.id AS id_0, g1_.id AS id_1 FROM User u0_ INNER JOIN user_group u2_ ON u0_.id = u2_.user_id INNER JOIN groups g1_ ON g1_.id = u2_.group_id WHERE (1 = 1 AND 2 = 2 OR 3 = 3) AND u0_.id IN (?)", $whereInQuery->getSQL() ); + + $this->assertPaginatorWhereInParameterToBe( + $whereInQuery, + [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + ); } public function testWhereInQuery_WhereNot() @@ -114,41 +169,100 @@ public function testWhereInQuery_WhereNot() 'SELECT u, g FROM Doctrine\Tests\ORM\Tools\Pagination\User u JOIN u.groups g WHERE NOT 1 = 2' ); $whereInQuery = clone $query; - $whereInQuery->setHint(Query::HINT_CUSTOM_TREE_WALKERS, array('Doctrine\ORM\Tools\Pagination\WhereInWalker')); + $whereInQuery->setHint(Query::HINT_CUSTOM_TREE_WALKERS, [WhereInWalker::class]); $whereInQuery->setHint(WhereInWalker::HINT_PAGINATOR_ID_COUNT, 10); + $whereInQuery->setParameter(WhereInWalker::PAGINATOR_ID_ALIAS, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]); $this->assertEquals( "SELECT u0_.id AS id_0, g1_.id AS id_1 FROM User u0_ INNER JOIN user_group u2_ ON u0_.id = u2_.user_id INNER JOIN groups g1_ ON g1_.id = u2_.group_id WHERE (NOT 1 = 2) AND u0_.id IN (?)", $whereInQuery->getSQL() ); + + $this->assertPaginatorWhereInParameterToBe( + $whereInQuery, + [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + ); } - + /** - * Arbitrary Join + * Arbitrary Join */ public function testWhereInQueryWithArbitraryJoin_NoWhere() { $whereInQuery = $this->entityManager->createQuery( 'SELECT p FROM Doctrine\Tests\ORM\Tools\Pagination\BlogPost p JOIN Doctrine\Tests\ORM\Tools\Pagination\Category c WITH p.category = c' ); - $whereInQuery->setHint(Query::HINT_CUSTOM_TREE_WALKERS, array('Doctrine\ORM\Tools\Pagination\WhereInWalker')); + $whereInQuery->setHint(Query::HINT_CUSTOM_TREE_WALKERS, [WhereInWalker::class]); $whereInQuery->setHint(WhereInWalker::HINT_PAGINATOR_ID_COUNT, 10); + $whereInQuery->setParameter(WhereInWalker::PAGINATOR_ID_ALIAS, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]); $this->assertEquals( "SELECT b0_.id AS id_0, b0_.author_id AS author_id_1, b0_.category_id AS category_id_2 FROM BlogPost b0_ INNER JOIN Category c1_ ON (b0_.category_id = c1_.id) WHERE b0_.id IN (?)", $whereInQuery->getSQL() ); + + $this->assertPaginatorWhereInParameterToBe( + $whereInQuery, + [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + ); } - + public function testWhereInQueryWithArbitraryJoin_SingleWhere() { $whereInQuery = $this->entityManager->createQuery( 'SELECT p FROM Doctrine\Tests\ORM\Tools\Pagination\BlogPost p JOIN Doctrine\Tests\ORM\Tools\Pagination\Category c WITH p.category = c WHERE 1 = 1' ); - $whereInQuery->setHint(Query::HINT_CUSTOM_TREE_WALKERS, array('Doctrine\ORM\Tools\Pagination\WhereInWalker')); + $whereInQuery->setHint(Query::HINT_CUSTOM_TREE_WALKERS, [WhereInWalker::class]); $whereInQuery->setHint(WhereInWalker::HINT_PAGINATOR_ID_COUNT, 10); + $whereInQuery->setParameter(WhereInWalker::PAGINATOR_ID_ALIAS, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]); $this->assertEquals( "SELECT b0_.id AS id_0, b0_.author_id AS author_id_1, b0_.category_id AS category_id_2 FROM BlogPost b0_ INNER JOIN Category c1_ ON (b0_.category_id = c1_.id) WHERE 1 = 1 AND b0_.id IN (?)", $whereInQuery->getSQL() ); + + $this->assertPaginatorWhereInParameterToBe( + $whereInQuery, + [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + ); + } + + public function testWillReplaceBoundQueryIdentifiersWithConvertedTypesAsPerIdentifierMapping() : void + { + $whereInQuery = $this->entityManager->createQuery( + 'SELECT e.id4 FROM ' . AuxiliaryEntity::class . ' e' + ); + $whereInQuery->setHint(Query::HINT_CUSTOM_TREE_WALKERS, [WhereInWalker::class]); + $whereInQuery->setHint(WhereInWalker::HINT_PAGINATOR_ID_COUNT, 3); + $whereInQuery->setParameter(WhereInWalker::PAGINATOR_ID_ALIAS, ['foo', 'bar', 'baz']); + + $this->assertPaginatorWhereInParameterToBe( + $whereInQuery, + ['sbb', 'one', 'onm'] + ); + } + + public function testWillReplaceBoundQueryIdentifiersWithConvertedTypesAsPerAssociatedEntityIdentifierMapping() : void + { + $whereInQuery = $this->entityManager->createQuery( + 'SELECT e FROM ' . OwningManyToOneIdForeignKeyEntity::class . ' e' + ); + $whereInQuery->setHint(Query::HINT_CUSTOM_TREE_WALKERS, [WhereInWalker::class]); + $whereInQuery->setHint(WhereInWalker::HINT_PAGINATOR_ID_COUNT, 3); + $whereInQuery->setParameter(WhereInWalker::PAGINATOR_ID_ALIAS, ['foo', 'bar', 'baz']); + + $this->assertPaginatorWhereInParameterToBe( + $whereInQuery, + ['sbb', 'one', 'onm'] + ); + } + + /** @param mixed $parameter */ + private function assertPaginatorWhereInParameterToBe(Query $query, $parameter) : void + { + $query->getSQL(); // forces walker to process the query + + $boundParameter = $query->getParameter(WhereInWalker::PAGINATOR_ID_ALIAS); + + self::assertNotNull($boundParameter); + self::assertSame($parameter, $boundParameter->getValue()); } } diff --git a/tests/Doctrine/Tests/ORM/Tools/ResolveTargetEntityListenerTest.php b/tests/Doctrine/Tests/ORM/Tools/ResolveTargetEntityListenerTest.php index 28753078d48..910df27f87c 100644 --- a/tests/Doctrine/Tests/ORM/Tools/ResolveTargetEntityListenerTest.php +++ b/tests/Doctrine/Tests/ORM/Tools/ResolveTargetEntityListenerTest.php @@ -40,27 +40,19 @@ public function setUp() public function testResolveTargetEntityListenerCanResolveTargetEntity() { $evm = $this->em->getEventManager(); - $this->listener->addResolveTargetEntity( - 'Doctrine\Tests\ORM\Tools\ResolveTargetInterface', - 'Doctrine\Tests\ORM\Tools\ResolveTargetEntity', - array() - ); - $this->listener->addResolveTargetEntity( - 'Doctrine\Tests\ORM\Tools\TargetInterface', - 'Doctrine\Tests\ORM\Tools\TargetEntity', - array() - ); + $this->listener->addResolveTargetEntity(ResolveTargetInterface::class, ResolveTargetEntity::class, []); + $this->listener->addResolveTargetEntity(TargetInterface::class, TargetEntity::class, []); $evm->addEventSubscriber($this->listener); - $cm = $this->factory->getMetadataFor('Doctrine\Tests\ORM\Tools\ResolveTargetEntity'); + $cm = $this->factory->getMetadataFor(ResolveTargetEntity::class); $meta = $cm->associationMappings; - $this->assertSame('Doctrine\Tests\ORM\Tools\TargetEntity', $meta['manyToMany']['targetEntity']); - $this->assertSame('Doctrine\Tests\ORM\Tools\ResolveTargetEntity', $meta['manyToOne']['targetEntity']); - $this->assertSame('Doctrine\Tests\ORM\Tools\ResolveTargetEntity', $meta['oneToMany']['targetEntity']); - $this->assertSame('Doctrine\Tests\ORM\Tools\TargetEntity', $meta['oneToOne']['targetEntity']); + $this->assertSame(TargetEntity::class, $meta['manyToMany']['targetEntity']); + $this->assertSame(ResolveTargetEntity::class, $meta['manyToOne']['targetEntity']); + $this->assertSame(ResolveTargetEntity::class, $meta['oneToMany']['targetEntity']); + $this->assertSame(TargetEntity::class, $meta['oneToOne']['targetEntity']); - $this->assertSame($cm, $this->factory->getMetadataFor('Doctrine\Tests\ORM\Tools\ResolveTargetInterface')); + $this->assertSame($cm, $this->factory->getMetadataFor(ResolveTargetInterface::class)); } /** @@ -70,17 +62,13 @@ public function testResolveTargetEntityListenerCanResolveTargetEntity() */ public function testResolveTargetEntityListenerCanRetrieveTargetEntityByInterfaceName() { - $this->listener->addResolveTargetEntity( - 'Doctrine\Tests\ORM\Tools\ResolveTargetInterface', - 'Doctrine\Tests\ORM\Tools\ResolveTargetEntity', - array() - ); + $this->listener->addResolveTargetEntity(ResolveTargetInterface::class, ResolveTargetEntity::class, []); $this->em->getEventManager()->addEventSubscriber($this->listener); - $cm = $this->factory->getMetadataFor('Doctrine\Tests\ORM\Tools\ResolveTargetInterface'); + $cm = $this->factory->getMetadataFor(ResolveTargetInterface::class); - $this->assertSame($this->factory->getMetadataFor('Doctrine\Tests\ORM\Tools\ResolveTargetEntity'), $cm); + $this->assertSame($this->factory->getMetadataFor(ResolveTargetEntity::class), $cm); } /** @@ -89,23 +77,15 @@ public function testResolveTargetEntityListenerCanRetrieveTargetEntityByInterfac public function testAssertTableColumnsAreNotAddedInManyToMany() { $evm = $this->em->getEventManager(); - $this->listener->addResolveTargetEntity( - 'Doctrine\Tests\ORM\Tools\ResolveTargetInterface', - 'Doctrine\Tests\ORM\Tools\ResolveTargetEntity', - array() - ); - $this->listener->addResolveTargetEntity( - 'Doctrine\Tests\ORM\Tools\TargetInterface', - 'Doctrine\Tests\ORM\Tools\TargetEntity', - array() - ); + $this->listener->addResolveTargetEntity(ResolveTargetInterface::class, ResolveTargetEntity::class, []); + $this->listener->addResolveTargetEntity(TargetInterface::class, TargetEntity::class, []); $evm->addEventListener(Events::loadClassMetadata, $this->listener); - $cm = $this->factory->getMetadataFor('Doctrine\Tests\ORM\Tools\ResolveTargetEntity'); + $cm = $this->factory->getMetadataFor(ResolveTargetEntity::class); $meta = $cm->associationMappings['manyToMany']; - $this->assertSame('Doctrine\Tests\ORM\Tools\TargetEntity', $meta['targetEntity']); - $this->assertEquals(array('resolvetargetentity_id', 'targetinterface_id'), $meta['joinTableColumns']); + $this->assertSame(TargetEntity::class, $meta['targetEntity']); + $this->assertEquals(['resolvetargetentity_id', 'targetinterface_id'], $meta['joinTableColumns']); } /** @@ -117,11 +97,7 @@ public function testAssertTableColumnsAreNotAddedInManyToMany() public function testDoesResolveTargetEntitiesInDQLAlsoWithInterfaces() { $evm = $this->em->getEventManager(); - $this->listener->addResolveTargetEntity( - 'Doctrine\Tests\ORM\Tools\ResolveTargetInterface', - 'Doctrine\Tests\ORM\Tools\ResolveTargetEntity', - array() - ); + $this->listener->addResolveTargetEntity(ResolveTargetInterface::class, ResolveTargetEntity::class, []); $evm->addEventSubscriber($this->listener); diff --git a/tests/Doctrine/Tests/ORM/Tools/SchemaToolTest.php b/tests/Doctrine/Tests/ORM/Tools/SchemaToolTest.php index bc54744b9c3..24415af92e6 100644 --- a/tests/Doctrine/Tests/ORM/Tools/SchemaToolTest.php +++ b/tests/Doctrine/Tests/ORM/Tools/SchemaToolTest.php @@ -2,10 +2,26 @@ namespace Doctrine\Tests\ORM\Tools; +use Doctrine\ORM\Mapping\ClassMetadata; +use Doctrine\ORM\Tools\Event\GenerateSchemaEventArgs; +use Doctrine\ORM\Tools\Event\GenerateSchemaTableEventArgs; use Doctrine\ORM\Tools\SchemaTool; use Doctrine\ORM\Tools\ToolEvents; -use Doctrine\ORM\Tools\Event\GenerateSchemaTableEventArgs; -use Doctrine\ORM\Tools\Event\GenerateSchemaEventArgs; +use Doctrine\Tests\Models\CMS\CmsAddress; +use Doctrine\Tests\Models\CMS\CmsArticle; +use Doctrine\Tests\Models\CMS\CmsComment; +use Doctrine\Tests\Models\CMS\CmsEmployee; +use Doctrine\Tests\Models\CMS\CmsGroup; +use Doctrine\Tests\Models\CMS\CmsPhonenumber; +use Doctrine\Tests\Models\CMS\CmsUser; +use Doctrine\Tests\Models\CompositeKeyInheritance\JoinedDerivedChildClass; +use Doctrine\Tests\Models\CompositeKeyInheritance\JoinedDerivedIdentityClass; +use Doctrine\Tests\Models\CompositeKeyInheritance\JoinedDerivedRootClass; +use Doctrine\Tests\Models\Forum\ForumAvatar; +use Doctrine\Tests\Models\Forum\ForumBoard; +use Doctrine\Tests\Models\Forum\ForumCategory; +use Doctrine\Tests\Models\Forum\ForumUser; +use Doctrine\Tests\Models\NullDefault\NullDefaultColumn; use Doctrine\Tests\OrmTestCase; class SchemaToolTest extends OrmTestCase @@ -15,37 +31,38 @@ public function testAddUniqueIndexForUniqueFieldAnnotation() $em = $this->_getTestEntityManager(); $schemaTool = new SchemaTool($em); - $classes = array( - $em->getClassMetadata('Doctrine\Tests\Models\CMS\CmsAddress'), - $em->getClassMetadata('Doctrine\Tests\Models\CMS\CmsArticle'), - $em->getClassMetadata('Doctrine\Tests\Models\CMS\CmsComment'), - $em->getClassMetadata('Doctrine\Tests\Models\CMS\CmsEmployee'), - $em->getClassMetadata('Doctrine\Tests\Models\CMS\CmsGroup'), - $em->getClassMetadata('Doctrine\Tests\Models\CMS\CmsPhonenumber'), - $em->getClassMetadata('Doctrine\Tests\Models\CMS\CmsUser'), - ); + $classes = [ + $em->getClassMetadata(CmsAddress::class), + $em->getClassMetadata(CmsArticle::class), + $em->getClassMetadata(CmsComment::class), + $em->getClassMetadata(CmsEmployee::class), + $em->getClassMetadata(CmsGroup::class), + $em->getClassMetadata(CmsPhonenumber::class), + $em->getClassMetadata(CmsUser::class), + ]; $schema = $schemaTool->getSchemaFromMetadata($classes); $this->assertTrue($schema->hasTable('cms_users'), "Table cms_users should exist."); - $this->assertTrue($schema->getTable('cms_users')->columnsAreIndexed(array('username')), "username column should be indexed."); + $this->assertTrue($schema->getTable('cms_users')->columnsAreIndexed(['username']), "username column should be indexed."); } - public function testAnnotationOptionsAttribute() + public function testAnnotationOptionsAttribute() : void { $em = $this->_getTestEntityManager(); $schemaTool = new SchemaTool($em); - $classes = array( - $em->getClassMetadata(__NAMESPACE__ . '\\TestEntityWithAnnotationOptionsAttribute'), + $schema = $schemaTool->getSchemaFromMetadata( + [$em->getClassMetadata(TestEntityWithAnnotationOptionsAttribute::class)] ); - - $schema = $schemaTool->getSchemaFromMetadata($classes); - - $expected = array('foo' => 'bar', 'baz' => array('key' => 'val')); - - $this->assertEquals($expected, $schema->getTable('TestEntityWithAnnotationOptionsAttribute')->getOptions(), "options annotation are passed to the tables options"); - $this->assertEquals($expected, $schema->getTable('TestEntityWithAnnotationOptionsAttribute')->getColumn('test')->getCustomSchemaOptions(), "options annotation are passed to the columns customSchemaOptions"); + $table = $schema->getTable('TestEntityWithAnnotationOptionsAttribute'); + + foreach ([$table->getOptions(), $table->getColumn('test')->getCustomSchemaOptions()] as $options) { + self::assertArrayHasKey('foo', $options); + self::assertSame('bar', $options['foo']); + self::assertArrayHasKey('baz', $options); + self::assertSame(['key' => 'val'], $options['baz']); + } } /** @@ -58,11 +75,11 @@ public function testPassColumnDefinitionToJoinColumn() $em = $this->_getTestEntityManager(); $schemaTool = new SchemaTool($em); - $avatar = $em->getClassMetadata('Doctrine\Tests\Models\Forum\ForumAvatar'); + $avatar = $em->getClassMetadata(ForumAvatar::class); $avatar->fieldMappings['id']['columnDefinition'] = $customColumnDef; - $user = $em->getClassMetadata('Doctrine\Tests\Models\Forum\ForumUser'); + $user = $em->getClassMetadata(ForumUser::class); - $classes = array($avatar, $user); + $classes = [$avatar, $user]; $schema = $schemaTool->getSchemaFromMetadata($classes); @@ -72,6 +89,44 @@ public function testPassColumnDefinitionToJoinColumn() $this->assertEquals($customColumnDef, $table->getColumn('avatar_id')->getColumnDefinition()); } + /** + * @group 6830 + */ + public function testPassColumnOptionsToJoinColumn() : void + { + $em = $this->_getTestEntityManager(); + $category = $em->getClassMetadata(GH6830Category::class); + $board = $em->getClassMetadata(GH6830Board::class); + + $schemaTool = new SchemaTool($em); + $schema = $schemaTool->getSchemaFromMetadata([$category, $board]); + + self::assertTrue($schema->hasTable('GH6830Category')); + self::assertTrue($schema->hasTable('GH6830Board')); + + $tableCategory = $schema->getTable('GH6830Category'); + $tableBoard = $schema->getTable('GH6830Board'); + + self::assertTrue($tableBoard->hasColumn('category_id')); + + self::assertSame( + $tableCategory->getColumn('id')->getFixed(), + $tableBoard->getColumn('category_id')->getFixed(), + 'Foreign key/join column should have the same value of option `fixed` as the referenced column' + ); + + self::assertEquals( + $tableCategory->getColumn('id')->getCustomSchemaOptions(), + $tableBoard->getColumn('category_id')->getCustomSchemaOptions(), + 'Foreign key/join column should have the same custom options as the referenced column' + ); + + self::assertEquals( + ['collation' => 'latin1_bin', 'foo' => 'bar'], + $tableBoard->getColumn('category_id')->getCustomSchemaOptions() + ); + } + /** * @group DDC-283 */ @@ -81,19 +136,19 @@ public function testPostGenerateEvents() $em = $this->_getTestEntityManager(); $em->getEventManager()->addEventListener( - array(ToolEvents::postGenerateSchemaTable, ToolEvents::postGenerateSchema), $listener + [ToolEvents::postGenerateSchemaTable, ToolEvents::postGenerateSchema], $listener ); $schemaTool = new SchemaTool($em); - $classes = array( - $em->getClassMetadata('Doctrine\Tests\Models\CMS\CmsAddress'), - $em->getClassMetadata('Doctrine\Tests\Models\CMS\CmsArticle'), - $em->getClassMetadata('Doctrine\Tests\Models\CMS\CmsComment'), - $em->getClassMetadata('Doctrine\Tests\Models\CMS\CmsEmployee'), - $em->getClassMetadata('Doctrine\Tests\Models\CMS\CmsGroup'), - $em->getClassMetadata('Doctrine\Tests\Models\CMS\CmsPhonenumber'), - $em->getClassMetadata('Doctrine\Tests\Models\CMS\CmsUser'), - ); + $classes = [ + $em->getClassMetadata(CmsAddress::class), + $em->getClassMetadata(CmsArticle::class), + $em->getClassMetadata(CmsComment::class), + $em->getClassMetadata(CmsEmployee::class), + $em->getClassMetadata(CmsGroup::class), + $em->getClassMetadata(CmsPhonenumber::class), + $em->getClassMetadata(CmsUser::class), + ]; $schema = $schemaTool->getSchemaFromMetadata($classes); @@ -106,16 +161,12 @@ public function testNullDefaultNotAddedToCustomSchemaOptions() $em = $this->_getTestEntityManager(); $schemaTool = new SchemaTool($em); - $classes = array( - $em->getClassMetadata('Doctrine\Tests\Models\NullDefault\NullDefaultColumn'), - ); - - $customSchemaOptions = $schemaTool->getSchemaFromMetadata($classes) + $customSchemaOptions = $schemaTool->getSchemaFromMetadata([$em->getClassMetadata(NullDefaultColumn::class)]) ->getTable('NullDefaultColumn') ->getColumn('nullDefault') ->getCustomSchemaOptions(); - $this->assertSame(array(), $customSchemaOptions); + $this->assertSame([], $customSchemaOptions); } /** @@ -126,7 +177,7 @@ public function testSchemaHasProperIndexesFromUniqueConstraintAnnotation() $em = $this->_getTestEntityManager(); $schemaTool = new SchemaTool($em); $classes = [ - $em->getClassMetadata(__NAMESPACE__ . '\\UniqueConstraintAnnotationModel'), + $em->getClassMetadata(UniqueConstraintAnnotationModel::class), ]; $schema = $schemaTool->getSchemaFromMetadata($classes); @@ -144,8 +195,8 @@ public function testRemoveUniqueIndexOverruledByPrimaryKey() $em = $this->_getTestEntityManager(); $schemaTool = new SchemaTool($em); $classes = [ - $em->getClassMetadata(__NAMESPACE__ . '\\FirstEntity'), - $em->getClassMetadata(__NAMESPACE__ . '\\SecondEntity') + $em->getClassMetadata(FirstEntity::class), + $em->getClassMetadata(SecondEntity::class) ]; $schema = $schemaTool->getSchemaFromMetadata($classes); @@ -157,6 +208,70 @@ public function testRemoveUniqueIndexOverruledByPrimaryKey() $this->assertCount(1, $indexes, "there should be only one index"); $this->assertTrue(current($indexes)->isPrimary(), "index should be primary"); } + + public function testSetDiscriminatorColumnWithoutLength() : void + { + $em = $this->_getTestEntityManager(); + $schemaTool = new SchemaTool($em); + $metadata = $em->getClassMetadata(FirstEntity::class); + + $metadata->setInheritanceType(ClassMetadata::INHERITANCE_TYPE_SINGLE_TABLE); + $metadata->setDiscriminatorColumn(['name' => 'discriminator', 'type' => 'string']); + + $schema = $schemaTool->getSchemaFromMetadata([$metadata]); + + $this->assertTrue($schema->hasTable('first_entity')); + $table = $schema->getTable('first_entity'); + + $this->assertTrue($table->hasColumn('discriminator')); + $column = $table->getColumn('discriminator'); + + $this->assertEquals(255, $column->getLength()); + } + + public function testDerivedCompositeKey() : void + { + $em = $this->_getTestEntityManager(); + $schemaTool = new SchemaTool($em); + + $schema = $schemaTool->getSchemaFromMetadata( + [ + $em->getClassMetadata(JoinedDerivedIdentityClass::class), + $em->getClassMetadata(JoinedDerivedRootClass::class), + $em->getClassMetadata(JoinedDerivedChildClass::class), + ] + ); + + self::assertTrue($schema->hasTable('joined_derived_identity')); + self::assertTrue($schema->hasTable('joined_derived_root')); + self::assertTrue($schema->hasTable('joined_derived_child')); + + $rootTable = $schema->getTable('joined_derived_root'); + self::assertNotNull($rootTable->getPrimaryKey()); + self::assertSame(['keyPart1_id', 'keyPart2'], $rootTable->getPrimaryKey()->getColumns()); + + $childTable = $schema->getTable('joined_derived_child'); + self::assertNotNull($childTable->getPrimaryKey()); + self::assertSame(['keyPart1_id', 'keyPart2'], $childTable->getPrimaryKey()->getColumns()); + + $childTableForeignKeys = $childTable->getForeignKeys(); + + self::assertCount(2, $childTableForeignKeys); + + $expectedColumns = [ + 'joined_derived_identity' => [['keyPart1_id'], ['id']], + 'joined_derived_root' => [['keyPart1_id', 'keyPart2'], ['keyPart1_id', 'keyPart2']], + ]; + + foreach ($childTableForeignKeys as $foreignKey) { + self::assertArrayHasKey($foreignKey->getForeignTableName(), $expectedColumns); + + [$localColumns, $foreignColumns] = $expectedColumns[$foreignKey->getForeignTableName()]; + + self::assertSame($localColumns, $foreignKey->getLocalColumns()); + self::assertSame($foreignColumns, $foreignKey->getForeignColumns()); + } + } } /** @@ -247,4 +362,41 @@ class SecondEntity * @Column(name="name") */ public $name; -} \ No newline at end of file +} + +/** + * @Entity + */ +class GH6830Board +{ + /** + * @Id + * @Column(type="integer") + */ + public $id; + + /** + * @ManyToOne(targetEntity=GH6830Category::class, inversedBy="boards") + * @JoinColumn(name="category_id", referencedColumnName="id") + */ + public $category; +} + +/** + * @Entity + */ +class GH6830Category +{ + /** + * @Id + * @Column(type="string", length=8, options={"fixed":true, "collation":"latin1_bin", "foo":"bar"}) + * + * @var string + */ + public $id; + + /** + * @OneToMany(targetEntity=GH6830Board::class, mappedBy="category") + */ + public $boards; +} diff --git a/tests/Doctrine/Tests/ORM/Tools/SchemaValidatorTest.php b/tests/Doctrine/Tests/ORM/Tools/SchemaValidatorTest.php index a17d92e7f98..682ee896d1a 100644 --- a/tests/Doctrine/Tests/ORM/Tools/SchemaValidatorTest.php +++ b/tests/Doctrine/Tests/ORM/Tools/SchemaValidatorTest.php @@ -24,52 +24,28 @@ public function setUp() $this->validator = new SchemaValidator($this->em); } - public function testCmsModelSet() - { - $this->em->getConfiguration()->getMetadataDriverImpl()->addPaths(array( - __DIR__ . "/../../Models/CMS" - )); - $this->validator->validateMapping(); - } - - public function testCompanyModelSet() - { - $this->em->getConfiguration()->getMetadataDriverImpl()->addPaths(array( - __DIR__ . "/../../Models/Company" - )); - $this->validator->validateMapping(); - } - - public function testECommerceModelSet() - { - $this->em->getConfiguration()->getMetadataDriverImpl()->addPaths(array( - __DIR__ . "/../../Models/ECommerce" - )); - $this->validator->validateMapping(); - } - - public function testForumModelSet() + /** + * @dataProvider modelSetProvider + */ + public function testCmsModelSet(string $path) { - $this->em->getConfiguration()->getMetadataDriverImpl()->addPaths(array( - __DIR__ . "/../../Models/Forum" - )); - $this->validator->validateMapping(); - } + $this->em->getConfiguration() + ->getMetadataDriverImpl() + ->addPaths([$path]); - public function testNavigationModelSet() - { - $this->em->getConfiguration()->getMetadataDriverImpl()->addPaths(array( - __DIR__ . "/../../Models/Navigation" - )); - $this->validator->validateMapping(); + self::assertEmpty($this->validator->validateMapping()); } - public function testRoutingModelSet() + public function modelSetProvider(): array { - $this->em->getConfiguration()->getMetadataDriverImpl()->addPaths(array( - __DIR__ . "/../../Models/Routing" - )); - $this->validator->validateMapping(); + return [ + 'cms' => [__DIR__ . '/../../Models/CMS'], + 'company' => [__DIR__ . '/../../Models/Company'], + 'ecommerce' => [__DIR__ . '/../../Models/ECommerce'], + 'forum' => [__DIR__ . '/../../Models/Forum'], + 'navigation' => [__DIR__ . '/../../Models/Navigation'], + 'routing' => [__DIR__ . '/../../Models/Routing'], + ]; } /** @@ -77,16 +53,16 @@ public function testRoutingModelSet() */ public function testInvalidManyToManyJoinColumnSchema() { - $class1 = $this->em->getClassMetadata(__NAMESPACE__ . '\InvalidEntity1'); - $class2 = $this->em->getClassMetadata(__NAMESPACE__ . '\InvalidEntity2'); + $class1 = $this->em->getClassMetadata(InvalidEntity1::class); + $class2 = $this->em->getClassMetadata(InvalidEntity2::class); $ce = $this->validator->validateClass($class1); $this->assertEquals( - array( + [ "The inverse join columns of the many-to-many table 'Entity1Entity2' have to contain to ALL identifier columns of the target entity 'Doctrine\Tests\ORM\Tools\InvalidEntity2', however 'key4' are missing.", "The join columns of the many-to-many table 'Entity1Entity2' have to contain to ALL identifier columns of the source entity 'Doctrine\Tests\ORM\Tools\InvalidEntity1', however 'key2' are missing." - ), + ], $ce ); } @@ -96,16 +72,16 @@ public function testInvalidManyToManyJoinColumnSchema() */ public function testInvalidToOneJoinColumnSchema() { - $class1 = $this->em->getClassMetadata(__NAMESPACE__ . '\InvalidEntity1'); - $class2 = $this->em->getClassMetadata(__NAMESPACE__ . '\InvalidEntity2'); + $class1 = $this->em->getClassMetadata(InvalidEntity1::class); + $class2 = $this->em->getClassMetadata(InvalidEntity2::class); $ce = $this->validator->validateClass($class2); $this->assertEquals( - array( + [ "The referenced column name 'id' has to be a primary key column on the target entity class 'Doctrine\Tests\ORM\Tools\InvalidEntity1'.", "The join columns of the association 'assoc' have to match to ALL identifier columns of the target entity 'Doctrine\Tests\ORM\Tools\InvalidEntity1', however 'key1, key2' are missing." - ), + ], $ce ); } @@ -115,12 +91,12 @@ public function testInvalidToOneJoinColumnSchema() */ public function testValidOneToOneAsIdentifierSchema() { - $class1 = $this->em->getClassMetadata(__NAMESPACE__ . '\DDC1587ValidEntity2'); - $class2 = $this->em->getClassMetadata(__NAMESPACE__ . '\DDC1587ValidEntity1'); + $class1 = $this->em->getClassMetadata(DDC1587ValidEntity2::class); + $class2 = $this->em->getClassMetadata(DDC1587ValidEntity1::class); $ce = $this->validator->validateClass($class1); - $this->assertEquals(array(), $ce); + $this->assertEquals([], $ce); } /** @@ -128,13 +104,14 @@ public function testValidOneToOneAsIdentifierSchema() */ public function testInvalidTripleAssociationAsKeyMapping() { - $classThree = $this->em->getClassMetadata(__NAMESPACE__ . '\DDC1649Three'); + $classThree = $this->em->getClassMetadata(DDC1649Three::class); $ce = $this->validator->validateClass($classThree); - $this->assertEquals(Array( + $this->assertEquals( + [ "Cannot map association 'Doctrine\Tests\ORM\Tools\DDC1649Three#two as identifier, because the target entity 'Doctrine\Tests\ORM\Tools\DDC1649Two' also maps an association as identifier.", "The referenced column name 'id' has to be a primary key column on the target entity class 'Doctrine\Tests\ORM\Tools\DDC1649Two'." - ), $ce); + ], $ce); } /** @@ -142,15 +119,15 @@ public function testInvalidTripleAssociationAsKeyMapping() */ public function testInvalidBiDirectionalRelationMappingMissingInversedByAttribute() { - $class = $this->em->getClassMetadata(__NAMESPACE__ . '\DDC3274One'); + $class = $this->em->getClassMetadata(DDC3274One::class); $ce = $this->validator->validateClass($class); $this->assertEquals( - array( + [ "The field Doctrine\Tests\ORM\Tools\DDC3274One#two is on the inverse side of a bi-directional " . "relationship, but the specified mappedBy association on the target-entity " . "Doctrine\Tests\ORM\Tools\DDC3274Two#one does not contain the required 'inversedBy=\"two\"' attribute." - ), + ], $ce ); } @@ -160,14 +137,14 @@ public function testInvalidBiDirectionalRelationMappingMissingInversedByAttribut */ public function testInvalidOrderByInvalidField() { - $class = $this->em->getClassMetadata(__NAMESPACE__ . '\DDC3322One'); + $class = $this->em->getClassMetadata(DDC3322One::class); $ce = $this->validator->validateClass($class); $this->assertEquals( - array( + [ "The association Doctrine\Tests\ORM\Tools\DDC3322One#invalidAssoc is ordered by a foreign field " . "invalidField that is not a field on the target entity Doctrine\Tests\ORM\Tools\DDC3322ValidEntity1." - ), + ], $ce ); } @@ -177,14 +154,14 @@ public function testInvalidOrderByInvalidField() */ public function testInvalidOrderByCollectionValuedAssociation() { - $class = $this->em->getClassMetadata(__NAMESPACE__ . '\DDC3322Two'); + $class = $this->em->getClassMetadata(DDC3322Two::class); $ce = $this->validator->validateClass($class); $this->assertEquals( - array( + [ "The association Doctrine\Tests\ORM\Tools\DDC3322Two#invalidAssoc is ordered by a field oneToMany " . "on Doctrine\Tests\ORM\Tools\DDC3322ValidEntity1 that is a collection-valued association." - ), + ], $ce ); } @@ -194,14 +171,14 @@ public function testInvalidOrderByCollectionValuedAssociation() */ public function testInvalidOrderByAssociationInverseSide() { - $class = $this->em->getClassMetadata(__NAMESPACE__ . '\DDC3322Three'); + $class = $this->em->getClassMetadata(DDC3322Three::class); $ce = $this->validator->validateClass($class); $this->assertEquals( - array( + [ "The association Doctrine\Tests\ORM\Tools\DDC3322Three#invalidAssoc is ordered by a field oneToOneInverse " . "on Doctrine\Tests\ORM\Tools\DDC3322ValidEntity1 that is the inverse side of an association." - ), + ], $ce ); } diff --git a/tests/Doctrine/Tests/ORM/Tools/SetupTest.php b/tests/Doctrine/Tests/ORM/Tools/SetupTest.php index 06ef2a07a90..3678a4cf4ce 100644 --- a/tests/Doctrine/Tests/ORM/Tools/SetupTest.php +++ b/tests/Doctrine/Tests/ORM/Tools/SetupTest.php @@ -2,14 +2,21 @@ namespace Doctrine\Tests\ORM\Tools; -use Doctrine\ORM\Tools\Setup; -use Doctrine\Common\Cache\Cache; use Doctrine\Common\Cache\ArrayCache; +use Doctrine\Common\Cache\Cache; +use Doctrine\ORM\Configuration; +use Doctrine\ORM\Mapping\Driver\AnnotationDriver; +use Doctrine\ORM\Mapping\Driver\XmlDriver; +use Doctrine\ORM\Mapping\Driver\YamlDriver; +use Doctrine\ORM\Tools\Setup; use Doctrine\ORM\Version; use Doctrine\Tests\OrmTestCase; +use Doctrine\Tests\VerifyDeprecations; class SetupTest extends OrmTestCase { + use VerifyDeprecations; + private $originalAutoloaderCount; private $originalIncludePath; @@ -31,7 +38,8 @@ public function tearDown() set_include_path($this->originalIncludePath); $loaders = spl_autoload_functions(); - for ($i = 0; $i < count($loaders); $i++) { + $numberOfLoaders = count($loaders); + for ($i = 0; $i < $numberOfLoaders; $i++) { if ($i > $this->originalAutoloaderCount+1) { spl_autoload_unregister($loaders[$i]); } @@ -47,28 +55,66 @@ public function testDirectoryAutoload() public function testAnnotationConfiguration() { - $config = Setup::createAnnotationMetadataConfiguration(array(), true); + $config = Setup::createAnnotationMetadataConfiguration([], true); - $this->assertInstanceOf('Doctrine\ORM\Configuration', $config); + $this->assertInstanceOf(Configuration::class, $config); $this->assertEquals(sys_get_temp_dir(), $config->getProxyDir()); $this->assertEquals('DoctrineProxies', $config->getProxyNamespace()); - $this->assertInstanceOf('Doctrine\ORM\Mapping\Driver\AnnotationDriver', $config->getMetadataDriverImpl()); + $this->assertInstanceOf(AnnotationDriver::class, $config->getMetadataDriverImpl()); } public function testXMLConfiguration() { - $config = Setup::createXMLMetadataConfiguration(array(), true); + $config = Setup::createXMLMetadataConfiguration([], true); - $this->assertInstanceOf('Doctrine\ORM\Configuration', $config); - $this->assertInstanceOf('Doctrine\ORM\Mapping\Driver\XmlDriver', $config->getMetadataDriverImpl()); + $this->assertInstanceOf(Configuration::class, $config); + $this->assertInstanceOf(XmlDriver::class, $config->getMetadataDriverImpl()); } public function testYAMLConfiguration() { - $config = Setup::createYAMLMetadataConfiguration(array(), true); + $config = Setup::createYAMLMetadataConfiguration([], true); + + $this->assertInstanceOf(Configuration::class, $config); + $this->assertInstanceOf(YamlDriver::class, $config->getMetadataDriverImpl()); + $this->assertHasDeprecationMessages(); + } + + /** + * @group 5904 + */ + public function testCacheNamespaceShouldBeGeneratedWhenCacheIsNotGiven() : void + { + $config = Setup::createConfiguration(false, '/foo'); + $cache = $config->getMetadataCacheImpl(); + + self::assertSame('dc2_1effb2475fcfba4f9e8b8a1dbc8f3caf_', $cache->getNamespace()); + } + + /** + * @group 5904 + */ + public function testCacheNamespaceShouldBeGeneratedWhenCacheIsGivenButHasNoNamespace() : void + { + $config = Setup::createConfiguration(false, '/foo', new ArrayCache()); + $cache = $config->getMetadataCacheImpl(); + + self::assertSame('dc2_1effb2475fcfba4f9e8b8a1dbc8f3caf_', $cache->getNamespace()); + } + + /** + * @group 5904 + */ + public function testConfiguredCacheNamespaceShouldBeUsedAsPrefixOfGeneratedNamespace() : void + { + $originalCache = new ArrayCache(); + $originalCache->setNamespace('foo'); + + $config = Setup::createConfiguration(false, '/foo', $originalCache); + $cache = $config->getMetadataCacheImpl(); - $this->assertInstanceOf('Doctrine\ORM\Configuration', $config); - $this->assertInstanceOf('Doctrine\ORM\Mapping\Driver\YamlDriver', $config->getMetadataDriverImpl()); + self::assertSame($originalCache, $cache); + self::assertSame('foo:dc2_1effb2475fcfba4f9e8b8a1dbc8f3caf_', $cache->getNamespace()); } /** @@ -76,7 +122,7 @@ public function testYAMLConfiguration() */ public function testConfigureProxyDir() { - $config = Setup::createAnnotationMetadataConfiguration(array(), true, "/foo"); + $config = Setup::createAnnotationMetadataConfiguration([], true, "/foo"); $this->assertEquals('/foo', $config->getProxyDir()); } @@ -86,7 +132,7 @@ public function testConfigureProxyDir() public function testConfigureCache() { $cache = new ArrayCache(); - $config = Setup::createAnnotationMetadataConfiguration(array(), true, null, $cache); + $config = Setup::createAnnotationMetadataConfiguration([], true, null, $cache); $this->assertSame($cache, $config->getResultCacheImpl()); $this->assertSame($cache, $config->getMetadataCacheImpl()); @@ -99,7 +145,7 @@ public function testConfigureCache() public function testConfigureCacheCustomInstance() { $cache = $this->createMock(Cache::class); - $config = Setup::createConfiguration(array(), true, $cache); + $config = Setup::createConfiguration(true, null, $cache); $this->assertSame($cache, $config->getResultCacheImpl()); $this->assertSame($cache, $config->getMetadataCacheImpl()); diff --git a/tests/Doctrine/Tests/ORM/UnitOfWorkTest.php b/tests/Doctrine/Tests/ORM/UnitOfWorkTest.php index 9b0c6a8f5f4..987b565fa38 100644 --- a/tests/Doctrine/Tests/ORM/UnitOfWorkTest.php +++ b/tests/Doctrine/Tests/ORM/UnitOfWorkTest.php @@ -3,9 +3,13 @@ namespace Doctrine\Tests\ORM; use Doctrine\Common\Collections\ArrayCollection; +use Doctrine\Common\EventManager; use Doctrine\Common\NotifyPropertyChanged; +use Doctrine\Common\Persistence\Event\LifecycleEventArgs; use Doctrine\Common\PropertyChangedListener; +use Doctrine\ORM\Events; use Doctrine\ORM\Mapping\ClassMetadata; +use Doctrine\ORM\ORMInvalidArgumentException; use Doctrine\ORM\UnitOfWork; use Doctrine\Tests\Mocks\ConnectionMock; use Doctrine\Tests\Mocks\DriverMock; @@ -13,6 +17,7 @@ use Doctrine\Tests\Mocks\EntityPersisterMock; use Doctrine\Tests\Mocks\UnitOfWorkMock; use Doctrine\Tests\Models\CMS\CmsPhonenumber; +use Doctrine\Tests\Models\CMS\CmsUser; use Doctrine\Tests\Models\Forum\ForumAvatar; use Doctrine\Tests\Models\Forum\ForumUser; use Doctrine\Tests\Models\GeoNames\City; @@ -46,18 +51,22 @@ class UnitOfWorkTest extends OrmTestCase */ private $_emMock; - protected function setUp() { + /** + * @var EventManager|\PHPUnit_Framework_MockObject_MockObject + */ + private $eventManager; + + protected function setUp() + { parent::setUp(); - $this->_connectionMock = new ConnectionMock(array(), new DriverMock()); - $this->_emMock = EntityManagerMock::create($this->_connectionMock); + $this->_connectionMock = new ConnectionMock([], new DriverMock()); + $this->eventManager = $this->getMockBuilder(EventManager::class)->getMock(); + $this->_emMock = EntityManagerMock::create($this->_connectionMock, null, $this->eventManager); // SUT $this->_unitOfWork = new UnitOfWorkMock($this->_emMock); $this->_emMock->setUnitOfWork($this->_unitOfWork); } - protected function tearDown() { - } - public function testRegisterRemovedOnNewEntityIsIgnored() { $user = new ForumUser(); @@ -73,8 +82,8 @@ public function testRegisterRemovedOnNewEntityIsIgnored() public function testSavingSingleEntityWithIdentityColumnForcesInsert() { // Setup fake persister and id generator for identity generation - $userPersister = new EntityPersisterMock($this->_emMock, $this->_emMock->getClassMetadata('Doctrine\Tests\Models\Forum\ForumUser')); - $this->_unitOfWork->setEntityPersister('Doctrine\Tests\Models\Forum\ForumUser', $userPersister); + $userPersister = new EntityPersisterMock($this->_emMock, $this->_emMock->getClassMetadata(ForumUser::class)); + $this->_unitOfWork->setEntityPersister(ForumUser::class, $userPersister); $userPersister->setMockIdGeneratorType(ClassMetadata::GENERATOR_TYPE_IDENTITY); // Test @@ -113,12 +122,12 @@ public function testCascadedIdentityColumnInsert() { // Setup fake persister and id generator for identity generation //ForumUser - $userPersister = new EntityPersisterMock($this->_emMock, $this->_emMock->getClassMetadata('Doctrine\Tests\Models\Forum\ForumUser')); - $this->_unitOfWork->setEntityPersister('Doctrine\Tests\Models\Forum\ForumUser', $userPersister); + $userPersister = new EntityPersisterMock($this->_emMock, $this->_emMock->getClassMetadata(ForumUser::class)); + $this->_unitOfWork->setEntityPersister(ForumUser::class, $userPersister); $userPersister->setMockIdGeneratorType(ClassMetadata::GENERATOR_TYPE_IDENTITY); // ForumAvatar - $avatarPersister = new EntityPersisterMock($this->_emMock, $this->_emMock->getClassMetadata('Doctrine\Tests\Models\Forum\ForumAvatar')); - $this->_unitOfWork->setEntityPersister('Doctrine\Tests\Models\Forum\ForumAvatar', $avatarPersister); + $avatarPersister = new EntityPersisterMock($this->_emMock, $this->_emMock->getClassMetadata(ForumAvatar::class)); + $this->_unitOfWork->setEntityPersister(ForumAvatar::class, $avatarPersister); $avatarPersister->setMockIdGeneratorType(ClassMetadata::GENERATOR_TYPE_IDENTITY); // Test @@ -144,17 +153,18 @@ public function testCascadedIdentityColumnInsert() public function testChangeTrackingNotify() { - $persister = new EntityPersisterMock($this->_emMock, $this->_emMock->getClassMetadata('Doctrine\Tests\ORM\NotifyChangedEntity')); - $this->_unitOfWork->setEntityPersister('Doctrine\Tests\ORM\NotifyChangedEntity', $persister); - $itemPersister = new EntityPersisterMock($this->_emMock, $this->_emMock->getClassMetadata('Doctrine\Tests\ORM\NotifyChangedRelatedItem')); - $this->_unitOfWork->setEntityPersister('Doctrine\Tests\ORM\NotifyChangedRelatedItem', $itemPersister); + $persister = new EntityPersisterMock($this->_emMock, $this->_emMock->getClassMetadata(NotifyChangedEntity::class)); + $this->_unitOfWork->setEntityPersister(NotifyChangedEntity::class, $persister); + $itemPersister = new EntityPersisterMock($this->_emMock, $this->_emMock->getClassMetadata(NotifyChangedRelatedItem::class)); + $this->_unitOfWork->setEntityPersister(NotifyChangedRelatedItem::class, $itemPersister); $entity = new NotifyChangedEntity; $entity->setData('thedata'); $this->_unitOfWork->persist($entity); $this->_unitOfWork->commit(); - $this->assertEquals(1, count($persister->getInserts())); + $this->assertCount(1, $persister->getInserts()); + $persister->reset(); $this->assertTrue($this->_unitOfWork->isInIdentityMap($entity)); @@ -164,7 +174,7 @@ public function testChangeTrackingNotify() $this->assertTrue($this->_unitOfWork->isScheduledForDirtyCheck($entity)); - $this->assertEquals(array('data' => array('thedata', 'newdata')), $this->_unitOfWork->getEntityChangeSet($entity)); + $this->assertEquals(['data' => ['thedata', 'newdata']], $this->_unitOfWork->getEntityChangeSet($entity)); $item = new NotifyChangedRelatedItem(); $entity->getItems()->add($item); @@ -186,10 +196,45 @@ public function testChangeTrackingNotify() $this->assertTrue($updates[0] === $item); } + public function testChangeTrackingNotifyIndividualCommit() + { + $persister = new EntityPersisterMock($this->_emMock, $this->_emMock->getClassMetadata("Doctrine\Tests\ORM\NotifyChangedEntity")); + $this->_unitOfWork->setEntityPersister('Doctrine\Tests\ORM\NotifyChangedEntity', $persister); + $itemPersister = new EntityPersisterMock($this->_emMock, $this->_emMock->getClassMetadata("Doctrine\Tests\ORM\NotifyChangedRelatedItem")); + $this->_unitOfWork->setEntityPersister('Doctrine\Tests\ORM\NotifyChangedRelatedItem', $itemPersister); + + $entity = new NotifyChangedEntity; + $entity->setData('thedata'); + + $entity2 = new NotifyChangedEntity; + $entity2->setData('thedata'); + + $this->_unitOfWork->persist($entity); + $this->_unitOfWork->persist($entity2); + $this->_unitOfWork->commit($entity); + $this->_unitOfWork->commit(); + + $this->assertEquals(2, count($persister->getInserts())); + + $persister->reset(); + + $this->assertTrue($this->_unitOfWork->isInIdentityMap($entity2)); + + $entity->setData('newdata'); + $entity2->setData('newdata'); + + $this->_unitOfWork->commit($entity); + + $this->assertTrue($this->_unitOfWork->isScheduledForDirtyCheck($entity2)); + $this->assertEquals(array('data' => array('thedata', 'newdata')), $this->_unitOfWork->getEntityChangeSet($entity2)); + $this->assertFalse($this->_unitOfWork->isScheduledForDirtyCheck($entity)); + $this->assertEquals(array(), $this->_unitOfWork->getEntityChangeSet($entity)); + } + public function testGetEntityStateOnVersionedEntityWithAssignedIdentifier() { - $persister = new EntityPersisterMock($this->_emMock, $this->_emMock->getClassMetadata('Doctrine\Tests\ORM\VersionedAssignedIdentifierEntity')); - $this->_unitOfWork->setEntityPersister('Doctrine\Tests\ORM\VersionedAssignedIdentifierEntity', $persister); + $persister = new EntityPersisterMock($this->_emMock, $this->_emMock->getClassMetadata(VersionedAssignedIdentifierEntity::class)); + $this->_unitOfWork->setEntityPersister(VersionedAssignedIdentifierEntity::class, $persister); $e = new VersionedAssignedIdentifierEntity(); $e->id = 42; @@ -199,8 +244,8 @@ public function testGetEntityStateOnVersionedEntityWithAssignedIdentifier() public function testGetEntityStateWithAssignedIdentity() { - $persister = new EntityPersisterMock($this->_emMock, $this->_emMock->getClassMetadata('Doctrine\Tests\Models\CMS\CmsPhonenumber')); - $this->_unitOfWork->setEntityPersister('Doctrine\Tests\Models\CMS\CmsPhonenumber', $persister); + $persister = new EntityPersisterMock($this->_emMock, $this->_emMock->getClassMetadata(CmsPhonenumber::class)); + $this->_unitOfWork->setEntityPersister(CmsPhonenumber::class, $persister); $ph = new CmsPhonenumber(); $ph->phonenumber = '12345'; @@ -211,7 +256,7 @@ public function testGetEntityStateWithAssignedIdentity() $persister->reset(); // if the entity is already managed the exists() check should be skipped - $this->_unitOfWork->registerManaged($ph, array('phonenumber' => '12345'), array()); + $this->_unitOfWork->registerManaged($ph, ['phonenumber' => '12345'], []); $this->assertEquals(UnitOfWork::STATE_MANAGED, $this->_unitOfWork->getEntityState($ph)); $this->assertFalse($persister->isExistsCalled()); $ph2 = new CmsPhonenumber(); @@ -226,9 +271,9 @@ public function testGetEntityStateWithAssignedIdentity() public function testNoUndefinedIndexNoticeOnScheduleForUpdateWithoutChanges() { // Setup fake persister and id generator - $userPersister = new EntityPersisterMock($this->_emMock, $this->_emMock->getClassMetadata('Doctrine\Tests\Models\Forum\ForumUser')); + $userPersister = new EntityPersisterMock($this->_emMock, $this->_emMock->getClassMetadata(ForumUser::class)); $userPersister->setMockIdGeneratorType(ClassMetadata::GENERATOR_TYPE_IDENTITY); - $this->_unitOfWork->setEntityPersister('Doctrine\Tests\Models\Forum\ForumUser', $userPersister); + $this->_unitOfWork->setEntityPersister(ForumUser::class, $userPersister); // Create a test user $user = new ForumUser(); @@ -239,8 +284,12 @@ public function testNoUndefinedIndexNoticeOnScheduleForUpdateWithoutChanges() // Schedule user for update without changes $this->_unitOfWork->scheduleForUpdate($user); + self::assertNotEmpty($this->_unitOfWork->getScheduledEntityUpdates()); + // This commit should not raise an E_NOTICE $this->_unitOfWork->commit(); + + self::assertEmpty($this->_unitOfWork->getScheduledEntityUpdates()); } /** @@ -262,10 +311,10 @@ public function testLockWithoutEntityThrowsException() public function testRejectsPersistenceOfObjectsWithInvalidAssociationValue($invalidValue) { $this->_unitOfWork->setEntityPersister( - 'Doctrine\Tests\Models\Forum\ForumUser', + ForumUser::class, new EntityPersisterMock( $this->_emMock, - $this->_emMock->getClassMetadata('Doctrine\Tests\Models\Forum\ForumUser') + $this->_emMock->getClassMetadata(ForumUser::class) ) ); @@ -287,10 +336,10 @@ public function testRejectsPersistenceOfObjectsWithInvalidAssociationValue($inva */ public function testRejectsChangeSetComputationForObjectsWithInvalidAssociationValue($invalidValue) { - $metadata = $this->_emMock->getClassMetadata('Doctrine\Tests\Models\Forum\ForumUser'); + $metadata = $this->_emMock->getClassMetadata(ForumUser::class); $this->_unitOfWork->setEntityPersister( - 'Doctrine\Tests\Models\Forum\ForumUser', + ForumUser::class, new EntityPersisterMock($this->_emMock, $metadata) ); @@ -315,7 +364,7 @@ public function testRemovedAndRePersistedEntitiesAreInTheIdentityMapAndAreNotGar $entity = new ForumUser(); $entity->id = 123; - $this->_unitOfWork->registerManaged($entity, array('id' => 123), array()); + $this->_unitOfWork->registerManaged($entity, ['id' => 123], []); $this->assertTrue($this->_unitOfWork->isInIdentityMap($entity)); $this->_unitOfWork->remove($entity); @@ -347,6 +396,49 @@ public function testPersistedEntityAndClearManager() $this->assertFalse($this->_unitOfWork->isScheduledForInsert($entity2)); } + /** + * @group #5579 + */ + public function testEntityChangeSetIsNotClearedAfterFlushOnSingleEntity() : void + { + $entity1 = new NotifyChangedEntity; + $entity2 = new NotifyChangedEntity; + + $entity1->setData('thedata'); + $entity2->setData('thedata'); + + $this->_unitOfWork->persist($entity1); + $this->_unitOfWork->persist($entity2); + + $this->_unitOfWork->commit($entity1); + self::assertEmpty($this->_unitOfWork->getEntityChangeSet($entity1)); + self::assertCount(1, $this->_unitOfWork->getEntityChangeSet($entity2)); + } + + /** + * @group #5579 + */ + public function testEntityChangeSetIsNotClearedAfterFlushOnArrayOfEntities() : void + { + $entity1 = new NotifyChangedEntity; + $entity2 = new NotifyChangedEntity; + $entity3 = new NotifyChangedEntity; + + $entity1->setData('thedata'); + $entity2->setData('thedata'); + $entity3->setData('thedata'); + + $this->_unitOfWork->persist($entity1); + $this->_unitOfWork->persist($entity2); + $this->_unitOfWork->persist($entity3); + + $this->_unitOfWork->commit([$entity1, $entity3]); + + self::assertEmpty($this->_unitOfWork->getEntityChangeSet($entity1)); + self::assertEmpty($this->_unitOfWork->getEntityChangeSet($entity3)); + self::assertCount(1, $this->_unitOfWork->getEntityChangeSet($entity2)); + } + /** * Data Provider * @@ -363,6 +455,340 @@ public function invalidAssociationValuesDataProvider() [new ArrayCollection()], ]; } + + /** + * @dataProvider entitiesWithValidIdentifiersProvider + * + * @param object $entity + * @param string $idHash + * + * @return void + */ + public function testAddToIdentityMapValidIdentifiers($entity, $idHash) + { + $this->_unitOfWork->persist($entity); + $this->_unitOfWork->addToIdentityMap($entity); + + self::assertSame($entity, $this->_unitOfWork->getByIdHash($idHash, get_class($entity))); + } + + public function entitiesWithValidIdentifiersProvider() + { + $emptyString = new EntityWithStringIdentifier(); + + $emptyString->id = ''; + + $nonEmptyString = new EntityWithStringIdentifier(); + + $nonEmptyString->id = uniqid('id', true); + + $emptyStrings = new EntityWithCompositeStringIdentifier(); + + $emptyStrings->id1 = ''; + $emptyStrings->id2 = ''; + + $nonEmptyStrings = new EntityWithCompositeStringIdentifier(); + + $nonEmptyStrings->id1 = uniqid('id1', true); + $nonEmptyStrings->id2 = uniqid('id2', true); + + $booleanTrue = new EntityWithBooleanIdentifier(); + + $booleanTrue->id = true; + + $booleanFalse = new EntityWithBooleanIdentifier(); + + $booleanFalse->id = false; + + return [ + 'empty string, single field' => [$emptyString, ''], + 'non-empty string, single field' => [$nonEmptyString, $nonEmptyString->id], + 'empty strings, two fields' => [$emptyStrings, ' '], + 'non-empty strings, two fields' => [$nonEmptyStrings, $nonEmptyStrings->id1 . ' ' . $nonEmptyStrings->id2], + 'boolean true' => [$booleanTrue, '1'], + 'boolean false' => [$booleanFalse, ''], + ]; + } + + public function testRegisteringAManagedInstanceRequiresANonEmptyIdentifier() + { + $this->expectException(ORMInvalidArgumentException::class); + + $this->_unitOfWork->registerManaged(new EntityWithBooleanIdentifier(), [], []); + } + + /** + * @dataProvider entitiesWithInvalidIdentifiersProvider + * + * @param object $entity + * @param array $identifier + * + * @return void + */ + public function testAddToIdentityMapInvalidIdentifiers($entity, array $identifier) + { + $this->expectException(ORMInvalidArgumentException::class); + + $this->_unitOfWork->registerManaged($entity, $identifier, []); + } + + + public function entitiesWithInvalidIdentifiersProvider() + { + $firstNullString = new EntityWithCompositeStringIdentifier(); + + $firstNullString->id2 = uniqid('id2', true); + + $secondNullString = new EntityWithCompositeStringIdentifier(); + + $secondNullString->id1 = uniqid('id1', true); + + return [ + 'null string, single field' => [new EntityWithStringIdentifier(), ['id' => null]], + 'null strings, two fields' => [new EntityWithCompositeStringIdentifier(), ['id1' => null, 'id2' => null]], + 'first null string, two fields' => [$firstNullString, ['id1' => null, 'id2' => $firstNullString->id2]], + 'second null string, two fields' => [$secondNullString, ['id1' => $secondNullString->id1, 'id2' => null]], + ]; + } + + /** + * @group 5689 + * @group 1465 + */ + public function testObjectHashesOfMergedEntitiesAreNotUsedInOriginalEntityDataMap() + { + $user = new CmsUser(); + $user->name = 'ocramius'; + $mergedUser = $this->_unitOfWork->merge($user); + + self::assertSame([], $this->_unitOfWork->getOriginalEntityData($user), 'No original data was stored'); + self::assertSame([], $this->_unitOfWork->getOriginalEntityData($mergedUser), 'No original data was stored'); + + + $user = null; + $mergedUser = null; + + // force garbage collection of $user (frees the used object hashes, which may be recycled) + gc_collect_cycles(); + + $newUser = new CmsUser(); + $newUser->name = 'ocramius'; + + $this->_unitOfWork->persist($newUser); + + self::assertSame([], $this->_unitOfWork->getOriginalEntityData($newUser), 'No original data was stored'); + } + + /** + * @group DDC-1955 + * @group 5570 + * @group 6174 + */ + public function testMergeWithNewEntityWillPersistItAndTriggerPrePersistListenersWithMergedEntityData() + { + $entity = new EntityWithRandomlyGeneratedField(); + + $generatedFieldValue = $entity->generatedField; + + $this + ->eventManager + ->expects(self::any()) + ->method('hasListeners') + ->willReturnCallback(function ($eventName) { + return $eventName === Events::prePersist; + }); + $this + ->eventManager + ->expects(self::once()) + ->method('dispatchEvent') + ->with( + self::anything(), + self::callback(function (LifecycleEventArgs $args) use ($entity, $generatedFieldValue) { + /* @var $object EntityWithRandomlyGeneratedField */ + $object = $args->getObject(); + + self::assertInstanceOf(EntityWithRandomlyGeneratedField::class, $object); + self::assertNotSame($entity, $object); + self::assertSame($generatedFieldValue, $object->generatedField); + + return true; + }) + ); + + /* @var $object EntityWithRandomlyGeneratedField */ + $object = $this->_unitOfWork->merge($entity); + + self::assertNotSame($object, $entity); + self::assertInstanceOf(EntityWithRandomlyGeneratedField::class, $object); + self::assertSame($object->generatedField, $entity->generatedField); + } + + /** + * @group DDC-1955 + * @group 5570 + * @group 6174 + */ + public function testMergeWithExistingEntityWillNotPersistItNorTriggerPrePersistListeners() + { + $persistedEntity = new EntityWithRandomlyGeneratedField(); + $mergedEntity = new EntityWithRandomlyGeneratedField(); + + $mergedEntity->id = $persistedEntity->id; + $mergedEntity->generatedField = random_int( + $persistedEntity->generatedField + 1, + $persistedEntity->generatedField + 1000 + ); + + $this + ->eventManager + ->expects(self::any()) + ->method('hasListeners') + ->willReturnCallback(function ($eventName) { + return $eventName === Events::prePersist; + }); + $this->eventManager->expects(self::never())->method('dispatchEvent'); + + $this->_unitOfWork->registerManaged( + $persistedEntity, + ['id' => $persistedEntity->id], + ['generatedField' => $persistedEntity->generatedField] + ); + + /* @var $merged EntityWithRandomlyGeneratedField */ + $merged = $this->_unitOfWork->merge($mergedEntity); + + self::assertSame($merged, $persistedEntity); + self::assertSame($persistedEntity->generatedField, $mergedEntity->generatedField); + } + + /** + * Unlike next test, this one demonstrates that the problem does + * not necessarily reproduce if all the pieces are being flushed together. + * + * @group DDC-2922 + * @group #1521 + */ + public function testNewAssociatedEntityPersistenceOfNewEntitiesThroughCascadedAssociationsFirst() + { + $persister1 = new EntityPersisterMock($this->_emMock, $this->_emMock->getClassMetadata(CascadePersistedEntity::class)); + $persister2 = new EntityPersisterMock($this->_emMock, $this->_emMock->getClassMetadata(EntityWithCascadingAssociation::class)); + $persister3 = new EntityPersisterMock($this->_emMock, $this->_emMock->getClassMetadata(EntityWithNonCascadingAssociation::class)); + $this->_unitOfWork->setEntityPersister(CascadePersistedEntity::class, $persister1); + $this->_unitOfWork->setEntityPersister(EntityWithCascadingAssociation::class, $persister2); + $this->_unitOfWork->setEntityPersister(EntityWithNonCascadingAssociation::class, $persister3); + + $cascadePersisted = new CascadePersistedEntity(); + $cascading = new EntityWithCascadingAssociation(); + $nonCascading = new EntityWithNonCascadingAssociation(); + + // First we persist and flush a EntityWithCascadingAssociation with + // the cascading association not set. Having the "cascading path" involve + // a non-new object is important to show that the ORM should be considering + // cascades across entity changesets in subsequent flushes. + $cascading->cascaded = $cascadePersisted; + $nonCascading->cascaded = $cascadePersisted; + + $this->_unitOfWork->persist($cascading); + $this->_unitOfWork->persist($nonCascading); + + $this->_unitOfWork->commit(); + + $this->assertCount(1, $persister1->getInserts()); + $this->assertCount(1, $persister2->getInserts()); + $this->assertCount(1, $persister3->getInserts()); + } + + /** + * This test exhibits the bug describe in the ticket, where an object that + * ought to be reachable causes errors. + * + * @group DDC-2922 + * @group #1521 + */ + public function testNewAssociatedEntityPersistenceOfNewEntitiesThroughNonCascadedAssociationsFirst() + { + $persister1 = new EntityPersisterMock($this->_emMock, $this->_emMock->getClassMetadata(CascadePersistedEntity::class)); + $persister2 = new EntityPersisterMock($this->_emMock, $this->_emMock->getClassMetadata(EntityWithCascadingAssociation::class)); + $persister3 = new EntityPersisterMock($this->_emMock, $this->_emMock->getClassMetadata(EntityWithNonCascadingAssociation::class)); + $this->_unitOfWork->setEntityPersister(CascadePersistedEntity::class, $persister1); + $this->_unitOfWork->setEntityPersister(EntityWithCascadingAssociation::class, $persister2); + $this->_unitOfWork->setEntityPersister(EntityWithNonCascadingAssociation::class, $persister3); + + $cascadePersisted = new CascadePersistedEntity(); + $cascading = new EntityWithCascadingAssociation(); + $nonCascading = new EntityWithNonCascadingAssociation(); + + // First we persist and flush a EntityWithCascadingAssociation with + // the cascading association not set. Having the "cascading path" involve + // a non-new object is important to show that the ORM should be considering + // cascades across entity changesets in subsequent flushes. + $cascading->cascaded = null; + + $this->_unitOfWork->persist($cascading); + $this->_unitOfWork->commit(); + + self::assertCount(0, $persister1->getInserts()); + self::assertCount(1, $persister2->getInserts()); + self::assertCount(0, $persister3->getInserts()); + + // Note that we have NOT directly persisted the CascadePersistedEntity, + // and EntityWithNonCascadingAssociation does NOT have a configured + // cascade-persist. + $nonCascading->nonCascaded = $cascadePersisted; + + // However, EntityWithCascadingAssociation *does* have a cascade-persist + // association, which ought to allow us to save the CascadePersistedEntity + // anyway through that connection. + $cascading->cascaded = $cascadePersisted; + + $this->_unitOfWork->persist($nonCascading); + $this->_unitOfWork->commit(); + + self::assertCount(1, $persister1->getInserts()); + self::assertCount(1, $persister2->getInserts()); + self::assertCount(1, $persister3->getInserts()); + } + + + /** + * This test exhibits the bug describe in the ticket, where an object that + * ought to be reachable causes errors. + * + * @group DDC-2922 + * @group #1521 + */ + public function testPreviousDetectedIllegalNewNonCascadedEntitiesAreCleanedUpOnSubsequentCommits() + { + $persister1 = new EntityPersisterMock($this->_emMock, $this->_emMock->getClassMetadata(CascadePersistedEntity::class)); + $persister2 = new EntityPersisterMock($this->_emMock, $this->_emMock->getClassMetadata(EntityWithNonCascadingAssociation::class)); + $this->_unitOfWork->setEntityPersister(CascadePersistedEntity::class, $persister1); + $this->_unitOfWork->setEntityPersister(EntityWithNonCascadingAssociation::class, $persister2); + + $cascadePersisted = new CascadePersistedEntity(); + $nonCascading = new EntityWithNonCascadingAssociation(); + + // We explicitly cause the ORM to detect a non-persisted new entity in the association graph: + $nonCascading->nonCascaded = $cascadePersisted; + + $this->_unitOfWork->persist($nonCascading); + + try { + $this->_unitOfWork->commit(); + + self::fail('An exception was supposed to be raised'); + } catch (ORMInvalidArgumentException $ignored) { + self::assertEmpty($persister1->getInserts()); + self::assertEmpty($persister2->getInserts()); + } + + $this->_unitOfWork->clear(); + $this->_unitOfWork->persist(new CascadePersistedEntity()); + $this->_unitOfWork->commit(); + + // Persistence operations should just recover normally: + self::assertCount(1, $persister1->getInserts()); + self::assertCount(0, $persister2->getInserts()); + } } /** @@ -370,7 +796,7 @@ public function invalidAssociationValuesDataProvider() */ class NotifyChangedEntity implements NotifyPropertyChanged { - private $_listeners = array(); + private $_listeners = []; /** * @Id * @Column(type="integer") @@ -469,3 +895,103 @@ class VersionedAssignedIdentifierEntity */ public $version; } + +/** @Entity */ +class EntityWithStringIdentifier +{ + /** + * @Id @Column(type="string") + * + * @var string|null + */ + public $id; +} + +/** @Entity */ +class EntityWithBooleanIdentifier +{ + /** + * @Id @Column(type="boolean") + * + * @var bool|null + */ + public $id; +} + +/** @Entity */ +class EntityWithCompositeStringIdentifier +{ + /** + * @Id @Column(type="string") + * + * @var string|null + */ + public $id1; + + /** + * @Id @Column(type="string") + * + * @var string|null + */ + public $id2; +} + +/** @Entity */ +class EntityWithRandomlyGeneratedField +{ + /** @Id @Column(type="string") */ + public $id; + + /** + * @Column(type="integer") + */ + public $generatedField; + + public function __construct() + { + $this->id = uniqid('id', true); + $this->generatedField = random_int(0, 100000); + } +} + +/** @Entity */ +class CascadePersistedEntity +{ + /** @Id @Column(type="string") @GeneratedValue(strategy="NONE") */ + private $id; + + public function __construct() + { + $this->id = uniqid(self::class, true); + } +} + +/** @Entity */ +class EntityWithCascadingAssociation +{ + /** @Id @Column(type="string") @GeneratedValue(strategy="NONE") */ + private $id; + + /** @ManyToOne(targetEntity=CascadePersistedEntity::class, cascade={"persist"}) */ + public $cascaded; + + public function __construct() + { + $this->id = uniqid(self::class, true); + } +} + +/** @Entity */ +class EntityWithNonCascadingAssociation +{ + /** @Id @Column(type="string") @GeneratedValue(strategy="NONE") */ + private $id; + + /** @ManyToOne(targetEntity=CascadePersistedEntity::class) */ + public $nonCascaded; + + public function __construct() + { + $this->id = uniqid(self::class, true); + } +} diff --git a/tests/Doctrine/Tests/ORM/Utility/HierarchyDiscriminatorResolverTest.php b/tests/Doctrine/Tests/ORM/Utility/HierarchyDiscriminatorResolverTest.php new file mode 100644 index 00000000000..cffb8cd3b33 --- /dev/null +++ b/tests/Doctrine/Tests/ORM/Utility/HierarchyDiscriminatorResolverTest.php @@ -0,0 +1,56 @@ +name = 'Some\Class\Child\Name'; + $childClassMetadata->discriminatorValue = 'child-discriminator'; + + $classMetadata = new ClassMetadata('Entity'); + $classMetadata->subClasses = [$childClassMetadata->name]; + $classMetadata->name = 'Some\Class\Name'; + $classMetadata->discriminatorValue = 'discriminator'; + + $em = $this->prophesize(EntityManagerInterface::class); + $em->getClassMetadata($classMetadata->name) + ->shouldBeCalled() + ->willReturn($classMetadata); + $em->getClassMetadata($childClassMetadata->name) + ->shouldBeCalled() + ->willReturn($childClassMetadata); + + $discriminators = HierarchyDiscriminatorResolver::resolveDiscriminatorsForClass($classMetadata, $em->reveal()); + + $this->assertCount(2, $discriminators); + $this->assertArrayHasKey($classMetadata->discriminatorValue, $discriminators); + $this->assertArrayHasKey($childClassMetadata->discriminatorValue, $discriminators); + } + + public function testResolveDiscriminatorsForClassWithNoSubclasses() + { + $classMetadata = new ClassMetadata('Entity'); + $classMetadata->subClasses = []; + $classMetadata->name = 'Some\Class\Name'; + $classMetadata->discriminatorValue = 'discriminator'; + + $em = $this->prophesize(EntityManagerInterface::class); + $em->getClassMetadata($classMetadata->name) + ->shouldBeCalled() + ->willReturn($classMetadata); + + $discriminators = HierarchyDiscriminatorResolver::resolveDiscriminatorsForClass($classMetadata, $em->reveal()); + + $this->assertCount(1, $discriminators); + $this->assertArrayHasKey($classMetadata->discriminatorValue, $discriminators); + } +} diff --git a/tests/Doctrine/Tests/ORM/Utility/IdentifierFlattenerTest.php b/tests/Doctrine/Tests/ORM/Utility/IdentifierFlattenerTest.php index dad6ce4b358..86b6503d376 100644 --- a/tests/Doctrine/Tests/ORM/Utility/IdentifierFlattenerTest.php +++ b/tests/Doctrine/Tests/ORM/Utility/IdentifierFlattenerTest.php @@ -36,12 +36,12 @@ protected function setUp() try { $this->_schemaTool->createSchema( - array( - $this->_em->getClassMetadata('Doctrine\Tests\Models\VersionedOneToOne\FirstRelatedEntity'), - $this->_em->getClassMetadata('Doctrine\Tests\Models\VersionedOneToOne\SecondRelatedEntity'), - $this->_em->getClassMetadata('Doctrine\Tests\Models\Cache\Flight'), - $this->_em->getClassMetadata('Doctrine\Tests\Models\Cache\City') - ) + [ + $this->_em->getClassMetadata(FirstRelatedEntity::class), + $this->_em->getClassMetadata(SecondRelatedEntity::class), + $this->_em->getClassMetadata(Flight::class), + $this->_em->getClassMetadata(City::class) + ] ); } catch (ORMException $e) { } @@ -65,10 +65,10 @@ public function testFlattenIdentifierWithOneToOneId() $this->_em->persist($firstRelatedEntity); $this->_em->flush(); - $firstEntity = $this->_em->getRepository('Doctrine\Tests\Models\VersionedOneToOne\FirstRelatedEntity') - ->findOneBy(array('name' => 'Fred')); + $firstEntity = $this->_em->getRepository(FirstRelatedEntity::class) + ->findOneBy(['name' => 'Fred']); - $class = $this->_em->getClassMetadata('Doctrine\Tests\Models\VersionedOneToOne\FirstRelatedEntity'); + $class = $this->_em->getClassMetadata(FirstRelatedEntity::class); $id = $class->getIdentifierValues($firstEntity); @@ -108,7 +108,7 @@ public function testFlattenIdentifierWithMutlipleIds() $this->_em->persist($flight); $this->_em->flush(); - $class = $this->_em->getClassMetadata('Doctrine\Tests\Models\Cache\Flight'); + $class = $this->_em->getClassMetadata(Flight::class); $id = $class->getIdentifierValues($flight); $this->assertCount(2, $id); diff --git a/tests/Doctrine/Tests/OrmFunctionalTestCase.php b/tests/Doctrine/Tests/OrmFunctionalTestCase.php index d18b9496571..93b07447c8c 100644 --- a/tests/Doctrine/Tests/OrmFunctionalTestCase.php +++ b/tests/Doctrine/Tests/OrmFunctionalTestCase.php @@ -3,17 +3,22 @@ namespace Doctrine\Tests; use Doctrine\Common\Cache\ArrayCache; +use Doctrine\Common\Persistence\Mapping\Driver\MappingDriver; +use Doctrine\DBAL\Driver\Connection; use Doctrine\DBAL\Driver\PDOSqlite\Driver as SqliteDriver; use Doctrine\DBAL\Logging\DebugStack; use Doctrine\DBAL\Types\Type; use Doctrine\ORM\Cache\CacheConfiguration; +use Doctrine\ORM\Cache\DefaultCacheFactory; +use Doctrine\ORM\Cache\Logging\StatisticsCacheLogger; use Doctrine\ORM\Configuration; use Doctrine\ORM\EntityManager; use Doctrine\ORM\Tools\DebugUnitOfWorkListener; use Doctrine\ORM\Tools\SchemaTool; +use Doctrine\Tests\DbalTypes\Rot13Type; use Doctrine\Tests\EventListener\CacheMetadataListener; -use Doctrine\ORM\Cache\Logging\StatisticsCacheLogger; -use Doctrine\ORM\Cache\DefaultCacheFactory; +use Doctrine\Tests\Models; +use PHPUnit\Framework\AssertionFailedError; /** * Base testcase class for all functional ORM testcases. @@ -63,239 +68,252 @@ abstract class OrmFunctionalTestCase extends OrmTestCase * * @var array */ - protected $_usedModelSets = array(); + protected $_usedModelSets = []; + + /** + * To be configured by the test that uses result set cache + * + * @var \Doctrine\Common\Cache\Cache|null + */ + protected $resultCacheImpl; /** * Whether the database schema has already been created. * * @var array */ - protected static $_tablesCreated = array(); + protected static $_tablesCreated = []; /** * Array of entity class name to their tables that were created. * * @var array */ - protected static $_entityTablesCreated = array(); + protected static $_entityTablesCreated = []; /** * List of model sets and their classes. * * @var array */ - protected static $_modelSets = array( - 'cms' => array( - 'Doctrine\Tests\Models\CMS\CmsUser', - 'Doctrine\Tests\Models\CMS\CmsPhonenumber', - 'Doctrine\Tests\Models\CMS\CmsAddress', - 'Doctrine\Tests\Models\CMS\CmsEmail', - 'Doctrine\Tests\Models\CMS\CmsGroup', - 'Doctrine\Tests\Models\CMS\CmsTag', - 'Doctrine\Tests\Models\CMS\CmsArticle', - 'Doctrine\Tests\Models\CMS\CmsComment', - ), - 'forum' => array(), - 'company' => array( - 'Doctrine\Tests\Models\Company\CompanyPerson', - 'Doctrine\Tests\Models\Company\CompanyEmployee', - 'Doctrine\Tests\Models\Company\CompanyManager', - 'Doctrine\Tests\Models\Company\CompanyOrganization', - 'Doctrine\Tests\Models\Company\CompanyEvent', - 'Doctrine\Tests\Models\Company\CompanyAuction', - 'Doctrine\Tests\Models\Company\CompanyRaffle', - 'Doctrine\Tests\Models\Company\CompanyCar', - 'Doctrine\Tests\Models\Company\CompanyContract', - ), - 'ecommerce' => array( - 'Doctrine\Tests\Models\ECommerce\ECommerceCart', - 'Doctrine\Tests\Models\ECommerce\ECommerceCustomer', - 'Doctrine\Tests\Models\ECommerce\ECommerceProduct', - 'Doctrine\Tests\Models\ECommerce\ECommerceShipping', - 'Doctrine\Tests\Models\ECommerce\ECommerceFeature', - 'Doctrine\Tests\Models\ECommerce\ECommerceCategory' - ), - 'generic' => array( - 'Doctrine\Tests\Models\Generic\BooleanModel', - 'Doctrine\Tests\Models\Generic\DateTimeModel', - 'Doctrine\Tests\Models\Generic\DecimalModel', - 'Doctrine\Tests\Models\Generic\SerializationModel', - ), - 'routing' => array( - 'Doctrine\Tests\Models\Routing\RoutingLeg', - 'Doctrine\Tests\Models\Routing\RoutingLocation', - 'Doctrine\Tests\Models\Routing\RoutingRoute', - 'Doctrine\Tests\Models\Routing\RoutingRouteBooking', - ), - 'navigation' => array( - 'Doctrine\Tests\Models\Navigation\NavUser', - 'Doctrine\Tests\Models\Navigation\NavCountry', - 'Doctrine\Tests\Models\Navigation\NavPhotos', - 'Doctrine\Tests\Models\Navigation\NavTour', - 'Doctrine\Tests\Models\Navigation\NavPointOfInterest', - ), - 'directorytree' => array( - 'Doctrine\Tests\Models\DirectoryTree\AbstractContentItem', - 'Doctrine\Tests\Models\DirectoryTree\File', - 'Doctrine\Tests\Models\DirectoryTree\Directory', - ), - 'ddc117' => array( - 'Doctrine\Tests\Models\DDC117\DDC117Article', - 'Doctrine\Tests\Models\DDC117\DDC117Reference', - 'Doctrine\Tests\Models\DDC117\DDC117Translation', - 'Doctrine\Tests\Models\DDC117\DDC117ArticleDetails', - 'Doctrine\Tests\Models\DDC117\DDC117ApproveChanges', - 'Doctrine\Tests\Models\DDC117\DDC117Editor', - 'Doctrine\Tests\Models\DDC117\DDC117Link', - ), - 'ddc3699' => array( - 'Doctrine\Tests\Models\DDC3699\DDC3699Parent', - 'Doctrine\Tests\Models\DDC3699\DDC3699RelationOne', - 'Doctrine\Tests\Models\DDC3699\DDC3699RelationMany', - 'Doctrine\Tests\Models\DDC3699\DDC3699Child', - ), - 'stockexchange' => array( - 'Doctrine\Tests\Models\StockExchange\Bond', - 'Doctrine\Tests\Models\StockExchange\Stock', - 'Doctrine\Tests\Models\StockExchange\Market', - ), - 'legacy' => array( - 'Doctrine\Tests\Models\Legacy\LegacyUser', - 'Doctrine\Tests\Models\Legacy\LegacyUserReference', - 'Doctrine\Tests\Models\Legacy\LegacyArticle', - 'Doctrine\Tests\Models\Legacy\LegacyCar', - ), - 'customtype' => array( - 'Doctrine\Tests\Models\CustomType\CustomTypeChild', - 'Doctrine\Tests\Models\CustomType\CustomTypeParent', - 'Doctrine\Tests\Models\CustomType\CustomTypeUpperCase', - ), - 'compositekeyinheritance' => array( - 'Doctrine\Tests\Models\CompositeKeyInheritance\JoinedRootClass', - 'Doctrine\Tests\Models\CompositeKeyInheritance\JoinedChildClass', - 'Doctrine\Tests\Models\CompositeKeyInheritance\SingleRootClass', - 'Doctrine\Tests\Models\CompositeKeyInheritance\SingleChildClass', - ), - 'taxi' => array( - 'Doctrine\Tests\Models\Taxi\PaidRide', - 'Doctrine\Tests\Models\Taxi\Ride', - 'Doctrine\Tests\Models\Taxi\Car', - 'Doctrine\Tests\Models\Taxi\Driver', - ), - 'cache' => array( - 'Doctrine\Tests\Models\Cache\Country', - 'Doctrine\Tests\Models\Cache\State', - 'Doctrine\Tests\Models\Cache\City', - 'Doctrine\Tests\Models\Cache\Traveler', - 'Doctrine\Tests\Models\Cache\TravelerProfileInfo', - 'Doctrine\Tests\Models\Cache\TravelerProfile', - 'Doctrine\Tests\Models\Cache\Travel', - 'Doctrine\Tests\Models\Cache\Attraction', - 'Doctrine\Tests\Models\Cache\Restaurant', - 'Doctrine\Tests\Models\Cache\Beach', - 'Doctrine\Tests\Models\Cache\Bar', - 'Doctrine\Tests\Models\Cache\Flight', - 'Doctrine\Tests\Models\Cache\Token', - 'Doctrine\Tests\Models\Cache\Login', - 'Doctrine\Tests\Models\Cache\Client', - 'Doctrine\Tests\Models\Cache\Person', - 'Doctrine\Tests\Models\Cache\Address', - 'Doctrine\Tests\Models\Cache\Action', - 'Doctrine\Tests\Models\Cache\ComplexAction', - 'Doctrine\Tests\Models\Cache\AttractionInfo', - 'Doctrine\Tests\Models\Cache\AttractionContactInfo', - 'Doctrine\Tests\Models\Cache\AttractionLocationInfo' - ), - 'tweet' => array( - 'Doctrine\Tests\Models\Tweet\User', - 'Doctrine\Tests\Models\Tweet\Tweet', - 'Doctrine\Tests\Models\Tweet\UserList', - ), - 'ddc2504' => array( - 'Doctrine\Tests\Models\DDC2504\DDC2504RootClass', - 'Doctrine\Tests\Models\DDC2504\DDC2504ChildClass', - 'Doctrine\Tests\Models\DDC2504\DDC2504OtherClass', - ), - 'ddc3346' => array( - 'Doctrine\Tests\Models\DDC3346\DDC3346Author', - 'Doctrine\Tests\Models\DDC3346\DDC3346Article', - ), - 'quote' => array( - 'Doctrine\Tests\Models\Quote\Address', - 'Doctrine\Tests\Models\Quote\Group', - 'Doctrine\Tests\Models\Quote\NumericEntity', - 'Doctrine\Tests\Models\Quote\Phone', - 'Doctrine\Tests\Models\Quote\User' - ), - 'vct_onetoone' => array( - 'Doctrine\Tests\Models\ValueConversionType\InversedOneToOneEntity', - 'Doctrine\Tests\Models\ValueConversionType\OwningOneToOneEntity' - ), - 'vct_onetoone_compositeid' => array( - 'Doctrine\Tests\Models\ValueConversionType\InversedOneToOneCompositeIdEntity', - 'Doctrine\Tests\Models\ValueConversionType\OwningOneToOneCompositeIdEntity' - ), - 'vct_onetoone_compositeid_foreignkey' => array( - 'Doctrine\Tests\Models\ValueConversionType\AuxiliaryEntity', - 'Doctrine\Tests\Models\ValueConversionType\InversedOneToOneCompositeIdForeignKeyEntity', - 'Doctrine\Tests\Models\ValueConversionType\OwningOneToOneCompositeIdForeignKeyEntity' - ), - 'vct_onetomany' => array( - 'Doctrine\Tests\Models\ValueConversionType\InversedOneToManyEntity', - 'Doctrine\Tests\Models\ValueConversionType\OwningManyToOneEntity' - ), - 'vct_onetomany_compositeid' => array( - 'Doctrine\Tests\Models\ValueConversionType\InversedOneToManyCompositeIdEntity', - 'Doctrine\Tests\Models\ValueConversionType\OwningManyToOneCompositeIdEntity' - ), - 'vct_onetomany_compositeid_foreignkey' => array( - 'Doctrine\Tests\Models\ValueConversionType\AuxiliaryEntity', - 'Doctrine\Tests\Models\ValueConversionType\InversedOneToManyCompositeIdForeignKeyEntity', - 'Doctrine\Tests\Models\ValueConversionType\OwningManyToOneCompositeIdForeignKeyEntity' - ), - 'vct_onetomany_extralazy' => array( - 'Doctrine\Tests\Models\ValueConversionType\InversedOneToManyExtraLazyEntity', - 'Doctrine\Tests\Models\ValueConversionType\OwningManyToOneExtraLazyEntity' - ), - 'vct_manytomany' => array( - 'Doctrine\Tests\Models\ValueConversionType\InversedManyToManyEntity', - 'Doctrine\Tests\Models\ValueConversionType\OwningManyToManyEntity' - ), - 'vct_manytomany_compositeid' => array( - 'Doctrine\Tests\Models\ValueConversionType\InversedManyToManyCompositeIdEntity', - 'Doctrine\Tests\Models\ValueConversionType\OwningManyToManyCompositeIdEntity' - ), - 'vct_manytomany_compositeid_foreignkey' => array( - 'Doctrine\Tests\Models\ValueConversionType\AuxiliaryEntity', - 'Doctrine\Tests\Models\ValueConversionType\InversedManyToManyCompositeIdForeignKeyEntity', - 'Doctrine\Tests\Models\ValueConversionType\OwningManyToManyCompositeIdForeignKeyEntity' - ), - 'vct_manytomany_extralazy' => array( - 'Doctrine\Tests\Models\ValueConversionType\InversedManyToManyExtraLazyEntity', - 'Doctrine\Tests\Models\ValueConversionType\OwningManyToManyExtraLazyEntity' - ), - 'geonames' => array( - 'Doctrine\Tests\Models\GeoNames\Country', - 'Doctrine\Tests\Models\GeoNames\Admin1', - 'Doctrine\Tests\Models\GeoNames\Admin1AlternateName', - 'Doctrine\Tests\Models\GeoNames\City' - ), - 'custom_id_object_type' => array( - 'Doctrine\Tests\Models\CustomType\CustomIdObjectTypeParent', - 'Doctrine\Tests\Models\CustomType\CustomIdObjectTypeChild', - ), - 'pagination' => array( - 'Doctrine\Tests\Models\Pagination\Company', - 'Doctrine\Tests\Models\Pagination\Logo', - 'Doctrine\Tests\Models\Pagination\Department', - 'Doctrine\Tests\Models\Pagination\User', - 'Doctrine\Tests\Models\Pagination\User1', - ), - 'versioned_many_to_one' => array( - 'Doctrine\Tests\Models\VersionedManyToOne\Category', - 'Doctrine\Tests\Models\VersionedManyToOne\Article', - ), - ); + protected static $_modelSets = [ + 'cms' => [ + Models\CMS\CmsUser::class, + Models\CMS\CmsPhonenumber::class, + Models\CMS\CmsAddress::class, + Models\CMS\CmsEmail::class, + Models\CMS\CmsGroup::class, + Models\CMS\CmsTag::class, + Models\CMS\CmsArticle::class, + Models\CMS\CmsComment::class, + ], + 'company' => [ + Models\Company\CompanyPerson::class, + Models\Company\CompanyEmployee::class, + Models\Company\CompanyManager::class, + Models\Company\CompanyOrganization::class, + Models\Company\CompanyEvent::class, + Models\Company\CompanyAuction::class, + Models\Company\CompanyRaffle::class, + Models\Company\CompanyCar::class, + Models\Company\CompanyContract::class, + ], + 'ecommerce' => [ + Models\ECommerce\ECommerceCart::class, + Models\ECommerce\ECommerceCustomer::class, + Models\ECommerce\ECommerceProduct::class, + Models\ECommerce\ECommerceShipping::class, + Models\ECommerce\ECommerceFeature::class, + Models\ECommerce\ECommerceCategory::class + ], + 'generic' => [ + Models\Generic\BooleanModel::class, + Models\Generic\DateTimeModel::class, + Models\Generic\DecimalModel::class, + Models\Generic\SerializationModel::class, + ], + 'routing' => [ + Models\Routing\RoutingLeg::class, + Models\Routing\RoutingLocation::class, + Models\Routing\RoutingRoute::class, + Models\Routing\RoutingRouteBooking::class, + ], + 'navigation' => [ + Models\Navigation\NavUser::class, + Models\Navigation\NavCountry::class, + Models\Navigation\NavPhotos::class, + Models\Navigation\NavTour::class, + Models\Navigation\NavPointOfInterest::class, + ], + 'directorytree' => [ + Models\DirectoryTree\AbstractContentItem::class, + Models\DirectoryTree\File::class, + Models\DirectoryTree\Directory::class, + ], + 'ddc117' => [ + Models\DDC117\DDC117Article::class, + Models\DDC117\DDC117Reference::class, + Models\DDC117\DDC117Translation::class, + Models\DDC117\DDC117ArticleDetails::class, + Models\DDC117\DDC117ApproveChanges::class, + Models\DDC117\DDC117Editor::class, + Models\DDC117\DDC117Link::class, + ], + 'ddc3699' => [ + Models\DDC3699\DDC3699Parent::class, + Models\DDC3699\DDC3699RelationOne::class, + Models\DDC3699\DDC3699RelationMany::class, + Models\DDC3699\DDC3699Child::class, + ], + 'stockexchange' => [ + Models\StockExchange\Bond::class, + Models\StockExchange\Stock::class, + Models\StockExchange\Market::class, + ], + 'legacy' => [ + Models\Legacy\LegacyUser::class, + Models\Legacy\LegacyUserReference::class, + Models\Legacy\LegacyArticle::class, + Models\Legacy\LegacyCar::class, + ], + 'customtype' => [ + Models\CustomType\CustomTypeChild::class, + Models\CustomType\CustomTypeParent::class, + Models\CustomType\CustomTypeUpperCase::class, + ], + 'compositekeyinheritance' => [ + Models\CompositeKeyInheritance\JoinedRootClass::class, + Models\CompositeKeyInheritance\JoinedChildClass::class, + Models\CompositeKeyInheritance\SingleRootClass::class, + Models\CompositeKeyInheritance\SingleChildClass::class, + ], + 'taxi' => [ + Models\Taxi\PaidRide::class, + Models\Taxi\Ride::class, + Models\Taxi\Car::class, + Models\Taxi\Driver::class, + ], + 'cache' => [ + Models\Cache\Country::class, + Models\Cache\State::class, + Models\Cache\City::class, + Models\Cache\Traveler::class, + Models\Cache\TravelerProfileInfo::class, + Models\Cache\TravelerProfile::class, + Models\Cache\Travel::class, + Models\Cache\Attraction::class, + Models\Cache\Restaurant::class, + Models\Cache\Beach::class, + Models\Cache\Bar::class, + Models\Cache\Flight::class, + Models\Cache\Token::class, + Models\Cache\Login::class, + Models\Cache\Client::class, + Models\Cache\Person::class, + Models\Cache\Address::class, + Models\Cache\Action::class, + Models\Cache\ComplexAction::class, + Models\Cache\AttractionInfo::class, + Models\Cache\AttractionContactInfo::class, + Models\Cache\AttractionLocationInfo::class + ], + 'tweet' => [ + Models\Tweet\User::class, + Models\Tweet\Tweet::class, + Models\Tweet\UserList::class, + ], + 'ddc2504' => [ + Models\DDC2504\DDC2504RootClass::class, + Models\DDC2504\DDC2504ChildClass::class, + Models\DDC2504\DDC2504OtherClass::class, + ], + 'ddc3346' => [ + Models\DDC3346\DDC3346Author::class, + Models\DDC3346\DDC3346Article::class, + ], + 'quote' => [ + Models\Quote\Address::class, + Models\Quote\City::class, + Models\Quote\FullAddress::class, + Models\Quote\Group::class, + Models\Quote\NumericEntity::class, + Models\Quote\Phone::class, + Models\Quote\User::class + ], + 'vct_onetoone' => [ + Models\ValueConversionType\InversedOneToOneEntity::class, + Models\ValueConversionType\OwningOneToOneEntity::class + ], + 'vct_onetoone_compositeid' => [ + Models\ValueConversionType\InversedOneToOneCompositeIdEntity::class, + Models\ValueConversionType\OwningOneToOneCompositeIdEntity::class + ], + 'vct_onetoone_compositeid_foreignkey' => [ + Models\ValueConversionType\AuxiliaryEntity::class, + Models\ValueConversionType\InversedOneToOneCompositeIdForeignKeyEntity::class, + Models\ValueConversionType\OwningOneToOneCompositeIdForeignKeyEntity::class + ], + 'vct_onetomany' => [ + Models\ValueConversionType\InversedOneToManyEntity::class, + Models\ValueConversionType\OwningManyToOneEntity::class + ], + 'vct_onetomany_compositeid' => [ + Models\ValueConversionType\InversedOneToManyCompositeIdEntity::class, + Models\ValueConversionType\OwningManyToOneCompositeIdEntity::class + ], + 'vct_onetomany_compositeid_foreignkey' => [ + Models\ValueConversionType\AuxiliaryEntity::class, + Models\ValueConversionType\InversedOneToManyCompositeIdForeignKeyEntity::class, + Models\ValueConversionType\OwningManyToOneCompositeIdForeignKeyEntity::class + ], + 'vct_onetomany_extralazy' => [ + Models\ValueConversionType\InversedOneToManyExtraLazyEntity::class, + Models\ValueConversionType\OwningManyToOneExtraLazyEntity::class + ], + 'vct_manytomany' => [ + Models\ValueConversionType\InversedManyToManyEntity::class, + Models\ValueConversionType\OwningManyToManyEntity::class + ], + 'vct_manytomany_compositeid' => [ + Models\ValueConversionType\InversedManyToManyCompositeIdEntity::class, + Models\ValueConversionType\OwningManyToManyCompositeIdEntity::class + ], + 'vct_manytomany_compositeid_foreignkey' => [ + Models\ValueConversionType\AuxiliaryEntity::class, + Models\ValueConversionType\InversedManyToManyCompositeIdForeignKeyEntity::class, + Models\ValueConversionType\OwningManyToManyCompositeIdForeignKeyEntity::class + ], + 'vct_manytomany_extralazy' => [ + Models\ValueConversionType\InversedManyToManyExtraLazyEntity::class, + Models\ValueConversionType\OwningManyToManyExtraLazyEntity::class + ], + 'geonames' => [ + Models\GeoNames\Country::class, + Models\GeoNames\Admin1::class, + Models\GeoNames\Admin1AlternateName::class, + Models\GeoNames\City::class + ], + 'custom_id_object_type' => [ + Models\CustomType\CustomIdObjectTypeParent::class, + Models\CustomType\CustomIdObjectTypeChild::class, + ], + 'pagination' => [ + Models\Pagination\Company::class, + Models\Pagination\Logo::class, + Models\Pagination\Department::class, + Models\Pagination\User::class, + Models\Pagination\User1::class, + ], + 'versioned_many_to_one' => [ + Models\VersionedManyToOne\Category::class, + Models\VersionedManyToOne\Article::class, + ], + 'issue5989' => [ + Models\Issue5989\Issue5989Person::class, + Models\Issue5989\Issue5989Employee::class, + Models\Issue5989\Issue5989Manager::class, + ], + ]; /** * @param string $setName @@ -323,7 +341,9 @@ protected function tearDown() $platform = $conn->getDatabasePlatform(); - $this->_sqlLoggerStack->enabled = false; + if ($this->_sqlLoggerStack instanceof DebugStack) { + $this->_sqlLoggerStack->enabled = false; + } if (isset($this->_usedModelSets['cms'])) { $conn->executeUpdate('DELETE FROM cms_users_groups'); @@ -460,8 +480,8 @@ protected function tearDown() $conn->executeUpdate('DELETE FROM cache_state'); $conn->executeUpdate('DELETE FROM cache_country'); $conn->executeUpdate('DELETE FROM cache_login'); - $conn->executeUpdate('DELETE FROM cache_complex_action'); $conn->executeUpdate('DELETE FROM cache_token'); + $conn->executeUpdate('DELETE FROM cache_complex_action'); $conn->executeUpdate('DELETE FROM cache_action'); $conn->executeUpdate('DELETE FROM cache_client'); } @@ -471,11 +491,26 @@ protected function tearDown() $conn->executeUpdate('DELETE FROM ddc3346_users'); } + if (isset($this->_usedModelSets['ornemental_orphan_removal'])) { + $conn->executeUpdate('DELETE FROM ornemental_orphan_removal_person'); + $conn->executeUpdate('DELETE FROM ornemental_orphan_removal_phone_number'); + } + if (isset($this->_usedModelSets['quote'])) { - $conn->executeUpdate('DELETE FROM ' . $platform->quoteIdentifier("quote-address")); - $conn->executeUpdate('DELETE FROM ' . $platform->quoteIdentifier("quote-group")); - $conn->executeUpdate('DELETE FROM ' . $platform->quoteIdentifier("quote-phone")); - $conn->executeUpdate('DELETE FROM ' . $platform->quoteIdentifier("quote-user")); + $conn->executeUpdate( + sprintf( + 'UPDATE %s SET %s = NULL', + $platform->quoteIdentifier("quote-address"), + $platform->quoteIdentifier('user-id') + ) + ); + + $conn->executeUpdate('DELETE FROM ' . $platform->quoteIdentifier('quote-users-groups')); + $conn->executeUpdate('DELETE FROM ' . $platform->quoteIdentifier('quote-group')); + $conn->executeUpdate('DELETE FROM ' . $platform->quoteIdentifier('quote-phone')); + $conn->executeUpdate('DELETE FROM ' . $platform->quoteIdentifier('quote-user')); + $conn->executeUpdate('DELETE FROM ' . $platform->quoteIdentifier('quote-address')); + $conn->executeUpdate('DELETE FROM ' . $platform->quoteIdentifier('quote-city')); } if (isset($this->_usedModelSets['vct_onetoone'])) { @@ -563,6 +598,12 @@ protected function tearDown() $conn->executeUpdate('DELETE FROM versioned_many_to_one_category'); } + if (isset($this->_usedModelSets['issue5989'])) { + $conn->executeUpdate('DELETE FROM issue5989_persons'); + $conn->executeUpdate('DELETE FROM issue5989_employees'); + $conn->executeUpdate('DELETE FROM issue5989_managers'); + } + $this->_em->clear(); } @@ -579,7 +620,7 @@ protected function setUpEntitySchema(array $classNames) throw new \RuntimeException("EntityManager not set, you have to call parent::setUp() before invoking this method."); } - $classes = array(); + $classes = []; foreach ($classNames as $className) { if ( ! isset(static::$_entityTablesCreated[$className])) { static::$_entityTablesCreated[$className] = true; @@ -602,18 +643,12 @@ protected function setUp() { $this->setUpDBALTypes(); - $forceCreateTables = false; - if ( ! isset(static::$_sharedConn)) { static::$_sharedConn = TestUtil::getConnection(); - - if (static::$_sharedConn->getDriver() instanceof SqliteDriver) { - $forceCreateTables = true; - } } if (isset($GLOBALS['DOCTRINE_MARK_SQL_LOGS'])) { - if (in_array(static::$_sharedConn->getDatabasePlatform()->getName(), array("mysql", "postgresql"))) { + if (in_array(static::$_sharedConn->getDatabasePlatform()->getName(), ["mysql", "postgresql"])) { static::$_sharedConn->executeQuery('SELECT 1 /*' . get_class($this) . '*/'); } else if (static::$_sharedConn->getDatabasePlatform()->getName() == "oracle") { static::$_sharedConn->executeQuery('SELECT 1 /*' . get_class($this) . '*/ FROM dual'); @@ -625,10 +660,10 @@ protected function setUp() $this->_schemaTool = new SchemaTool($this->_em); } - $classes = array(); + $classes = []; foreach ($this->_usedModelSets as $setName => $bool) { - if ( ! isset(static::$_tablesCreated[$setName])/* || $forceCreateTables*/) { + if ( ! isset(static::$_tablesCreated[$setName])) { foreach (static::$_modelSets[$setName] as $className) { $classes[] = $this->_em->getClassMetadata($className); } @@ -647,12 +682,14 @@ protected function setUp() /** * Gets an EntityManager for testing purposes. * - * @param \Doctrine\ORM\Configuration $config The Configuration to pass to the EntityManager. - * @param \Doctrine\Common\EventManager $eventManager The EventManager to pass to the EntityManager. + * @return EntityManager * - * @return \Doctrine\ORM\EntityManager + * @throws \Doctrine\ORM\ORMException */ - protected function _getEntityManager($config = null, $eventManager = null) { + protected function _getEntityManager( + Connection $connection = null, + MappingDriver $mappingDriver = null + ) { // NOTE: Functional tests use their own shared metadata cache, because // the actual database platform used during execution has effect on some // metadata mapping behaviors (like the choice of the ID generation). @@ -679,6 +716,10 @@ protected function _getEntityManager($config = null, $eventManager = null) { $config->setProxyDir(__DIR__ . '/Proxies'); $config->setProxyNamespace('Doctrine\Tests\Proxies'); + if (null !== $this->resultCacheImpl) { + $config->setResultCacheImpl($this->resultCacheImpl); + } + $enableSecondLevelCache = getenv('ENABLE_SECOND_LEVEL_CACHE'); if ($this->isSecondLevelCacheEnabled || $enableSecondLevelCache) { @@ -701,19 +742,24 @@ protected function _getEntityManager($config = null, $eventManager = null) { $this->isSecondLevelCacheEnabled = true; } - $config->setMetadataDriverImpl($config->newDefaultAnnotationDriver(array( - realpath(__DIR__ . '/Models/Cache'), - realpath(__DIR__ . '/Models/GeoNames') - ), true)); + $config->setMetadataDriverImpl( + $mappingDriver ?? $config->newDefaultAnnotationDriver( + [ + realpath(__DIR__ . '/Models/Cache'), + realpath(__DIR__ . '/Models/GeoNames') + ], + true + ) + ); - $conn = static::$_sharedConn; + $conn = $connection ?: static::$_sharedConn; $conn->getConfiguration()->setSQLLogger($this->_sqlLoggerStack); // get rid of more global state $evm = $conn->getEventManager(); foreach ($evm->getListeners() AS $event => $listeners) { foreach ($listeners AS $listener) { - $evm->removeEventListener(array($event), $listener); + $evm->removeEventListener([$event], $listener); } } @@ -729,31 +775,32 @@ protected function _getEntityManager($config = null, $eventManager = null) { } if (isset($GLOBALS['debug_uow_listener'])) { - $evm->addEventListener(array('onFlush'), new DebugUnitOfWorkListener()); + $evm->addEventListener(['onFlush'], new DebugUnitOfWorkListener()); } return EntityManager::create($conn, $config); } /** - * @param \Exception $e + * @param \Throwable $e * * @return void * - * @throws \Exception + * @throws \Throwable */ - protected function onNotSuccessfulTest($e) + protected function onNotSuccessfulTest(\Throwable $e) { - if ($e instanceof \PHPUnit_Framework_AssertionFailedError) { + if ($e instanceof AssertionFailedError) { throw $e; } if(isset($this->_sqlLoggerStack->queries) && count($this->_sqlLoggerStack->queries)) { $queries = ""; - for($i = count($this->_sqlLoggerStack->queries)-1; $i > max(count($this->_sqlLoggerStack->queries)-25, 0) && isset($this->_sqlLoggerStack->queries[$i]); $i--) { - $query = $this->_sqlLoggerStack->queries[$i]; - $params = array_map(function($p) { if (is_object($p)) return get_class($p); else return "'".$p."'"; }, $query['params'] ?: array()); - $queries .= ($i+1).". SQL: '".$query['sql']."' Params: ".implode(", ", $params).PHP_EOL; + $last25queries = array_slice(array_reverse($this->_sqlLoggerStack->queries, true), 0, 25, true); + foreach ($last25queries as $i => $query) { + $params = array_map(function($p) { if (is_object($p)) return get_class($p); else return var_export($p, true); }, $query['params'] ?: [] + ); + $queries .= $i.". SQL: '".$query['sql']."' Params: ".implode(", ", $params).PHP_EOL; } $trace = $e->getTrace(); @@ -797,9 +844,9 @@ protected function getCurrentQueryCount() protected function setUpDBALTypes() { if (Type::hasType('rot13')) { - Type::overrideType('rot13', 'Doctrine\Tests\DbalTypes\Rot13Type'); + Type::overrideType('rot13', Rot13Type::class); } else { - Type::addType('rot13', 'Doctrine\Tests\DbalTypes\Rot13Type'); + Type::addType('rot13', Rot13Type::class); } } } diff --git a/tests/Doctrine/Tests/OrmTestCase.php b/tests/Doctrine/Tests/OrmTestCase.php index 200f5345011..6fdbe147110 100644 --- a/tests/Doctrine/Tests/OrmTestCase.php +++ b/tests/Doctrine/Tests/OrmTestCase.php @@ -10,6 +10,7 @@ use Doctrine\ORM\Cache\DefaultCacheFactory; use Doctrine\ORM\Configuration; use Doctrine\ORM\Mapping\Driver\AnnotationDriver; +use Doctrine\Tests\Mocks; use Doctrine\Tests\Mocks\EntityManagerMock; /** @@ -62,7 +63,7 @@ abstract class OrmTestCase extends DoctrineTestCase * * @return \Doctrine\ORM\Mapping\Driver\AnnotationDriver */ - protected function createAnnotationDriver($paths = array(), $alias = null) + protected function createAnnotationDriver($paths = [], $alias = null) { if (version_compare(Version::VERSION, '3.0.0', '>=')) { $reader = new Annotations\CachedReader(new Annotations\AnnotationReader(), new ArrayCache()); @@ -113,10 +114,8 @@ protected function createAnnotationDriver($paths = array(), $alias = null) * @param mixed $conf * @param \Doctrine\Common\EventManager|null $eventManager * @param bool $withSharedMetadata - * - * @return \Doctrine\ORM\EntityManager */ - protected function _getTestEntityManager($conn = null, $conf = null, $eventManager = null, $withSharedMetadata = true) + protected function _getTestEntityManager($conn = null, $conf = null, $eventManager = null, $withSharedMetadata = true) : EntityManagerMock { $metadataCache = $withSharedMetadata ? self::getSharedMetadataCacheImpl() @@ -125,13 +124,14 @@ protected function _getTestEntityManager($conn = null, $conf = null, $eventManag $config = new Configuration(); $config->setMetadataCacheImpl($metadataCache); - $config->setMetadataDriverImpl($config->newDefaultAnnotationDriver(array(), true)); + $config->setMetadataDriverImpl($config->newDefaultAnnotationDriver([], true)); $config->setQueryCacheImpl(self::getSharedQueryCacheImpl()); $config->setProxyDir(__DIR__ . '/Proxies'); $config->setProxyNamespace('Doctrine\Tests\Proxies'); - $config->setMetadataDriverImpl($config->newDefaultAnnotationDriver(array( + $config->setMetadataDriverImpl($config->newDefaultAnnotationDriver( + [ realpath(__DIR__ . '/Models/Cache') - ), true)); + ], true)); if ($this->isSecondLevelCacheEnabled) { @@ -147,12 +147,12 @@ protected function _getTestEntityManager($conn = null, $conf = null, $eventManag } if ($conn === null) { - $conn = array( - 'driverClass' => 'Doctrine\Tests\Mocks\DriverMock', - 'wrapperClass' => 'Doctrine\Tests\Mocks\ConnectionMock', + $conn = [ + 'driverClass' => Mocks\DriverMock::class, + 'wrapperClass' => Mocks\ConnectionMock::class, 'user' => 'john', 'password' => 'wayne' - ); + ]; } if (is_array($conn)) { diff --git a/tests/Doctrine/Tests/TestUtil.php b/tests/Doctrine/Tests/TestUtil.php index 8a830f7243e..812961c92e9 100644 --- a/tests/Doctrine/Tests/TestUtil.php +++ b/tests/Doctrine/Tests/TestUtil.php @@ -125,10 +125,10 @@ private static function getSpecifiedConnectionParams() private static function getFallbackConnectionParams() { - $params = array( + $params = [ 'driver' => 'pdo_sqlite', 'memory' => true - ); + ]; if (isset($GLOBALS['db_path'])) { $params['path'] = $GLOBALS['db_path']; @@ -151,14 +151,14 @@ private static function addDbEventSubscribers(Connection $conn) private static function getParamsForTemporaryConnection() { - $connectionParams = array( + $connectionParams = [ 'driver' => $GLOBALS['tmpdb_type'], 'user' => $GLOBALS['tmpdb_username'], 'password' => $GLOBALS['tmpdb_password'], 'host' => $GLOBALS['tmpdb_host'], 'dbname' => null, 'port' => $GLOBALS['tmpdb_port'] - ); + ]; if (isset($GLOBALS['tmpdb_name'])) { $connectionParams['dbname'] = $GLOBALS['tmpdb_name']; @@ -177,14 +177,14 @@ private static function getParamsForTemporaryConnection() private static function getParamsForMainConnection() { - $connectionParams = array( + $connectionParams = [ 'driver' => $GLOBALS['db_type'], 'user' => $GLOBALS['db_username'], 'password' => $GLOBALS['db_password'], 'host' => $GLOBALS['db_host'], 'dbname' => $GLOBALS['db_name'], 'port' => $GLOBALS['db_port'] - ); + ]; if (isset($GLOBALS['db_server'])) { $connectionParams['server'] = $GLOBALS['db_server']; diff --git a/tests/Doctrine/Tests/VerifyDeprecations.php b/tests/Doctrine/Tests/VerifyDeprecations.php new file mode 100644 index 00000000000..8ccd9472e64 --- /dev/null +++ b/tests/Doctrine/Tests/VerifyDeprecations.php @@ -0,0 +1,69 @@ +actualDeprecations = []; + $this->expectedDeprecations = []; + + $this->originalHandler = set_error_handler( + function (int $errorNumber, string $errorMessage) : void { + $this->actualDeprecations[] = $errorMessage; + }, + E_USER_DEPRECATED + ); + } + + /** @after */ + public function resetErrorHandler() : void + { + set_error_handler($this->originalHandler, E_USER_DEPRECATED); + $this->originalHandler = null; + } + + /** @after */ + public function validateDeprecationExpectations() : void + { + if ($this->expectedDeprecations === []) { + return; + } + + self::assertSame( + $this->expectedDeprecations, + $this->actualDeprecations, + 'Triggered deprecation messages do not match with expected ones.' + ); + } + + protected function expectDeprecationMessage(string $message) : void + { + $this->expectedDeprecations[] = $message; + } + + protected function assertHasDeprecationMessages() : void + { + self::assertNotSame([], $this->actualDeprecations, 'Failed asserting that test has triggered deprecation messages.'); + } + + protected function assertNotHasDeprecationMessages() : void + { + self::assertSame([], $this->actualDeprecations, 'Failed asserting that test has not triggered deprecation messages.'); + } +} diff --git a/tests/README.markdown b/tests/README.markdown index c1027acedd3..5b8fb05b65a 100644 --- a/tests/README.markdown +++ b/tests/README.markdown @@ -1,8 +1,25 @@ -# Running the Doctrine 2 Testsuite +# Running the Doctrine ORM Testsuite -## Setting up a PHPUnit Configuration XML +To execute the ORM testsuite, you just need to execute this simple steps: -.. + * Clone the project from GitHub + * Enter the ORM folder + * Install the dependencies + * Execute the tests + + All this is (normally) done with: + + git clone git@github.com:doctrine/orm.git + cd orm + composer install + ./vendor/bin/phpunit + +## Pre-requisites +Doctrine2 works on many database vendors; the tests can detect the presence of installed vendors, but you need at least one of those; the easier to install is SQLite. + +If you're using Debian, or a Debian-derivate Linux distribution (like Ubuntu), you can install SQLite with: + + sudo apt-get install sqlite ## Testing Lock-Support @@ -14,7 +31,7 @@ Install Gearman with PHP as follows: 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: +You can then go into `tests/` and start up two workers: php Doctrine/Tests/ORM/Functional/Locking/LockAgentWorker.php @@ -22,4 +39,4 @@ 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. \ No newline at end of file +This can run considerable time, because it is using sleep() to test for the timing ranges of locks. diff --git a/tests/travis/install-mysql-5.7.sh b/tests/travis/install-mysql-5.7.sh new file mode 100755 index 00000000000..9dbd6edfd2f --- /dev/null +++ b/tests/travis/install-mysql-5.7.sh @@ -0,0 +1,8 @@ +#!/usr/bin/env bash + +set -ex + +echo "Restart mysql..." +sudo mysql -e "use mysql; update user set authentication_string=PASSWORD('') where User='root'; update user set plugin='mysql_native_password';FLUSH PRIVILEGES;" +sudo mysql_upgrade -u root +sudo service mysql restart diff --git a/tests/travis/mariadb.travis.xml b/tests/travis/mariadb.travis.xml index bac3fa48060..d4a3fef40cf 100644 --- a/tests/travis/mariadb.travis.xml +++ b/tests/travis/mariadb.travis.xml @@ -1,5 +1,11 @@ - + @@ -13,6 +19,8 @@ + + diff --git a/tests/travis/mysql.travis.xml b/tests/travis/mysql.travis.xml index bac3fa48060..d4a3fef40cf 100644 --- a/tests/travis/mysql.travis.xml +++ b/tests/travis/mysql.travis.xml @@ -1,5 +1,11 @@ - + @@ -13,6 +19,8 @@ + + diff --git a/tests/travis/pgsql.travis.xml b/tests/travis/pgsql.travis.xml index d1a0a49f274..d429084476f 100644 --- a/tests/travis/pgsql.travis.xml +++ b/tests/travis/pgsql.travis.xml @@ -1,5 +1,11 @@ - + @@ -16,6 +22,8 @@ + + diff --git a/tests/travis/sqlite.travis.xml b/tests/travis/sqlite.travis.xml index f9b3ef1f322..b783a34ffa8 100644 --- a/tests/travis/sqlite.travis.xml +++ b/tests/travis/sqlite.travis.xml @@ -1,5 +1,14 @@ - + + + + diff --git a/tools/sandbox/bootstrap.php b/tools/sandbox/bootstrap.php index 1e7d8ba000d..410ea7f72e3 100644 --- a/tools/sandbox/bootstrap.php +++ b/tools/sandbox/bootstrap.php @@ -19,7 +19,7 @@ $config = new \Doctrine\ORM\Configuration(); // Set up Metadata Drivers -$driverImpl = $config->newDefaultAnnotationDriver(array(__DIR__ . "/Entities")); +$driverImpl = $config->newDefaultAnnotationDriver([__DIR__ . "/Entities"]); $config->setMetadataDriverImpl($driverImpl); // Set up caches, depending on $debug variable. @@ -33,10 +33,10 @@ $config->setProxyNamespace('Proxies'); // Database connection information -$connectionOptions = array( +$connectionOptions = [ 'driver' => 'pdo_sqlite', 'path' => 'database.sqlite' -); +]; // Enable second-level cache $cacheConfig = new \Doctrine\ORM\Cache\CacheConfiguration(); @@ -52,4 +52,4 @@ $config->setSecondLevelCacheEnabled(true); $config->setSecondLevelCacheConfiguration($cacheConfig); -return EntityManager::create($connectionOptions, $config); \ No newline at end of file +return EntityManager::create($connectionOptions, $config); diff --git a/tools/sandbox/doctrine.php b/tools/sandbox/doctrine.php index 052968690ef..04c99e327b9 100644 --- a/tools/sandbox/doctrine.php +++ b/tools/sandbox/doctrine.php @@ -5,12 +5,15 @@ $cli = new \Symfony\Component\Console\Application('Doctrine Command Line Interface', Doctrine\Common\Version::VERSION); $cli->setCatchExceptions(true); -$cli->setHelperSet(new Symfony\Component\Console\Helper\HelperSet(array( - 'db' => new \Doctrine\DBAL\Tools\Console\Helper\ConnectionHelper($em->getConnection()), - 'em' => new \Doctrine\ORM\Tools\Console\Helper\EntityManagerHelper($em) -))); +$cli->setHelperSet(new Symfony\Component\Console\Helper\HelperSet( + [ + 'db' => new \Doctrine\DBAL\Tools\Console\Helper\ConnectionHelper($em->getConnection()), + 'em' => new \Doctrine\ORM\Tools\Console\Helper\EntityManagerHelper($em) + ] +)); -$cli->addCommands(array( +$cli->addCommands( + [ // DBAL Commands new \Doctrine\DBAL\Tools\Console\Command\RunSqlCommand(), new \Doctrine\DBAL\Tools\Console\Command\ImportCommand(), @@ -34,5 +37,6 @@ new \Doctrine\ORM\Tools\Console\Command\RunDqlCommand(), new \Doctrine\ORM\Tools\Console\Command\ValidateSchemaCommand(), -)); + ] +); $cli->run(); diff --git a/tools/sandbox/xml/Entities.Address.dcm.xml b/tools/sandbox/xml/Entities.Address.dcm.xml index 7e8dd018340..92475ed233d 100644 --- a/tools/sandbox/xml/Entities.Address.dcm.xml +++ b/tools/sandbox/xml/Entities.Address.dcm.xml @@ -2,7 +2,7 @@ + https://www.doctrine-project.org/schemas/orm/doctrine-mapping.xsd"> diff --git a/tools/sandbox/xml/Entities.User.dcm.xml b/tools/sandbox/xml/Entities.User.dcm.xml index e548fd1a77c..4fe7e4c4af0 100644 --- a/tools/sandbox/xml/Entities.User.dcm.xml +++ b/tools/sandbox/xml/Entities.User.dcm.xml @@ -2,7 +2,7 @@ + https://www.doctrine-project.org/schemas/orm/doctrine-mapping.xsd">