Compare commits

...

327 Commits
2.8.1 ... 2.9.2

Author SHA1 Message Date
Yup
75b4b88c5b Add automatic type detection for Embedded. (#8724)
* Add automatic type detection for Embedded.

* Inline statement.

Co-authored-by: Benjamin Eberlei <kontakt@beberlei.de>
2021-05-31 11:53:14 +02:00
Benjamin Eberlei
d9e59d6862 [GH-8723] Remove use of nullability to automatically detect nullable status (#8732)
* [GH-8723] Remove use of nullability to automatically detect nullable status.

* [GH-8723] Make Column::$nullable default to false again, fix tests.
2021-05-31 10:19:16 +02:00
Yup
5fa94969de Adapt flush($argument) in documentation as it's deprecated. (#8728) 2021-05-29 22:22:19 +02:00
Juan Iglesias
f2c3ddac97 Add note about performance and inheritance mapping (#8704)
Co-authored-by: Claudio Zizza <859964+SenseException@users.noreply.github.com>
2021-05-27 08:27:55 +02:00
Grégoire Paris
46f0da9ffa Merge pull request #8710 from franmomu/recompute
Handle generic parameters in UnitOfWork
2021-05-25 13:29:21 +02:00
Fran Moreno
1e832a6782 Add generics to parameters 2021-05-25 13:01:47 +02:00
Grégoire Paris
56bdb44efd Merge pull request #8722 from alcaeus/fix-metadata-cache-clear 2021-05-25 12:55:00 +02:00
Andreas Braun
fffac44991 Bump doctrine/cache patch dependency to fix build with lowest deps 2021-05-25 11:58:11 +02:00
Andreas Braun
e42b3d6584 Fix metadata cache compatibility layer 2021-05-25 10:38:00 +02:00
Grégoire Paris
7ab2c3abbd Merge pull request #8708 from VincentLanglet/patch-2
Fix ClassMetadaInfo template inference
2021-05-25 08:49:50 +02:00
Grégoire Paris
498c816b65 Merge pull request #8717 from greg0ire/update-branch-metadata
Mark 2.8.x as unmaintained, and 2.9.x as current
2021-05-25 00:01:21 +02:00
Vincent Langlet
eec740079d Fix ClassMetadataInfo template inference 2021-05-24 21:52:40 +02:00
Grégoire Paris
c359715a97 Mark 2.8.x as unmaintained, and 2.9.x as current 2021-05-24 21:32:26 +02:00
Benjamin Eberlei
f3e55fae9f Update .doctrine-project.json to include 2.9 stable and 2.10 upcoming 2021-05-24 17:54:12 +02:00
Michael Babker
91c3bd4121 Fix links to attribute sections (#8714) 2021-05-24 17:52:30 +02:00
Peter Gribanov
e6cf12c66f remove usage Webmozart (#8713) 2021-05-24 17:50:15 +02:00
Grégoire Paris
99d67cb77d Merge pull request #8705 from greg0ire/2.9.x
Merge 2.8.x into 2.9.x
2021-05-21 09:15:28 +02:00
Grégoire Paris
43f66d5808 Merge remote-tracking branch 'origin/2.8.x' into 2.9.x 2021-05-21 09:04:27 +02:00
Grégoire Paris
a6577b89a2 Merge pull request #8701 from jderusse/symfony6
Allow Symfony 6.0
2021-05-20 07:58:49 +02:00
Jérémy Derussé
0ca87566a9 Allow Symfony 6.0 2021-05-20 07:48:21 +02:00
Grégoire Paris
5d01f94a36 Merge pull request #8699 from greg0ire/fix-psalm
Fix some static analysis issues
2021-05-20 07:43:12 +02:00
Grégoire Paris
3d02b02636 Update static analysis baseline files
These issues were not introduced with new code, but with upgrades.
2021-05-20 00:03:39 +02:00
Grégoire Paris
6de321cb09 Address Psalm issues introduced by persistence 2021-05-20 00:03:39 +02:00
Grégoire Paris
535bc92dc8 Merge pull request #8700 from deguif/fix-undefined-offset
Fix undefined index
2021-05-18 12:20:38 +02:00
François-Xavier de Guillebon
ebb5d03f7a Fix undefined offset 2021-05-18 10:00:19 +02:00
Grégoire Paris
8e13369621 Merge pull request #8698 from deguif/cache-deprecation
Fix cache deprecation
2021-05-17 22:15:13 +02:00
François-Xavier de Guillebon
8eff4b775a Fix cache deprecation 2021-05-17 21:33:52 +02:00
Grégoire Paris
b85403d0a2 Merge pull request #8691 from alcaeus/check-deprecations
Check for use of deprecated API with Psalm
2021-05-15 18:50:30 +02:00
Andreas Braun
22ce3adfce Move to psalm level 2
This converts more issues to errors, most notably around deprecations. This can be used to later remove deprecated API.
2021-05-15 17:01:43 +02:00
tweet9ra
3a194ad699 SimpleObjectHydrator: skip unsuit custom type before converting it (#8566)
When using inheritance, it is possible to map the same column to properties of
different child classes. This can result in the same column being selecting several
times with different aliases in one SQL query, and only one aliased field needs
to be hydrated per row.
We now check that such an aliased value is mapped to the class we are hydrated
before attempting to convert it as it might result in an error when using a custom
type that does not get the expected data to initialize php value.

Co-authored-by: Sergey Naumov <s.naumov@lamoda.ru>
2021-05-15 09:37:16 +02:00
Andreas Braun
d52dab54dd Merge pull request #8672 from alcaeus/allow-cache-2.0 2021-05-14 20:21:56 +02:00
Andreas Braun
b5ac7714bc Remove ignored phpstan errors related to doctrine/cache 2.0 2021-05-13 20:38:21 +02:00
Andreas Braun
590551d5c3 Fix setup tool tests 2021-05-13 20:16:52 +02:00
Andreas Braun
c9fb9fdb40 Improve BC layer for getMetadataCacheImpl 2021-05-13 20:16:52 +02:00
Andreas Braun
965926dcc8 Update phpstan baseline to account for doctrine/cache deprecation 2021-05-13 20:16:52 +02:00
Andreas Braun
a6e30c5f4c Fix checkstyle violations 2021-05-13 20:16:52 +02:00
Andreas Braun
30ab6f4cea Add upgrade note for cache changes 2021-05-13 20:16:52 +02:00
Andreas Braun
5e5a44dce2 Suggest using symfony/cache in setup tool 2021-05-13 20:16:52 +02:00
Andreas Braun
d7bf30b291 Fix setup tool tests 2021-05-13 20:16:51 +02:00
Andreas Braun
ce8da6623f Stop using doctrine/cache 2021-05-13 20:16:51 +02:00
Andreas Braun
2ecec0c5d6 Remove reliance on doctrine/cache implementations in tests 2021-05-13 20:16:51 +02:00
Andreas Braun
6f128e4515 Allow installing doctrine/cache 2.0 2021-05-13 20:11:14 +02:00
Benjamin Eberlei
e24b0f0be7 [GH-8589] A new approach to non-nullable typed associations for BC (#8678)
* [GH-8589] A new approach to non-nullable typed associations for BC

* Address review comment about keeping the target entity type detection.
2021-05-10 19:08:16 +02:00
Benjamin Eberlei
6753b26f73 [GH-8676] Allow nested annotations to work without parents as attributes (#8677)
* [GH-8676] Allow nested annotations to work without parents as attributes.

* Housekeeping
2021-05-09 19:58:44 +02:00
Grégoire Paris
4ccc4e19fc Merge pull request #8600 from VincentLanglet/computeChangeset
Remove internal tag from computeChangeSet
2021-05-05 19:27:39 +02:00
Simon Podlipsky
4e2009433b Reflect that default EntityManager is not always named default (#8671)
Follows up #8646
2021-05-05 18:53:34 +02:00
Grégoire Paris
c25b822217 Merge pull request #8673 from Seldaek/patch-1
Add hint for ->iterate() deprecation
2021-05-05 13:31:30 +02:00
Jordi Boggiano
c3dcc5af91 Add hint for ->iterate() deprecation 2021-05-05 10:31:33 +02:00
Grégoire Paris
b2f404b25f Merge pull request #8651 from alcaeus/deprecate-doctrine-metadata-cache
Introduce PSR-6 for metadata caching
2021-05-01 14:53:46 +02:00
Alexandr Li
d141f27875 ConvertDoctrine1Schema: Fix Doctrine 1 notnull field import (#8649)
* ConvertDoctrine1Schema: Fix Doctrine 1 `notnull` field import

* cs fix

Co-authored-by: Grégoire Paris <postmaster@greg0ire.fr>
2021-05-01 13:56:41 +02:00
Andreas Braun
4691839201 Extend DoctrineTestCase to fix missing methods 2021-04-29 12:54:23 +02:00
Andreas Braun
91387382b7 Allow symfony/cache 4.4 to provide PHP 7.1 support 2021-04-29 09:48:27 +02:00
Andreas Braun
f634c64b7a Use stubs over mocks in tests
Co-authored-by: Grégoire Paris <postmaster@greg0ire.fr>
2021-04-29 09:42:18 +02:00
Andreas Braun
7ba9c980b5 Introduce PSR-6 for metadata caching 2021-04-29 09:42:18 +02:00
Grégoire Paris
dacdcf2c7b Merge pull request #8662 from greg0ire/2.9.x
Merge 2.8.x into 2.9.x
2021-04-29 09:27:40 +02:00
Grégoire Paris
f296fee9e4 Merge remote-tracking branch 'origin/2.8.x' into 2.9.x 2021-04-29 09:20:26 +02:00
Grégoire Paris
8555fc1d34 Merge pull request #8659 from greg0ire/make-tests-independent
Make tests independent
2021-04-29 09:07:26 +02:00
Grégoire Paris
b0826fd746 Merge pull request #8201 from oojacoboo/2.8.x
Throw Exception when unable to locate identifier
2021-04-28 15:57:50 +02:00
Jacob Thomason
fe93c2e9d5 Throw Exception that includes name of entity when unable to locate identifier 2021-04-28 15:33:03 +02:00
Grégoire Paris
850d57827f Make tests independent
It seems like IdentityMapTest cannot be run on its own when the second
level cache is enabled (with ENABLE_SECOND_LEVEL_CACHE=1).
It does work when running the whole test suite because
ExtraLazyCollectionTest disables part of that cache in its setUp()
method.
In this patch, we restore the class metadata as it was before running
setUp() and put the test in IdentityMapTest inside the group that is
excluded when running with ENABLE_SECOND_LEVEL_CACHE=1 on the CI.
2021-04-28 14:12:31 +02:00
Benjamin Eberlei
e1388fa986 [GH-8327] Make EntityManagerProvider compatible with expected DoctrineBundle usage (#8646)
* [GH-8327] Make EntityManagerProvider compatible with expected DoctrineBundle usage.

* phpcs

* [Gh-8327] Delegate to EntityManagerProvider::getDefaultManager in ConnectionFromManagerProvider
2021-04-25 19:44:12 +02:00
Grégoire Paris
9a48450481 Merge pull request #7608 from mavroprovato/patch-1
Avoid unnecessary flush after processing first row
2021-04-24 14:23:09 +02:00
Kostas Kokkoros
cff8b96dd6 Avoid unnecessary flush after processing first row
The code as is needlessly flushes after just one row is updated or
removed. It makes more sense to update after ``$batchSize`` elements are
updated or removed, just as it is in the insert case.
2021-04-24 13:01:33 +02:00
Grégoire Paris
996c1c74b3 Merge pull request #8644 from greg0ire/more-accurate-return-type
Describe return types more accurately
2021-04-22 22:31:05 +02:00
Grégoire Paris
48612e6dc6 Merge pull request #8641 from Jean85/remove-deprecated-proxy-usage
Replace deprecated Proxy usages with parent interface to reduce baseline
2021-04-19 23:37:22 +02:00
Benjamin Eberlei
ddfee26f80 Support for Array parameters in SQL filters (#8375)
* #1168 Add support for array parameters on the SQLFilter

* DDC-1168 Add support for array parameters on the SQLFilter

* [GH-2624] Rework array support to use new getParameterList()

* [DDC-1952] Change at() mocking to using returnCallback()

* [DDC-1952] Make arrays of values explicit with new setParameterList

* Adjust tests to use country as list and locale as single value.

* [DDC-1952] Add tests for new exxeption conditions.

* Apply suggestions from code review

Co-authored-by: Grégoire Paris <postmaster@greg0ire.fr>

Co-authored-by: Manuel Nogales <nogales.manuel@gmail.com>
Co-authored-by: Grégoire Paris <postmaster@greg0ire.fr>
2021-04-19 19:46:22 +02:00
Grégoire Paris
eb860a704e Change incorrect DBAL return types 2021-04-19 19:27:00 +02:00
Grégoire Paris
51ffcb4891 Describe return types more accurately
This fixes an SA regression introduced when using stricter types in
SchemaTool.

Fixes #8642
2021-04-19 19:09:10 +02:00
Grégoire Paris
72f500318a Merge pull request #8544 from greg0ire/bc-type-declarations
Add type declarations where backwards-compatible
2021-04-19 14:02:17 +02:00
Grégoire Paris
55f030f66b Add type declarations where backwards-compatible
This includes:
- private methods
- return type declarations of final protected methods
- return type declarations of public and protected methods of final classes

Parameter type declarations are a more delicate matter and should
probably be handled separately to make it easier to catch issues during
code review.

Type declarations can be more trusted than simple phpdoc when it
comes to static analysis, having them means we can infer the phpdoc of
calling methods with confidence.

Note that it seems that some of the phpdoc I initially inferred these
declarations from were apparently wrong, in particular some mentioning
Doctrine\Dbal\Statement when was is really passed around is
Doctrine\Dbal\Driver\Statement.
2021-04-19 13:51:00 +02:00
orklah
95af30eb72 FileLockRegion::__construct 3rd param is meant to be an int (#8640) 2021-04-19 13:29:43 +02:00
Alessandro Lai
9ea0769d78 Replace deprecated Proxy usages with parent interface to reduce baseline 2021-04-19 10:43:49 +02:00
Benjamin Eberlei
22413453da Reintroduce PHP 7.1 support (#8613)
* Reintroduce PHP 7.1 support

* phpcs

* Another object typehint

* More compatibility

* phpcs

* Reduce doctrine/inflector versions again since 1.4.4 is released.

* Housekeeping: phpcbf

* Simplify PHPUnit Polyfill abstraction.

* Missing assertDoesNotMatchRegularExpression

* phpcs

* Add 7.1 on Github actions, since dependencies now supported.

* Simplify code to work with renamed phpunit assertions and document when to remove.

* phpcs

* Downgrade target phpstan version to 7.1.0

* Run --prefer-lowest with PHP 7.1 not 7.3
2021-04-18 21:24:51 +02:00
Grégoire Paris
06fadcdd8c Merge pull request #8630 from Jean85/reduce-baseline
Reduce baseline
2021-04-18 18:50:59 +02:00
Alessandro Lai
7c56aa2141 Reduce baseline with a nullable return where needed 2021-04-18 18:39:20 +02:00
Alessandro Lai
4cdcb5f760 Reduce baseline for AbstractCollectionPersister 2021-04-18 18:39:20 +02:00
Alessandro Lai
b542b36e45 Remove baseline for DefaultCacheFactory 2021-04-18 18:39:20 +02:00
Alessandro Lai
e5a7a13e1e Remove single baseline rule from DefaultCache 2021-04-18 18:39:20 +02:00
Alessandro Lai
8336dd3779 Remove baseline for AbstractQuery 2021-04-18 18:39:14 +02:00
Grégoire Paris
b04d7a62ae Merge pull request #8548 from orklah/test2
Adding details to types in PHPDoc
2021-04-18 18:09:28 +02:00
Grégoire Paris
a959a474fd Merge pull request #8636 from greg0ire/update-gitattributes
Update ignore rules to reflect current situation
2021-04-18 17:56:47 +02:00
Benjamin Eberlei
ce128e742b [GH-5202] Implement Query::HINT_READ_ONLY flag (#7936)
* Rebase QueryHintReadOnly on 2.9.x

* Housekeeping: phpcs

* [GH-5202] Dont mark known entities as read only.

* [GH-5202] Not mark objects read only when proxy before.

* phpcs
2021-04-18 16:45:25 +02:00
Benjamin Eberlei
dac87dae06 [GH-8327] Deprecate EntityManagerHelper for a provider abstraction. (#8524)
* cli config

* [GH-8327] Deprecate EntityManager HelperSet for a provider abstraction.

* Housekeeping: phpcs

* [GH-8327] Refactor tests towards use of SingleManagerProvider instead of HelperSet.

* [GH-8327] Refactor tests towards use of SingleManagerProvider instead of HelperSet.

* [GH-8327] Refactor tests towards use of SingleManagerProvider instead of HelperSet.

* Housekeeping: cs

* Update tests/Doctrine/Tests/ORM/Tools/Console/ConsoleRunnerTest.php

Co-authored-by: Grégoire Paris <postmaster@greg0ire.fr>

* [GH-8327] Change option from entity-manager to em for consistency with DoctrineBundle.

* Add final to new methods and classes

Co-authored-by: Grégoire Paris <postmaster@greg0ire.fr>

* [GH-8327] Bugfix: phpstan detected stricter type checks needed.

* phpcs

Co-authored-by: Grégoire Paris <postmaster@greg0ire.fr>
2021-04-18 14:32:42 +02:00
Jakub Caban
a2230485b2 Fix typed properties for default metadata (#7939) (#8589)
* Make Column::$type, Column::$nullable and JoinColumn::$nullable nullable by default

* Add tests for mapped typed properties (type and nullable)

* Fix Yaml driver tests and remove driver exceptions thrown too early

* Fix PHP driver tests

* Fix static PHP driver tests

* Fix XML driver tests

* Coding Standards

* Deprecate unused MappingException method

* Add manyToOne test and check nullable at the right place

* Coding Standards

* Bugfix: Temporarily change association join columns in CascadeRemoveOrderTest to circumvent new CommitOrderCalculator bug.

* phpcs

Co-authored-by: Benjamin Eberlei <kontakt@beberlei.de>
2021-04-18 14:26:41 +02:00
Benjamin Eberlei
a68aa580c5 [GH-8345] Fields for unique constraints (#8629)
* Add possibility to use fields instead of column for unique constraint and indexes (#8345)

* Document changes in annotation reference

* phpcs

* Ensure exactly one of fields/columns is set for index/uniqueConstraint

* Adapt docs to fields/columns changes

* phpcs

* Implement fields in Attribute driver and fix mapping classes constructors.

* Coding Standard

* Apply suggestions from code review

Co-authored-by: Grégoire Paris <postmaster@greg0ire.fr>

* phpcs

Co-authored-by: Jakub Caban <kuba.iluvatar@gmail.com>
Co-authored-by: Grégoire Paris <postmaster@greg0ire.fr>
2021-04-18 14:06:30 +02:00
Grégoire Paris
5ee71c54d4 Update ignore rules to reflect current situation
We no longer use Travis, we do not use git submodules as far as I know,
and we now use baseline files as well as project metadata.
2021-04-18 10:49:48 +02:00
orklah
dc37c2cd2f psalm fixes 2021-04-17 17:11:04 +02:00
Grégoire Paris
261a405970 Merge pull request #8635 from greg0ire/2.9.x
Manually merge 2.8.x into 2.9.x
2021-04-17 16:42:07 +02:00
Grégoire Paris
1ea51d88c4 Merge remote-tracking branch 'origin/2.8.x' into 2.9.x 2021-04-17 16:31:14 +02:00
Grégoire Paris
da3a9fa361 Merge pull request #8634 from orklah/static-upgrade
upgrade static tools
2021-04-17 15:41:51 +02:00
orklah
4fd81d26ff upgrade static tools 2021-04-17 13:12:35 +02:00
Benjamin Eberlei
f8e06ad31e [GH-6396] Allow custom hydrators access to meta columns via Query::HINT_INCLUDE_META_COLUMNS hint. (#8382) 2021-04-16 21:27:29 +02:00
Grégoire Paris
559c1ba806 Merge pull request #8628 from greg0ire/2.9.x
Merge 2.8.x up into 2.9.x
2021-04-16 20:08:51 +02:00
Grégoire Paris
4665758c44 Merge remote-tracking branch 'origin/2.8.x' into 2.9.x 2021-04-16 19:59:27 +02:00
Grégoire Paris
e2e9f8fa97 Merge pull request #8627 from greg0ire/add-baselines
Add baseline files for static analyzers
2021-04-16 19:04:04 +02:00
Grégoire Paris
f7249ec709 Declare return type
This helps SA tools figure out that it is fine to call count on the
return value of that method.
As a side-effect, using $metadata->name is not really an option since it
is not part of the ClassMetadata interface.
2021-04-16 13:14:54 +02:00
Grégoire Paris
87dbcca454 Add baseline files for static analyzers
There are many CS and SA-related changes in the ORM as we pursue better
code quality, and easier contributions. These often involve huge
changes, which can be hard to review and inevitably lead to some
regressions. I know some of those could have been avoided if we were
using stricter levels for PHPStan and Psalm.

By adding baselines, we ensure new code is at level 5 for both tools,
which should allow us to catch the most interesting issues.
2021-04-16 09:23:11 +02:00
Grégoire Paris
ceeea8ccd1 Merge pull request #8620 from greg0ire/2.9.x
Manually merge 2.8.x into 2.9.x
2021-04-13 19:23:10 +02:00
Grégoire Paris
6e16ef8c31 Merge remote-tracking branch 'origin/2.8.x' into 2.9.x 2021-04-13 18:51:39 +02:00
Grégoire Paris
305e0d6664 Merge pull request #8617 from greg0ire/cs9
Upgrade to doctrine/coding-standard 9
2021-04-13 18:48:12 +02:00
Grégoire Paris
199be94e6d Upgrade to doctrine/coding-standard 9 2021-04-13 09:00:33 +02:00
Benjamin Eberlei
09a7d9f18a [GH-6578] Add validation that inherited entity class is mapped in discriminator. (#8378) 2021-04-10 18:13:31 +02:00
Grégoire Paris
f57f33b67f Merge pull request #8606 from greg0ire/2.9.x 2021-04-09 13:33:34 +02:00
Grégoire Paris
e86cddb360 Merge remote-tracking branch 'origin/2.8.x' into 2.9.x 2021-04-09 13:21:30 +02:00
Grégoire Paris
fa588af3b1 Merge pull request #8604 from janatjak/2.8.x
Fix psalm param typehint for OneToManyAssociationBuilder::setOrderBy method
2021-04-09 12:57:12 +02:00
Grégoire Paris
d4741720fa Merge pull request #8605 from greg0ire/fix-phpdoc-lsp-violations 2021-04-09 11:59:28 +02:00
Grégoire Paris
343385d060 Pin squizlabs/php_codesniffer
We are referencing rules in phpcs.xml.dist, and may experience
unexpected BC-breaks because of that when they get renamed.
2021-04-09 09:27:44 +02:00
Grégoire Paris
6d04dced03 Address sniff rename
This sniff seems to have been renamed or split in the latest version of
phpcs.
2021-04-09 09:19:10 +02:00
Grégoire Paris
22fa3a8556 Document actual return types
Some executors may return integers, for instance executors that only
execute update or delete statements.
Also, in case an integer is not returned, what's actually returned is a
Doctrine\DBAL\Driver\ResultStatement, and not a Doctrine\DBAL\Driver\Statement
2021-04-09 08:52:56 +02:00
Jakub Janata
eb05756dc3 Fix psalm param typehint for OneToManyAssociationBuilder::setOrderBy method 2021-04-08 22:52:50 +02:00
Grégoire Paris
5bb7e20708 Merge pull request #8602 from NicoHaase/fix-8599
Adjusted return type annotation for getOriginalEntityData
2021-04-07 23:22:19 +02:00
Nico Haase
a9076313c7 Adjusted return type 2021-04-07 21:06:58 +02:00
Grégoire Paris
2a87821b28 Merge pull request #8552 from acoulton/maint-phpunit-upgrade 2021-04-07 15:33:06 +02:00
acoulton
da5877d60c Only polyfill older phpunit methods when required 2021-04-07 12:08:55 +01:00
Andrew Coulton
67dfe8e1af Simplify mock building calls
Co-authored-by: Grégoire Paris <postmaster@greg0ire.fr>
2021-04-07 11:07:35 +01:00
Vincent Langlet
2dfe51b396 Remove internal tag 2021-04-07 11:41:34 +02:00
Grégoire Paris
5ac036de02 Merge pull request #8594 from greg0ire/make-sure-test-is-run 2021-04-06 17:47:17 +02:00
Grégoire Paris
fda0d7b440 Merge pull request #8596 from doctrine/2.8.x-merge-up-into-2.9.x_606c485ba431f2.86881997 2021-04-06 15:06:02 +02:00
Grégoire Paris
23e1fd8ad6 Drop assertion about not being an instance of proxy
We do not want to enforce it as it is an internal details that seems to
vary from environment to environment.
2021-04-06 14:55:25 +02:00
Benjamin Eberlei
f8fa0fe069 [GH-8592] Deprecated Named (Native) Queries in Metadata/EntityRepository (#8593)
* [GH-8592] Deprecated Named (Native) Queries in Metadata and EntityRepository.

* [GH-8592] Add deprecation notice for named queries in docs [ci-skip]
2021-04-05 21:59:08 +02:00
Grégoire Paris
a588555ecd Merge pull request #8586 from KartaviK/patch-3
Additional psalm param typehint for orderBy argument in findBy method
2021-04-05 20:38:36 +02:00
Grégoire Paris
501057da83 Ensure test is suffixed with Test 2021-04-05 14:42:17 +02:00
Grégoire Paris
7de84537f6 Merge pull request #8591 from DmitriiBezborodnikov/case_insensive_parenthesis
Return case insensitive check
2021-04-05 14:40:51 +02:00
Grégoire Paris
97f8325dad Make sure tests are suffixed with Test
They will not be taken into account when running vendor/bin/phpunit
otherwise.
2021-04-05 14:32:40 +02:00
Grégoire Paris
0ebd7052d7 Drop create table at shutdown
It makes tests more isolated from each other: another test relying on
some tables including some of the ones created here may fail creating
the tables it needs because they already exist.
2021-04-05 14:03:49 +02:00
Dmitrii Bezborodnikov
5d73378b92 Return case insensitive check 2021-04-05 14:03:49 +02:00
Grégoire Paris
10572ec441 Merge pull request #8590 from VincentLanglet/patch-2
Fix phpdoc of ClassMetadataInfo::getIdentifierValues
2021-04-04 23:47:09 +02:00
Vincent Langlet
76278d801d Fix phpdoc 2021-04-04 21:19:54 +02:00
Roman Varkuta
ca80830b26 Describe $orderBy parameter as a hash
A list of string is incorrect, it actually looks like this:
['someField' => 'DESC', 'someOtherField' => 'ASC'…]`
2021-04-03 12:45:24 +02:00
Grégoire Paris
1ed89c756a Merge pull request #8582 from doctrine/2.8.x-merge-up-into-2.9.x_6066399d9875f8.96494390
Merge release 2.8.3 into 2.9.x
2021-04-02 09:12:58 +02:00
Grégoire Paris
bb078b5cb7 Merge remote-tracking branch 'origin/2.8.x' into 2.8.x-merge-up-into-2.9.x_6066399d9875f8.96494390 2021-04-02 09:00:35 +02:00
Grégoire Paris
bcb4889a2c Merge pull request #8583 from greg0ire/sync-static-analysis-workflows
Synchronize static analysis jobs with upstream
2021-04-02 08:58:50 +02:00
Grégoire Paris
961da8b0cc Synchronize static analysis jobs with upstream 2021-04-01 23:32:04 +02:00
Benjamin Eberlei
657a30f8ce [GH-6394] Bugfix: IdentifierFlattener support for association non-object values. (#8384)
* [GH-6394] Bugfix: IdentifierFlattener support for association non-object values

* [GH-6394] Bugfix: BasicEntityPersister::update used wrong identifiers for version assignment.

* Exclude MissingNativeTypeHint phpcs rule as 7.4 is not lowest version.
2021-04-01 23:16:53 +02:00
Benjamin Eberlei
c3f8996af5 Bump requirement to DBAL 2.13 (#8577) 2021-04-01 21:26:25 +02:00
Grégoire Paris
0655083e50 Merge remote-tracking branch 'origin/2.8.x' into 2.9.x 2021-04-01 09:02:08 +02:00
Grégoire Paris
0b25d4d8b0 Merge pull request #8573 from greg0ire/fix-build
Fix build issues
2021-04-01 07:49:27 +02:00
Grégoire Paris
a88242ee6c Adapt test logic to PHP and SQLite
There seems to be at least 2 camps in the software world when it comes
to the question "What's today minus one month", today being at the end
of march.

While PHP and SQLite agree that that would be the 2nd of March, other
RDBMS than SQLite and humans will tell you that it's the last day of
February.

This patch ensures that we check one logic for SQLite, and the other
logic for other platforms.
2021-03-30 21:08:29 +02:00
Grégoire Paris
fe4964008d Accommodate 2 behaviors of symfony/console in test
Decorated text used to be wrapped too early in SymfonyStyle->block()
See https://github.com/symfony/symfony/pull/40348
The fix was not contributed to version 3, which means we have to rewrite
the test so that it passes for both the correct and the buggy version.
2021-03-30 08:41:10 +02:00
Grégoire Paris
3f3de70c3e Merge pull request #8564 from cybercitizen7/featureIncludeDirectory
Adding DIR to include statement to fix issue with pathing
2021-03-26 19:46:40 +01:00
darkw1z
eb4e317144 Adding DIR to include statement to fix issue with pathing 2021-03-26 14:04:46 +01:00
Grégoire Paris
c8f2f61ea1 Merge pull request #8556 from VincentLanglet/patch-2
Fix fieldMapping phpdoc
2021-03-26 08:26:40 +01:00
Vincent Langlet
c9502d3d0b Fix fieldMapping phpdoc 2021-03-24 15:07:08 +01:00
Benjamin Eberlei
b6b3c97436 [GH-8265] Attribute Metadata Driver (#8266)
* [GH-8265] Prototype for Attribute Metadata Driver

* [GH-8265] Skip AttributeDriverTest on PHP 7.

* [GH-8265] Fill more test entities with Attribute declarations to pass tests.

* [GH-8265] More test entity attributes for passing AttributeDriverTest.

* [GH-8265] Final changes to get AttributeDriverTest passing with test entities.

* [GH-8265] automatically update cs for new code when possible.

* [GH-8265] exclude sniffs that break because of phpcs not knowing attributes.

* [GH-8265] Fix AttributeReader styles.

* [GH-8265] Fix AttributeReader styles.

* [GH-8265] Missing changes to AttributeDriver

* [GH-8265] Fix InverseJoinColumn attribute cs violations.

* [GH-8265] Fix AbstractMappingDriverTest::_loadDriver and other CS

* [GH-8265] Coding styles

* [GH-8265] Coding styles

* [GH-8265] Coding styles

* [GH-8265] Coding styles

* [GH-8265] Convert Cache, ChangeTrackingPolicy, Column to named annotations.

* [GH-8265] Convert all annotations to named constructor for attribute support.

* [GH-8265] Style after attribute changes.

* [GH-8265] more styles

* [GH-8265] Remove workaround code for attributes.

* More cs

* More cs

* More cs

* More cs

* Add Attribute Metadata driver reference.

* Housekeeping: phpcs

* More merge conflict resolutions

* phpcs

* fix broken merge

* Change NamedArgumentConstructorAnnotation interface to use NamedArgumentConstructor annotation instead.

* phpcs

* Housekeeping: cs

* Housekeeping: cs

* Update docs with review comments

* Improve attribute docs

Co-authored-by: Grégoire Paris <postmaster@greg0ire.fr>

* Rename AttributesDriver to AttributeDriver

Co-authored-by: Grégoire Paris <postmaster@greg0ire.fr>
2021-03-23 13:30:57 +01:00
Benjamin Eberlei
8f6d146bc4 Bump doctrine/deprecations to at least v0.5.3 (#8553) 2021-03-22 23:23:03 +01:00
Grégoire Paris
3358ccde39 Merge pull request #8547 from greg0ire/psalm-lv6-phpdoc
Make phpdoc types correct
2021-03-21 22:11:51 +01:00
acoulton
1f4e6ebeeb Add a forward-compatibility wrapper for phpunit8 assertions
While doctrine still supports php7.2 the test cases need to run
under phpunit8 as well. However some assertion methods produce
deprecation warnings in the test output with phpunit >= 9.

This commit adds a thin forward compatiblity wrapper for the
new assertion method names so that they can be used with both
supported phpunit versions.
2021-03-18 11:25:18 +00:00
acoulton
a94db4f5c0 Fix remaining warnings from the phpunit9 upgrade
Some tests were still using deprecated assertion and mocking methods,
resulting in a long list of warnings in the phpunit output.

This commit resolves all the warnings:

* Fixes a couple of test names in `@depends` tags (presumably these
  tests were renamed at some point for coding standards).

* Changes how mocks are configured when asserting the same method
  is called multiple times with a sequence of arguments / sequence
  of return values. The old `->at` expectation is deprecated because
  it can be brittle and give unreliable results. Some of this
  mocking could probably still be refactored further, but my focus
  was on solving the deprecation with the existing setup.

* Removes one use of prophecy for mocking, in favour of using
  phpunit mock objects. Prophecy now requires an extra composer
  dependency and a trait which seems overkill given it was only
  used in one place.

* Updates to the new names for assertFileExists and assertRegExp
  (and their `not` versions) - these are functionally equivalent.

* Replaces the last few references to old PHPUnit_Framework_XXX
  classes with their namespaced equivalent. These were mostly in
  comments, or in native php `assert()` statements that were sanity
  checking mocked object types. These asserts are probably redundant
  (and are clearly not running in CI since the classes they referenced
  no longer exist).
2021-03-18 10:51:43 +00:00
Grégoire Paris
47475f3a67 Merge pull request #8532 from acoulton/bug-fix-ci-db-connection
All CI runs are using the sqlite fallback connection instead of the expected driver
2021-03-17 19:49:56 +01:00
acoulton
61c4a5da0a Rename tmpdb_ to privileged_db in test config and TestUtil
To avoid confusion, the `tmpdb_` test config values are now named
`privileged_db_` and better documented in the phpunit.xml.dist.

The TestUtil class has been refactored to more closely mirror the
structure and method / variable naming of the equivalent in
doctrine/dbal. This does not introduce any significant functional
changes. The only real difference is that the test output now prints
the selected database driver the first time it is referenced,
rather than repeating this through the test run.
2021-03-17 10:31:22 +00:00
acoulton
dd34bca4eb Upgrade previously-skipped tests to phpunit 9
These tests had not been running in CI so missed the previous
phpunit upgrade.

Note that assertions in decimal/floaty values in GH7941Test have
been changed to compare numerically with a reasonable level of
precision, instead of using regex. This is because the types
returned by the different drivers are inconsistent, and phpunit
now only allows regex comparisons on strings.
2021-03-17 10:31:22 +00:00
acoulton
3e21c50f61 Fix unit test and CI database driver / credential configuration
Builds using the github actions phpunit.xml files were not properly
recognising driver-specific configuration values, so were all
falling back to use the in-memory sqlite database instead of the
expected driver. This also meant a number of tests were skipped
as they rely on functionality not available in sqlite.

This commit addresses that by:

* REMOVING the automatic fallback to the sqlite memory database -
  phpunit.xml must now always specify explicit parameters for the
  desired connection.

* Displaying the active driver in the build output for visibility
  and debugging.

* Changing the way TestUtil loads the database config in line
  with the equivalent logic in doctrine/dbal, and to support the
  way that the config is/was specified in the phpunit.xml files
  for CI.

Note that this means a couple of the expected config variable names
have changed. Developers that are using customised phpunit.xml files
locally will need to update them to provide:

* Database config variables if they want to use the sqlite/memory
  driver - see phpunit.xml.dist for details.
* `db_driver` instead of `db_type`
* `db_user` instead of `db_username`
* `db_dbname` instead of `db_name`
* And, if in use, the equivalent changes to the `tmpdb_` values

The other change is that now if you provide any value for
`db_driver` we will attempt to create that connection type and
that will throw if other details (username / password / etc as
required by the driver) are not provided. Previously providing
partial configuration would cause TestUtil to silently fall back
to the in-memory sqlite driver.
2021-03-17 10:31:22 +00:00
Grégoire Paris
bc3592bcc8 Make phpdoc type correct 2021-03-16 19:20:11 +01:00
Grégoire Paris
4fccec1322 Merge pull request #8545 from orklah/psalm-plugins-2
remove some empty() use when safe
2021-03-15 23:51:09 +01:00
orklah
0177133385 remove unwanted check with 0 2021-03-15 23:28:20 +01:00
orklah
8df5cb84fa remove some empty() use when safe 2021-03-15 23:28:19 +01:00
Grégoire Paris
3b7275e183 Merge remote-tracking branch 'origin/2.8.x' into 2.9.x 2021-03-14 18:57:41 +01:00
Grégoire Paris
5247c56fce Merge pull request #8539 from greg0ire/cs-20210311
🎉 Final CS batch 🎉
2021-03-14 18:47:03 +01:00
Grégoire Paris
cc37c490c2 Synchronize coding standard workflow with upstream
Now that there no longer are cs issues, we can thank diff-sniffer and
kiss it goodbye!
2021-03-13 09:55:38 +01:00
Grégoire Paris
95824efd61 Manually fix cs 2021-03-13 09:46:38 +01:00
Grégoire Paris
44d4712e64 Ignore rule about annotation phpdoc
These phpdoc is parsed by doctrine/annotations, and that package does
not understand things like array<string, mixed> yet.
2021-03-13 09:46:38 +01:00
Grégoire Paris
930f44c02f Ignore rule for externally-defined property 2021-03-13 00:08:03 +01:00
Grégoire Paris
6e3c011e65 Ignore rule about superflous comment
We can fix it with a breaking change.
2021-03-13 00:08:03 +01:00
Grégoire Paris
a82de0d422 Ignore rule about unused method
It cannot work when you call the private method like a callable.
2021-03-13 00:08:03 +01:00
Grégoire Paris
9917488179 Ignore rule about empty statements
This should be implemented in a separate pull request.
2021-03-12 08:20:46 +01:00
Grégoire Paris
93f31d2c33 Merge pull request #8533 from acoulton/test-string-lock-version
Add test coverage for passing optimistic lock version as string
2021-03-11 21:41:32 +01:00
acoulton
77356b954f Add test coverage for passing optimistic lock version as string
As discussed in #8527, when using optimistic locking with integer
version columns, Doctrine has always supported passing the lock
version as a string. For example when passing in a version
received in POST / GET.

Technically speaking this does not comply with the docs and phdoc
(which show the app explicitly casting to int before passing).

Nonetheless the maintainers decided it should continue to be valid
for now and reinstated the old soft-equals logic with #8531.

This modified test just avoids accidental changes in future.
2021-03-11 13:24:53 +00:00
Grégoire Paris
92f764206e Ignore broken rule 2021-03-11 09:11:24 +01:00
Grégoire Paris
141539673e Merge pull request #8530 from doctrine/cs-20210310
CS-batch 25/26 🤩
2021-03-11 00:05:31 +01:00
Grégoire Paris
23dc804c9b Merge pull request #8531 from beberlei/GH-8527-RevertLockEquals
[GH-8527] Revert cs fixes for entity version compares in lock+merge
2021-03-10 23:30:25 +01:00
Benjamin Eberlei
9e3baa7baa [GH-8527] Revert cs fixes for entity version compares in lock+merge 2021-03-10 22:46:07 +01:00
Grégoire Paris
322ea51ecf Manually fix cs 2021-03-10 22:17:31 +01:00
Grégoire Paris
21b046452b Merge pull request #8529 from greg0ire/cs-20210308
CS batch 24/26 🤞
2021-03-10 19:53:52 +01:00
Grégoire Paris
c57b81ada4 Manually fix cs 2021-03-09 21:15:33 +01:00
Grégoire Paris
4fa7c9c6de Merge pull request #8521 from greg0ire/cs-20210228
CS batch 23/an estimated 26
2021-03-08 19:57:18 +01:00
Benjamin Eberlei
2685b65c2b [GH-6855] Trigger deprecation for unsupported lifecycle callback mapping on embedded classes.(#8381) 2021-03-04 22:08:11 +01:00
Benjamin Eberlei
3902a4eb6e [GH-8458] Properly deprecate ConvertDoctrine1Schema (#8517) 2021-03-02 09:38:09 +01:00
Jakub Caban
b3ed525d4d Use typed properties for default metadata for #7939 (#8439)
[GH-7939] Detect column and association types from typed properties.

* Use typed properties for default metadata for #7939

* Coding Standards

* Remove $name from CmsUserTypes and adapt tests

* Factor out conditions required for typed property

* Factor out typed validation and completion methods

* Move Typed tests model to separate namespace

* Don't pass by reference, return array

* Document changes to default mapping for typed properties

* Better wording in annotation reference

* Add missing targetEntity assertion on typed association

* Try to comply with CS

* USe constants instead of strings

* Use one-line comments for single line content

* phpcs

* phpcs

Co-authored-by: Benjamin Eberlei <kontakt@beberlei.de>
2021-03-01 22:13:58 +01:00
Grégoire Paris
3580517aac Manually fix cs 2021-03-01 21:49:10 +01:00
Benjamin Eberlei
4cdc6b1a71 [GH-7128] Improve OneToManyRequiresMappedBy Exception message (#8380) 2021-03-01 21:42:57 +01:00
plfort
38ccbd8638 DDC-2076 - MEMBER OF - Remove useless join over target table of ManyToMany relationship (#8438)
Co-authored-by: Pierre-Louis FORT <pierre-louis.fort@theia.fr>
2021-02-28 23:37:40 +01:00
Grégoire Paris
f9e7c3c2d8 Merge pull request #8516 from greg0ire/cs-20210227
CS batch 22/an estimated 26
2021-02-28 21:27:52 +01:00
Grégoire Paris
3600c0fbca Manually fix cs 2021-02-28 18:31:38 +01:00
Grégoire Paris
f779513042 Remove unused properties
They should have been removed as part of a6b43b93ac
2021-02-28 18:31:38 +01:00
Benjamin Eberlei
b4e6530d2d [GH-8471] Deprecate Partial DQL syntax and forcing partial loads. (#8472)
* [GH-8471] Deprecate Partial DQL syntax and forcing partial loads.
2021-02-28 18:17:12 +01:00
Diego Rin Martín
07d426edf5 Changed lock function to compare timestamps instead of DateTimeInterface objects directly. (#8508)
When using optimistic lock with DateTimeInterface based version field a bug appears due to the use of the === operator for comparing the lock version and the entity version. This comparison always resolves to false because the === operator when comparing objects is only true when both sides are the exact same instance of the object.

To fix the issue I have decided to compare timestamps instead the DateTimeInterface based objects directly, calling getTimestamp() method and doing a strict comparison.

Modified OptimisticLockException to use DateTimeInterface instead of DateTime class.

Added test suite to cover case.

Fixes #8499
2021-02-27 18:40:48 +01:00
Grégoire Paris
4afd4069be Merge pull request #8515 from greg0ire/cs-20210226
CS batch 21/an estimated 26
2021-02-27 14:30:25 +01:00
Grégoire Paris
239215c2e5 Merge pull request #8502 from greg0ire/rework-contributing-md
Rework CONTRIBUTING.md
2021-02-27 13:03:20 +01:00
Grégoire Paris
e6f11652d2 Add section for 2.9.x branch 2021-02-27 12:16:49 +01:00
Grégoire Paris
2910a73927 Rework badges urls
Some .x were missing, and ugly urlencoding can be avoided.
2021-02-27 12:10:47 +01:00
Grégoire Paris
3959b2743c Remove references to Travis 2021-02-27 12:03:35 +01:00
Grégoire Paris
658e54027e Remove trailing whitespace 2021-02-27 12:01:06 +01:00
Grégoire Paris
ba882451b0 Refer to our actual coding/standard
We do much more than just PSR 1 and 2
2021-02-27 12:01:05 +01:00
Grégoire Paris
1ed9840123 Refer to global workflow policy
We are doing things differently now, and the how is already documented.
2021-02-27 12:01:05 +01:00
Grégoire Paris
71044894a1 Manually fix cs 2021-02-26 21:30:49 +01:00
Grégoire Paris
1a41d6b87c Fix configuration mix up 2021-02-26 08:25:44 +01:00
Grégoire Paris
5dfcb08999 Merge pull request #8512 from greg0ire/cs-20210225
CS batch 20/an estimated 26
2021-02-25 23:23:24 +01:00
Grégoire Paris
284bd6fd03 Manually fix cs 2021-02-25 21:22:50 +01:00
Grégoire Paris
e40ac3e1d0 Merge pull request #8510 from greg0ire/cs-20210224
CS batch 19/an estimated 26
2021-02-24 22:41:28 +01:00
Grégoire Paris
0bce2472f2 Manually fix cs 2021-02-24 18:51:02 +01:00
Grégoire Paris
89f57de884 Merge pull request #8504 from greg0ire/cs-20210223
CS batch 18/an estimated 26
2021-02-23 23:18:42 +01:00
Grégoire Paris
ae19f40958 Merge pull request #8495 from Warxcell/fix_to_iterable_with_cache
Fix bug when using Result Cache with Query::toIterable
2021-02-23 20:16:39 +01:00
Grégoire Paris
c2d69a3c48 Merge pull request #8507 from greg0ire/address-move-away-from-master
Address move away from master
2021-02-23 18:19:47 +01:00
Grégoire Paris
6ce91dd37b Address move away from master 2021-02-23 09:24:40 +01:00
Grégoire Paris
57e6ba25c9 Merge pull request #8505 from dbu/patch-1
fix typo in changelog
2021-02-23 08:56:31 +01:00
David Buchmann
9d2e67bbb4 fix typo in changelog 2021-02-23 08:17:31 +01:00
Grégoire Paris
2dce5b20ad Manually fix cs 2021-02-22 23:50:09 +01:00
Warxcell
930859f803 Fix bug when using ResultCache with Query::toIterable.
Signed-off-by: Warxcell <warxcell@gmail.com>
2021-02-22 23:35:22 +02:00
Yup
a70c73ae3a Use RegEx to match if queryPart contains OR/AND (#8453)
This allows fixes cases of queries that contain line feeds or tabs but
do not benefit from automatic wrapping of parenthesis.
2021-02-22 20:58:06 +01:00
David Buchmann
074346b8d5 Note deprecation of AbstractQuery::iterator (#8497) 2021-02-22 20:30:05 +01:00
Grégoire Paris
9ed4a8c043 Merge pull request #8498 from greg0ire/cs-20210222
CS batch 17/an estimated 26
2021-02-22 20:25:06 +01:00
Grégoire Paris
9c917811e5 Manually fix cs 2021-02-22 09:12:04 +01:00
Grégoire Paris
f883820257 Ignore rule about wrong comment style 2021-02-22 08:48:46 +01:00
Grégoire Paris
a32045dd51 Ignore rule violated by external package 2021-02-22 07:52:57 +01:00
Grégoire Paris
672b04a55d Merge pull request #8483 from olsavmic/fix-single-scalar-hydrator-memory-leak-on-exception
Fix single scalar hydrator memory leak on exception
2021-02-21 21:12:50 +01:00
Grégoire Paris
261334aca2 Merge pull request #8494 from greg0ire/cs-20210221
CS batch 16/an estimated 26
2021-02-21 20:29:47 +01:00
Warxcell
7f6ed094cd Add test to verify that using ResultCache with Query::toIterable is failing. 2021-02-21 21:12:52 +02:00
Grégoire Paris
a792655813 Manually fix cs 2021-02-21 12:20:19 +01:00
Grégoire Paris
fb71204910 Relax assertion (#8493)
EntityManager is too restrictive, any implementation can actually be
returned here.

Closes #8488
2021-02-21 07:43:56 +01:00
Grégoire Paris
b918661cf1 Merge pull request #8492 from greg0ire/cs-20210220
CS batch 15/an estimated 26
2021-02-20 20:49:25 +01:00
Michael Olšavský
7971a53164 Method hydrateAll() does not take into account possible exception
from hydrateAllData() which in turn does not call cleanup()
2021-02-20 18:58:50 +01:00
Grégoire Paris
a175f96ae8 Manually fix cs 2021-02-20 15:37:15 +01:00
Grégoire Paris
7c1cde6471 Ignore rule that triggers on external property 2021-02-20 15:32:26 +01:00
Grégoire Paris
1ffc0cacf4 Merge pull request #8491 from greg0ire/cs-20210219
CS batch 14/an estimated 26
2021-02-20 11:10:27 +01:00
Grégoire Paris
e979d0d50f Manually fix cs 2021-02-20 00:01:41 +01:00
Grégoire Paris
553ea03079 Ignore rule about case mismatch
@group does not have to do with the Group entity at all.
2021-02-19 23:33:25 +01:00
Grégoire Paris
149014879d Ignore rule about property defined externally 2021-02-19 23:11:43 +01:00
Grégoire Paris
b991c58988 Merge pull request #8490 from greg0ire/cs-20210218
CS batch 13/an estimated 26
2021-02-19 23:08:25 +01:00
Aleksandr Frolov
ee9627b82e Update QueryBuilder::setParameters docs (#8487)
Use `ArrayCollection` instead of plain array (which is supported only for bc)
2021-02-19 01:45:14 +01:00
Grégoire Paris
e3f03414f9 Manually fix cs 2021-02-18 23:17:03 +01:00
Grégoire Paris
1f406fd3df Merge pull request #8484 from greg0ire/cs-20210217
CS batch 12/an estimated 26
2021-02-18 21:54:43 +01:00
Grégoire Paris
0ae53a6703 Merge pull request #8485 from doctrine/2.8.x-merge-up-into-2.9.x_602d59a0aa86b9.63081052
Merge release 2.8.2 into 2.9.x
2021-02-17 20:50:44 +01:00
Grégoire Paris
49864a7f57 Merge remote-tracking branch 'origin/2.8.x' into 2.8.x-merge-up-into-2.9.x_602d59a0aa86b9.63081052 2021-02-17 20:39:28 +01:00
Grégoire Paris
b747bf15ff Manually fix cs 2021-02-17 16:32:39 +01:00
Grégoire Paris
5fe85bfc03 Ignore rule about underscore in method name
We inherit from a class defined in another package.
2021-02-17 15:55:21 +01:00
Grégoire Paris
0dccf05ca8 Automatically fix cs 2021-02-17 15:55:21 +01:00
Grégoire Paris
ebae57eb96 Merge pull request #8480 from greg0ire/cs-20210216
CS batch 11/an estimated 26
2021-02-16 23:10:18 +01:00
Benjamin Eberlei
30a7c2aa67 [GH-8410] Fix memory leak in new toIterable and state bug. (#8467)
* [GH-8410] Fix memory leak in new toIterable and state bug.

The new AbstractQuery::toIterable() had a memory leak that
AbstractQuery::iterable() did not have. This leak is now fixed.

After fixing the leak, one test failed where the identity map in
ObjectHydrator triggered and lead to a notice. Introduced a new
AbstractHydrator::cleanupAfterRowIteration() that the ObjectHydrator
uses to cleanup the state.

* [GH-8413] Bugfix: Iterating with multiple, mixed results

When multiple entity results are part of a row, the result handling
must be different. In addition mixed results with scalars are broken
and now throw an exception as illegal operation.

* Housekeeping: phpcs

* [GH-8413] Add assertions for entity alias iteration.

* [GH-8387] Missing @deprecated on Query::iterate
2021-02-16 17:52:20 +01:00
Benjamin Eberlei
3a9b8fde9b Housekeeping: Fix cs 2021-02-16 16:24:19 +01:00
Yosh
4f864bc178 Identifier type is not set when many2many relations are deleted (#8401)
* Ensure identifier type is set on deleteJoinTableRecords

* Housekeeping: phpcs

* Housekeeping: phpcs

Co-authored-by: Benjamin Eberlei <kontakt@beberlei.de>
2021-02-16 16:12:39 +01:00
Grégoire Paris
d76cbd755f Manually fix cs 2021-02-16 09:07:26 +01:00
Grégoire Paris
4aece04ae7 Automatically fix cs 2021-02-16 08:48:48 +01:00
Grégoire Paris
f31dbf8d4e Merge pull request #8479 from greg0ire/cs-20210215
CS batch 10/an estimated 27
2021-02-15 23:44:27 +01:00
Grégoire Paris
416f35dba9 Manually fix cs 2021-02-14 21:00:58 +01:00
Grégoire Paris
c29370e061 Automatically fix cs 2021-02-14 14:39:35 +01:00
Grégoire Paris
4e0f6837d0 Merge pull request #8478 from beberlei/CsFixes2
CS Fixes 2 string interpolation to sprintf
2021-02-14 14:39:00 +01:00
Benjamin Eberlei
e45d212f02 Housekeeping: CS fixes Doctrine\ORM\Mapping\MappingException 2021-02-14 14:28:42 +01:00
Benjamin Eberlei
8f62bd39b5 Housekeeping: CS fixes Doctrine\ORM\ORMException 2021-02-14 09:53:19 +01:00
Benjamin Eberlei
5e11afcdf1 Housekeeping: CS fixes Doctrine\ORM\Mapping\MappingException 2021-02-14 09:49:39 +01:00
Benjamin Eberlei
f833222017 Cs fixes1 (#8475)
* Housekeeping: CS Query, AbstractQuery, NativeQuery.

* Housekeeping: phpcs TreeWalker

* Housekeeping: CS Doctrine\ORM\EntityManager

* Housekeeping: CS Doctrine\ORM\Cache

* Upgrade git-phpcs

* Drop unused method parameter

* Describe types more precisely

Co-authored-by: Grégoire Paris <postmaster@greg0ire.fr>
2021-02-14 09:23:15 +01:00
Grégoire Paris
c7f39ebbde Merge pull request #8477 from greg0ire/cs-20210214
CS batch 9/an estimated 28
2021-02-14 09:20:11 +01:00
Grégoire Paris
15f08ed006 Manually fix cs 2021-02-14 00:04:18 +01:00
Grégoire Paris
b6fd4b5ef3 Automatically fix cs 2021-02-14 00:04:11 +01:00
Benjamin Eberlei
e2e59e94f5 [GH-8383] deprecate notify change tracking policy (#8473)
* [GH-8383] Deprecate notify change tracking policy.

* [GH-8383] Add warning to documentation about notify change tracking policy deprecation.
2021-02-13 23:14:28 +01:00
Grégoire Paris
5e4dae88f3 Merge pull request #8476 from greg0ire/cs-20210213
CS batch 8/an estimated 30
2021-02-13 17:26:58 +01:00
Grégoire Paris
7312ddeda7 Manually fix cs 2021-02-13 13:46:01 +01:00
Grégoire Paris
9a67b6f699 Merge pull request #8474 from greg0ire/cs-20210212
CS batch 7/an estimated 30
2021-02-12 23:03:28 +01:00
Grégoire Paris
f59a0c349b Manually fix cs 2021-02-12 20:43:17 +01:00
Grégoire Paris
4c8831f716 Remove unused helper method 2021-02-12 20:04:56 +01:00
Benjamin Eberlei
6fe388a705 Introduce doctrine/deprecations (#8466)
* Introduce doctrine/deprecations, empty out VerifyDeprecations trait for now.

* Replace more usages of VerifyDeprecations (akwardkly for now)

* Update doctrine/deprecations to v0.2.0

* Remove ORM VerifyDeprecations trait and its use.

* Use doctrine/deprecatios VerifyDeprecations trait where useful

* Housekeeping: phpcs

* Fix reference link for toIterable/iterate deprecation
2021-02-12 18:14:34 +01:00
Vincent Langlet
172a8d9414 Restrict EntityManagerInterface::getRepository (#8417) 2021-02-12 17:44:22 +01:00
Grégoire Paris
01ca442be7 Ignore error about no assignment
These files must be require'd
2021-02-12 08:45:07 +01:00
Grégoire Paris
01374ca2ab Ignore rule about lone comment
That comment is mistaken for a method comment because it precedes one.
The issue was reported but will most likely not be fixed.
2021-02-12 07:39:56 +01:00
Grégoire Paris
94e8b1d43c Merge pull request #8470 from greg0ire/cs-20210211
CS batch 6/an estimated 30
2021-02-12 07:25:43 +01:00
Grégoire Paris
61d0f96c17 Manually fix cs 2021-02-11 21:02:10 +01:00
Grégoire Paris
41729be80a Spell "first" properly 2021-02-11 18:24:56 +01:00
Grégoire Paris
6dbaa39016 Merge pull request #8469 from greg0ire/cs-20210209
CS batch 5/an estimated 30
2021-02-10 21:11:11 +01:00
Grégoire Paris
58c95a92d1 Manually fix cs 2021-02-09 22:58:05 +01:00
Grégoire Paris
4958180b02 Merge pull request #8468 from greg0ire/cs-20210208
CS batch 4/an estimated 30
2021-02-09 22:22:41 +01:00
Grégoire Paris
d00dbf7e2d Merge pull request #8357 from snapshotpl/add-psalm-annotation
Add psalm annotation to ArrayCollection of Parameters
2021-02-08 21:25:58 +01:00
Grégoire Paris
8312ff0cb5 Merge pull request #8353 from fezfez/patch-1
Add docs to export-ignore
2021-02-08 21:23:35 +01:00
Witold Wasiczko
17012f1fea Improve psalm types 2021-02-08 21:16:56 +01:00
Witold Wasiczko
324ac3972f Add psalm annotation for parameters 2021-02-08 21:16:25 +01:00
Grégoire Paris
fb9b9b276e Manually fix cs 2021-02-08 13:53:04 +01:00
Benjamin Eberlei
323469cdb7 Add /*.phpunit.xml to .gitignore 2021-02-07 19:38:52 +01:00
Grégoire Paris
792a9a9149 Merge pull request #8464 from greg0ire/cs-20210207
CS batch 3/many
2021-02-07 14:21:09 +01:00
Grégoire Paris
0f655f9fb6 Manually fix cs 2021-02-07 12:21:40 +01:00
Grégoire Paris
2d7acbd07f Merge pull request #8457 from greg0ire/cs-20210206
CS Batch 2/many
2021-02-06 12:22:10 +01:00
andrews05
835030297a Add support for INDEX BY an associated entity (2.9.x) (#7918)
* Add support for INDEX BY an associated entity

This allows specifying an association in the INDEX BY clause of a query
which will index by the association's join column.

Related to #7661.

* Reintroduce IndexBy#simpleStateFieldPathExpression as deprecated property.

* Housekeeping: phpcs

* Housekeeping: phpcs

Co-authored-by: Benjamin Eberlei <kontakt@beberlei.de>
2021-02-06 11:46:18 +01:00
Grégoire Paris
b06679cc14 Manually fix cs 2021-02-06 11:44:32 +01:00
Julian Ullrich
2693a93aed fixed entity generation for numeric values (#8434)
* fixed entity generation for numeric values

* fixed entity generation for numeric values

Co-authored-by: julian <julian@ullrichmail.net>
2021-02-06 00:35:45 +01:00
Benjamin Eberlei
8724589c6e Housekeeping: Fix wrong typehint - Closes #8421 2021-02-06 00:23:45 +01:00
Grégoire Paris
4cc78d9478 Merge remote-tracking branch 'origin/2.8.x' into 2.9.x 2021-02-05 23:40:59 +01:00
Grégoire Paris
424305ef38 Merge pull request #8455 from greg0ire/cs
Cs
2021-02-05 23:40:01 +01:00
Grégoire Paris
9d01f6a45c Run phpcbf after running git-phpcs
git-phpcs can publish comments to Github, that will be helpful.
phpcbf will still be helpful to ensure no one upgrades the coding
standard without also fixing issues that can be autofixed.
2021-02-05 21:39:13 +01:00
Grégoire Paris
7ed487b534 Manually fix CS 2021-02-05 21:38:33 +01:00
Grégoire Paris
68d24288ce Merge remote-tracking branch 'origin/2.8.x' into 2.9.x 2021-02-05 20:06:04 +01:00
Grégoire Paris
40f3925589 Merge pull request #8144 from greg0ire/cs
Automated fixes with phpcbf + manual fixes
2021-02-05 08:44:58 +01:00
Alexander Schranz
f92c3dba32 Fix --complete flag in orm:ensure-production-settings command (#8426) 2021-02-01 22:08:04 +01:00
Grégoire Paris
5abad7c0af Merge remote-tracking branch 'origin/2.8.x' into 2.9.x 2021-01-31 00:01:45 +01:00
Grégoire Paris
bcbd4401b8 Ignore export directory 2021-01-30 23:50:15 +01:00
Grégoire Paris
d6aca8e146 Fix proxy file exclude pattern
__CG__ is a file prefix, not a directory
2021-01-30 23:45:46 +01:00
Grégoire Paris
8f1911a4fe Fix cs by hand 2021-01-30 23:29:40 +01:00
Grégoire Paris
7f30cd3102 Require doctrine/common ^3.0.3
That release comes with a fix for a bug that affects us since we are
using return type declarations for wakeUp() in proxyfied classes in on
of our tests.
2021-01-30 18:55:32 +01:00
Grégoire Paris
f01fe3e050 Fix or remove wrong assertions 2021-01-30 18:55:32 +01:00
Grégoire Paris
210c2ee6a4 Remove strict types 2021-01-30 18:55:32 +01:00
Grégoire Paris
497dfd1a84 Avoid covariant return types
It's not supported by PHP 7.2/7.3
2021-01-30 18:55:31 +01:00
Grégoire Paris
d9f0e2a27f Add exclude rules for tricky cases 2021-01-30 18:55:31 +01:00
Grégoire Paris
9a40ac6e2a Restore weird phpdoc
Tests do not pass when I format that phpdoc nicely.
2021-01-30 18:55:31 +01:00
Grégoire Paris
1687d9c479 Restore version annotation, but capitalized
@version is commonly used for svn ids and is forbidden
2021-01-30 18:55:31 +01:00
Gabriel Ostrolucký
1a46ed8901 Relax contract of EntityListenerResolver so it doesn't require class name (#8448)
Co-authored-by: Grégoire Paris <postmaster@greg0ire.fr>
2021-01-30 13:37:26 +01:00
Grégoire Paris
36d0352c01 Add missing use statements 2021-01-30 11:21:44 +01:00
Grégoire Paris
15eacd787b Remove weird extra argument 2021-01-30 11:21:44 +01:00
Grégoire Paris
5b3f9bdd7b Fix type declarations 2021-01-30 11:21:44 +01:00
Grégoire Paris
e00dba94f4 Remove strict types 2021-01-30 11:21:44 +01:00
Grégoire Paris
ab0e4007a5 Use interface instead of concretion 2021-01-30 11:17:40 +01:00
Grégoire Paris
32266c54f9 Fix compatibility with parent signature 2021-01-30 11:17:39 +01:00
Grégoire Paris
dd2120cd41 Make default value compatible with phpdoc 2021-01-30 11:17:39 +01:00
Grégoire Paris
8991df0785 Add missing return types 2021-01-30 11:17:39 +01:00
Grégoire Paris
ca31923a39 Run phpcbf in the CI
There are still many CS issues to fix, but with this, we now know people
can run vendor/bin/phpcbf to fix their issues and only their issues.
2021-01-30 11:17:39 +01:00
Grégoire Paris
68bc00b6c6 Automatically fix CS 2021-01-30 10:58:42 +01:00
Grégoire Paris
5b55b8c6cf Disable rules that would result in BC-breaks 2021-01-29 23:21:12 +01:00
Grégoire Paris
10f381bc95 Restrict fixes to be compatible with PHP 7.2 2021-01-29 21:16:18 +01:00
Nikolay Gagarinov
40aa8fe5db update getting-started fix type, improve doc (#8440)
* update getting-started fix type, improve doc

* Update getting-started.rst
2021-01-26 21:40:41 +01:00
Simon Podlipsky
5801474ba3 Catch doctrine/persistence MappingException (#8264)
When driver chain is used doctrine/persistence MappingException is thrown instead of doctrine/orm MappingException
2021-01-11 09:07:06 +01:00
Claudio Zizza
9dbd960631 Update website config to current repository branches (#8420) 2021-01-11 09:06:06 +01:00
Grégoire Paris
544df89055 Use proper workflow name (#8418)
This must have been a copy/paste/adapt mistake.
2021-01-11 09:05:18 +01:00
orklah
f0ad5f72b2 bump psalm and fix some issues on level 6 (#8409) 2021-01-08 20:30:15 +01:00
azjezz
378944dd27 remove T from class metadata (#8398) 2020-12-19 20:48:16 +01:00
Benjamin Eberlei
8b749642cd [GH-8231] Bugfix: Missed dirty check synchronization check. (#8392)
When an entity with change tracking policy "deferred explicit" gets
removed, then persisted again, it is not schedulded for a dirty check
synchronization. This is not the case for entities that are persisted
and are already in the managed state.
2020-12-14 11:00:07 +01:00
Nic Wortel
277b53a970 Use the ramsey/composer-install action to install dependencies (#8388)
Follow-up of https://github.com/doctrine/.github/pull/16.
2020-12-10 20:03:47 +01:00
Benjamin Morel
2febb4509a Fix Psalm param (#8386) 2020-12-09 11:03:01 +01:00
Benjamin Eberlei
cbc252f3b7 Add Doctrine\ORM\Query\Expr::mod() (#8377)
* Add Doctrine\ORM\Query\Expr::mod()

Co-authored-by: Menno Holtkamp <menno.holtkamp@shopforce.nl>

* [GH-6739] Add entry to documentation

Co-authored-by: Menno Holtkamp <menno.holtkamp@shopforce.nl>
2020-12-06 23:09:20 +01:00
Benjamin Eberlei
21d2c88013 [GH-7486] Bugfix: failing the command when clearing empty cache is wrong semantics. (#8376) 2020-12-06 22:00:00 +01:00
Vašek Henzl
e7d33eb1a9 Infer datetime_immutable DBAL type for \DateTimeImmutable instance parameters (#8328)
The support for passing \DateTimeImmutable instance as a query parameter has
been added to ORM in #1333 (the year 2015), a long time before immutable date
types (datetime_immutable etc) were introduced to DBAL in doctrine/dbal#2450
(2017).

Back then, it made sense to treat \DateTimeImmutable (or any
\DateTimeInterface) in the same way as \DateTime and infer parameter type as
datetime. However, when immutable date types were later added to DBAL, it
wasn't reflected anyhow in type inference in ORM and \DateTimeImmmutable
instances are still inferred as datetime DBAL type.

This PR fixes this IMO incorrect behaviour of
ParameterTypeInferer::inferType(): for a \DateTimeImmmutable parameter, it now
returns datetime_immutable DBAL type; for \DateTime or any other types
implementing \DateTimeInterface, it returns datetime DBAL type as it did
before.

This behaviour is in line with DateTimeImmutableType handling only
\DateTimeImmutable and DateTimeType handling any \DateTimeInterface.

Why? In most cases, it doesn't matter and datetime works for \DateTimeImmutable
parameters just fine. But it does matter if using custom implementation of
datetime_immutable type like UTCDateTimeImmutableType from
simpod/doctrine-utcdatetime. Then the broken type inference is revealed.

This is partially related to #6443, however, this PR isn't about custom DBAL
types but about correct type inference for build-in types.
2020-12-05 23:36:33 +01:00
Michel Hunziker
cab7a4558d Fix invalid psalm annotation (#8374) 2020-12-05 14:47:49 +01:00
Stéphane
35cf4810c1 Add docs to export-ignore 2020-11-27 18:50:57 +01:00
1264 changed files with 44193 additions and 28699 deletions

View File

@@ -7,26 +7,38 @@
"versions": [
{
"name": "3.0",
"branchName": "master",
"branchName": "3.0.x",
"slug": "latest",
"upcoming": true
},
{
"name": "2.8",
"branchName": "2.8.x",
"slug": "2.8",
"name": "2.10",
"branchName": "2.10.x",
"slug": "2.10",
"upcoming": true
},
{
"name": "2.7",
"branchName": "2.7",
"slug": "2.7",
"name": "2.9",
"branchName": "2.9.x",
"slug": "2.9",
"current": true,
"aliases": [
"current",
"stable"
]
},
{
"name": "2.8",
"branchName": "2.8.x",
"slug": "2.8",
"maintained": false
},
{
"name": "2.7",
"branchName": "2.7",
"slug": "2.7",
"maintained": false
},
{
"name": "2.6",
"branchName": "2.6",

6
.gitattributes vendored
View File

@@ -1,10 +1,10 @@
/tests export-ignore
/tools export-ignore
/docs export-ignore
/.github export-ignore
.doctrine-project.json export-ignore
.gitattributes export-ignore
.gitignore export-ignore
.gitmodules export-ignore
.travis.yml export-ignore
build.properties export-ignore
build.properties.dev export-ignore
build.xml export-ignore
@@ -14,4 +14,6 @@ run-all.sh export-ignore
phpcs.xml.dist export-ignore
phpbench.json export-ignore
phpstan.neon export-ignore
phpstan-baseline.neon export-ignore
psalm.xml export-ignore
psalm-baseline.xml export-ignore

View File

@@ -1,12 +1,17 @@
name: Static Analysis
name: "Coding Standards"
on:
pull_request:
branches:
- "*.x"
push:
branches:
- "*.x"
jobs:
coding-standards:
name: "Coding Standards"
runs-on: "ubuntu-latest"
runs-on: "ubuntu-20.04"
strategy:
matrix:
@@ -16,8 +21,6 @@ jobs:
steps:
- name: "Checkout"
uses: "actions/checkout@v2"
with:
fetch-depth: 10
- name: "Install PHP"
uses: "shivammathur/setup-php@v2"
@@ -26,21 +29,11 @@ jobs:
php-version: "${{ matrix.php-version }}"
tools: "cs2pr"
- name: "Cache dependencies installed with composer"
uses: "actions/cache@v1"
- name: "Install dependencies with Composer"
uses: "ramsey/composer-install@v1"
with:
path: "~/.composer/cache"
key: "php-${{ matrix.php-version }}-composer-locked-${{ hashFiles('composer.lock') }}"
restore-keys: "php-${{ matrix.php-version }}-composer-locked-"
dependency-versions: "highest"
- name: "Install dependencies with composer"
run: "composer update --no-interaction --no-progress --no-suggest"
- name: "Install git-phpcs"
run: "wget https://github.com/diff-sniffer/git/releases/download/0.3.2/git-phpcs.phar"
- name: "Fetch head branch"
run: "git remote set-branches --add origin $GITHUB_BASE_REF && git fetch origin $GITHUB_BASE_REF"
- name: "Run git-phpcs"
run: "php git-phpcs.phar origin/$GITHUB_BASE_REF...$GITHUB_SHA --report=checkstyle | cs2pr"
# https://github.com/doctrine/.github/issues/3
- name: "Run PHP_CodeSniffer"
run: "vendor/bin/phpcs -q --no-colors --report=checkstyle | cs2pr"

View File

@@ -19,11 +19,6 @@ jobs:
- "7.3"
- "7.4"
- "8.0"
deps:
- "normal"
include:
- deps: "low"
php-version: "7.3"
steps:
- name: "Checkout"
@@ -39,20 +34,8 @@ jobs:
coverage: "pcov"
ini-values: "zend.assertions=1"
- name: "Cache dependencies installed with composer"
uses: "actions/cache@v2"
with:
path: "~/.composer/cache"
key: "php-${{ matrix.php-version }}-composer-locked-${{ hashFiles('composer.lock') }}"
restore-keys: "php-${{ matrix.php-version }}-composer-locked-"
- name: "Install dependencies with composer"
run: "composer update --no-interaction --no-progress --no-suggest"
if: "${{ matrix.deps == 'normal' }}"
- name: "Install lowest possible dependencies with composer"
run: "composer update --no-interaction --no-progress --no-suggest --prefer-dist --prefer-lowest"
if: "${{ matrix.deps == 'low' }}"
- name: "Install dependencies with Composer"
uses: "ramsey/composer-install@v1"
- name: "Run PHPUnit"
run: "vendor/bin/phpunit -c ci/github/phpunit/sqlite.xml --coverage-clover=coverage-no-cache.xml"
@@ -67,7 +50,7 @@ jobs:
- name: "Upload coverage file"
uses: "actions/upload-artifact@v2"
with:
name: "phpunit-sqlite-${{ matrix.deps }}-${{ matrix.php-version }}-coverage"
name: "phpunit-sqlite-${{ matrix.php-version }}-coverage"
path: "coverage*.xml"
@@ -109,15 +92,8 @@ jobs:
coverage: "pcov"
ini-values: "zend.assertions=1"
- name: "Cache dependencies installed with composer"
uses: "actions/cache@v2"
with:
path: "~/.composer/cache"
key: "php-${{ matrix.php-version }}-composer-locked-${{ hashFiles('composer.lock') }}"
restore-keys: "php-${{ matrix.php-version }}-composer-locked-"
- name: "Install dependencies with composer"
run: "composer update --no-interaction --no-progress --no-suggest"
- name: "Install dependencies with Composer"
uses: "ramsey/composer-install@v1"
- name: "Run PHPUnit"
run: "vendor/bin/phpunit -c ci/github/phpunit/pdo_pgsql.xml --coverage-clover=coverage.xml"
@@ -171,15 +147,8 @@ jobs:
ini-values: "zend.assertions=1"
extensions: "${{ matrix.extension }}"
- name: "Cache dependencies installed with composer"
uses: "actions/cache@v2"
with:
path: "~/.composer/cache"
key: "php-${{ matrix.php-version }}-composer-locked-${{ hashFiles('composer.lock') }}"
restore-keys: "php-${{ matrix.php-version }}-composer-locked-"
- name: "Install dependencies with composer"
run: "composer update --no-interaction --no-progress --no-suggest"
- name: "Install dependencies with Composer"
uses: "ramsey/composer-install@v1"
- name: "Run PHPUnit"
run: "vendor/bin/phpunit -c ci/github/phpunit/${{ matrix.extension }}.xml --coverage-clover=coverage.xml"
@@ -233,15 +202,8 @@ jobs:
ini-values: "zend.assertions=1"
extensions: "${{ matrix.extension }}"
- name: "Cache dependencies installed with composer"
uses: "actions/cache@v2"
with:
path: "~/.composer/cache"
key: "php-${{ matrix.php-version }}-composer-locked-${{ hashFiles('composer.lock') }}"
restore-keys: "php-${{ matrix.php-version }}-composer-locked-"
- name: "Install dependencies with composer"
run: "composer update --no-interaction --no-progress --no-suggest"
- name: "Install dependencies with Composer"
uses: "ramsey/composer-install@v1"
- name: "Run PHPUnit"
run: "vendor/bin/phpunit -c ci/github/phpunit/${{ matrix.extension }}.xml --coverage-clover=coverage-no-cache.xml"
@@ -259,6 +221,38 @@ jobs:
name: "${{ github.job }}-${{ matrix.mysql-version }}-${{ matrix.extension }}-${{ matrix.php-version }}-coverage"
path: "coverage*.xml"
phpunit-lower-php-versions:
name: "PHPUnit with SQLite"
runs-on: "ubuntu-20.04"
strategy:
matrix:
php-version:
- "7.1"
deps:
- "highest"
- "lowest"
steps:
- name: "Checkout"
uses: "actions/checkout@v2"
with:
fetch-depth: 2
- name: "Install PHP"
uses: "shivammathur/setup-php@v2"
with:
php-version: "${{ matrix.php-version }}"
ini-values: "zend.assertions=1"
- name: "Install dependencies with Composer"
uses: "ramsey/composer-install@v1"
with:
dependency-versions: "${{ matrix.deps }}"
- name: "Run PHPUnit"
run: "vendor/bin/phpunit -c ci/github/phpunit/sqlite.xml"
upload_coverage:
name: "Upload coverage to Codecov"
runs-on: "ubuntu-20.04"

View File

@@ -1,12 +1,18 @@
name: Static Analysis
name: "Static Analysis"
on:
pull_request:
branches:
- "*.x"
push:
branches:
- "*.x"
jobs:
static-analysis-phpstan:
name: "PHPStan"
runs-on: "ubuntu-latest"
name: "Static Analysis with PHPStan"
runs-on: "ubuntu-20.04"
strategy:
matrix:
@@ -22,24 +28,18 @@ jobs:
with:
coverage: "none"
php-version: "${{ matrix.php-version }}"
tools: cs2pr
- name: "Cache dependencies installed with composer"
uses: "actions/cache@v1"
- name: "Install dependencies with Composer"
uses: "ramsey/composer-install@v1"
with:
path: "~/.composer/cache"
key: "php-${{ matrix.php-version }}-composer-locked-${{ hashFiles('composer.lock') }}"
restore-keys: "php-${{ matrix.php-version }}-composer-locked-"
- name: "Install dependencies with composer"
run: "composer update --no-progress --no-suggest --no-interaction --prefer-dist"
dependency-versions: "highest"
- name: "Run a static analysis with phpstan/phpstan"
run: "php vendor/bin/phpstan analyse --error-format=checkstyle | cs2pr"
run: "vendor/bin/phpstan analyse"
static-analysis-psalm:
name: "Psalm"
runs-on: "ubuntu-latest"
name: "Static Analysis with Psalm"
runs-on: "ubuntu-20.04"
strategy:
matrix:
@@ -56,15 +56,10 @@ jobs:
coverage: "none"
php-version: "${{ matrix.php-version }}"
- name: "Cache dependencies installed with composer"
uses: "actions/cache@v1"
- name: "Install dependencies with Composer"
uses: "ramsey/composer-install@v1"
with:
path: "~/.composer/cache"
key: "php-${{ matrix.php-version }}-composer-locked-${{ hashFiles('composer.lock') }}"
restore-keys: "php-${{ matrix.php-version }}-composer-locked-"
- name: "Install dependencies with composer"
run: "composer update --no-interaction --no-progress --no-suggest"
dependency-versions: "highest"
- name: "Run a static analysis with vimeo/psalm"
run: "vendor/bin/psalm --show-info=false --stats --output-format=github --threads=$(nproc)"

1
.gitignore vendored
View File

@@ -16,3 +16,4 @@ vendor/
/.phpcs-cache
composer.lock
/.phpunit.result.cache
/*.phpunit.xml

View File

@@ -6,30 +6,17 @@ Before we can merge your Pull-Request here are some guidelines that you need to
These guidelines exist not to annoy you, but to keep the code base clean,
unified and future proof.
## We only accept PRs to "master"
Doctrine has [general contributing guidelines][contributor workflow], make
sure you follow them.
Our branching strategy is "everything to master first", even
bugfixes and we then merge them into the stable branches. You should only
open pull requests against the master branch. Otherwise we cannot accept the PR.
There is one exception to the rule, when we merged a bug into some stable branches
we do occasionally accept pull requests that merge the same bug fix into earlier
branches.
[contributor workflow]: https://www.doctrine-project.org/contribute/index.html
## Coding Standard
We use PSR-1 and PSR-2:
This project follows [`doctrine/coding-standard`][coding standard homepage].
You may fix many some of the issues with `vendor/bin/phpcbf`.
* https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-1-basic-coding-standard.md
* https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md
with some exceptions/differences:
* Keep the nesting of control structures per method as small as possible
* Align equals (=) signs
* Add spaces between assignment, control and return statements
* Prefer early exit over nesting conditions
* Add spaces around a negation if condition ``if ( ! $cond)``
[coding standard homepage]: https://github.com/doctrine/coding-standard
## Unit-Tests
@@ -56,25 +43,19 @@ curl -sS https://getcomposer.org/installer | php --
To run the testsuite against another database, copy the ``phpunit.xml.dist``
to for example ``mysql.phpunit.xml`` and edit the parameters. You can
take a look at the ``tests/travis`` folder for some examples. Then run:
take a look at the ``ci/github/phpunit`` directory for some examples. Then run:
vendor/bin/phpunit -c mysql.phpunit.xml
If you do not provide these parameters, the test suite will use an in-memory
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/orm/tree/master/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2306Test.php` for an
See `https://github.com/doctrine/orm/tree/2.8.x/tests/Doctrine/Tests/ORM/Functional/Ticket/DDC2306Test.php` for an
example.
## Travis
We automatically run your pull request through [Travis CI](http://www.travis-ci.org)
against SQLite, MySQL and PostgreSQL. If you break the tests, we cannot merge your code,
so please make sure that your code is working before opening up a Pull-Request.
## Getting merged
Please allow us time to review your pull requests. We will give our best to review

View File

@@ -1,7 +1,7 @@
| [Master][Master] | [2.8.x][2.8] |
|:----------------:|:----------:|
| [![Build status][Master image]][Master] | [![Build status][2.8 image]][2.8] |
| [![Coverage Status][Master coverage image]][Master coverage] | [![Coverage Status][2.8 coverage image]][2.8 coverage] |
| [3.0.x][3.0] | [2.9.x][2.9] | [2.8.x][2.8] |
|:----------------:|:----------------:|:----------:|
| [![Build status][3.0 image]][3.0] | [![Build status][2.9 image]][2.9] | [![Build status][2.8 image]][2.8] |
| [![Coverage Status][3.0 coverage image]][3.0 coverage]| [![Coverage Status][2.9 coverage image]][2.9 coverage] | [![Coverage Status][2.8 coverage image]][2.8 coverage] |
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
@@ -16,11 +16,15 @@ without requiring unnecessary code duplication.
* [Documentation](https://www.doctrine-project.org/projects/doctrine-orm/en/latest/index.html)
[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://codecov.io/gh/doctrine/orm/branch/master/graph/badge.svg
[Master coverage]: https://codecov.io/gh/doctrine/orm/branch/master
[2.8 image]: https://img.shields.io/travis/doctrine/orm/2.8.svg?style=flat-square
[3.0 image]: https://github.com/doctrine/orm/actions/workflows/continuous-integration.yml/badge.svg?branch=3.0.x
[3.0]: https://github.com/doctrine/orm/tree/3.0.x
[3.0 coverage image]: https://codecov.io/gh/doctrine/orm/branch/3.0.x/graph/badge.svg
[3.0 coverage]: https://codecov.io/gh/doctrine/orm/branch/3.0.x
[2.9 image]: https://github.com/doctrine/orm/actions/workflows/continuous-integration.yml/badge.svg?branch=2.9.x
[2.9]: https://github.com/doctrine/orm/tree/2.9.x
[2.9 coverage image]: https://codecov.io/gh/doctrine/orm/branch/2.9.x/graph/badge.svg
[2.9 coverage]: https://codecov.io/gh/doctrine/orm/branch/2.9.x
[2.8 image]: https://github.com/doctrine/orm/actions/workflows/continuous-integration.yml/badge.svg
[2.8]: https://github.com/doctrine/orm/tree/2.8
[2.8 coverage image]: https://codecov.io/gh/doctrine/orm/branch/2.8/graph/badge.svg
[2.8 coverage]: https://codecov.io/gh/doctrine/orm/branch/2.8
[2.8 coverage image]: https://codecov.io/gh/doctrine/orm/branch/2.8.x/graph/badge.svg
[2.8 coverage]: https://codecov.io/gh/doctrine/orm/branch/2.8.x

View File

@@ -10,8 +10,8 @@ we cannot protect you from SQL injection.
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/orm/blob/master/docs/en/reference/security.rst)
- [DBAL Security Page](https://www.doctrine-project.org/projects/doctrine-dbal/en/latest/reference/security.html)
- [ORM Security Page](https://www.doctrine-project.org/projects/doctrine-orm/en/latest/reference/security.html)
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

View File

@@ -1,3 +1,31 @@
# Upgrade to 2.9
## Minor BC BREAK: Setup tool needs cache implementation
With the deprecation of doctrine/cache, the setup tool might no longer work as expected without a different cache
implementation. To work around this:
* Install symfony/cache: `composer require symfony/cache`. This will keep previous behaviour without any changes
* Instantiate caches yourself: to use a different cache implementation, pass a cache instance when calling any
configuration factory in the setup tool:
```diff
- $config = Setup::createAnnotationMetadataConfiguration($paths, $isDevMode, $proxyDir);
+ $cache = \Doctrine\Common\Cache\Psr6\DoctrineProvider::wrap($anyPsr6Implementation);
+ $config = Setup::createAnnotationMetadataConfiguration($paths, $isDevMode, $proxyDir, $cache);
```
* As a quick workaround, you can lock the doctrine/cache dependency to work around this: `composer require doctrine/cache ^1.11`.
Note that this is only recommended as a bandaid fix, as future versions of ORM will no longer work with doctrine/cache
1.11.
## Deprecated: doctrine/cache for metadata caching
The `Doctrine\ORM\Configuration#setMetadataCacheImpl()` method is deprecated and should no longer be used. Please use
`Doctrine\ORM\Configuration#setMetadataCache()` with any PSR-6 cache adapter instead.
## Removed: flushing metadata cache
To support PSR-6 caches, the `--flush` option for the `orm:clear-cache:metadata` command is ignored. Metadata cache is
now always cleared regardless of the cache adapter being used.
# Upgrade to 2.8
## Minor BC BREAK: Failed commit now throw OptimisticLockException
@@ -5,6 +33,11 @@
Method `Doctrine\ORM\UnitOfWork#commit()` can throw an OptimisticLockException when a commit silently fails and returns false
since `Doctrine\DBAL\Connection#commit()` signature changed from returning void to boolean
## Deprecated: `Doctrine\ORM\AbstractQuery#iterator()`
The method `Doctrine\ORM\AbstractQuery#iterator()` is deprecated in favor of `Doctrine\ORM\AbstractQuery#toIterable()`.
Note that `toIterable()` yields results of the query, unlike `iterator()` which yielded each result wrapped into an array.
# Upgrade to 2.7
## Added `Doctrine\ORM\AbstractQuery#enableResultCache()` and `Doctrine\ORM\AbstractQuery#disableResultCache()` methods

View File

@@ -1,4 +1,4 @@
#!/usr/bin/env php
<?php
include('doctrine.php');
include(__DIR__ . '/doctrine.php');

View File

@@ -7,6 +7,10 @@
failOnRisky="true"
>
<php>
<!-- use an in-memory sqlite database -->
<var name="db_driver" value="pdo_sqlite"/>
<var name="db_memory" value="true"/>
<!-- necessary change for some CLI/console output test assertions -->
<env name="COLUMNS" value="120"/>
</php>

View File

@@ -16,29 +16,34 @@
"sort-packages": true
},
"require": {
"php": "^7.2|^8.0",
"php": "^7.1|^8.0",
"ext-pdo": "*",
"composer/package-versions-deprecated": "^1.8",
"doctrine/annotations": "^1.11.1",
"doctrine/cache": "^1.9.1",
"doctrine/annotations": "^1.13",
"doctrine/cache": "^1.11.3|^2.0.3",
"doctrine/collections": "^1.5",
"doctrine/common": "^3.0",
"doctrine/dbal": "^2.10.0",
"doctrine/common": "^3.0.3",
"doctrine/dbal": "^2.13.0",
"doctrine/deprecations": "^0.5.3",
"doctrine/event-manager": "^1.1",
"doctrine/inflector": "^1.4|^2.0",
"doctrine/instantiator": "^1.3",
"doctrine/lexer": "^1.0",
"doctrine/persistence": "^2.0",
"symfony/console": "^3.0|^4.0|^5.0"
"doctrine/persistence": "^2.2",
"psr/cache": "^1 || ^2 || ^3",
"symfony/console": "^3.0|^4.0|^5.0|^6.0"
},
"require-dev": {
"doctrine/coding-standard": "^8.0",
"phpstan/phpstan": "^0.12.18",
"phpunit/phpunit": "^8.5|^9.4",
"symfony/yaml": "^3.4|^4.0|^5.0",
"vimeo/psalm": "4.1.1"
"doctrine/coding-standard": "^9.0",
"phpstan/phpstan": "^0.12.83",
"phpunit/phpunit": "^7.5|^8.5|^9.4",
"squizlabs/php_codesniffer": "3.6.0",
"symfony/cache": "^4.4|^5.2",
"symfony/yaml": "^3.4|^4.0|^5.0|^6.0",
"vimeo/psalm": "4.7.0"
},
"suggest": {
"symfony/cache": "Provides cache support for Setup Tool with doctrine/cache 2.0",
"symfony/yaml": "If you want to use YAML Metadata Mapping Driver"
},
"autoload": {
@@ -51,12 +56,7 @@
}
},
"bin": ["bin/doctrine"],
"extra": {
"branch-alias": {
"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"]
"exclude": ["!vendor", "tests", "*phpunit.xml", "build.xml", "build.properties", "composer.phar", "vendor/satooshi", "lib/vendor", "*.swp"]
}
}

View File

@@ -10,6 +10,11 @@ code should look like. We will implement it on a
`Layer Supertype <http://martinfowler.com/eaaCatalog/layerSupertype.html>`_
for all our domain objects.
.. note::
The notify change tracking policy is deprecated and will be removed in ORM 3.0.
(`Details <https://github.com/doctrine/orm/issues/8383>`_)
Implementing NotifyPropertyChanged
----------------------------------

View File

@@ -101,10 +101,11 @@ Gets or sets the metadata driver implementation that is used by
Doctrine to acquire the object-relational metadata for your
classes.
There are currently 4 available implementations:
There are currently 5 available implementations:
- ``Doctrine\ORM\Mapping\Driver\AnnotationDriver``
- ``Doctrine\ORM\Mapping\Driver\AttributeDriver``
- ``Doctrine\ORM\Mapping\Driver\XmlDriver``
- ``Doctrine\ORM\Mapping\Driver\YamlDriver``
- ``Doctrine\ORM\Mapping\Driver\DriverChain``

View File

@@ -89,7 +89,7 @@ as part of the lifecycle of the instance variables entity-class.
Required attributes:
- **type**: Name of the Doctrine Type which is converted between PHP
and Database representation.
and Database representation. Default to ``string`` or :ref:`Type from PHP property type <reference-php-mapping-types>`
Optional attributes:
@@ -350,7 +350,7 @@ in order to specify that it is an embedded class.
Required attributes:
- **class**: The embeddable class
- **class**: The embeddable class. You can omit this value if you use a PHP property type instead.
.. code-block:: php
@@ -513,7 +513,8 @@ Required attributes:
- **name**: Name of the Index
- **columns**: Array of columns.
- **fields**: Array of fields. Exactly one of **fields**, **columns** is required.
- **columns**: Array of columns. Exactly one of **fields**, **columns** is required.
Optional attributes:
@@ -535,6 +536,19 @@ Basic example:
{
}
Basic example using fields:
.. code-block:: php
<?php
/**
* @Entity
* @Table(name="ecommerce_products",indexes={@Index(name="search_idx", fields={"name", "email"})})
*/
class ECommerceProduct
{
}
Example with partial indexes:
.. code-block:: php
@@ -715,6 +729,7 @@ Required attributes:
- **targetEntity**: FQCN of the referenced target entity. Can be the
unqualified class name if both classes are in the same namespace.
You can omit this value if you use a PHP property type instead.
*IMPORTANT:* No leading backslash!
Optional attributes:
@@ -840,6 +855,11 @@ Example:
@NamedNativeQuery
~~~~~~~~~~~~~~~~~
.. note::
Named Native Queries are deprecated as of version 2.9 and will be removed in ORM 3.0
Is used to specify a native SQL named query.
The NamedNativeQuery annotation can be applied to an entity or mapped superclass.
@@ -923,6 +943,7 @@ Required attributes:
- **targetEntity**: FQCN of the referenced target entity. Can be the
unqualified class name if both classes are in the same namespace.
When typed properties are used it is inherited from PHP type.
*IMPORTANT:* No leading backslash!
Optional attributes:
@@ -1263,7 +1284,8 @@ Required attributes:
- **name**: Name of the Index
- **columns**: Array of columns.
- **fields**: Array of fields. Exactly one of **fields**, **columns** is required.
- **columns**: Array of columns. Exactly one of **fields**, **columns** is required.
Optional attributes:
@@ -1285,6 +1307,19 @@ Basic example:
{
}
Basic example using fields:
.. code-block:: php
<?php
/**
* @Entity
* @Table(name="ecommerce_products",uniqueConstraints={@UniqueConstraint(name="search_idx", fields={"name", "email"})})
*/
class ECommerceProduct
{
}
Example with partial indexes:
.. code-block:: php

View File

@@ -22,9 +22,9 @@ One tip for working with relations is to read the relation from left to right, w
- ManyToOne - Many instances of the current Entity refer to One instance of the referred Entity.
- OneToOne - One instance of the current Entity refers to One instance of the referred Entity.
See below for all the possible relations.
See below for all the possible relations.
An association is considered to be unidirectional if only one side of the association has
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
@@ -1061,6 +1061,70 @@ join columns default to the simple, unqualified class name of the
targeted class followed by "\_id". The referencedColumnName always
defaults to "id", just as in one-to-one or many-to-one mappings.
Additionally, when using typed properties with Doctrine 2.9 or newer
you can skip ``targetEntity`` in ``ManyToOne`` and ``OneToOne``
associations as they will be set based on type. Also ``nullable``
attribute on ``JoinColumn`` will be inherited from PHP type. So that:
.. configuration-block::
.. code-block:: php
<?php
/** @OneToOne */
private Shipment $shipment;
.. code-block:: xml
<doctrine-mapping>
<entity class="Product">
<one-to-one field="shipment" />
</entity>
</doctrine-mapping>
.. code-block:: yaml
Product:
type: entity
oneToOne:
shipment: ~
Is essentially the same as following:
.. configuration-block::
.. code-block:: php
<?php
/**
* One Product has One Shipment.
* @OneToOne(targetEntity="Shipment")
* @JoinColumn(name="shipment_id", referencedColumnName="id", nullable=false)
*/
private Shipment $shipment;
.. code-block:: xml
<doctrine-mapping>
<entity class="Product">
<one-to-one field="shipment" target-entity="Shipment">
<join-column name="shipment_id" referenced-column-name="id" nulable=false />
</one-to-one>
</entity>
</doctrine-mapping>
.. code-block:: yaml
Product:
type: entity
oneToOne:
shipment:
targetEntity: Shipment
joinColumn:
name: shipment_id
referencedColumnName: id
nullable: false
If you accept these defaults, you can reduce the mapping code to a
minimum.

File diff suppressed because it is too large Load Diff

View File

@@ -211,6 +211,25 @@ list:
- ``options``: (optional) Key-value pairs of options that get passed
to the underlying database platform when generating DDL statements.
.. _reference-php-mapping-types:
PHP Types Mapping
_________________
Since version 2.9 Doctrine can determine usable defaults from property types
on entity classes. When property type is nullable the default for ``nullable``
Column attribute is set to TRUE. Additionally, Doctrine will map PHP types
to ``type`` attribute as follows:
- ``DateInterval``: ``dateinterval``
- ``DateTime``: ``datetime``
- ``DateTimeImmutable``: ``datetime_immutable``
- ``array``: ``json``
- ``bool``: ``boolean``
- ``float``: ``float``
- ``int``: ``integer``
- ``string`` or any other type: ``string``
.. _reference-mapping-types:
Doctrine Mapping Types
@@ -328,7 +347,7 @@ annotation.
In most cases using the automatic generator strategy (``@GeneratedValue``) is
what you want. It defaults to the identifier generation mechanism your current
database vendor prefers: AUTO_INCREMENT with MySQL, sequences with PostgreSQL
database vendor prefers: AUTO_INCREMENT with MySQL, sequences with PostgreSQL
and Oracle and so on.
Identifier Generation Strategies

View File

@@ -89,11 +89,11 @@ with the batching strategy that was already used for bulk inserts:
foreach ($q->toIterable() as $user) {
$user->increaseCredit();
$user->calculateNewBonuses();
++$i;
if (($i % $batchSize) === 0) {
$em->flush(); // Executes all updates.
$em->clear(); // Detaches all objects from Doctrine!
}
++$i;
}
$em->flush();
@@ -147,11 +147,11 @@ The following example shows how to do this:
$q = $em->createQuery('select u from MyProject\Model\User u');
foreach($q->toIterable() as $row) {
$em->remove($row);
++$i;
if (($i % $batchSize) === 0) {
$em->flush(); // Executes all deletions.
$em->clear(); // Detaches all objects from Doctrine!
}
++$i;
}
$em->flush();

View File

@@ -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 <https://github.com/doctrine/cache/tree/master/lib/Doctrine/Common/Cache>`_.
`cache directory on GitHub <https://github.com/doctrine/cache/tree/2.8.x/lib/Doctrine/Common/Cache>`_.
PhpFileCache
~~~~~~~~~~~~

View File

@@ -61,6 +61,11 @@ This policy can be configured as follows:
Notify
~~~~~~
.. note::
The notify change tracking policy is deprecated and will be removed in ORM 3.0.
(`Details <https://github.com/doctrine/orm/issues/8383>`_)
This policy is based on the assumption that the entities notify
interested listeners of changes to their properties. For that
purpose, a class that wants to use this policy needs to implement

View File

@@ -603,6 +603,13 @@ then phonenumber-id:
...
'nameUpper' => string 'JWAGE' (length=5)
You can also index by a to-one association, which will use the id of
the associated entity (the join column) as the key in the result set:
.. code-block:: sql
SELECT p, u FROM Participant INDEX BY p.user JOIN p.user u WHERE p.event = 3
UPDATE queries
--------------
@@ -1370,7 +1377,8 @@ userland:
that contain char or binary data. Doctrine has no way of implicitly
reloading this data. Partially loaded objects have to be passed to
``EntityManager::refresh()`` if they are to be reloaded fully from
the database.
the database. This query hint is deprecated and will be removed
in the future (`Details <https://github.com/doctrine/orm/issues/8471>`_)
- Query::HINT\_REFRESH - This query is used internally by
``EntityManager::refresh()`` and can be used in userland as well.
If you specify this hint and a query returns the data for an entity
@@ -1615,7 +1623,7 @@ From, Join and Index by
RangeVariableDeclaration ::= AbstractSchemaName ["AS"] AliasIdentificationVariable
JoinAssociationDeclaration ::= JoinAssociationPathExpression ["AS"] AliasIdentificationVariable [IndexBy]
Join ::= ["LEFT" ["OUTER"] | "INNER"] "JOIN" (JoinAssociationDeclaration | RangeVariableDeclaration) ["WITH" ConditionalExpression]
IndexBy ::= "INDEX" "BY" StateFieldPathExpression
IndexBy ::= "INDEX" "BY" SingleValuedPathExpression
Select Expressions
~~~~~~~~~~~~~~~~~~

View File

@@ -53,6 +53,9 @@ proper quoting of parameters.
}
}
If the parameter is an array and should be quoted as a list of values for an IN query
this is possible with the alternative ``SQLFilter#setParameterList()`` and
``SQLFilter#getParameterList()`` functions.
Configuration
-------------

View File

@@ -44,13 +44,35 @@ Read-Only Entities
------------------
You can mark entities as read only (See metadata mapping
references for details). This means that the entity marked as read only is never considered
for updates, which means when you call flush on the EntityManager these entities are skipped
even if properties changed. Read-Only allows to persist new entities of a kind and remove existing
ones, they are just not considered for updates.
references for details).
This means that the entity marked as read only is never considered for updates.
During flush on the EntityManager these entities are skipped even if properties
changed.
Read-Only allows to persist new entities of a kind and remove existing ones,
they are just not considered for updates.
See :ref:`annref_entity`
You can also explicitly mark individual entities read only directly on the
UnitOfWork via a call to ``markReadOnly()``:
.. code-block:: php
$user = $entityManager->find(User::class, $id);
$entityManager->getUnitOfWork()->markReadOnly($user);
Or you can set all objects that are the result of a query hydration to be
marked as read only with the following query hint:
.. code-block:: php
$query = $entityManager->createQuery('SELECT u FROM App\\Entity\\User u');
$query->setHint(Query::HINT_READ_ONLY, true);
$users = $query->getResult();
Extra-Lazy Collections
----------------------

View File

@@ -274,6 +274,9 @@ be a leaf entity in the inheritance hierarchy, (ie. have no subclasses).
Otherwise Doctrine *CANNOT* create proxy instances
of this entity and will *ALWAYS* load the entity eagerly.
There is also another important performance consideration that it is *NOT POSSIBLE*
to query for the base entity without any LEFT JOINs to the sub-types.
SQL Schema considerations
~~~~~~~~~~~~~~~~~~~~~~~~~

View File

@@ -14,6 +14,7 @@ metadata:
- **XML files** (XmlDriver)
- **Class DocBlock Annotations** (AnnotationDriver)
- **Attributes** (AttributeDriver)
- **YAML files** (YamlDriver)
- **PHP Code in files or static functions** (PhpDriver)

View File

@@ -71,7 +71,7 @@ with inheritance hierarchies.
use Doctrine\ORM\Query\ResultSetMappingBuilder;
$sql = "SELECT u.id, u.name, a.id AS address_id, a.street, a.city " .
$sql = "SELECT u.id, u.name, a.id AS address_id, a.street, a.city " .
"FROM users u INNER JOIN address a ON u.address_id = a.id";
$rsm = new ResultSetMappingBuilder($entityManager);
@@ -265,7 +265,7 @@ detail:
<?php
/**
* Adds a meta column (foreign key or discriminator column) to the result set.
*
*
* @param string $alias
* @param string $columnAlias
* @param string $columnName
@@ -320,10 +320,10 @@ entity.
$rsm->addEntityResult('User', 'u');
$rsm->addFieldResult('u', 'id', 'id');
$rsm->addFieldResult('u', 'name', 'name');
$query = $this->_em->createNativeQuery('SELECT id, name FROM users WHERE name = ?', $rsm);
$query->setParameter(1, 'romanb');
$users = $query->getResult();
The result would look like this:
@@ -356,10 +356,10 @@ thus owns the foreign key.
$rsm->addFieldResult('u', 'id', 'id');
$rsm->addFieldResult('u', 'name', 'name');
$rsm->addMetaResult('u', 'address_id', 'address_id');
$query = $this->_em->createNativeQuery('SELECT id, name, address_id FROM users WHERE name = ?', $rsm);
$query->setParameter(1, 'romanb');
$users = $query->getResult();
Foreign keys are used by Doctrine for lazy-loading purposes when
@@ -385,12 +385,12 @@ associations that are lazy.
$rsm->addFieldResult('a', 'address_id', 'id');
$rsm->addFieldResult('a', 'street', 'street');
$rsm->addFieldResult('a', 'city', 'city');
$sql = 'SELECT u.id, u.name, a.id AS address_id, a.street, a.city FROM users u ' .
'INNER JOIN address a ON u.address_id = a.id WHERE u.name = ?';
$query = $this->_em->createNativeQuery($sql, $rsm);
$query->setParameter(1, 'romanb');
$users = $query->getResult();
In this case the nested entity ``Address`` is registered with the
@@ -420,10 +420,10 @@ to map the hierarchy (both use a discriminator column).
$rsm->addFieldResult('u', 'name', 'name');
$rsm->addMetaResult('u', 'discr', 'discr'); // discriminator column
$rsm->setDiscriminatorColumn('u', 'discr');
$query = $this->_em->createNativeQuery('SELECT id, name, discr FROM users WHERE name = ?', $rsm);
$query->setParameter(1, 'romanb');
$users = $query->getResult();
Note that in the case of Class Table Inheritance, an example as
@@ -435,6 +435,10 @@ strategy but with native SQL it is your responsibility.
Named Native Query
------------------
.. note::
Named Native Queries are deprecated as of version 2.9 and will be removed in ORM 3.0
You can also map a native query using a named native query mapping.
To achieve that, you must describe the SQL resultset structure
@@ -789,7 +793,7 @@ followed by a dot ("."), followed by the name or the field or property of the pr
6:
name: address.country
column: a_country
If you retrieve a single entity and if you use the default mapping,

View File

@@ -1,6 +1,14 @@
Partial Objects
===============
.. note::
Creating Partial Objects through DQL is deprecated and
will be removed in the future, use data transfer object
support in DQL instead. (`Details
<https://github.com/doctrine/orm/issues/8471>`_)
A partial object is an object whose state is not fully initialized
after being reconstituted from the database and that is
disconnected from the rest of its data. The following section will

View File

@@ -277,10 +277,17 @@ following syntax:
.. code-block:: php
<?php
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Query\Parameter;
// $qb instanceof QueryBuilder
// Query here...
$qb->setParameters(array(1 => 'value for ?1', 2 => 'value for ?2'));
$qb->setParameters(new ArrayCollection([
new Parameter('1', 'value for ?1'),
new Parameter('2', 'value for ?2')
]));
Getting already bound parameters is easy - simply use the above
mentioned syntax with "getParameter()" or "getParameters()":
@@ -513,6 +520,9 @@ complete list of supported helper methods available:
// Example - $qb->expr()->sqrt('u.currentBalance')
public function sqrt($x); // Returns Expr\Func
// Example - $qb->expr()->mod('u.currentBalance', '10')
public function mod($x); // Returns Expr\Func
// Example - $qb->expr()->count('u.firstname')
public function count($x); // Returns Expr\Func

View File

@@ -134,6 +134,10 @@ optimize the performance of the Flush Operation:
explicit strategies of notifying the UnitOfWork what objects/properties
changed.
.. note::
Flush only a single entity with ``$entityManager->flush($entity)`` is deprecated and will be removed in ORM 3.0.
(`Details <https://github.com/doctrine/orm/issues/8459>`_)
Query Internals
---------------

View File

@@ -483,6 +483,7 @@ classes. We'll store them in ``src/Bug.php`` and ``src/User.php``, respectively.
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity
* @ORM\Table(name="bugs")
*/
class Bug
@@ -661,12 +662,12 @@ domain model to match the requirements:
Lazy load proxies always contain an instance of
Doctrine's EntityManager and all its dependencies. Therefore a
var\_dump() will possibly dump a very large recursive structure
``var_dump()`` will possibly dump a very large recursive structure
which is impossible to render and read. You have to use
``Doctrine\Common\Util\Debug::dump()`` to restrict the dumping to a
human readable level. Additionally you should be aware that dumping
the EntityManager to a Browser may take several minutes, and the
Debug::dump() method just ignores any occurrences of it in Proxy
``Debug::dump()`` method just ignores any occurrences of it in Proxy
instances.
Because we only work with collections for the references we must be

View File

@@ -309,7 +309,7 @@
<xs:complexType name="embedded">
<xs:attribute name="name" type="xs:string" use="required" />
<xs:attribute name="class" type="orm:fqcn" use="required" />
<xs:attribute name="class" type="orm:fqcn" use="optional" />
<xs:attribute name="column-prefix" type="xs:string" use="optional" />
<xs:attribute name="use-column-prefix" type="xs:boolean" default="true" use="optional" />
</xs:complexType>
@@ -332,7 +332,8 @@
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:sequence>
<xs:attribute name="name" type="xs:NMTOKEN" use="optional"/>
<xs:attribute name="columns" type="xs:string" use="required"/>
<xs:attribute name="columns" type="xs:string" use="optional"/>
<xs:attribute name="fields" type="xs:string" use="optional"/>
<xs:anyAttribute namespace="##other"/>
</xs:complexType>
@@ -351,6 +352,7 @@
</xs:sequence>
<xs:attribute name="name" type="xs:NMTOKEN" use="optional"/>
<xs:attribute name="columns" type="xs:string" use="required"/>
<xs:attribute name="fields" type="xs:string" use="optional"/>
<xs:attribute name="flags" type="xs:string" use="optional"/>
<xs:anyAttribute namespace="##other"/>
</xs:complexType>
@@ -539,7 +541,7 @@
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:sequence>
<xs:attribute name="field" type="xs:NMTOKEN" use="required" />
<xs:attribute name="target-entity" type="xs:string" use="required" />
<xs:attribute name="target-entity" type="xs:string" />
<xs:attribute name="inversed-by" type="xs:NMTOKEN" />
<xs:attribute name="fetch" type="orm:fetch-type" default="LAZY" />
<xs:anyAttribute namespace="##other"/>
@@ -557,7 +559,7 @@
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:sequence>
<xs:attribute name="field" type="xs:NMTOKEN" use="required" />
<xs:attribute name="target-entity" type="xs:string" use="required" />
<xs:attribute name="target-entity" type="xs:string" />
<xs:attribute name="mapped-by" type="xs:NMTOKEN" />
<xs:attribute name="inversed-by" type="xs:NMTOKEN" />
<xs:attribute name="fetch" type="orm:fetch-type" default="LAZY" />

View File

@@ -1,4 +1,5 @@
<?php
/*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
@@ -20,14 +21,22 @@
namespace Doctrine\ORM;
use Countable;
use Doctrine\Common\Collections\Collection;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\DBAL\Cache\QueryCacheProfile;
use Doctrine\ORM\Mapping\MappingException as ORMMappingException;
use Doctrine\Persistence\Mapping\MappingException;
use Doctrine\ORM\Query\Parameter;
use Doctrine\DBAL\Driver\ResultStatement;
use Doctrine\Deprecations\Deprecation;
use Doctrine\ORM\Cache\Logging\CacheLogger;
use Doctrine\ORM\Cache\QueryCacheKey;
use Doctrine\ORM\Cache\TimestampCacheKey;
use Doctrine\ORM\Internal\Hydration\IterableResult;
use Doctrine\ORM\Mapping\MappingException as ORMMappingException;
use Doctrine\ORM\Query\Parameter;
use Doctrine\ORM\Query\QueryException;
use Doctrine\ORM\Query\ResultSetMapping;
use Doctrine\Persistence\Mapping\MappingException;
use Traversable;
use function array_map;
use function array_shift;
use function count;
@@ -41,19 +50,11 @@ use function ksort;
use function reset;
use function serialize;
use function sha1;
use function trigger_error;
use const E_USER_DEPRECATED;
/**
* Base contract for ORM queries. Base class for Query and NativeQuery.
*
* @link www.doctrine-project.org
* @since 2.0
* @author Benjamin Eberlei <kontakt@beberlei.de>
* @author Guilherme Blanco <guilhermeblanco@hotmail.com>
* @author Jonathan Wage <jonwage@gmail.com>
* @author Roman Borschel <roman@code-factory.org>
* @author Konsta Vesterinen <kvesteri@cc.hut.fi>
*/
abstract class AbstractQuery
{
@@ -62,27 +63,27 @@ abstract class AbstractQuery
/**
* Hydrates an object graph. This is the default behavior.
*/
const HYDRATE_OBJECT = 1;
public const HYDRATE_OBJECT = 1;
/**
* Hydrates an array graph.
*/
const HYDRATE_ARRAY = 2;
public const HYDRATE_ARRAY = 2;
/**
* Hydrates a flat, rectangular result set with scalar values.
*/
const HYDRATE_SCALAR = 3;
public const HYDRATE_SCALAR = 3;
/**
* Hydrates a single scalar value.
*/
const HYDRATE_SINGLE_SCALAR = 4;
public const HYDRATE_SINGLE_SCALAR = 4;
/**
* Very simple object hydrator (optimized for performance).
*/
const HYDRATE_SIMPLEOBJECT = 5;
public const HYDRATE_SIMPLEOBJECT = 5;
/**
* The parameter map of this query.
@@ -95,7 +96,7 @@ abstract class AbstractQuery
/**
* The user-specified ResultSetMapping to use.
*
* @var \Doctrine\ORM\Query\ResultSetMapping
* @var ResultSetMapping
*/
protected $_resultSetMapping;
@@ -109,7 +110,7 @@ abstract class AbstractQuery
/**
* The map of query hints.
*
* @var array
* @psalm-var array<string, mixed>
*/
protected $_hints = [];
@@ -120,33 +121,27 @@ abstract class AbstractQuery
*/
protected $_hydrationMode = self::HYDRATE_OBJECT;
/**
* @var \Doctrine\DBAL\Cache\QueryCacheProfile
*/
/** @var QueryCacheProfile|null */
protected $_queryCacheProfile;
/**
* Whether or not expire the result cache.
*
* @var boolean
* @var bool
*/
protected $_expireResultCache = false;
/**
* @var \Doctrine\DBAL\Cache\QueryCacheProfile
*/
/** @var QueryCacheProfile */
protected $_hydrationCacheProfile;
/**
* Whether to use second level cache, if available.
*
* @var boolean
* @var bool
*/
protected $cacheable = false;
/**
* @var boolean
*/
/** @var bool */
protected $hasCache = false;
/**
@@ -159,31 +154,25 @@ abstract class AbstractQuery
/**
* Second level query cache mode.
*
* @var integer|null
* @var int|null
*/
protected $cacheMode;
/**
* @var \Doctrine\ORM\Cache\Logging\CacheLogger|null
*/
/** @var CacheLogger|null */
protected $cacheLogger;
/**
* @var integer
*/
/** @var int */
protected $lifetime = 0;
/**
* Initializes a new instance of a class derived from <tt>AbstractQuery</tt>.
*
* @param \Doctrine\ORM\EntityManagerInterface $em
*/
public function __construct(EntityManagerInterface $em)
{
$this->_em = $em;
$this->parameters = new ArrayCollection();
$this->_hints = $em->getConfiguration()->getDefaultQueryHints();
$this->hasCache = $this->_em->getConfiguration()->isSecondLevelCacheEnabled();
$this->_em = $em;
$this->parameters = new ArrayCollection();
$this->_hints = $em->getConfiguration()->getDefaultQueryHints();
$this->hasCache = $this->_em->getConfiguration()->isSecondLevelCacheEnabled();
if ($this->hasCache) {
$this->cacheLogger = $em->getConfiguration()
@@ -195,19 +184,19 @@ abstract class AbstractQuery
/**
* Enable/disable second level query (result) caching for this query.
*
* @param boolean $cacheable
* @param bool $cacheable
*
* @return static This query instance.
*/
public function setCacheable($cacheable)
{
$this->cacheable = (boolean) $cacheable;
$this->cacheable = (bool) $cacheable;
return $this;
}
/**
* @return boolean TRUE if the query results are enable for second level cache, FALSE otherwise.
* @return bool TRUE if the query results are enable for second level cache, FALSE otherwise.
*/
public function isCacheable()
{
@@ -227,17 +216,17 @@ abstract class AbstractQuery
}
/**
* Obtain the name of the second level query cache region in which query results will be stored
*
* @return string|null The cache region name; NULL indicates the default region.
*/
* Obtain the name of the second level query cache region in which query results will be stored
*
* @return string|null The cache region name; NULL indicates the default region.
*/
public function getCacheRegion()
{
return $this->cacheRegion;
}
/**
* @return boolean TRUE if the query cache and second level cache are enabled, FALSE otherwise.
* @return bool TRUE if the query cache and second level cache are enabled, FALSE otherwise.
*/
protected function isCacheEnabled()
{
@@ -245,7 +234,7 @@ abstract class AbstractQuery
}
/**
* @return integer
* @return int
*/
public function getLifetime()
{
@@ -255,19 +244,19 @@ abstract class AbstractQuery
/**
* Sets the life-time for this query into second level cache.
*
* @param integer $lifetime
* @param int $lifetime
*
* @return static This query instance.
*/
public function setLifetime($lifetime)
{
$this->lifetime = (integer) $lifetime;
$this->lifetime = (int) $lifetime;
return $this;
}
/**
* @return integer
* @return int
*/
public function getCacheMode()
{
@@ -275,13 +264,13 @@ abstract class AbstractQuery
}
/**
* @param integer $cacheMode
* @param int $cacheMode
*
* @return static This query instance.
*/
public function setCacheMode($cacheMode)
{
$this->cacheMode = (integer) $cacheMode;
$this->cacheMode = (int) $cacheMode;
return $this;
}
@@ -298,7 +287,7 @@ abstract class AbstractQuery
/**
* Retrieves the associated EntityManager of this Query instance.
*
* @return \Doctrine\ORM\EntityManager
* @return EntityManagerInterface
*/
public function getEntityManager()
{
@@ -323,6 +312,7 @@ abstract class AbstractQuery
* Get all defined parameters.
*
* @return ArrayCollection The defined query parameters.
* @psalm-return ArrayCollection<int, Parameter>
*/
public function getParameters()
{
@@ -334,14 +324,14 @@ abstract class AbstractQuery
*
* @param mixed $key The key (index or name) of the bound parameter.
*
* @return Query\Parameter|null The value of the bound parameter, or NULL if not available.
* @return Parameter|null The value of the bound parameter, or NULL if not available.
*/
public function getParameter($key)
{
$key = Query\Parameter::normalizeName($key);
$filteredParameters = $this->parameters->filter(
function (Query\Parameter $parameter) use ($key) : bool {
static function (Query\Parameter $parameter) use ($key): bool {
$parameterName = $parameter->getName();
return $key === $parameterName;
@@ -355,10 +345,9 @@ abstract class AbstractQuery
* Sets a collection of query parameters.
*
* @param ArrayCollection|mixed[] $parameters
* @psalm-param ArrayCollection<int, Parameter>|mixed[] $parameters
*
* @return static This query instance.
*
* @psalm-param ArrayCollection<int, Parameter>|mixed[] $parameters
*/
public function setParameters($parameters)
{
@@ -411,10 +400,9 @@ abstract class AbstractQuery
* @param mixed $value
*
* @return mixed[]|string|int|float|bool
*
* @throws \Doctrine\ORM\ORMInvalidArgumentException
*
* @psalm-return array|scalar
*
* @throws ORMInvalidArgumentException
*/
public function processParameterValue($value)
{
@@ -446,15 +434,12 @@ abstract class AbstractQuery
if ($value === null) {
throw ORMInvalidArgumentException::invalidIdentifierBindingEntity();
}
} catch (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.
$value = $this->potentiallyProcessIterable($value);
} catch (MappingException $e) {
// as previous, but depending on MappingDriver this exception from Persistence
// is thrown and not the ORM one.
} 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.
Depending on MappingDriver, either MappingException or
ORMMappingException is thrown. */
$value = $this->potentiallyProcessIterable($value);
}
@@ -499,8 +484,6 @@ abstract class AbstractQuery
/**
* Sets the ResultSetMapping that should be used for hydration.
*
* @param \Doctrine\ORM\Query\ResultSetMapping $rsm
*
* @return static This query instance.
*/
public function setResultSetMapping(Query\ResultSetMapping $rsm)
@@ -514,7 +497,7 @@ abstract class AbstractQuery
/**
* Gets the ResultSetMapping used for hydration.
*
* @return \Doctrine\ORM\Query\ResultSetMapping
* @return ResultSetMapping
*/
protected function getResultSetMapping()
{
@@ -523,18 +506,14 @@ abstract class AbstractQuery
/**
* Allows to translate entity namespaces to full qualified names.
*
* @param Query\ResultSetMapping $rsm
*
* @return void
*/
private function translateNamespaces(Query\ResultSetMapping $rsm)
private function translateNamespaces(Query\ResultSetMapping $rsm): void
{
$translate = function ($alias) : string {
$translate = function ($alias): string {
return $this->_em->getClassMetadata($alias)->getName();
};
$rsm->aliasMap = array_map($translate, $rsm->aliasMap);
$rsm->aliasMap = array_map($translate, $rsm->aliasMap);
$rsm->declaringClasses = array_map($translate, $rsm->declaringClasses);
}
@@ -550,21 +529,19 @@ abstract class AbstractQuery
* some form of caching with UnitOfWork registration you should use
* {@see AbstractQuery::setResultCacheProfile()}.
*
* @return static This query instance.
*
* @example
* $lifetime = 100;
* $resultKey = "abc";
* $query->setHydrationCacheProfile(new QueryCacheProfile());
* $query->setHydrationCacheProfile(new QueryCacheProfile($lifetime, $resultKey));
*
* @param \Doctrine\DBAL\Cache\QueryCacheProfile $profile
*
* @return static This query instance.
*/
public function setHydrationCacheProfile(QueryCacheProfile $profile = null)
public function setHydrationCacheProfile(?QueryCacheProfile $profile = null)
{
if ($profile !== null && ! $profile->getResultCacheDriver()) {
$resultCacheDriver = $this->_em->getConfiguration()->getHydrationCacheImpl();
$profile = $profile->setResultCacheDriver($resultCacheDriver);
$profile = $profile->setResultCacheDriver($resultCacheDriver);
}
$this->_hydrationCacheProfile = $profile;
@@ -573,7 +550,7 @@ abstract class AbstractQuery
}
/**
* @return \Doctrine\DBAL\Cache\QueryCacheProfile
* @return QueryCacheProfile
*/
public function getHydrationCacheProfile()
{
@@ -586,15 +563,13 @@ abstract class AbstractQuery
* If no result cache driver is set in the QueryCacheProfile, the default
* result cache driver is used from the configuration.
*
* @param \Doctrine\DBAL\Cache\QueryCacheProfile $profile
*
* @return static This query instance.
*/
public function setResultCacheProfile(QueryCacheProfile $profile = null)
public function setResultCacheProfile(?QueryCacheProfile $profile = null)
{
if ($profile !== null && ! $profile->getResultCacheDriver()) {
$resultCacheDriver = $this->_em->getConfiguration()->getResultCacheImpl();
$profile = $profile->setResultCacheDriver($resultCacheDriver);
$profile = $profile->setResultCacheDriver($resultCacheDriver);
}
$this->_queryCacheProfile = $profile;
@@ -613,6 +588,7 @@ abstract class AbstractQuery
*/
public function setResultCacheDriver($resultCacheDriver = null)
{
/** @phpstan-ignore-next-line */
if ($resultCacheDriver !== null && ! ($resultCacheDriver instanceof \Doctrine\Common\Cache\Cache)) {
throw ORMException::invalidResultCacheDriver();
}
@@ -668,7 +644,7 @@ abstract class AbstractQuery
*
* @return static This query instance.
*/
public function enableResultCache(?int $lifetime = null, ?string $resultCacheId = null) : self
public function enableResultCache(?int $lifetime = null, ?string $resultCacheId = null): self
{
$this->setResultCacheLifetime($lifetime);
$this->setResultCacheId($resultCacheId);
@@ -681,7 +657,7 @@ abstract class AbstractQuery
*
* @return static This query instance.
*/
public function disableResultCache() : self
public function disableResultCache(): self
{
$this->_queryCacheProfile = null;
@@ -697,7 +673,7 @@ abstract class AbstractQuery
*/
public function setResultCacheLifetime($lifetime)
{
$lifetime = ($lifetime !== null) ? (int) $lifetime : 0;
$lifetime = $lifetime !== null ? (int) $lifetime : 0;
$this->_queryCacheProfile = $this->_queryCacheProfile
? $this->_queryCacheProfile->setLifetime($lifetime)
@@ -711,7 +687,7 @@ abstract class AbstractQuery
*
* @deprecated
*
* @return integer
* @return int
*/
public function getResultCacheLifetime()
{
@@ -721,7 +697,7 @@ abstract class AbstractQuery
/**
* Defines if the result cache is active or not.
*
* @param boolean $expire Whether or not to force resultset cache expiration.
* @param bool $expire Whether or not to force resultset cache expiration.
*
* @return static This query instance.
*/
@@ -735,7 +711,7 @@ abstract class AbstractQuery
/**
* Retrieves if the resultset cache is active or not.
*
* @return boolean
* @return bool
*/
public function getExpireResultCache()
{
@@ -743,7 +719,7 @@ abstract class AbstractQuery
}
/**
* @return QueryCacheProfile
* @return QueryCacheProfile|null
*/
public function getQueryCacheProfile()
{
@@ -816,7 +792,7 @@ abstract class AbstractQuery
*
* Alias for execute(null, HYDRATE_ARRAY).
*
* @return array
* @return mixed[]
*/
public function getArrayResult()
{
@@ -828,7 +804,7 @@ abstract class AbstractQuery
*
* Alias for execute(null, HYDRATE_SCALAR).
*
* @return array
* @return mixed[]
*/
public function getScalarResult()
{
@@ -852,17 +828,16 @@ abstract class AbstractQuery
return null;
}
if ($this->_hydrationMode !== self::HYDRATE_SINGLE_SCALAR && ! $result) {
return null;
}
if ( ! is_array($result)) {
if (! is_array($result)) {
return $result;
}
if (count($result) > 1) {
throw new NonUniqueResultException;
throw new NonUniqueResultException();
}
return array_shift($result);
@@ -888,15 +863,15 @@ abstract class AbstractQuery
$result = $this->execute(null, $hydrationMode);
if ($this->_hydrationMode !== self::HYDRATE_SINGLE_SCALAR && ! $result) {
throw new NoResultException;
throw new NoResultException();
}
if ( ! is_array($result)) {
if (! is_array($result)) {
return $result;
}
if (count($result) > 1) {
throw new NonUniqueResultException;
throw new NonUniqueResultException();
}
return array_shift($result);
@@ -941,7 +916,7 @@ abstract class AbstractQuery
*/
public function getHint($name)
{
return isset($this->_hints[$name]) ? $this->_hints[$name] : false;
return $this->_hints[$name] ?? false;
}
/**
@@ -959,7 +934,7 @@ abstract class AbstractQuery
/**
* Return the key value map of query hints that are currently set.
*
* @return array
* @return array<string,mixed>
*/
public function getHints()
{
@@ -970,25 +945,27 @@ abstract class AbstractQuery
* Executes the query and returns an IterableResult that can be used to incrementally
* iterate over the result.
*
* @deprecated
* @deprecated 2.8 Use {@see toIterable} instead. See https://github.com/doctrine/orm/issues/8463
*
* @param ArrayCollection|array|null $parameters The query parameters.
* @param string|int|null $hydrationMode The hydration mode to use.
* @param ArrayCollection|mixed[]|null $parameters The query parameters.
* @param string|int|null $hydrationMode The hydration mode to use.
*
* @return \Doctrine\ORM\Internal\Hydration\IterableResult
* @return IterableResult
*/
public function iterate($parameters = null, $hydrationMode = null)
{
@trigger_error(
'Method ' . __METHOD__ . '() is deprecated and will be removed in Doctrine ORM 3.0. Use toIterable() instead.',
E_USER_DEPRECATED
Deprecation::trigger(
'doctrine/orm',
'https://github.com/doctrine/orm/issues/8463',
'Method %s() is deprecated and will be removed in Doctrine ORM 3.0. Use toIterable() instead.',
__METHOD__
);
if ($hydrationMode !== null) {
$this->setHydrationMode($hydrationMode);
}
if ( ! empty($parameters)) {
if (! empty($parameters)) {
$this->setParameters($parameters);
}
@@ -1002,24 +979,31 @@ abstract class AbstractQuery
* Executes the query and returns an iterable that can be used to incrementally
* iterate over the result.
*
* @param ArrayCollection|mixed[] $parameters The query parameters.
* @param string|int|null $hydrationMode The hydration mode to use.
* @param ArrayCollection|array|mixed[] $parameters The query parameters.
* @param string|int|null $hydrationMode The hydration mode to use.
* @psalm-param ArrayCollection<int, Parameter>|mixed[] $parameters
*
* @return iterable<mixed>
*/
public function toIterable(iterable $parameters = [], $hydrationMode = null) : iterable
public function toIterable(iterable $parameters = [], $hydrationMode = null): iterable
{
if ($hydrationMode !== null) {
$this->setHydrationMode($hydrationMode);
}
if (($this->isCountable($parameters) && count($parameters) !== 0)
if (
($this->isCountable($parameters) && count($parameters) !== 0)
|| ($parameters instanceof Traversable && iterator_count($parameters) !== 0)
) {
$this->setParameters($parameters);
}
$rsm = $this->getResultSetMapping();
$rsm = $this->getResultSetMapping();
if ($rsm->isMixed && count($rsm->scalarMappings) > 0) {
throw QueryException::iterateWithMixedResultNotAllowed();
}
$stmt = $this->_doExecute();
return $this->_em->newHydrator($this->_hydrationMode)->toIterable($stmt, $rsm, $this->_hints);
@@ -1028,8 +1012,9 @@ abstract class AbstractQuery
/**
* Executes the query.
*
* @param ArrayCollection|array|null $parameters Query parameters.
* @param string|int|null $hydrationMode Processing mode to be used during the hydration process.
* @param ArrayCollection|mixed[]|null $parameters Query parameters.
* @param string|int|null $hydrationMode Processing mode to be used during the hydration process.
* @psalm-param ArrayCollection<int, Parameter>|mixed[]|null $parameters
*
* @return mixed
*/
@@ -1045,8 +1030,9 @@ abstract class AbstractQuery
/**
* Execute query ignoring second level cache.
*
* @param ArrayCollection|array|null $parameters
* @param string|int|null $hydrationMode
* @param ArrayCollection|mixed[]|null $parameters
* @param string|int|null $hydrationMode
* @psalm-param ArrayCollection<int, Parameter>|mixed[]|null $parameters
*
* @return mixed
*/
@@ -1056,11 +1042,11 @@ abstract class AbstractQuery
$this->setHydrationMode($hydrationMode);
}
if ( ! empty($parameters)) {
if (! empty($parameters)) {
$this->setParameters($parameters);
}
$setCacheEntry = static function () : void {
$setCacheEntry = static function ($data): void {
};
if ($this->_hydrationCacheProfile !== null) {
@@ -1074,11 +1060,11 @@ abstract class AbstractQuery
return $result[$realCacheKey];
}
if ( ! $result) {
if (! $result) {
$result = [];
}
$setCacheEntry = static function ($data) use ($cache, $result, $cacheKey, $realCacheKey, $queryCacheProfile) : void {
$setCacheEntry = static function ($data) use ($cache, $result, $cacheKey, $realCacheKey, $queryCacheProfile): void {
$result[$realCacheKey] = $data;
$cache->save($cacheKey, $result, $queryCacheProfile->getLifetime());
@@ -1104,8 +1090,9 @@ abstract class AbstractQuery
/**
* Load from second level cache or executes the query and put into cache.
*
* @param ArrayCollection|array|null $parameters
* @param string|int|null $hydrationMode
* @param ArrayCollection|mixed[]|null $parameters
* @param string|int|null $hydrationMode
* @psalm-param ArrayCollection<int, Parameter>|mixed[]|null $parameters
*
* @return mixed
*/
@@ -1120,7 +1107,7 @@ abstract class AbstractQuery
$this->getTimestampKey()
);
$result = $queryCache->get($queryKey, $rsm, $this->_hints);
$result = $queryCache->get($queryKey, $rsm, $this->_hints);
if ($result !== null) {
if ($this->cacheLogger) {
@@ -1144,10 +1131,7 @@ abstract class AbstractQuery
return $result;
}
/**
* @return \Doctrine\ORM\Cache\TimestampCacheKey|null
*/
private function getTimestampKey()
private function getTimestampKey(): ?TimestampCacheKey
{
$entityName = reset($this->_resultSetMapping->aliasMap);
@@ -1218,7 +1202,9 @@ abstract class AbstractQuery
/**
* Executes the query and returns a the resulting Statement object.
*
* @return \Doctrine\DBAL\Driver\Statement The executed database statement that holds the results.
* @return ResultStatement|int The executed database statement that holds
* the results, or an integer indicating how
* many rows were affected.
*/
abstract protected function _doExecute();
@@ -1244,10 +1230,12 @@ abstract class AbstractQuery
{
$query = $this->getSQL();
$hints = $this->getHints();
$params = array_map(function(Parameter $parameter) {
$params = array_map(function (Parameter $parameter) {
$value = $parameter->getValue();
// Small optimization
// Does not invoke processParameterValue for scalar values
if (is_scalar($value = $parameter->getValue())) {
// Does not invoke processParameterValue for scalar value
if (is_scalar($value)) {
return $value;
}
@@ -1260,7 +1248,7 @@ abstract class AbstractQuery
}
/** @param iterable<mixed> $subject */
private function isCountable(iterable $subject) : bool
private function isCountable(iterable $subject): bool
{
return $subject instanceof Countable || is_array($subject);
}

View File

@@ -20,44 +20,44 @@
namespace Doctrine\ORM;
use Doctrine\ORM\Cache\QueryCache;
use Doctrine\ORM\Cache\Region;
/**
* Provides an API for querying/managing the second level cache regions.
*
* @since 2.5
* @author Fabio B. Silva <fabio.bat.silva@gmail.com>
*/
interface Cache
{
const DEFAULT_QUERY_REGION_NAME = 'query_cache_region';
public const DEFAULT_QUERY_REGION_NAME = 'query_cache_region';
const DEFAULT_TIMESTAMP_REGION_NAME = 'timestamp_cache_region';
public const DEFAULT_TIMESTAMP_REGION_NAME = 'timestamp_cache_region';
/**
* May read items from the cache, but will not add items.
*/
const MODE_GET = 1;
public const MODE_GET = 1;
/**
* Will never read items from the cache,
* but will add items to the cache as it reads them from the database.
*/
const MODE_PUT = 2;
public const MODE_PUT = 2;
/**
* May read items from the cache, and add items to the cache.
*/
const MODE_NORMAL = 3;
public const MODE_NORMAL = 3;
/**
* The query will never read items from the cache,
* but will refresh items to the cache as it reads them from the database.
*/
const MODE_REFRESH = 4;
public const MODE_REFRESH = 4;
/**
* @param string $className The entity class.
*
* @return \Doctrine\ORM\Cache\Region|null
* @return Region|null
*/
public function getEntityCacheRegion($className);
@@ -65,7 +65,7 @@ interface Cache
* @param string $className The entity class.
* @param string $association The field name that represents the association.
*
* @return \Doctrine\ORM\Cache\Region|null
* @return Region|null
*/
public function getCollectionCacheRegion($className, $association);
@@ -75,7 +75,7 @@ interface Cache
* @param string $className The entity class.
* @param mixed $identifier The entity identifier
*
* @return boolean true if the underlying cache contains corresponding data; false otherwise.
* @return bool true if the underlying cache contains corresponding data; false otherwise.
*/
public function containsEntity($className, $identifier);
@@ -112,7 +112,7 @@ interface Cache
* @param string $association The field name that represents the association.
* @param mixed $ownerIdentifier The identifier of the owning entity.
*
* @return boolean true if the underlying cache contains corresponding data; false otherwise.
* @return bool true if the underlying cache contains corresponding data; false otherwise.
*/
public function containsCollection($className, $association, $ownerIdentifier);
@@ -149,7 +149,7 @@ interface Cache
*
* @param string $regionName The cache name given to the query.
*
* @return boolean true if the underlying cache contains corresponding data; false otherwise.
* @return bool true if the underlying cache contains corresponding data; false otherwise.
*/
public function containsQuery($regionName);
@@ -172,7 +172,7 @@ interface Cache
*
* @param string|null $regionName Query cache region name, or default query cache if the region name is NULL.
*
* @return \Doctrine\ORM\Cache\QueryCache The Query Cache associated with the region name.
* @return QueryCache The Query Cache associated with the region name.
*/
public function getQueryCache($regionName = null);
}

View File

@@ -22,16 +22,13 @@ namespace Doctrine\ORM\Cache;
/**
* Association cache entry
*
* @since 2.5
* @author Fabio B. Silva <fabio.bat.silva@gmail.com>
*/
class AssociationCacheEntry implements CacheEntry
{
/**
* READ-ONLY: Public only for performance reasons, it should be considered immutable.
*
* @var array The entity identifier
* @var array<string, mixed> The entity identifier
*/
public $identifier;
@@ -43,13 +40,13 @@ class AssociationCacheEntry implements CacheEntry
public $class;
/**
* @param string $class The entity class.
* @param array $identifier The entity identifier.
* @param string $class The entity class.
* @param array<string, mixed> $identifier The entity identifier.
*/
public function __construct($class, array $identifier)
{
$this->class = $class;
$this->identifier = $identifier;
$this->class = $class;
$this->identifier = $identifier;
}
/**
@@ -57,7 +54,7 @@ class AssociationCacheEntry implements CacheEntry
*
* This method allow Doctrine\Common\Cache\PhpFileCache compatibility
*
* @param array $values array containing property values
* @param array<string, mixed> $values array containing property values
*
* @return AssociationCacheEntry
*/

View File

@@ -24,34 +24,23 @@ use Doctrine\ORM\Cache\Logging\CacheLogger;
/**
* Configuration container for second-level cache.
*
* @since 2.5
* @author Fabio B. Silva <fabio.bat.silva@gmail.com>
*/
class CacheConfiguration
{
/**
* @var \Doctrine\ORM\Cache\CacheFactory|null
*/
/** @var CacheFactory|null */
private $cacheFactory;
/**
* @var \Doctrine\ORM\Cache\RegionsConfiguration|null
*/
/** @var RegionsConfiguration|null */
private $regionsConfig;
/**
* @var \Doctrine\ORM\Cache\Logging\CacheLogger|null
*/
/** @var CacheLogger|null */
private $cacheLogger;
/**
* @var \Doctrine\ORM\Cache\QueryCacheValidator|null
*/
/** @var QueryCacheValidator|null */
private $queryValidator;
/**
* @return \Doctrine\ORM\Cache\CacheFactory|null
* @return CacheFactory|null
*/
public function getCacheFactory()
{
@@ -59,8 +48,6 @@ class CacheConfiguration
}
/**
* @param \Doctrine\ORM\Cache\CacheFactory $factory
*
* @return void
*/
public function setCacheFactory(CacheFactory $factory)
@@ -69,7 +56,7 @@ class CacheConfiguration
}
/**
* @return \Doctrine\ORM\Cache\Logging\CacheLogger|null
* @return CacheLogger|null
*/
public function getCacheLogger()
{
@@ -77,7 +64,7 @@ class CacheConfiguration
}
/**
* @param \Doctrine\ORM\Cache\Logging\CacheLogger $logger
* @return void
*/
public function setCacheLogger(CacheLogger $logger)
{
@@ -85,7 +72,7 @@ class CacheConfiguration
}
/**
* @return \Doctrine\ORM\Cache\RegionsConfiguration
* @return RegionsConfiguration
*/
public function getRegionsConfiguration()
{
@@ -97,7 +84,7 @@ class CacheConfiguration
}
/**
* @param \Doctrine\ORM\Cache\RegionsConfiguration $regionsConfig
* @return void
*/
public function setRegionsConfiguration(RegionsConfiguration $regionsConfig)
{
@@ -105,7 +92,7 @@ class CacheConfiguration
}
/**
* @return \Doctrine\ORM\Cache\QueryCacheValidator
* @return QueryCacheValidator
*/
public function getQueryValidator()
{
@@ -119,7 +106,7 @@ class CacheConfiguration
}
/**
* @param \Doctrine\ORM\Cache\QueryCacheValidator $validator
* @return void
*/
public function setQueryValidator(QueryCacheValidator $validator)
{

View File

@@ -26,11 +26,7 @@ namespace Doctrine\ORM\Cache;
* <b>IMPORTANT NOTE:</b>
*
* Fields of classes that implement CacheEntry are public for performance reason.
*
* @since 2.5
* @author Fabio B. Silva <fabio.bat.silva@gmail.com>
*/
interface CacheEntry
{
}

View File

@@ -1,4 +1,5 @@
<?php
/*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
@@ -21,11 +22,10 @@ namespace Doctrine\ORM\Cache;
use Doctrine\ORM\ORMException;
use function sprintf;
/**
* Exception for cache.
*
* @since 2.5
* @author Fabio B. Silva <fabio.bat.silva@gmail.com>
*/
class CacheException extends ORMException
{
@@ -33,7 +33,7 @@ class CacheException extends ORMException
* @param string $sourceEntity
* @param string $fieldName
*
* @return \Doctrine\ORM\Cache\CacheException
* @return CacheException
*/
public static function updateReadOnlyCollection($sourceEntity, $fieldName)
{
@@ -43,7 +43,7 @@ class CacheException extends ORMException
/**
* @param string $entityName
*
* @return \Doctrine\ORM\Cache\CacheException
* @return CacheException
*/
public static function updateReadOnlyEntity($entityName)
{
@@ -53,7 +53,7 @@ class CacheException extends ORMException
/**
* @param string $entityName
*
* @return \Doctrine\ORM\Cache\CacheException
* @return CacheException
*/
public static function nonCacheableEntity($entityName)
{

View File

@@ -20,93 +20,91 @@
namespace Doctrine\ORM\Cache;
use Doctrine\ORM\Mapping\ClassMetadata;
use Doctrine\ORM\Cache;
use Doctrine\ORM\Cache\Persister\Collection\CachedCollectionPersister;
use Doctrine\ORM\Cache\Persister\Entity\CachedEntityPersister;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\Mapping\ClassMetadata;
use Doctrine\ORM\Persisters\Collection\CollectionPersister;
use Doctrine\ORM\Persisters\Entity\EntityPersister;
/**
* Contract for building second level cache regions components.
*
* @since 2.5
* @author Fabio B. Silva <fabio.bat.silva@gmail.com>
*/
interface CacheFactory
{
/**
* Build an entity persister for the given entity metadata.
*
* @param \Doctrine\ORM\EntityManagerInterface $em The entity manager.
* @param \Doctrine\ORM\Persisters\Entity\EntityPersister $persister The entity persister that will be cached.
* @param \Doctrine\ORM\Mapping\ClassMetadata $metadata The entity metadata.
* @param EntityManagerInterface $em The entity manager.
* @param EntityPersister $persister The entity persister that will be cached.
* @param ClassMetadata $metadata The entity metadata.
*
* @return \Doctrine\ORM\Cache\Persister\Entity\CachedEntityPersister
* @return CachedEntityPersister
*/
public function buildCachedEntityPersister(EntityManagerInterface $em, EntityPersister $persister, ClassMetadata $metadata);
/**
* Build a collection persister for the given relation mapping.
*
* @param \Doctrine\ORM\EntityManagerInterface $em The entity manager.
* @param \Doctrine\ORM\Persisters\Collection\CollectionPersister $persister The collection persister that will be cached.
* @param array $mapping The association mapping.
* @param EntityManagerInterface $em The entity manager.
* @param CollectionPersister $persister The collection persister that will be cached.
* @param mixed[] $mapping The association mapping.
*
* @return \Doctrine\ORM\Cache\Persister\Collection\CachedCollectionPersister
* @return CachedCollectionPersister
*/
public function buildCachedCollectionPersister(EntityManagerInterface $em, CollectionPersister $persister, array $mapping);
/**
* Build a query cache based on the given region name
*
* @param \Doctrine\ORM\EntityManagerInterface $em The Entity manager.
* @param string $regionName The region name.
* @param EntityManagerInterface $em The Entity manager.
* @param string $regionName The region name.
*
* @return \Doctrine\ORM\Cache\QueryCache The built query cache.
* @return QueryCache The built query cache.
*/
public function buildQueryCache(EntityManagerInterface $em, $regionName = null);
/**
* Build an entity hydrator
*
* @param \Doctrine\ORM\EntityManagerInterface $em The Entity manager.
* @param \Doctrine\ORM\Mapping\ClassMetadata $metadata The entity metadata.
* @param EntityManagerInterface $em The Entity manager.
* @param ClassMetadata $metadata The entity metadata.
*
* @return \Doctrine\ORM\Cache\EntityHydrator The built entity hydrator.
* @return EntityHydrator The built entity hydrator.
*/
public function buildEntityHydrator(EntityManagerInterface $em, ClassMetadata $metadata);
/**
* Build a collection hydrator
*
* @param \Doctrine\ORM\EntityManagerInterface $em The Entity manager.
* @param array $mapping The association mapping.
* @param EntityManagerInterface $em The Entity manager.
* @param mixed[] $mapping The association mapping.
*
* @return \Doctrine\ORM\Cache\CollectionHydrator The built collection hydrator.
* @return CollectionHydrator The built collection hydrator.
*/
public function buildCollectionHydrator(EntityManagerInterface $em, array $mapping);
/**
* Build a cache region
*
* @param array $cache The cache configuration.
* @param array<string,mixed> $cache The cache configuration.
*
* @return \Doctrine\ORM\Cache\Region The cache region.
* @return Region The cache region.
*/
public function getRegion(array $cache);
/**
* Build timestamp cache region
*
* @return \Doctrine\ORM\Cache\TimestampRegion The timestamp region.
* @return TimestampRegion The timestamp region.
*/
public function getTimestampRegion();
/**
* Build \Doctrine\ORM\Cache
*
* @param EntityManagerInterface $entityManager
*
* @return \Doctrine\ORM\Cache
* @return Cache
*/
public function createCache(EntityManagerInterface $entityManager);
}

View File

@@ -23,9 +23,6 @@ namespace Doctrine\ORM\Cache;
/**
* Defines entity / collection / query key to be stored in the cache region.
* Allows multiple roles to be stored in the same cache region.
*
* @since 2.5
* @author Fabio B. Silva <fabio.bat.silva@gmail.com>
*/
abstract class CacheKey
{

View File

@@ -22,9 +22,6 @@ namespace Doctrine\ORM\Cache;
/**
* Collection cache entry
*
* @since 2.5
* @author Fabio B. Silva <fabio.bat.silva@gmail.com>
*/
class CollectionCacheEntry implements CacheEntry
{
@@ -48,7 +45,7 @@ class CollectionCacheEntry implements CacheEntry
*
* This method allows for Doctrine\Common\Cache\PhpFileCache compatibility
*
* @param array $values array containing property values
* @param array<string, mixed> $values array containing property values
*
* @return CollectionCacheEntry
*/

View File

@@ -20,18 +20,20 @@
namespace Doctrine\ORM\Cache;
use function implode;
use function ksort;
use function str_replace;
use function strtolower;
/**
* Defines entity collection roles to be stored in the cache region.
*
* @since 2.5
* @author Fabio B. Silva <fabio.bat.silva@gmail.com>
*/
class CollectionCacheKey extends CacheKey
{
/**
* READ-ONLY: Public only for performance reasons, it should be considered immutable.
*
* @var array The owner entity identifier
* @var array<string, mixed> The owner entity identifier
*/
public $ownerIdentifier;
@@ -50,17 +52,17 @@ class CollectionCacheKey extends CacheKey
public $association;
/**
* @param string $entityClass The entity class.
* @param string $association The field name that represents the association.
* @param array $ownerIdentifier The identifier of the owning entity.
* @param string $entityClass The entity class.
* @param string $association The field name that represents the association.
* @param array<string, mixed> $ownerIdentifier The identifier of the owning entity.
*/
public function __construct($entityClass, $association, array $ownerIdentifier)
{
ksort($ownerIdentifier);
$this->ownerIdentifier = $ownerIdentifier;
$this->entityClass = (string) $entityClass;
$this->association = (string) $association;
$this->hash = str_replace('\\', '.', strtolower($entityClass)) . '_' . implode(' ', $ownerIdentifier) . '__' . $association;
$this->ownerIdentifier = $ownerIdentifier;
$this->entityClass = (string) $entityClass;
$this->association = (string) $association;
$this->hash = str_replace('\\', '.', strtolower($entityClass)) . '_' . implode(' ', $ownerIdentifier) . '__' . $association;
}
}

View File

@@ -20,33 +20,31 @@
namespace Doctrine\ORM\Cache;
use Doctrine\ORM\PersistentCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping\ClassMetadata;
use Doctrine\ORM\PersistentCollection;
/**
* Hydrator cache entry for collections
*
* @since 2.5
* @author Fabio B. Silva <fabio.bat.silva@gmail.com>
*/
interface CollectionHydrator
{
/**
* @param \Doctrine\ORM\Mapping\ClassMetadata $metadata The entity metadata.
* @param \Doctrine\ORM\Cache\CollectionCacheKey $key The cached collection key.
* @param array|\Doctrine\Common\Collections\Collection $collection The collection.
* @param ClassMetadata $metadata The entity metadata.
* @param CollectionCacheKey $key The cached collection key.
* @param array|mixed[]|Collection $collection The collection.
*
* @return \Doctrine\ORM\Cache\CollectionCacheEntry
* @return CollectionCacheEntry
*/
public function buildCacheEntry(ClassMetadata $metadata, CollectionCacheKey $key, $collection);
/**
* @param \Doctrine\ORM\Mapping\ClassMetadata $metadata The owning entity metadata.
* @param \Doctrine\ORM\Cache\CollectionCacheKey $key The cached collection key.
* @param \Doctrine\ORM\Cache\CollectionCacheEntry $entry The cached collection entry.
* @param \Doctrine\ORM\PersistentCollection $collection The collection to load the cache into.
* @param ClassMetadata $metadata The owning entity metadata.
* @param CollectionCacheKey $key The cached collection key.
* @param CollectionCacheEntry $entry The cached collection entry.
* @param PersistentCollection $collection The collection to load the cache into.
*
* @return array
* @return mixed[]
*/
public function loadCacheEntry(ClassMetadata $metadata, CollectionCacheKey $key, CollectionCacheEntry $entry, PersistentCollection $collection);
}

View File

@@ -26,32 +26,29 @@ namespace Doctrine\ORM\Cache;
*
* When a entry is locked another process should not be able to read or write the entry.
* All evict operation should not consider locks, even though an entry is locked evict should be able to delete the entry and its lock.
*
* @since 2.5
* @author Fabio B. Silva <fabio.bat.silva@gmail.com>
*/
interface ConcurrentRegion extends Region
{
/**
* Attempts to read lock the mapping for the given key.
*
* @param \Doctrine\ORM\Cache\CacheKey $key The key of the item to lock.
* @param CacheKey $key The key of the item to lock.
*
* @return \Doctrine\ORM\Cache\Lock A lock instance or NULL if the lock already exists.
* @return Lock A lock instance or NULL if the lock already exists.
*
* @throws \Doctrine\ORM\Cache\LockException Indicates a problem accessing the region.
* @throws LockException Indicates a problem accessing the region.
*/
public function lock(CacheKey $key);
/**
* Attempts to read unlock the mapping for the given key.
*
* @param \Doctrine\ORM\Cache\CacheKey $key The key of the item to unlock.
* @param \Doctrine\ORM\Cache\Lock $lock The lock previously obtained from {@link readLock}
* @param CacheKey $key The key of the item to unlock.
* @param Lock $lock The lock previously obtained from {@link readLock}
*
* @return void
*
* @throws \Doctrine\ORM\Cache\LockException Indicates a problem accessing the region.
* @throws LockException Indicates a problem accessing the region.
*/
public function unlock(CacheKey $key, Lock $lock);
}

View File

@@ -20,44 +20,35 @@
namespace Doctrine\ORM\Cache;
use Doctrine\ORM\Cache;
use Doctrine\Common\Util\ClassUtils;
use Doctrine\ORM\Mapping\ClassMetadata;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\Cache;
use Doctrine\ORM\Cache\Persister\CachedPersister;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\Mapping\ClassMetadata;
use Doctrine\ORM\ORMInvalidArgumentException;
use Doctrine\ORM\UnitOfWork;
use function is_array;
use function is_object;
/**
* Provides an API for querying/managing the second level cache regions.
*
* @since 2.5
* @author Fabio B. Silva <fabio.bat.silva@gmail.com>
*/
class DefaultCache implements Cache
{
/**
* @var \Doctrine\ORM\EntityManagerInterface
*/
/** @var EntityManagerInterface */
private $em;
/**
* @var \Doctrine\ORM\UnitOfWork
*/
/** @var UnitOfWork */
private $uow;
/**
* @var \Doctrine\ORM\Cache\CacheFactory
*/
/** @var CacheFactory */
private $cacheFactory;
/**
* @var \Doctrine\ORM\Cache\QueryCache[]
*/
/** @var QueryCache[] */
private $queryCaches = [];
/**
* @var \Doctrine\ORM\Cache\QueryCache
*/
/** @var QueryCache|null */
private $defaultQueryCache;
public function __construct(EntityManagerInterface $em)
@@ -77,7 +68,7 @@ class DefaultCache implements Cache
$metadata = $this->em->getClassMetadata($className);
$persister = $this->uow->getEntityPersister($metadata->rootEntityName);
if ( ! ($persister instanceof CachedPersister)) {
if (! ($persister instanceof CachedPersister)) {
return null;
}
@@ -92,7 +83,7 @@ class DefaultCache implements Cache
$metadata = $this->em->getClassMetadata($className);
$persister = $this->uow->getCollectionPersister($metadata->getAssociationMapping($association));
if ( ! ($persister instanceof CachedPersister)) {
if (! ($persister instanceof CachedPersister)) {
return null;
}
@@ -104,10 +95,10 @@ class DefaultCache implements Cache
*/
public function containsEntity($className, $identifier)
{
$metadata = $this->em->getClassMetadata($className);
$persister = $this->uow->getEntityPersister($metadata->rootEntityName);
$metadata = $this->em->getClassMetadata($className);
$persister = $this->uow->getEntityPersister($metadata->rootEntityName);
if ( ! ($persister instanceof CachedPersister)) {
if (! ($persister instanceof CachedPersister)) {
return false;
}
@@ -122,7 +113,7 @@ class DefaultCache implements Cache
$metadata = $this->em->getClassMetadata($className);
$persister = $this->uow->getEntityPersister($metadata->rootEntityName);
if ( ! ($persister instanceof CachedPersister)) {
if (! ($persister instanceof CachedPersister)) {
return;
}
@@ -137,7 +128,7 @@ class DefaultCache implements Cache
$metadata = $this->em->getClassMetadata($className);
$persister = $this->uow->getEntityPersister($metadata->rootEntityName);
if ( ! ($persister instanceof CachedPersister)) {
if (! ($persister instanceof CachedPersister)) {
return;
}
@@ -154,7 +145,7 @@ class DefaultCache implements Cache
foreach ($metadatas as $metadata) {
$persister = $this->uow->getEntityPersister($metadata->rootEntityName);
if ( ! ($persister instanceof CachedPersister)) {
if (! ($persister instanceof CachedPersister)) {
continue;
}
@@ -170,7 +161,7 @@ class DefaultCache implements Cache
$metadata = $this->em->getClassMetadata($className);
$persister = $this->uow->getCollectionPersister($metadata->getAssociationMapping($association));
if ( ! ($persister instanceof CachedPersister)) {
if (! ($persister instanceof CachedPersister)) {
return false;
}
@@ -185,7 +176,7 @@ class DefaultCache implements Cache
$metadata = $this->em->getClassMetadata($className);
$persister = $this->uow->getCollectionPersister($metadata->getAssociationMapping($association));
if ( ! ($persister instanceof CachedPersister)) {
if (! ($persister instanceof CachedPersister)) {
return;
}
@@ -200,7 +191,7 @@ class DefaultCache implements Cache
$metadata = $this->em->getClassMetadata($className);
$persister = $this->uow->getCollectionPersister($metadata->getAssociationMapping($association));
if ( ! ($persister instanceof CachedPersister)) {
if (! ($persister instanceof CachedPersister)) {
return;
}
@@ -215,16 +206,14 @@ class DefaultCache implements Cache
$metadatas = $this->em->getMetadataFactory()->getAllMetadata();
foreach ($metadatas as $metadata) {
foreach ($metadata->associationMappings as $association) {
if ( ! $association['type'] & ClassMetadata::TO_MANY) {
if (! $association['type'] & ClassMetadata::TO_MANY) {
continue;
}
$persister = $this->uow->getCollectionPersister($association);
if ( ! ($persister instanceof CachedPersister)) {
if (! ($persister instanceof CachedPersister)) {
continue;
}
@@ -279,7 +268,7 @@ class DefaultCache implements Cache
$this->defaultQueryCache = $this->cacheFactory->buildQueryCache($this->em);
}
if ( ! isset($this->queryCaches[$regionName])) {
if (! isset($this->queryCaches[$regionName])) {
$this->queryCaches[$regionName] = $this->cacheFactory->buildQueryCache($this->em, $regionName);
}
@@ -287,14 +276,12 @@ class DefaultCache implements Cache
}
/**
* @param \Doctrine\ORM\Mapping\ClassMetadata $metadata The entity metadata.
* @param mixed $identifier The entity identifier.
*
* @return \Doctrine\ORM\Cache\EntityCacheKey
*/
private function buildEntityCacheKey(ClassMetadata $metadata, $identifier)
* @param ClassMetadata $metadata The entity metadata.
* @param mixed $identifier The entity identifier.
*/
private function buildEntityCacheKey(ClassMetadata $metadata, $identifier): EntityCacheKey
{
if ( ! is_array($identifier)) {
if (! is_array($identifier)) {
$identifier = $this->toIdentifierArray($metadata, $identifier);
}
@@ -302,15 +289,16 @@ class DefaultCache implements Cache
}
/**
* @param \Doctrine\ORM\Mapping\ClassMetadata $metadata The entity metadata.
* @param string $association The field name that represents the association.
* @param mixed $ownerIdentifier The identifier of the owning entity.
*
* @return \Doctrine\ORM\Cache\CollectionCacheKey
* @param ClassMetadata $metadata The entity metadata.
* @param string $association The field name that represents the association.
* @param mixed $ownerIdentifier The identifier of the owning entity.
*/
private function buildCollectionCacheKey(ClassMetadata $metadata, $association, $ownerIdentifier)
{
if ( ! is_array($ownerIdentifier)) {
private function buildCollectionCacheKey(
ClassMetadata $metadata,
string $association,
$ownerIdentifier
): CollectionCacheKey {
if (! is_array($ownerIdentifier)) {
$ownerIdentifier = $this->toIdentifierArray($metadata, $ownerIdentifier);
}
@@ -318,12 +306,12 @@ class DefaultCache implements Cache
}
/**
* @param \Doctrine\ORM\Mapping\ClassMetadata $metadata The entity metadata.
* @param mixed $identifier The entity identifier.
* @param ClassMetadata $metadata The entity metadata.
* @param mixed $identifier The entity identifier.
*
* @return array
* @return array<string, mixed>
*/
private function toIdentifierArray(ClassMetadata $metadata, $identifier)
private function toIdentifierArray(ClassMetadata $metadata, $identifier): array
{
if (is_object($identifier) && $this->em->getMetadataFactory()->hasMetadataFor(ClassUtils::getClass($identifier))) {
$identifier = $this->uow->getSingleIdentifierValue($identifier);
@@ -335,5 +323,4 @@ class DefaultCache implements Cache
return [$metadata->identifier[0] => $identifier];
}
}

View File

@@ -38,42 +38,30 @@ use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\Mapping\ClassMetadata;
use Doctrine\ORM\Persisters\Collection\CollectionPersister;
use Doctrine\ORM\Persisters\Entity\EntityPersister;
use InvalidArgumentException;
use LogicException;
use function sprintf;
use const DIRECTORY_SEPARATOR;
/**
* @since 2.5
* @author Fabio B. Silva <fabio.bat.silva@gmail.com>
*/
class DefaultCacheFactory implements CacheFactory
{
/**
* @var CacheAdapter
*/
/** @var CacheAdapter */
private $cache;
/**
* @var \Doctrine\ORM\Cache\RegionsConfiguration
*/
/** @var RegionsConfiguration */
private $regionsConfig;
/**
* @var \Doctrine\ORM\Cache\TimestampRegion|null
*/
/** @var TimestampRegion|null */
private $timestampRegion;
/**
* @var \Doctrine\ORM\Cache\Region[]
*/
/** @var Region[] */
private $regions = [];
/**
* @var string|null
*/
/** @var string|null */
private $fileLockRegionDirectory;
/**
* @param RegionsConfiguration $cacheConfig
* @param CacheAdapter $cache
*/
public function __construct(RegionsConfiguration $cacheConfig, CacheAdapter $cache)
{
$this->cache = $cache;
@@ -82,6 +70,8 @@ class DefaultCacheFactory implements CacheFactory
/**
* @param string $fileLockRegionDirectory
*
* @return void
*/
public function setFileLockRegionDirectory($fileLockRegionDirectory)
{
@@ -97,7 +87,7 @@ class DefaultCacheFactory implements CacheFactory
}
/**
* @param \Doctrine\ORM\Cache\Region $region
* @return void
*/
public function setRegion(Region $region)
{
@@ -105,7 +95,7 @@ class DefaultCacheFactory implements CacheFactory
}
/**
* @param \Doctrine\ORM\Cache\TimestampRegion $region
* @return void
*/
public function setTimestampRegion(TimestampRegion $region)
{
@@ -117,8 +107,8 @@ class DefaultCacheFactory implements CacheFactory
*/
public function buildCachedEntityPersister(EntityManagerInterface $em, EntityPersister $persister, ClassMetadata $metadata)
{
$region = $this->getRegion($metadata->cache);
$usage = $metadata->cache['usage'];
$region = $this->getRegion($metadata->cache);
$usage = $metadata->cache['usage'];
if ($usage === ClassMetadata::CACHE_USAGE_READ_ONLY) {
return new ReadOnlyCachedEntityPersister($persister, $region, $em, $metadata);
@@ -129,10 +119,14 @@ class DefaultCacheFactory implements CacheFactory
}
if ($usage === ClassMetadata::CACHE_USAGE_READ_WRITE) {
if (! $region instanceof ConcurrentRegion) {
throw new InvalidArgumentException(sprintf('Unable to use access strategy type of [%s] without a ConcurrentRegion', $usage));
}
return new ReadWriteCachedEntityPersister($persister, $region, $em, $metadata);
}
throw new \InvalidArgumentException(sprintf("Unrecognized access strategy type [%s]", $usage));
throw new InvalidArgumentException(sprintf('Unrecognized access strategy type [%s]', $usage));
}
/**
@@ -140,8 +134,8 @@ class DefaultCacheFactory implements CacheFactory
*/
public function buildCachedCollectionPersister(EntityManagerInterface $em, CollectionPersister $persister, array $mapping)
{
$usage = $mapping['cache']['usage'];
$region = $this->getRegion($mapping['cache']);
$usage = $mapping['cache']['usage'];
$region = $this->getRegion($mapping['cache']);
if ($usage === ClassMetadata::CACHE_USAGE_READ_ONLY) {
return new ReadOnlyCachedCollectionPersister($persister, $region, $em, $mapping);
@@ -152,10 +146,14 @@ class DefaultCacheFactory implements CacheFactory
}
if ($usage === ClassMetadata::CACHE_USAGE_READ_WRITE) {
if (! $region instanceof ConcurrentRegion) {
throw new InvalidArgumentException(sprintf('Unable to use access strategy type of [%s] without a ConcurrentRegion', $usage));
}
return new ReadWriteCachedCollectionPersister($persister, $region, $em, $mapping);
}
throw new \InvalidArgumentException(sprintf("Unrecognized access strategy type [%s]", $usage));
throw new InvalidArgumentException(sprintf('Unrecognized access strategy type [%s]', $usage));
}
/**
@@ -168,7 +166,7 @@ class DefaultCacheFactory implements CacheFactory
$this->getRegion(
[
'region' => $regionName ?: Cache::DEFAULT_QUERY_REGION_NAME,
'usage' => ClassMetadata::CACHE_USAGE_NONSTRICT_READ_WRITE
'usage' => ClassMetadata::CACHE_USAGE_NONSTRICT_READ_WRITE,
]
)
);
@@ -203,45 +201,39 @@ class DefaultCacheFactory implements CacheFactory
$cacheAdapter = $this->createRegionCache($name);
$lifetime = $this->regionsConfig->getLifetime($cache['region']);
$region = ($cacheAdapter instanceof MultiGetCache)
$region = $cacheAdapter instanceof MultiGetCache
? new DefaultMultiGetRegion($name, $cacheAdapter, $lifetime)
: new DefaultRegion($name, $cacheAdapter, $lifetime);
if ($cache['usage'] === ClassMetadata::CACHE_USAGE_READ_WRITE) {
if (
'' === $this->fileLockRegionDirectory ||
null === $this->fileLockRegionDirectory
$this->fileLockRegionDirectory === '' ||
$this->fileLockRegionDirectory === null
) {
throw new \LogicException(
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(). '
);
}
$directory = $this->fileLockRegionDirectory . DIRECTORY_SEPARATOR . $cache['region'];
$region = new FileLockRegion($region, $directory, $this->regionsConfig->getLockLifetime($cache['region']));
$region = new FileLockRegion($region, $directory, (string) $this->regionsConfig->getLockLifetime($cache['region']));
}
return $this->regions[$cache['region']] = $region;
}
/**
* @param string $name
*
* @return CacheAdapter
*/
private function createRegionCache($name)
private function createRegionCache(string $name): CacheAdapter
{
$cacheAdapter = clone $this->cache;
if (!$cacheAdapter instanceof CacheProvider) {
if (! $cacheAdapter instanceof CacheProvider) {
return $cacheAdapter;
}
$namespace = $cacheAdapter->getNamespace();
if ('' !== $namespace) {
if ($namespace !== '') {
$namespace .= ':';
}

View File

@@ -20,36 +20,32 @@
namespace Doctrine\ORM\Cache;
use Doctrine\ORM\Query;
use Doctrine\ORM\PersistentCollection;
use Doctrine\ORM\Mapping\ClassMetadata;
use Doctrine\ORM\Cache\Persister\CachedPersister;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\Mapping\ClassMetadata;
use Doctrine\ORM\PersistentCollection;
use Doctrine\ORM\Query;
use Doctrine\ORM\UnitOfWork;
use function array_walk;
use function assert;
/**
* Default hydrator cache for collections
*
* @since 2.5
* @author Fabio B. Silva <fabio.bat.silva@gmail.com>
*/
class DefaultCollectionHydrator implements CollectionHydrator
{
/**
* @var \Doctrine\ORM\EntityManagerInterface
*/
/** @var EntityManagerInterface */
private $em;
/**
* @var \Doctrine\ORM\UnitOfWork
*/
/** @var UnitOfWork */
private $uow;
/**
* @var array
*/
/** @var array<string,mixed> */
private static $hints = [Query::HINT_CACHE_ENABLED => true];
/**
* @param \Doctrine\ORM\EntityManagerInterface $em The entity manager.
* @param EntityManagerInterface $em The entity manager.
*/
public function __construct(EntityManagerInterface $em)
{
@@ -77,23 +73,23 @@ class DefaultCollectionHydrator implements CollectionHydrator
public function loadCacheEntry(ClassMetadata $metadata, CollectionCacheKey $key, CollectionCacheEntry $entry, PersistentCollection $collection)
{
$assoc = $metadata->associationMappings[$key->association];
/* @var $targetPersister \Doctrine\ORM\Cache\Persister\CachedPersister */
$targetPersister = $this->uow->getEntityPersister($assoc['targetEntity']);
$targetRegion = $targetPersister->getCacheRegion();
$list = [];
assert($targetPersister instanceof CachedPersister);
$targetRegion = $targetPersister->getCacheRegion();
$list = [];
/** @var EntityCacheEntry[]|null $entityEntries */
$entityEntries = $targetRegion->getMultiple($entry);
if ($entityEntries === null) {
return null;
}
/* @var $entityEntries \Doctrine\ORM\Cache\EntityCacheEntry[] */
foreach ($entityEntries as $index => $entityEntry) {
$list[$index] = $this->uow->createEntity($entityEntry->class, $entityEntry->resolveAssociationEntries($this->em), self::$hints);
}
array_walk($list, function($entity, $index) use ($collection) {
array_walk($list, static function ($entity, $index) use ($collection) {
$collection->hydrateSet($index, $entity);
});

View File

@@ -21,49 +21,45 @@
namespace Doctrine\ORM\Cache;
use Doctrine\Common\Util\ClassUtils;
use Doctrine\ORM\Query;
use Doctrine\ORM\Mapping\ClassMetadata;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\Mapping\ClassMetadata;
use Doctrine\ORM\Query;
use Doctrine\ORM\UnitOfWork;
use Doctrine\ORM\Utility\IdentifierFlattener;
use function array_merge;
use function is_array;
use function is_object;
use function reset;
/**
* Default hydrator cache for entities
*
* @since 2.5
* @author Fabio B. Silva <fabio.bat.silva@gmail.com>
*/
class DefaultEntityHydrator implements EntityHydrator
{
/**
* @var \Doctrine\ORM\EntityManagerInterface
*/
/** @var EntityManagerInterface */
private $em;
/**
* @var \Doctrine\ORM\UnitOfWork
*/
/** @var UnitOfWork */
private $uow;
/**
* The IdentifierFlattener used for manipulating identifiers
*
* @var \Doctrine\ORM\Utility\IdentifierFlattener
* @var IdentifierFlattener
*/
private $identifierFlattener;
/**
* @var array
*/
/** @var array<string,mixed> */
private static $hints = [Query::HINT_CACHE_ENABLED => true];
/**
* @param \Doctrine\ORM\EntityManagerInterface $em The entity manager.
* @param EntityManagerInterface $em The entity manager.
*/
public function __construct(EntityManagerInterface $em)
{
$this->em = $em;
$this->uow = $em->getUnitOfWork();
$this->em = $em;
$this->uow = $em->getUnitOfWork();
$this->identifierFlattener = new IdentifierFlattener($em->getUnitOfWork(), $em->getMetadataFactory());
}
@@ -80,19 +76,19 @@ class DefaultEntityHydrator implements EntityHydrator
}
foreach ($metadata->associationMappings as $name => $assoc) {
if ( ! isset($data[$name])) {
if (! isset($data[$name])) {
continue;
}
if ( ! ($assoc['type'] & ClassMetadata::TO_ONE)) {
if (! ($assoc['type'] & ClassMetadata::TO_ONE)) {
unset($data[$name]);
continue;
}
if ( ! isset($assoc['cache'])) {
if (! isset($assoc['cache'])) {
$targetClassMetadata = $this->em->getClassMetadata($assoc['targetEntity']);
$owningAssociation = ( ! $assoc['isOwningSide'])
$owningAssociation = ! $assoc['isOwningSide']
? $targetClassMetadata->associationMappings[$assoc['mappedBy']]
: $assoc;
$associationIds = $this->identifierFlattener->flattenIdentifier(
@@ -113,7 +109,7 @@ class DefaultEntityHydrator implements EntityHydrator
$targetAssoc = $targetClassMetadata->associationMappings[$fieldName];
foreach($assoc['targetToSourceKeyColumns'] as $referencedColumn => $localColumn) {
foreach ($assoc['targetToSourceKeyColumns'] as $referencedColumn => $localColumn) {
if (isset($targetAssoc['sourceToTargetKeyColumns'][$referencedColumn])) {
$data[$localColumn] = $fieldValue;
}
@@ -123,7 +119,7 @@ class DefaultEntityHydrator implements EntityHydrator
continue;
}
if ( ! isset($assoc['id'])) {
if (! isset($assoc['id'])) {
$targetClass = ClassUtils::getClass($data[$name]);
$targetId = $this->uow->getEntityIdentifier($data[$name]);
$data[$name] = new AssociationCacheEntry($targetClass, $targetId);
@@ -138,7 +134,7 @@ class DefaultEntityHydrator implements EntityHydrator
// @TODO - fix it !
// handle UnitOfWork#createEntity hash generation
if ( ! is_array($targetId)) {
if (! is_array($targetId)) {
$data[reset($assoc['joinColumnFieldNames'])] = $targetId;
$targetEntity = $this->em->getClassMetadata($assoc['targetEntity']);
@@ -160,20 +156,20 @@ class DefaultEntityHydrator implements EntityHydrator
$hints = self::$hints;
if ($entity !== null) {
$hints[Query::HINT_REFRESH] = true;
$hints[Query::HINT_REFRESH_ENTITY] = $entity;
$hints[Query::HINT_REFRESH] = true;
$hints[Query::HINT_REFRESH_ENTITY] = $entity;
}
foreach ($metadata->associationMappings as $name => $assoc) {
if ( ! isset($assoc['cache']) || ! isset($data[$name])) {
if (! isset($assoc['cache']) || ! isset($data[$name])) {
continue;
}
$assocClass = $data[$name]->class;
$assocId = $data[$name]->identifier;
$isEagerLoad = ($assoc['fetch'] === ClassMetadata::FETCH_EAGER || ($assoc['type'] === ClassMetadata::ONE_TO_ONE && ! $assoc['isOwningSide']));
$assocClass = $data[$name]->class;
$assocId = $data[$name]->identifier;
$isEagerLoad = ($assoc['fetch'] === ClassMetadata::FETCH_EAGER || ($assoc['type'] === ClassMetadata::ONE_TO_ONE && ! $assoc['isOwningSide']));
if ( ! $isEagerLoad) {
if (! $isEagerLoad) {
$data[$name] = $this->em->getReference($assocClass, $assocId);
continue;

View File

@@ -21,68 +21,63 @@
namespace Doctrine\ORM\Cache;
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;
use Doctrine\ORM\PersistentCollection;
use Doctrine\Common\Proxy\Proxy;
use Doctrine\ORM\Cache;
use Doctrine\ORM\Cache\Logging\CacheLogger;
use Doctrine\ORM\Cache\Persister\Entity\CachedEntityPersister;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\Mapping\ClassMetadata;
use Doctrine\ORM\PersistentCollection;
use Doctrine\ORM\Query;
use Doctrine\ORM\Query\ResultSetMapping;
use Doctrine\ORM\UnitOfWork;
use function array_key_exists;
use function array_map;
use function array_shift;
use function array_unshift;
use function assert;
use function count;
use function is_array;
use function key;
use function reset;
/**
* Default query cache implementation.
*
* @since 2.5
* @author Fabio B. Silva <fabio.bat.silva@gmail.com>
*/
class DefaultQueryCache implements QueryCache
{
/**
* @var \Doctrine\ORM\EntityManagerInterface
*/
/** @var EntityManagerInterface */
private $em;
/**
* @var \Doctrine\ORM\UnitOfWork
*/
/** @var UnitOfWork */
private $uow;
/**
* @var \Doctrine\ORM\Cache\Region
*/
/** @var Region */
private $region;
/**
* @var \Doctrine\ORM\Cache\QueryCacheValidator
*/
/** @var QueryCacheValidator */
private $validator;
/**
* @var \Doctrine\ORM\Cache\Logging\CacheLogger
*/
/** @var CacheLogger */
protected $cacheLogger;
/**
* @var array
*/
/** @var array<string,mixed> */
private static $hints = [Query::HINT_CACHE_ENABLED => true];
/**
* @param \Doctrine\ORM\EntityManagerInterface $em The entity manager.
* @param \Doctrine\ORM\Cache\Region $region The query region.
* @param EntityManagerInterface $em The entity manager.
* @param Region $region The query region.
*/
public function __construct(EntityManagerInterface $em, Region $region)
{
$cacheConfig = $em->getConfiguration()->getSecondLevelCacheConfiguration();
$this->em = $em;
$this->region = $region;
$this->uow = $em->getUnitOfWork();
$this->cacheLogger = $cacheConfig->getCacheLogger();
$this->validator = $cacheConfig->getQueryValidator();
$this->em = $em;
$this->region = $region;
$this->uow = $em->getUnitOfWork();
$this->cacheLogger = $cacheConfig->getCacheLogger();
$this->validator = $cacheConfig->getQueryValidator();
}
/**
@@ -90,17 +85,17 @@ class DefaultQueryCache implements QueryCache
*/
public function get(QueryCacheKey $key, ResultSetMapping $rsm, array $hints = [])
{
if ( ! ($key->cacheMode & Cache::MODE_GET)) {
if (! ($key->cacheMode & Cache::MODE_GET)) {
return null;
}
$cacheEntry = $this->region->get($key);
if ( ! $cacheEntry instanceof QueryCacheEntry) {
if (! $cacheEntry instanceof QueryCacheEntry) {
return null;
}
if ( ! $this->validator->isValid($key, $cacheEntry)) {
if (! $this->validator->isValid($key, $cacheEntry)) {
$this->region->evict($key);
return null;
@@ -117,7 +112,7 @@ class DefaultQueryCache implements QueryCache
$cm = $this->em->getClassMetadata($entityName);
$generateKeys = static function (array $entry) use ($cm) : EntityCacheKey {
$generateKeys = static function (array $entry) use ($cm): EntityCacheKey {
return new EntityCacheKey($cm->rootEntityName, $entry['identifier']);
};
@@ -140,8 +135,8 @@ class DefaultQueryCache implements QueryCache
$this->cacheLogger->entityCacheHit($regionName, $cacheKeys->identifiers[$index]);
}
if ( ! $hasRelation) {
$result[$index] = $this->uow->createEntity($entityEntry->class, $entityEntry->resolveAssociationEntries($this->em), self::$hints);
if (! $hasRelation) {
$result[$index] = $this->uow->createEntity($entityEntry->class, $entityEntry->resolveAssociationEntries($this->em), self::$hints);
continue;
}
@@ -156,9 +151,10 @@ class DefaultQueryCache implements QueryCache
$assocMetadata = $this->em->getClassMetadata($assoc['targetEntity']);
if ($assoc['type'] & ClassMetadata::TO_ONE) {
$assocKey = new EntityCacheKey($assocMetadata->rootEntityName, $assoc['identifier']);
$assocEntry = $assocRegion->get($assocKey);
if (($assocEntry = $assocRegion->get($assocKey = new EntityCacheKey($assocMetadata->rootEntityName, $assoc['identifier']))) === null) {
if ($assocEntry === null) {
if ($this->cacheLogger !== null) {
$this->cacheLogger->entityCacheMiss($assocRegion->getName(), $assocKey);
}
@@ -177,11 +173,11 @@ class DefaultQueryCache implements QueryCache
continue;
}
if ( ! isset($assoc['list']) || empty($assoc['list'])) {
if (! isset($assoc['list']) || empty($assoc['list'])) {
continue;
}
$generateKeys = function ($id) use ($assocMetadata): EntityCacheKey {
$generateKeys = static function ($id) use ($assocMetadata): EntityCacheKey {
return new EntityCacheKey($assocMetadata->rootEntityName, $id);
};
@@ -249,29 +245,29 @@ class DefaultQueryCache implements QueryCache
public function put(QueryCacheKey $key, ResultSetMapping $rsm, $result, array $hints = [])
{
if ($rsm->scalarMappings) {
throw new CacheException("Second level cache does not support scalar results.");
throw new CacheException('Second level cache does not support scalar results.');
}
if (count($rsm->entityMappings) > 1) {
throw new CacheException("Second level cache does not support multiple root entities.");
throw new CacheException('Second level cache does not support multiple root entities.');
}
if ( ! $rsm->isSelect) {
throw new CacheException("Second-level cache query supports only select statements.");
if (! $rsm->isSelect) {
throw new CacheException('Second-level cache query supports only select statements.');
}
if (($hints[Query\SqlWalker::HINT_PARTIAL] ?? false) === true || ($hints[Query::HINT_FORCE_PARTIAL_LOAD] ?? false) === true) {
throw new CacheException("Second level cache does not support partial entities.");
throw new CacheException('Second level cache does not support partial entities.');
}
if ( ! ($key->cacheMode & Cache::MODE_PUT)) {
if (! ($key->cacheMode & Cache::MODE_PUT)) {
return false;
}
$data = [];
$entityName = reset($rsm->aliasMap);
$rootAlias = key($rsm->aliasMap);
$persister = $this->uow->getEntityPersister($entityName);
$data = [];
$entityName = reset($rsm->aliasMap);
$rootAlias = key($rsm->aliasMap);
$persister = $this->uow->getEntityPersister($entityName);
if (! $persister instanceof CachedEntityPersister) {
throw CacheException::nonCacheableEntity($entityName);
@@ -288,7 +284,7 @@ class DefaultQueryCache implements QueryCache
if (($key->cacheMode & Cache::MODE_REFRESH) || ! $region->contains($entityKey)) {
// Cancel put result if entity put fail
if ( ! $persister->storeEntityCache($entity, $entityKey)) {
if (! $persister->storeEntityCache($entity, $entityKey)) {
return false;
}
}
@@ -298,11 +294,11 @@ class DefaultQueryCache implements QueryCache
// @TODO - move to cache hydration components
foreach ($rsm->relationMap as $alias => $name) {
$parentAlias = $rsm->parentAliasMap[$alias];
$parentClass = $rsm->aliasMap[$parentAlias];
$metadata = $this->em->getClassMetadata($parentClass);
$assoc = $metadata->associationMappings[$name];
$assocValue = $this->getAssociationValue($rsm, $alias, $entity);
$parentAlias = $rsm->parentAliasMap[$alias];
$parentClass = $rsm->aliasMap[$parentAlias];
$metadata = $this->em->getClassMetadata($parentClass);
$assoc = $metadata->associationMappings[$name];
$assocValue = $this->getAssociationValue($rsm, $alias, $entity);
if ($assocValue === null) {
continue;
@@ -311,7 +307,8 @@ class DefaultQueryCache implements QueryCache
// root entity association
if ($rootAlias === $parentAlias) {
// Cancel put result if association put fail
if ( ($assocInfo = $this->storeAssociationCache($key, $assoc, $assocValue)) === null) {
$assocInfo = $this->storeAssociationCache($key, $assoc, $assocValue);
if ($assocInfo === null) {
return false;
}
@@ -321,7 +318,7 @@ class DefaultQueryCache implements QueryCache
}
// store single nested association
if ( ! is_array($assocValue)) {
if (! is_array($assocValue)) {
// Cancel put result if association put fail
if ($this->storeAssociationCache($key, $assoc, $assocValue) === null) {
return false;
@@ -344,15 +341,13 @@ class DefaultQueryCache implements QueryCache
}
/**
* @param \Doctrine\ORM\Cache\QueryCacheKey $key
* @param array $assoc
* @param mixed $assocValue
* @param array<string,mixed> $assoc
* @param mixed $assocValue
*
* @return mixed[]|null
*
* @psalm-return array{targetEntity: string, type: mixed, list?: array[], identifier?: array}|null
* @psalm-return array{targetEntity: class-string, type: mixed, list?: array[], identifier?: array}|null
*/
private function storeAssociationCache(QueryCacheKey $key, array $assoc, $assocValue)
private function storeAssociationCache(QueryCacheKey $key, array $assoc, $assocValue): ?array
{
$assocPersister = $this->uow->getEntityPersister($assoc['targetEntity']);
$assocMetadata = $assocPersister->getClassMetadata();
@@ -363,9 +358,9 @@ class DefaultQueryCache implements QueryCache
$assocIdentifier = $this->uow->getEntityIdentifier($assocValue);
$entityKey = new EntityCacheKey($assocMetadata->rootEntityName, $assocIdentifier);
if ( ! $assocValue instanceof Proxy && ($key->cacheMode & Cache::MODE_REFRESH) || ! $assocRegion->contains($entityKey)) {
if (! $assocValue instanceof Proxy && ($key->cacheMode & Cache::MODE_REFRESH) || ! $assocRegion->contains($entityKey)) {
// Entity put fail
if ( ! $assocPersister->storeEntityCache($assocValue, $entityKey)) {
if (! $assocPersister->storeEntityCache($assocValue, $entityKey)) {
return null;
}
}
@@ -373,7 +368,7 @@ class DefaultQueryCache implements QueryCache
return [
'targetEntity' => $assocMetadata->rootEntityName,
'identifier' => $assocIdentifier,
'type' => $assoc['type']
'type' => $assoc['type'],
];
}
@@ -386,7 +381,7 @@ class DefaultQueryCache implements QueryCache
if (($key->cacheMode & Cache::MODE_REFRESH) || ! $assocRegion->contains($entityKey)) {
// Entity put fail
if ( ! $assocPersister->storeEntityCache($assocItem, $entityKey)) {
if (! $assocPersister->storeEntityCache($assocItem, $entityKey)) {
return null;
}
}
@@ -402,14 +397,15 @@ class DefaultQueryCache implements QueryCache
}
/**
* @param \Doctrine\ORM\Query\ResultSetMapping $rsm
* @param string $assocAlias
* @param object $entity
* @param object $entity
*
* @return array|object
* @return array<object>|object
*/
private function getAssociationValue(ResultSetMapping $rsm, $assocAlias, $entity)
{
private function getAssociationValue(
ResultSetMapping $rsm,
string $assocAlias,
$entity
) {
$path = [];
$alias = $assocAlias;
@@ -420,9 +416,8 @@ class DefaultQueryCache implements QueryCache
array_unshift($path, [
'field' => $field,
'class' => $class
]
);
'class' => $class,
]);
$alias = $parent;
}
@@ -431,10 +426,10 @@ class DefaultQueryCache implements QueryCache
}
/**
* @param mixed $value
* @param array $path
* @param mixed $value
* @param array<mixed> $path
*
* @return array|object|null
* @return mixed
*/
private function getAssociationPathValue($value, array $path)
{
@@ -447,7 +442,7 @@ class DefaultQueryCache implements QueryCache
return null;
}
if (empty($path)) {
if ($path === []) {
return $value;
}

View File

@@ -22,18 +22,17 @@ namespace Doctrine\ORM\Cache;
use Doctrine\ORM\EntityManagerInterface;
use function array_map;
/**
* Entity cache entry
*
* @since 2.5
* @author Fabio B. Silva <fabio.bat.silva@gmail.com>
*/
class EntityCacheEntry implements CacheEntry
{
/**
* READ-ONLY: Public only for performance reasons, it should be considered immutable.
*
* @var array The entity map data
* @var array<string,mixed> The entity map data
*/
public $data;
@@ -41,12 +40,14 @@ class EntityCacheEntry implements CacheEntry
* READ-ONLY: Public only for performance reasons, it should be considered immutable.
*
* @var string The entity class name
* @psalm-var class-string
*/
public $class;
/**
* @param string $class The entity class.
* @param array $data The entity data.
* @param string $class The entity class.
* @param array<string,mixed> $data The entity data.
* @psalm-param class-string $class
*/
public function __construct($class, array $data)
{
@@ -59,7 +60,7 @@ class EntityCacheEntry implements CacheEntry
*
* This method allow Doctrine\Common\Cache\PhpFileCache compatibility
*
* @param array $values array containing property values
* @param array<string,mixed> $values array containing property values
*
* @return EntityCacheEntry
*/
@@ -71,14 +72,12 @@ class EntityCacheEntry implements CacheEntry
/**
* Retrieves the entity data resolving cache entries
*
* @param \Doctrine\ORM\EntityManagerInterface $em
*
* @return array
* @return array<string, mixed>
*/
public function resolveAssociationEntries(EntityManagerInterface $em)
{
return array_map(function($value) use ($em) {
if ( ! ($value instanceof AssociationCacheEntry)) {
return array_map(static function ($value) use ($em) {
if (! ($value instanceof AssociationCacheEntry)) {
return $value;
}

View File

@@ -20,18 +20,20 @@
namespace Doctrine\ORM\Cache;
use function implode;
use function ksort;
use function str_replace;
use function strtolower;
/**
* Defines entity classes roles to be stored in the cache region.
*
* @since 2.5
* @author Fabio B. Silva <fabio.bat.silva@gmail.com>
*/
class EntityCacheKey extends CacheKey
{
/**
* READ-ONLY: Public only for performance reasons, it should be considered immutable.
*
* @var array The entity identifier
* @var array<string, mixed> The entity identifier
*/
public $identifier;
@@ -43,8 +45,8 @@ class EntityCacheKey extends CacheKey
public $entityClass;
/**
* @param string $entityClass The entity class name. In a inheritance hierarchy it should always be the root entity class.
* @param array $identifier The entity identifier
* @param string $entityClass The entity class name. In a inheritance hierarchy it should always be the root entity class.
* @param array<string, mixed> $identifier The entity identifier
*/
public function __construct($entityClass, array $identifier)
{

View File

@@ -24,26 +24,23 @@ use Doctrine\ORM\Mapping\ClassMetadata;
/**
* Hydrator cache entry for entities
*
* @since 2.5
* @author Fabio B. Silva <fabio.bat.silva@gmail.com>
*/
interface EntityHydrator
{
/**
* @param \Doctrine\ORM\Mapping\ClassMetadata $metadata The entity metadata.
* @param \Doctrine\ORM\Cache\EntityCacheKey $key The entity cache key.
* @param object $entity The entity.
* @param ClassMetadata $metadata The entity metadata.
* @param EntityCacheKey $key The entity cache key.
* @param object $entity The entity.
*
* @return \Doctrine\ORM\Cache\EntityCacheEntry
* @return EntityCacheEntry
*/
public function buildCacheEntry(ClassMetadata $metadata, EntityCacheKey $key, $entity);
/**
* @param \Doctrine\ORM\Mapping\ClassMetadata $metadata The entity metadata.
* @param \Doctrine\ORM\Cache\EntityCacheKey $key The entity cache key.
* @param \Doctrine\ORM\Cache\EntityCacheEntry $entry The entity cache entry.
* @param object $entity The entity to load the cache into. If not specified, a new entity is created.
* @param ClassMetadata $metadata The entity metadata.
* @param EntityCacheKey $key The entity cache key.
* @param EntityCacheEntry $entry The entity cache entry.
* @param object $entity The entity to load the cache into. If not specified, a new entity is created.
*/
public function loadCacheEntry(ClassMetadata $metadata, EntityCacheKey $key, EntityCacheEntry $entry, $entity = null);
}

View File

@@ -20,27 +20,23 @@
namespace Doctrine\ORM\Cache;
use function time;
use function uniqid;
/**
* Cache Lock
*
* @since 2.5
* @author Fabio B. Silva <fabio.bat.silva@gmail.com>
*/
class Lock
{
/**
* @var string
*/
/** @var string */
public $value;
/**
* @var integer
*/
/** @var int */
public $time;
/**
* @param string $value
* @param integer $time
* @param string $value
* @param int $time
*/
public function __construct($value, $time = null)
{
@@ -49,7 +45,7 @@ class Lock
}
/**
* @return \Doctrine\ORM\Cache\Lock
* @return Lock
*/
public static function createLockRead()
{

View File

@@ -22,11 +22,7 @@ namespace Doctrine\ORM\Cache;
/**
* Lock exception for cache.
*
* @since 2.5
* @author Fabio B. Silva <fabio.bat.silva@gmail.com>
*/
class LockException extends CacheException
{
}

View File

@@ -26,81 +26,78 @@ use Doctrine\ORM\Cache\QueryCacheKey;
/**
* Interface for logging.
*
* @since 2.5
* @author Fabio B. Silva <fabio.bat.silva@gmail.com>
*/
interface CacheLogger
{
/**
* Log an entity put into second level cache.
*
* @param string $regionName The name of the cache region.
* @param \Doctrine\ORM\Cache\EntityCacheKey $key The cache key of the entity.
* @param string $regionName The name of the cache region.
* @param EntityCacheKey $key The cache key of the entity.
*/
public function entityCachePut($regionName, EntityCacheKey $key);
/**
* Log an entity get from second level cache resulted in a hit.
*
* @param string $regionName The name of the cache region.
* @param \Doctrine\ORM\Cache\EntityCacheKey $key The cache key of the entity.
* @param string $regionName The name of the cache region.
* @param EntityCacheKey $key The cache key of the entity.
*/
public function entityCacheHit($regionName, EntityCacheKey $key);
/**
* Log an entity get from second level cache resulted in a miss.
*
* @param string $regionName The name of the cache region.
* @param \Doctrine\ORM\Cache\EntityCacheKey $key The cache key of the entity.
* @param string $regionName The name of the cache region.
* @param EntityCacheKey $key The cache key of the entity.
*/
public function entityCacheMiss($regionName, EntityCacheKey $key);
/**
* Log an entity put into second level cache.
*
* @param string $regionName The name of the cache region.
* @param \Doctrine\ORM\Cache\CollectionCacheKey $key The cache key of the collection.
*/
* Log an entity put into second level cache.
*
* @param string $regionName The name of the cache region.
* @param CollectionCacheKey $key The cache key of the collection.
*/
public function collectionCachePut($regionName, CollectionCacheKey $key);
/**
* Log an entity get from second level cache resulted in a hit.
*
* @param string $regionName The name of the cache region.
* @param \Doctrine\ORM\Cache\CollectionCacheKey $key The cache key of the collection.
* @param string $regionName The name of the cache region.
* @param CollectionCacheKey $key The cache key of the collection.
*/
public function collectionCacheHit($regionName, CollectionCacheKey $key);
/**
* Log an entity get from second level cache resulted in a miss.
*
* @param string $regionName The name of the cache region.
* @param \Doctrine\ORM\Cache\CollectionCacheKey $key The cache key of the collection.
* @param string $regionName The name of the cache region.
* @param CollectionCacheKey $key The cache key of the collection.
*/
public function collectionCacheMiss($regionName, CollectionCacheKey $key);
/**
* Log a query put into the query cache.
*
* @param string $regionName The name of the cache region.
* @param \Doctrine\ORM\Cache\QueryCacheKey $key The cache key of the query.
* @param string $regionName The name of the cache region.
* @param QueryCacheKey $key The cache key of the query.
*/
public function queryCachePut($regionName, QueryCacheKey $key);
/**
* Log a query get from the query cache resulted in a hit.
*
* @param string $regionName The name of the cache region.
* @param \Doctrine\ORM\Cache\QueryCacheKey $key The cache key of the query.
* @param string $regionName The name of the cache region.
* @param QueryCacheKey $key The cache key of the query.
*/
public function queryCacheHit($regionName, QueryCacheKey $key);
/**
* Log a query get from the query cache resulted in a miss.
*
* @param string $regionName The name of the cache region.
* @param \Doctrine\ORM\Cache\QueryCacheKey $key The cache key of the query.
* @param string $regionName The name of the cache region.
* @param QueryCacheKey $key The cache key of the query.
*/
public function queryCacheMiss($regionName, QueryCacheKey $key);
}

View File

@@ -26,20 +26,16 @@ use Doctrine\ORM\Cache\QueryCacheKey;
/**
* Cache logger chain
*
* @since 2.5
* @author Fabio B. Silva <fabio.bat.silva@gmail.com>
*/
class CacheLoggerChain implements CacheLogger
{
/**
* @var array<\Doctrine\ORM\Cache\Logging\CacheLogger>
*/
/** @var array<CacheLogger> */
private $loggers = [];
/**
* @param string $name
* @param \Doctrine\ORM\Cache\Logging\CacheLogger $logger
* @param string $name
*
* @return void
*/
public function setLogger($name, CacheLogger $logger)
{
@@ -49,15 +45,15 @@ class CacheLoggerChain implements CacheLogger
/**
* @param string $name
*
* @return \Doctrine\ORM\Cache\Logging\CacheLogger|null
* @return CacheLogger|null
*/
public function getLogger($name)
{
return isset($this->loggers[$name]) ? $this->loggers[$name] : null;
return $this->loggers[$name] ?? null;
}
/**
* @return array<\Doctrine\ORM\Cache\Logging\CacheLogger>
* @return array<CacheLogger>
*/
public function getLoggers()
{

View File

@@ -24,27 +24,20 @@ use Doctrine\ORM\Cache\CollectionCacheKey;
use Doctrine\ORM\Cache\EntityCacheKey;
use Doctrine\ORM\Cache\QueryCacheKey;
use function array_sum;
/**
* Provide basic second level cache statistics.
*
* @since 2.5
* @author Fabio B. Silva <fabio.bat.silva@gmail.com>
*/
class StatisticsCacheLogger implements CacheLogger
{
/**
* @var int[]
*/
/** @var int[] */
private $cacheMissCountMap = [];
/**
* @var int[]
*/
/** @var int[] */
private $cacheHitCountMap = [];
/**
* @var int[]
*/
/** @var int[] */
private $cachePutCountMap = [];
/**
@@ -146,7 +139,7 @@ class StatisticsCacheLogger implements CacheLogger
*/
public function getRegionHitCount($regionName)
{
return isset($this->cacheHitCountMap[$regionName]) ? $this->cacheHitCountMap[$regionName] : 0;
return $this->cacheHitCountMap[$regionName] ?? 0;
}
/**
@@ -158,7 +151,7 @@ class StatisticsCacheLogger implements CacheLogger
*/
public function getRegionMissCount($regionName)
{
return isset($this->cacheMissCountMap[$regionName]) ? $this->cacheMissCountMap[$regionName] : 0;
return $this->cacheMissCountMap[$regionName] ?? 0;
}
/**
@@ -170,11 +163,11 @@ class StatisticsCacheLogger implements CacheLogger
*/
public function getRegionPutCount($regionName)
{
return isset($this->cachePutCountMap[$regionName]) ? $this->cachePutCountMap[$regionName] : 0;
return $this->cachePutCountMap[$regionName] ?? 0;
}
/**
* @return array
* @return array<string, int>
*/
public function getRegionsMiss()
{
@@ -182,7 +175,7 @@ class StatisticsCacheLogger implements CacheLogger
}
/**
* @return array
* @return array<string, int>
*/
public function getRegionsHit()
{
@@ -190,7 +183,7 @@ class StatisticsCacheLogger implements CacheLogger
}
/**
* @return array
* @return array<string, int>
*/
public function getRegionsPut()
{
@@ -201,6 +194,8 @@ class StatisticsCacheLogger implements CacheLogger
* Clear region statistics
*
* @param string $regionName The name of the cache region.
*
* @return void
*/
public function clearRegionStats($regionName)
{
@@ -211,6 +206,8 @@ class StatisticsCacheLogger implements CacheLogger
/**
* Clear all statistics
*
* @return void
*/
public function clearStats()
{

View File

@@ -24,9 +24,6 @@ namespace Doctrine\ORM\Cache;
* Defines a region that supports multi-get reading.
*
* With one method call we can get multiple items.
*
* @since 2.5
* @author Asmir Mustafic
*/
interface MultiGetRegion
{

View File

@@ -1,4 +1,5 @@
<?php
/*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
@@ -19,11 +20,10 @@
namespace Doctrine\ORM\Cache\Persister;
use Doctrine\ORM\Cache\Region;
/**
* Interface for persister that support second level cache.
*
* @since 2.5
* @author Fabio B. Silva <fabio.bat.silva@gmail.com>
*/
interface CachedPersister
{
@@ -40,7 +40,7 @@ interface CachedPersister
/**
* Gets the The region access.
*
* @return \Doctrine\ORM\Cache\Region
* @return Region
*/
public function getCacheRegion();
}

View File

@@ -21,99 +21,82 @@
namespace Doctrine\ORM\Cache\Persister\Collection;
use Doctrine\Common\Collections\Criteria;
use Doctrine\ORM\Cache\EntityCacheKey;
use Doctrine\ORM\Cache\CollectionCacheKey;
use Doctrine\ORM\Cache\Persister\Entity\CachedEntityPersister;
use Doctrine\ORM\Persisters\Collection\CollectionPersister;
use Doctrine\ORM\PersistentCollection;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\Cache\Region;
use Doctrine\Common\Util\ClassUtils;
use Doctrine\ORM\Cache\CollectionCacheKey;
use Doctrine\ORM\Cache\CollectionHydrator;
use Doctrine\ORM\Cache\EntityCacheKey;
use Doctrine\ORM\Cache\Logging\CacheLogger;
use Doctrine\ORM\Cache\Persister\Entity\CachedEntityPersister;
use Doctrine\ORM\Cache\Region;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\Mapping\ClassMetadata;
use Doctrine\ORM\Mapping\ClassMetadataFactory;
use Doctrine\ORM\PersistentCollection;
use Doctrine\ORM\Persisters\Collection\CollectionPersister;
use Doctrine\ORM\UnitOfWork;
use function array_values;
use function assert;
use function count;
use function is_array;
/**
* @author Fabio B. Silva <fabio.bat.silva@gmail.com>
* @author Guilherme Blanco <guilhermeblanco@hotmail.com>
* @since 2.5
*/
abstract class AbstractCollectionPersister implements CachedCollectionPersister
{
/**
* @var \Doctrine\ORM\UnitOfWork
*/
/** @var UnitOfWork */
protected $uow;
/**
* @var \Doctrine\ORM\Mapping\ClassMetadataFactory
*/
/** @var ClassMetadataFactory */
protected $metadataFactory;
/**
* @var \Doctrine\ORM\Persisters\Collection\CollectionPersister
*/
/** @var CollectionPersister */
protected $persister;
/**
* @var \Doctrine\ORM\Mapping\ClassMetadata
*/
/** @var ClassMetadata */
protected $sourceEntity;
/**
* @var \Doctrine\ORM\Mapping\ClassMetadata
*/
/** @var ClassMetadata */
protected $targetEntity;
/**
* @var array
*/
/** @var mixed[] */
protected $association;
/**
* @var array
*/
/** @var mixed[] */
protected $queuedCache = [];
/**
* @var \Doctrine\ORM\Cache\Region
*/
/** @var Region */
protected $region;
/**
* @var string
*/
/** @var string */
protected $regionName;
/**
* @var \Doctrine\ORM\Cache\CollectionHydrator
*/
/** @var CollectionHydrator */
protected $hydrator;
/**
* @var \Doctrine\ORM\Cache\Logging\CacheLogger
*/
/** @var CacheLogger|null */
protected $cacheLogger;
/**
* @param \Doctrine\ORM\Persisters\Collection\CollectionPersister $persister The collection persister that will be cached.
* @param \Doctrine\ORM\Cache\Region $region The collection region.
* @param \Doctrine\ORM\EntityManagerInterface $em The entity manager.
* @param array $association The association mapping.
* @param CollectionPersister $persister The collection persister that will be cached.
* @param Region $region The collection region.
* @param EntityManagerInterface $em The entity manager.
* @param mixed[] $association The association mapping.
*/
public function __construct(CollectionPersister $persister, Region $region, EntityManagerInterface $em, array $association)
{
$configuration = $em->getConfiguration();
$cacheConfig = $configuration->getSecondLevelCacheConfiguration();
$cacheFactory = $cacheConfig->getCacheFactory();
$configuration = $em->getConfiguration();
$cacheConfig = $configuration->getSecondLevelCacheConfiguration();
$cacheFactory = $cacheConfig->getCacheFactory();
$this->region = $region;
$this->persister = $persister;
$this->association = $association;
$this->regionName = $region->getName();
$this->uow = $em->getUnitOfWork();
$this->metadataFactory = $em->getMetadataFactory();
$this->cacheLogger = $cacheConfig->getCacheLogger();
$this->hydrator = $cacheFactory->buildCollectionHydrator($em, $association);
$this->sourceEntity = $em->getClassMetadata($association['sourceEntity']);
$this->targetEntity = $em->getClassMetadata($association['targetEntity']);
$this->region = $region;
$this->persister = $persister;
$this->association = $association;
$this->regionName = $region->getName();
$this->uow = $em->getUnitOfWork();
$this->metadataFactory = $em->getMetadataFactory();
$this->cacheLogger = $cacheConfig->getCacheLogger();
$this->hydrator = $cacheFactory->buildCollectionHydrator($em, $association);
$this->sourceEntity = $em->getClassMetadata($association['sourceEntity']);
$this->targetEntity = $em->getClassMetadata($association['targetEntity']);
}
/**
@@ -141,22 +124,17 @@ abstract class AbstractCollectionPersister implements CachedCollectionPersister
}
/**
* @param \Doctrine\ORM\PersistentCollection $collection
* @param \Doctrine\ORM\Cache\CollectionCacheKey $key
*
* @return object[]|null
*/
public function loadCollectionCache(PersistentCollection $collection, CollectionCacheKey $key)
{
if (($cache = $this->region->get($key)) === null) {
$cache = $this->region->get($key);
if ($cache === null) {
return null;
}
if (($cache = $this->hydrator->loadCacheEntry($this->sourceEntity, $key, $cache, $collection)) === null) {
return null;
}
return $cache;
return $this->hydrator->loadCacheEntry($this->sourceEntity, $key, $cache, $collection);
}
/**
@@ -164,14 +142,14 @@ abstract class AbstractCollectionPersister implements CachedCollectionPersister
*/
public function storeCollectionCache(CollectionCacheKey $key, $elements)
{
/* @var $targetPersister CachedEntityPersister */
$associationMapping = $this->sourceEntity->associationMappings[$key->association];
$targetPersister = $this->uow->getEntityPersister($this->targetEntity->rootEntityName);
$targetRegion = $targetPersister->getCacheRegion();
$targetHydrator = $targetPersister->getEntityHydrator();
assert($targetPersister instanceof CachedEntityPersister);
$targetRegion = $targetPersister->getCacheRegion();
$targetHydrator = $targetPersister->getEntityHydrator();
// Only preserve ordering if association configured it
if ( ! (isset($associationMapping['indexBy']) && $associationMapping['indexBy'])) {
if (! (isset($associationMapping['indexBy']) && $associationMapping['indexBy'])) {
// Elements may be an array or a Collection
$elements = array_values(is_array($elements) ? $elements : $elements->getValues());
}
@@ -183,15 +161,15 @@ abstract class AbstractCollectionPersister implements CachedCollectionPersister
continue;
}
$class = $this->targetEntity;
$className = ClassUtils::getClass($elements[$index]);
$class = $this->targetEntity;
$className = ClassUtils::getClass($elements[$index]);
if ($className !== $this->targetEntity->name) {
$class = $this->metadataFactory->getMetadataFor($className);
}
$entity = $elements[$index];
$entityEntry = $targetHydrator->buildCacheEntry($class, $entityKey, $entity);
$entity = $elements[$index];
$entityEntry = $targetHydrator->buildCacheEntry($class, $entityKey, $entity);
$targetRegion->put($entityKey, $entityEntry);
}
@@ -262,7 +240,7 @@ abstract class AbstractCollectionPersister implements CachedCollectionPersister
/**
* Clears cache entries related to the current collection
*
* @param PersistentCollection $collection
* @return void
*/
protected function evictCollectionCache(PersistentCollection $collection)
{
@@ -282,13 +260,15 @@ abstract class AbstractCollectionPersister implements CachedCollectionPersister
/**
* @param string $targetEntity
* @param object $element
*
* @return void
*/
protected function evictElementCache($targetEntity, $element)
{
/* @var $targetPersister CachedEntityPersister */
$targetPersister = $this->uow->getEntityPersister($targetEntity);
$targetRegion = $targetPersister->getCacheRegion();
$key = new EntityCacheKey($targetEntity, $this->uow->getEntityIdentifier($element));
assert($targetPersister instanceof CachedEntityPersister);
$targetRegion = $targetPersister->getCacheRegion();
$key = new EntityCacheKey($targetEntity, $this->uow->getEntityIdentifier($element));
$targetRegion->evict($key);

View File

@@ -20,44 +20,39 @@
namespace Doctrine\ORM\Cache\Persister\Collection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Cache\CollectionCacheKey;
use Doctrine\ORM\Cache\Persister\CachedPersister;
use Doctrine\ORM\Persisters\Collection\CollectionPersister;
use Doctrine\ORM\Mapping\ClassMetadata;
use Doctrine\ORM\PersistentCollection;
use Doctrine\ORM\Persisters\Collection\CollectionPersister;
/**
* Interface for second level cache collection persisters.
*
* @author Fabio B. Silva <fabio.bat.silva@gmail.com>
* @since 2.5
*/
interface CachedCollectionPersister extends CachedPersister, CollectionPersister
{
/**
* @return \Doctrine\ORM\Mapping\ClassMetadata
* @return ClassMetadata
*/
public function getSourceEntityMetadata();
/**
* @return \Doctrine\ORM\Mapping\ClassMetadata
* @return ClassMetadata
*/
public function getTargetEntityMetadata();
/**
* Loads a collection from cache
*
* @param \Doctrine\ORM\PersistentCollection $collection
* @param \Doctrine\ORM\Cache\CollectionCacheKey $key
*
* @return \Doctrine\ORM\PersistentCollection|null
* @return PersistentCollection|null
*/
public function loadCollectionCache(PersistentCollection $collection, CollectionCacheKey $key);
/**
* Stores a collection into cache
*
* @param \Doctrine\ORM\Cache\CollectionCacheKey $key
* @param array|\Doctrine\Common\Collections\Collection $elements
* @param array|mixed[]|Collection $elements
*
* @return void
*/

View File

@@ -23,10 +23,8 @@ namespace Doctrine\ORM\Cache\Persister\Collection;
use Doctrine\ORM\Cache\CollectionCacheKey;
use Doctrine\ORM\PersistentCollection;
/**
* @author Fabio B. Silva <fabio.bat.silva@gmail.com>
* @since 2.5
*/
use function spl_object_hash;
class NonStrictReadWriteCachedCollectionPersister extends AbstractCollectionPersister
{
/**
@@ -78,7 +76,7 @@ class NonStrictReadWriteCachedCollectionPersister extends AbstractCollectionPers
$isInitialized = $collection->isInitialized();
$isDirty = $collection->isDirty();
if ( ! $isInitialized && ! $isDirty) {
if (! $isInitialized && ! $isDirty) {
return;
}
@@ -98,7 +96,7 @@ class NonStrictReadWriteCachedCollectionPersister extends AbstractCollectionPers
$this->queuedCache['update'][spl_object_hash($collection)] = [
'key' => $key,
'list' => $collection
'list' => $collection,
];
}
}

View File

@@ -20,19 +20,15 @@
namespace Doctrine\ORM\Cache\Persister\Collection;
use Doctrine\ORM\PersistentCollection;
use Doctrine\ORM\Cache\CacheException;
use Doctrine\Common\Util\ClassUtils;
use Doctrine\ORM\Cache\CacheException;
use Doctrine\ORM\PersistentCollection;
/**
* @author Fabio B. Silva <fabio.bat.silva@gmail.com>
* @since 2.5
*/
class ReadOnlyCachedCollectionPersister extends NonStrictReadWriteCachedCollectionPersister
{
/**
* {@inheritdoc}
*/
* {@inheritdoc}
*/
public function update(PersistentCollection $collection)
{
if ($collection->isDirty() && $collection->getSnapshot()) {

View File

@@ -20,23 +20,21 @@
namespace Doctrine\ORM\Cache\Persister\Collection;
use Doctrine\ORM\Persisters\Collection\CollectionPersister;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\Cache\CollectionCacheKey;
use Doctrine\ORM\Cache\ConcurrentRegion;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\PersistentCollection;
use Doctrine\ORM\Persisters\Collection\CollectionPersister;
use function spl_object_hash;
/**
* @author Fabio B. Silva <fabio.bat.silva@gmail.com>
* @since 2.5
*/
class ReadWriteCachedCollectionPersister extends AbstractCollectionPersister
{
/**
* @param \Doctrine\ORM\Persisters\Collection\CollectionPersister $persister The collection persister that will be cached.
* @param \Doctrine\ORM\Cache\ConcurrentRegion $region The collection region.
* @param \Doctrine\ORM\EntityManagerInterface $em The entity manager.
* @param array $association The association mapping.
* @param CollectionPersister $persister The collection persister that will be cached.
* @param ConcurrentRegion $region The collection region.
* @param EntityManagerInterface $em The entity manager.
* @param mixed[] $association The association mapping.
*/
public function __construct(CollectionPersister $persister, ConcurrentRegion $region, EntityManagerInterface $em, array $association)
{
@@ -100,7 +98,7 @@ class ReadWriteCachedCollectionPersister extends AbstractCollectionPersister
$this->queuedCache['delete'][spl_object_hash($collection)] = [
'key' => $key,
'lock' => $lock
'lock' => $lock,
];
}
@@ -112,7 +110,7 @@ class ReadWriteCachedCollectionPersister extends AbstractCollectionPersister
$isInitialized = $collection->isInitialized();
$isDirty = $collection->isDirty();
if ( ! $isInitialized && ! $isDirty) {
if (! $isInitialized && ! $isDirty) {
return;
}
@@ -128,7 +126,7 @@ class ReadWriteCachedCollectionPersister extends AbstractCollectionPersister
$this->queuedCache['update'][spl_object_hash($collection)] = [
'key' => $key,
'lock' => $lock
'lock' => $lock,
];
}
}

View File

@@ -20,117 +20,97 @@
namespace Doctrine\ORM\Cache\Persister\Entity;
use Doctrine\ORM\Cache;
use Doctrine\ORM\Cache\Region;
use Doctrine\ORM\Cache\EntityCacheKey;
use Doctrine\ORM\Cache\CollectionCacheKey;
use Doctrine\ORM\Cache\TimestampCacheKey;
use Doctrine\ORM\Cache\QueryCacheKey;
use Doctrine\ORM\Cache\Persister\CachedPersister;
use Doctrine\ORM\Mapping\ClassMetadata;
use Doctrine\ORM\PersistentCollection;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\Persisters\Entity\EntityPersister;
use Doctrine\Common\Util\ClassUtils;
use Doctrine\Common\Collections\Criteria;
use Doctrine\Common\Util\ClassUtils;
use Doctrine\ORM\Cache;
use Doctrine\ORM\Cache\CollectionCacheKey;
use Doctrine\ORM\Cache\EntityCacheKey;
use Doctrine\ORM\Cache\EntityHydrator;
use Doctrine\ORM\Cache\Logging\CacheLogger;
use Doctrine\ORM\Cache\Persister\CachedPersister;
use Doctrine\ORM\Cache\QueryCacheKey;
use Doctrine\ORM\Cache\Region;
use Doctrine\ORM\Cache\TimestampCacheKey;
use Doctrine\ORM\Cache\TimestampRegion;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\Mapping\ClassMetadata;
use Doctrine\ORM\Mapping\ClassMetadataFactory;
use Doctrine\ORM\PersistentCollection;
use Doctrine\ORM\Persisters\Entity\EntityPersister;
use Doctrine\ORM\UnitOfWork;
use function assert;
use function serialize;
use function sha1;
/**
* @author Fabio B. Silva <fabio.bat.silva@gmail.com>
* @since 2.5
*/
abstract class AbstractEntityPersister implements CachedEntityPersister
{
/**
* @var \Doctrine\ORM\UnitOfWork
*/
/** @var UnitOfWork */
protected $uow;
/**
* @var \Doctrine\ORM\Mapping\ClassMetadataFactory
*/
/** @var ClassMetadataFactory */
protected $metadataFactory;
/**
* @var \Doctrine\ORM\Persisters\Entity\EntityPersister
*/
/** @var EntityPersister */
protected $persister;
/**
* @var \Doctrine\ORM\Mapping\ClassMetadata
*/
/** @var ClassMetadata */
protected $class;
/**
* @var array
*/
/** @var mixed[] */
protected $queuedCache = [];
/**
* @var \Doctrine\ORM\Cache\Region
*/
/** @var Region */
protected $region;
/**
* @var \Doctrine\ORM\Cache\TimestampRegion
*/
/** @var TimestampRegion */
protected $timestampRegion;
/**
* @var \Doctrine\ORM\Cache\TimestampCacheKey
*/
/** @var TimestampCacheKey */
protected $timestampKey;
/**
* @var \Doctrine\ORM\Cache\EntityHydrator
*/
/** @var EntityHydrator */
protected $hydrator;
/**
* @var \Doctrine\ORM\Cache
*/
/** @var Cache */
protected $cache;
/**
* @var \Doctrine\ORM\Cache\Logging\CacheLogger
*/
/** @var CacheLogger|null */
protected $cacheLogger;
/**
* @var string
*/
/** @var string */
protected $regionName;
/**
* Associations configured as FETCH_EAGER, as well as all inverse one-to-one associations.
*
* @var array|null
* @var array<string>|null
*/
protected $joinedAssociations;
/**
* @param \Doctrine\ORM\Persisters\Entity\EntityPersister $persister The entity persister to cache.
* @param \Doctrine\ORM\Cache\Region $region The entity cache region.
* @param \Doctrine\ORM\EntityManagerInterface $em The entity manager.
* @param \Doctrine\ORM\Mapping\ClassMetadata $class The entity metadata.
* @param EntityPersister $persister The entity persister to cache.
* @param Region $region The entity cache region.
* @param EntityManagerInterface $em The entity manager.
* @param ClassMetadata $class The entity metadata.
*/
public function __construct(EntityPersister $persister, Region $region, EntityManagerInterface $em, ClassMetadata $class)
{
$configuration = $em->getConfiguration();
$cacheConfig = $configuration->getSecondLevelCacheConfiguration();
$cacheFactory = $cacheConfig->getCacheFactory();
$configuration = $em->getConfiguration();
$cacheConfig = $configuration->getSecondLevelCacheConfiguration();
$cacheFactory = $cacheConfig->getCacheFactory();
$this->class = $class;
$this->region = $region;
$this->persister = $persister;
$this->cache = $em->getCache();
$this->regionName = $region->getName();
$this->uow = $em->getUnitOfWork();
$this->metadataFactory = $em->getMetadataFactory();
$this->cacheLogger = $cacheConfig->getCacheLogger();
$this->timestampRegion = $cacheFactory->getTimestampRegion();
$this->hydrator = $cacheFactory->buildEntityHydrator($em, $class);
$this->timestampKey = new TimestampCacheKey($this->class->rootEntityName);
$this->class = $class;
$this->region = $region;
$this->persister = $persister;
$this->cache = $em->getCache();
$this->regionName = $region->getName();
$this->uow = $em->getUnitOfWork();
$this->metadataFactory = $em->getMetadataFactory();
$this->cacheLogger = $cacheConfig->getCacheLogger();
$this->timestampRegion = $cacheFactory->getTimestampRegion();
$this->hydrator = $cacheFactory->buildEntityHydrator($em, $class);
$this->timestampKey = new TimestampCacheKey($this->class->rootEntityName);
}
/**
@@ -152,7 +132,7 @@ abstract class AbstractEntityPersister implements CachedEntityPersister
/**
* {@inheritdoc}
*/
public function getSelectSQL($criteria, $assoc = null, $lockMode = null, $limit = null, $offset = null, array $orderBy = null)
public function getSelectSQL($criteria, $assoc = null, $lockMode = null, $limit = null, $offset = null, ?array $orderBy = null)
{
return $this->persister->getSelectSQL($criteria, $assoc, $lockMode, $limit, $offset, $orderBy);
}
@@ -192,9 +172,9 @@ abstract class AbstractEntityPersister implements CachedEntityPersister
/**
* {@inheritdoc}
*/
public function exists($entity, Criteria $extraConditions = null)
public function exists($entity, ?Criteria $extraConditions = null)
{
if (null === $extraConditions) {
if ($extraConditions === null) {
$key = new EntityCacheKey($this->class->rootEntityName, $this->class->getIdentifierValues($entity));
if ($this->region->contains($key)) {
@@ -214,7 +194,7 @@ abstract class AbstractEntityPersister implements CachedEntityPersister
}
/**
* @return \Doctrine\ORM\Cache\EntityHydrator
* @return EntityHydrator
*/
public function getEntityHydrator()
{
@@ -226,8 +206,8 @@ abstract class AbstractEntityPersister implements CachedEntityPersister
*/
public function storeEntityCache($entity, EntityCacheKey $key)
{
$class = $this->class;
$className = ClassUtils::getClass($entity);
$class = $this->class;
$className = ClassUtils::getClass($entity);
if ($className !== $this->class->name) {
$class = $this->metadataFactory->getMetadataFor($className);
@@ -246,16 +226,17 @@ abstract class AbstractEntityPersister implements CachedEntityPersister
/**
* @param object $entity
*/
private function storeJoinedAssociations($entity)
private function storeJoinedAssociations($entity): void
{
if ($this->joinedAssociations === null) {
$associations = [];
foreach ($this->class->associationMappings as $name => $assoc) {
if (isset($assoc['cache']) &&
if (
isset($assoc['cache']) &&
($assoc['type'] & ClassMetadata::TO_ONE) &&
($assoc['fetch'] === ClassMetadata::FETCH_EAGER || ! $assoc['isOwningSide'])) {
($assoc['fetch'] === ClassMetadata::FETCH_EAGER || ! $assoc['isOwningSide'])
) {
$associations[] = $name;
}
}
@@ -291,7 +272,7 @@ abstract class AbstractEntityPersister implements CachedEntityPersister
*
* @return string
*/
protected function getHash($query, $criteria, array $orderBy = null, $limit = null, $offset = null)
protected function getHash($query, $criteria, ?array $orderBy = null, $limit = null, $offset = null)
{
[$params] = $criteria instanceof Criteria
? $this->persister->expandCriteriaParameters($criteria)
@@ -361,9 +342,9 @@ abstract class AbstractEntityPersister implements CachedEntityPersister
/**
* {@inheritdoc}
*/
public function load(array $criteria, $entity = null, $assoc = null, array $hints = [], $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) {
if ($entity !== null || $assoc !== null || $hints !== [] || $lockMode !== null) {
return $this->persister->load($criteria, $entity, $assoc, $hints, $lockMode, $limit, $orderBy);
}
@@ -383,7 +364,9 @@ abstract class AbstractEntityPersister implements CachedEntityPersister
return $result[0];
}
if (($result = $this->persister->load($criteria, $entity, $assoc, $hints, $lockMode, $limit, $orderBy)) === null) {
$result = $this->persister->load($criteria, $entity, $assoc, $hints, $lockMode, $limit, $orderBy);
if ($result === null) {
return null;
}
@@ -405,7 +388,7 @@ abstract class AbstractEntityPersister implements CachedEntityPersister
/**
* {@inheritdoc}
*/
public function loadAll(array $criteria = [], array $orderBy = null, $limit = null, $offset = null)
public function loadAll(array $criteria = [], ?array $orderBy = null, $limit = null, $offset = null)
{
$query = $this->persister->getSelectSQL($criteria, null, null, $limit, $offset, $orderBy);
$hash = $this->getHash($query, $criteria, null, null, null);
@@ -469,8 +452,8 @@ abstract class AbstractEntityPersister implements CachedEntityPersister
return null;
}
$class = $this->class;
$className = ClassUtils::getClass($entity);
$class = $this->class;
$className = ClassUtils::getClass($entity);
if ($className !== $this->class->name) {
$class = $this->metadataFactory->getMetadataFor($className);
@@ -479,7 +462,7 @@ abstract class AbstractEntityPersister implements CachedEntityPersister
$cacheEntry = $this->hydrator->buildCacheEntry($class, $cacheKey, $entity);
$cached = $this->region->put($cacheKey, $cacheEntry);
if ($cached && (null === $this->joinedAssociations || $this->joinedAssociations)) {
if ($cached && ($this->joinedAssociations === null || $this->joinedAssociations)) {
$this->storeJoinedAssociations($entity);
}
@@ -549,7 +532,7 @@ abstract class AbstractEntityPersister implements CachedEntityPersister
$persister = $this->uow->getCollectionPersister($assoc);
$hasCache = ($persister instanceof CachedPersister);
if ( ! $hasCache) {
if (! $hasCache) {
return $this->persister->loadManyToManyCollection($assoc, $sourceEntity, $collection);
}
@@ -584,7 +567,7 @@ abstract class AbstractEntityPersister implements CachedEntityPersister
$persister = $this->uow->getCollectionPersister($assoc);
$hasCache = ($persister instanceof CachedPersister);
if ( ! $hasCache) {
if (! $hasCache) {
return $this->persister->loadOneToManyCollection($assoc, $sourceEntity, $collection);
}
@@ -636,15 +619,15 @@ abstract class AbstractEntityPersister implements CachedEntityPersister
}
/**
* @param array $association
* @param array $ownerId
* @param array<string, mixed> $association
* @param array<string, mixed> $ownerId
*
* @return CollectionCacheKey
*/
protected function buildCollectionCacheKey(array $association, $ownerId)
{
/** @var ClassMetadata $metadata */
$metadata = $this->metadataFactory->getMetadataFor($association['sourceEntity']);
assert($metadata instanceof ClassMetadata);
return new CollectionCacheKey($metadata->rootEntityName, $association['fieldName'], $ownerId);
}

View File

@@ -21,27 +21,24 @@
namespace Doctrine\ORM\Cache\Persister\Entity;
use Doctrine\ORM\Cache\EntityCacheKey;
use Doctrine\ORM\Cache\EntityHydrator;
use Doctrine\ORM\Cache\Persister\CachedPersister;
use Doctrine\ORM\Persisters\Entity\EntityPersister;
/**
* Interface for second level cache entity persisters.
*
* @author Fabio B. Silva <fabio.bat.silva@gmail.com>
* @since 2.5
*/
interface CachedEntityPersister extends CachedPersister, EntityPersister
{
/**
* @return \Doctrine\ORM\Cache\EntityHydrator
* @return EntityHydrator
*/
public function getEntityHydrator();
/**
* @param object $entity
* @param \Doctrine\ORM\Cache\EntityCacheKey $key
* @param object $entity
*
* @return boolean
* @return bool
*/
public function storeEntityCache($entity, EntityCacheKey $key);
}

View File

@@ -22,12 +22,10 @@ namespace Doctrine\ORM\Cache\Persister\Entity;
use Doctrine\ORM\Cache\EntityCacheKey;
use function get_class;
/**
* Specific non-strict read/write cached entity persister
*
* @author Fabio B. Silva <fabio.bat.silva@gmail.com>
* @author Guilherme Blanco <guilhermeblanco@hotmail.com>
* @since 2.5
*/
class NonStrictReadWriteCachedEntityPersister extends AbstractEntityPersister
{
@@ -102,17 +100,14 @@ class NonStrictReadWriteCachedEntityPersister extends AbstractEntityPersister
/**
* @param object $entity
* @param bool $isChanged
*
* @return bool
*/
private function updateCache($entity, $isChanged)
private function updateCache($entity, bool $isChanged): bool
{
$class = $this->metadataFactory->getMetadataFor(get_class($entity));
$key = new EntityCacheKey($class->rootEntityName, $this->uow->getEntityIdentifier($entity));
$entry = $this->hydrator->buildCacheEntry($class, $key, $entity);
$cached = $this->region->put($key, $entry);
$isChanged = $isChanged ?: $cached;
$class = $this->metadataFactory->getMetadataFor(get_class($entity));
$key = new EntityCacheKey($class->rootEntityName, $this->uow->getEntityIdentifier($entity));
$entry = $this->hydrator->buildCacheEntry($class, $key, $entity);
$cached = $this->region->put($key, $entry);
$isChanged = $isChanged || $cached;
if ($this->cacheLogger && $cached) {
$this->cacheLogger->entityCachePut($this->regionName, $key);

View File

@@ -20,14 +20,11 @@
namespace Doctrine\ORM\Cache\Persister\Entity;
use Doctrine\ORM\Cache\CacheException;
use Doctrine\Common\Util\ClassUtils;
use Doctrine\ORM\Cache\CacheException;
/**
* Specific read-only region entity persister
*
* @author Fabio B. Silva <fabio.bat.silva@gmail.com>
* @since 2.5
*/
class ReadOnlyCachedEntityPersister extends NonStrictReadWriteCachedEntityPersister
{

View File

@@ -20,26 +20,22 @@
namespace Doctrine\ORM\Cache\Persister\Entity;
use Doctrine\ORM\Persisters\Entity\EntityPersister;
use Doctrine\ORM\Mapping\ClassMetadata;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\Cache\ConcurrentRegion;
use Doctrine\ORM\Cache\EntityCacheKey;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\Mapping\ClassMetadata;
use Doctrine\ORM\Persisters\Entity\EntityPersister;
/**
* Specific read-write entity persister
*
* @author Fabio B. Silva <fabio.bat.silva@gmail.com>
* @author Guilherme Blanco <guilhermeblanco@hotmail.com>
* @since 2.5
*/
class ReadWriteCachedEntityPersister extends AbstractEntityPersister
{
/**
* @param \Doctrine\ORM\Persisters\Entity\EntityPersister $persister The entity persister to cache.
* @param \Doctrine\ORM\Cache\ConcurrentRegion $region The entity cache region.
* @param \Doctrine\ORM\EntityManagerInterface $em The entity manager.
* @param \Doctrine\ORM\Mapping\ClassMetadata $class The entity metadata.
* @param EntityPersister $persister The entity persister to cache.
* @param ConcurrentRegion $region The entity cache region.
* @param EntityManagerInterface $em The entity manager.
* @param ClassMetadata $class The entity metadata.
*/
public function __construct(EntityPersister $persister, ConcurrentRegion $region, EntityManagerInterface $em, ClassMetadata $class)
{
@@ -115,7 +111,7 @@ class ReadWriteCachedEntityPersister extends AbstractEntityPersister
$this->queuedCache['delete'][] = [
'lock' => $lock,
'key' => $key
'key' => $key,
];
return $deleted;
@@ -137,7 +133,7 @@ class ReadWriteCachedEntityPersister extends AbstractEntityPersister
$this->queuedCache['update'][] = [
'lock' => $lock,
'key' => $key
'key' => $key,
];
}
}

View File

@@ -25,38 +25,31 @@ use Doctrine\ORM\Query\ResultSetMapping;
/**
* Defines the contract for caches capable of storing query results.
* These caches should only concern themselves with storing the matching result ids.
*
* @since 2.5
* @author Fabio B. Silva <fabio.bat.silva@gmail.com>
*/
interface QueryCache
{
/**
* @return boolean
* @return bool
*/
public function clear();
/**
* @param \Doctrine\ORM\Cache\QueryCacheKey $key
* @param \Doctrine\ORM\Query\ResultSetMapping $rsm
* @param mixed $result
* @param array $hints
* @param mixed $result
* @param mixed[] $hints
*
* @return boolean
* @return bool
*/
public function put(QueryCacheKey $key, ResultSetMapping $rsm, $result, array $hints = []);
/**
* @param \Doctrine\ORM\Cache\QueryCacheKey $key
* @param \Doctrine\ORM\Query\ResultSetMapping $rsm
* @param array $hints
* @param mixed[] $hints
*
* @return array|null
* @return mixed[]|null
*/
public function get(QueryCacheKey $key, ResultSetMapping $rsm, array $hints = []);
/**
* @return \Doctrine\ORM\Cache\Region
* @return Region
*/
public function getRegion();
}

View File

@@ -20,18 +20,17 @@
namespace Doctrine\ORM\Cache;
use function microtime;
/**
* Query cache entry
*
* @since 2.5
* @author Fabio B. Silva <fabio.bat.silva@gmail.com>
*/
class QueryCacheEntry implements CacheEntry
{
/**
* READ-ONLY: Public only for performance reasons, it should be considered immutable.
*
* @var array List of entity identifiers
* @var array<string, mixed> List of entity identifiers
*/
public $result;
@@ -43,8 +42,8 @@ class QueryCacheEntry implements CacheEntry
public $time;
/**
* @param array $result
* @param float $time
* @param array<string, mixed> $result
* @param float $time
*/
public function __construct($result, $time = null)
{
@@ -53,7 +52,7 @@ class QueryCacheEntry implements CacheEntry
}
/**
* @param array $values
* @param array<string, mixed> $values
*
* @return QueryCacheEntry
*/

View File

@@ -24,23 +24,20 @@ use Doctrine\ORM\Cache;
/**
* A cache key that identifies a particular query.
*
* @since 2.5
* @author Fabio B. Silva <fabio.bat.silva@gmail.com>
*/
class QueryCacheKey extends CacheKey
{
/**
* READ-ONLY: Public only for performance reasons, it should be considered immutable.
*
* @var integer Cache key lifetime
* @var int Cache key lifetime
*/
public $lifetime;
/**
* READ-ONLY: Public only for performance reasons, it should be considered immutable.
*
* @var integer Cache mode (Doctrine\ORM\Cache::MODE_*)
* @var int Cache mode (Doctrine\ORM\Cache::MODE_*)
*/
public $cacheMode;
@@ -52,16 +49,15 @@ class QueryCacheKey extends CacheKey
public $timestampKey;
/**
* @param string $hash Result cache id
* @param integer $lifetime Query lifetime
* @param int $cacheMode Query cache mode
* @param TimestampCacheKey|null $timestampKey
* @param string $hash Result cache id
* @param int $lifetime Query lifetime
* @param int $cacheMode Query cache mode
*/
public function __construct(
$hash,
$lifetime = 0,
$cacheMode = Cache::MODE_NORMAL,
TimestampCacheKey $timestampKey = null
?TimestampCacheKey $timestampKey = null
) {
$this->hash = $hash;
$this->lifetime = $lifetime;

View File

@@ -22,19 +22,13 @@ namespace Doctrine\ORM\Cache;
/**
* Cache query validator interface.
*
* @since 2.5
* @author Fabio B. Silva <fabio.bat.silva@gmail.com>
*/
interface QueryCacheValidator
{
/**
* Checks if the query entry is valid
*
* @param \Doctrine\ORM\Cache\QueryCacheKey $key
* @param \Doctrine\ORM\Cache\QueryCacheEntry $entry
*
* @return boolean
* @return bool
*/
public function isValid(QueryCacheKey $key, QueryCacheEntry $entry);
}

View File

@@ -22,9 +22,6 @@ namespace Doctrine\ORM\Cache;
/**
* Defines a contract for accessing a particular named region.
*
* @since 2.5
* @author Fabio B. Silva <fabio.bat.silva@gmail.com>
*/
interface Region extends MultiGetRegion
{
@@ -38,47 +35,47 @@ interface Region extends MultiGetRegion
/**
* Determine whether this region contains data for the given key.
*
* @param \Doctrine\ORM\Cache\CacheKey $key The cache key
* @param CacheKey $key The cache key
*
* @return boolean TRUE if the underlying cache contains corresponding data; FALSE otherwise.
* @return bool TRUE if the underlying cache contains corresponding data; FALSE otherwise.
*/
public function contains(CacheKey $key);
/**
* Get an item from the cache.
*
* @param \Doctrine\ORM\Cache\CacheKey $key The key of the item to be retrieved.
* @param CacheKey $key The key of the item to be retrieved.
*
* @return \Doctrine\ORM\Cache\CacheEntry|null The cached entry or NULL
* @return CacheEntry|null The cached entry or NULL
*
* @throws \Doctrine\ORM\Cache\CacheException Indicates a problem accessing the item or region.
* @throws CacheException Indicates a problem accessing the item or region.
*/
public function get(CacheKey $key);
/**
* Put an item into the cache.
*
* @param \Doctrine\ORM\Cache\CacheKey $key The key under which to cache the item.
* @param \Doctrine\ORM\Cache\CacheEntry $entry The entry to cache.
* @param \Doctrine\ORM\Cache\Lock $lock The lock previously obtained.
* @param CacheKey $key The key under which to cache the item.
* @param CacheEntry $entry The entry to cache.
* @param Lock $lock The lock previously obtained.
*
* @throws \Doctrine\ORM\Cache\CacheException Indicates a problem accessing the region.
* @throws CacheException Indicates a problem accessing the region.
*/
public function put(CacheKey $key, CacheEntry $entry, Lock $lock = null);
public function put(CacheKey $key, CacheEntry $entry, ?Lock $lock = null);
/**
* Remove an item from the cache.
*
* @param \Doctrine\ORM\Cache\CacheKey $key The key under which to cache the item.
* @param CacheKey $key The key under which to cache the item.
*
* @throws \Doctrine\ORM\Cache\CacheException Indicates a problem accessing the region.
* @throws CacheException Indicates a problem accessing the region.
*/
public function evict(CacheKey $key);
/**
* Remove all contents of this particular cache region.
*
* @throws \Doctrine\ORM\Cache\CacheException Indicates problem accessing the region.
* @throws CacheException Indicates problem accessing the region.
*/
public function evictAll();
}

View File

@@ -20,15 +20,16 @@
namespace Doctrine\ORM\Cache\Region;
use Doctrine\Common\Cache\Cache;
use Doctrine\Common\Cache\MultiGetCache;
use Doctrine\ORM\Cache\CacheEntry;
use Doctrine\ORM\Cache\CollectionCacheEntry;
use function assert;
use function count;
/**
* A cache region that enables the retrieval of multiple elements with one call
*
* @since 2.5
* @author Asmir Mustafic <goetas@gmail.com>
*/
class DefaultMultiGetRegion extends DefaultRegion
{
@@ -36,7 +37,7 @@ class DefaultMultiGetRegion extends DefaultRegion
* Note that the multiple type is due to doctrine/cache not integrating the MultiGetCache interface
* in its signature due to BC in 1.x
*
* @var MultiGetCache|\Doctrine\Common\Cache\Cache
* @var MultiGetCache|Cache
*/
protected $cache;
@@ -47,7 +48,7 @@ class DefaultMultiGetRegion extends DefaultRegion
*/
public function __construct($name, MultiGetCache $cache, $lifetime = 0)
{
/* @var $cache \Doctrine\Common\Cache\Cache */
assert($cache instanceof Cache);
parent::__construct($name, $cache, $lifetime);
}

View File

@@ -20,7 +20,9 @@
namespace Doctrine\ORM\Cache\Region;
use BadMethodCallException;
use Doctrine\Common\Cache\Cache as CacheAdapter;
use Doctrine\Common\Cache\CacheProvider;
use Doctrine\Common\Cache\ClearableCache;
use Doctrine\ORM\Cache\CacheEntry;
use Doctrine\ORM\Cache\CacheKey;
@@ -28,41 +30,34 @@ use Doctrine\ORM\Cache\CollectionCacheEntry;
use Doctrine\ORM\Cache\Lock;
use Doctrine\ORM\Cache\Region;
use function get_class;
use function sprintf;
/**
* The simplest cache region compatible with all doctrine-cache drivers.
*
* @since 2.5
* @author Fabio B. Silva <fabio.bat.silva@gmail.com>
*/
class DefaultRegion implements Region
{
const REGION_KEY_SEPARATOR = '_';
public const REGION_KEY_SEPARATOR = '_';
/**
* @var CacheAdapter
*/
/** @var CacheAdapter */
protected $cache;
/**
* @var string
*/
/** @var string */
protected $name;
/**
* @var integer
*/
/** @var int */
protected $lifetime = 0;
/**
* @param string $name
* @param CacheAdapter $cache
* @param integer $lifetime
* @param string $name
* @param int $lifetime
*/
public function __construct($name, CacheAdapter $cache, $lifetime = 0)
{
$this->cache = $cache;
$this->name = (string) $name;
$this->lifetime = (integer) $lifetime;
$this->lifetime = (int) $lifetime;
}
/**
@@ -74,7 +69,7 @@ class DefaultRegion implements Region
}
/**
* @return \Doctrine\Common\Cache\CacheProvider
* @return CacheProvider
*/
public function getCache()
{
@@ -125,7 +120,6 @@ class DefaultRegion implements Region
}
/**
* @param CacheKey $key
* @return string
*/
protected function getCacheEntryKey(CacheKey $key)
@@ -135,14 +129,18 @@ class DefaultRegion implements Region
/**
* {@inheritdoc}
*
* @return bool
*/
public function put(CacheKey $key, CacheEntry $entry, Lock $lock = null)
public function put(CacheKey $key, CacheEntry $entry, ?Lock $lock = null)
{
return $this->cache->save($this->getCacheEntryKey($key), $entry, $this->lifetime);
}
/**
* {@inheritdoc}
*
* @return bool
*/
public function evict(CacheKey $key)
{
@@ -151,11 +149,13 @@ class DefaultRegion implements Region
/**
* {@inheritdoc}
*
* @return bool
*/
public function evictAll()
{
if (! $this->cache instanceof ClearableCache) {
throw new \BadMethodCallException(sprintf(
throw new BadMethodCallException(sprintf(
'Clearing all cache entries is not supported by the supplied cache adapter of type %s',
get_class($this->cache)
));

View File

@@ -20,53 +20,62 @@
namespace Doctrine\ORM\Cache\Region;
use Doctrine\ORM\Cache\CacheEntry;
use Doctrine\ORM\Cache\CacheKey;
use Doctrine\ORM\Cache\CollectionCacheEntry;
use Doctrine\ORM\Cache\ConcurrentRegion;
use Doctrine\ORM\Cache\Lock;
use Doctrine\ORM\Cache\Region;
use Doctrine\ORM\Cache\CacheKey;
use Doctrine\ORM\Cache\CacheEntry;
use Doctrine\ORM\Cache\ConcurrentRegion;
use InvalidArgumentException;
use function array_filter;
use function array_map;
use function chmod;
use function file_get_contents;
use function file_put_contents;
use function fileatime;
use function glob;
use function is_dir;
use function is_file;
use function is_writable;
use function mkdir;
use function sprintf;
use function time;
use function unlink;
use const DIRECTORY_SEPARATOR;
use const LOCK_EX;
/**
* Very naive concurrent region, based on file locks.
*
* @since 2.5
* @author Fabio B. Silva <fabio.bat.silvagmail.com>
*/
class FileLockRegion implements ConcurrentRegion
{
const LOCK_EXTENSION = 'lock';
public const LOCK_EXTENSION = 'lock';
/**
* var \Doctrine\ORM\Cache\Region
*/
/** @var Region */
private $region;
/**
* @var string
*/
/** @var string */
private $directory;
/**
* var integer
*/
/** @psalm-var numeric-string */
private $lockLifetime;
/**
* @param \Doctrine\ORM\Cache\Region $region
* @param string $directory
* @param string $lockLifetime
* @param string $directory
* @param numeric-string $lockLifetime
*
* @throws \InvalidArgumentException
* @throws InvalidArgumentException
*/
public function __construct(Region $region, $directory, $lockLifetime)
{
if ( ! is_dir($directory) && ! @mkdir($directory, 0775, true)) {
throw new \InvalidArgumentException(sprintf('The directory "%s" does not exist and could not be created.', $directory));
if (! is_dir($directory) && ! @mkdir($directory, 0775, true)) {
throw new InvalidArgumentException(sprintf('The directory "%s" does not exist and could not be created.', $directory));
}
if ( ! is_writable($directory)) {
throw new \InvalidArgumentException(sprintf('The directory "%s" is not writable.', $directory));
if (! is_writable($directory)) {
throw new InvalidArgumentException(sprintf('The directory "%s" is not writable.', $directory));
}
$this->region = $region;
@@ -74,24 +83,18 @@ class FileLockRegion implements ConcurrentRegion
$this->lockLifetime = $lockLifetime;
}
/**
* @param \Doctrine\ORM\Cache\CacheKey $key
* @param \Doctrine\ORM\Cache\Lock $lock
*
* @return boolean
*/
private function isLocked(CacheKey $key, Lock $lock = null)
private function isLocked(CacheKey $key, ?Lock $lock = null): bool
{
$filename = $this->getLockFileName($key);
if ( ! is_file($filename)) {
if (! is_file($filename)) {
return false;
}
$time = $this->getLockTime($filename);
$content = $this->getLockContent($filename);
$time = $this->getLockTime($filename);
$content = $this->getLockContent($filename);
if ( ! $content || ! $time) {
if (! $content || ! $time) {
@unlink($filename);
return false;
@@ -102,7 +105,7 @@ class FileLockRegion implements ConcurrentRegion
}
// outdated lock
if (($time + $this->lockLifetime) <= time()) {
if ($time + $this->lockLifetime <= time()) {
@unlink($filename);
return false;
@@ -111,32 +114,23 @@ class FileLockRegion implements ConcurrentRegion
return true;
}
/**
* @param \Doctrine\ORM\Cache\CacheKey $key
*
* @return string
*/
private function getLockFileName(CacheKey $key)
private function getLockFileName(CacheKey $key): string
{
return $this->directory . DIRECTORY_SEPARATOR . $key->hash . '.' . self::LOCK_EXTENSION;
}
/**
* @param string $filename
*
* @return string
* @return string|false
*/
private function getLockContent($filename)
private function getLockContent(string $filename)
{
return @file_get_contents($filename);
}
/**
* @param string $filename
*
* @return integer
* @return int|false
*/
private function getLockTime($filename)
private function getLockTime(string $filename)
{
return @fileatime($filename);
}
@@ -188,7 +182,7 @@ class FileLockRegion implements ConcurrentRegion
/**
* {@inheritdoc}
*/
public function put(CacheKey $key, CacheEntry $entry, Lock $lock = null)
public function put(CacheKey $key, CacheEntry $entry, ?Lock $lock = null)
{
if ($this->isLocked($key, $lock)) {
return false;
@@ -216,7 +210,7 @@ class FileLockRegion implements ConcurrentRegion
{
// The check below is necessary because on some platforms glob returns false
// when nothing matched (even though no errors occurred)
$filenames = glob(sprintf("%s/*.%s" , $this->directory, self::LOCK_EXTENSION));
$filenames = glob(sprintf('%s/*.%s', $this->directory, self::LOCK_EXTENSION));
if ($filenames) {
foreach ($filenames as $filename) {
@@ -239,9 +233,10 @@ class FileLockRegion implements ConcurrentRegion
$lock = Lock::createLockRead();
$filename = $this->getLockFileName($key);
if ( ! @file_put_contents($filename, $lock->value, LOCK_EX)) {
if (! @file_put_contents($filename, $lock->value, LOCK_EX)) {
return null;
}
chmod($filename, 0664);
return $lock;
@@ -258,10 +253,6 @@ class FileLockRegion implements ConcurrentRegion
return false;
}
if ( ! @unlink($this->getLockFileName($key))) {
return false;
}
return true;
return @unlink($this->getLockFileName($key));
}
}

View File

@@ -20,15 +20,12 @@
namespace Doctrine\ORM\Cache\Region;
use Doctrine\ORM\Cache\CacheKey;
use Doctrine\ORM\Cache\TimestampCacheEntry;
use Doctrine\ORM\Cache\TimestampRegion;
use Doctrine\ORM\Cache\CacheKey;
/**
* Tracks the timestamps of the most recent updates to particular keys.
*
* @since 2.5
* @author Fabio B. Silva <fabio.bat.silva@gmail.com>
*/
class UpdateTimestampCache extends DefaultRegion implements TimestampRegion
{
@@ -37,6 +34,6 @@ class UpdateTimestampCache extends DefaultRegion implements TimestampRegion
*/
public function update(CacheKey $key)
{
$this->put($key, new TimestampCacheEntry);
$this->put($key, new TimestampCacheEntry());
}
}

View File

@@ -22,44 +22,33 @@ namespace Doctrine\ORM\Cache;
/**
* Cache regions configuration
*
* @since 2.5
* @author Fabio B. Silva <fabio.bat.silva@gmail.com>
*/
class RegionsConfiguration
{
/**
* @var array
*/
/** @var array<string,int> */
private $lifetimes = [];
/**
* @var array
*/
/** @var array<string,int> */
private $lockLifetimes = [];
/**
* @var integer
*/
/** @var int */
private $defaultLifetime;
/**
* @var integer
*/
/** @var int */
private $defaultLockLifetime;
/**
* @param integer $defaultLifetime
* @param integer $defaultLockLifetime
* @param int $defaultLifetime
* @param int $defaultLockLifetime
*/
public function __construct($defaultLifetime = 3600, $defaultLockLifetime = 60)
{
$this->defaultLifetime = (integer) $defaultLifetime;
$this->defaultLockLifetime = (integer) $defaultLockLifetime;
$this->defaultLifetime = (int) $defaultLifetime;
$this->defaultLockLifetime = (int) $defaultLockLifetime;
}
/**
* @return integer
* @return int
*/
public function getDefaultLifetime()
{
@@ -67,15 +56,17 @@ class RegionsConfiguration
}
/**
* @param integer $defaultLifetime
* @param int $defaultLifetime
*
* @return void
*/
public function setDefaultLifetime($defaultLifetime)
{
$this->defaultLifetime = (integer) $defaultLifetime;
$this->defaultLifetime = (int) $defaultLifetime;
}
/**
* @return integer
* @return int
*/
public function getDefaultLockLifetime()
{
@@ -83,52 +74,54 @@ class RegionsConfiguration
}
/**
* @param integer $defaultLockLifetime
* @param int $defaultLockLifetime
*
* @return void
*/
public function setDefaultLockLifetime($defaultLockLifetime)
{
$this->defaultLockLifetime = (integer) $defaultLockLifetime;
$this->defaultLockLifetime = (int) $defaultLockLifetime;
}
/**
* @param string $regionName
*
* @return integer
* @return int
*/
public function getLifetime($regionName)
{
return isset($this->lifetimes[$regionName])
? $this->lifetimes[$regionName]
: $this->defaultLifetime;
return $this->lifetimes[$regionName] ?? $this->defaultLifetime;
}
/**
* @param string $name
* @param integer $lifetime
* @param string $name
* @param int $lifetime
*
* @return void
*/
public function setLifetime($name, $lifetime)
{
$this->lifetimes[$name] = (integer) $lifetime;
$this->lifetimes[$name] = (int) $lifetime;
}
/**
* @param string $regionName
*
* @return integer
* @return int
*/
public function getLockLifetime($regionName)
{
return isset($this->lockLifetimes[$regionName])
? $this->lockLifetimes[$regionName]
: $this->defaultLockLifetime;
return $this->lockLifetimes[$regionName] ?? $this->defaultLockLifetime;
}
/**
* @param string $name
* @param integer $lifetime
* @param string $name
* @param int $lifetime
*
* @return void
*/
public function setLockLifetime($name, $lifetime)
{
$this->lockLifetimes[$name] = (integer) $lifetime;
$this->lockLifetimes[$name] = (int) $lifetime;
}
}

View File

@@ -20,11 +20,10 @@
namespace Doctrine\ORM\Cache;
use function microtime;
/**
* Timestamp cache entry
*
* @since 2.5
* @author Fabio B. Silva <fabio.bat.silva@gmail.com>
*/
class TimestampCacheEntry implements CacheEntry
{
@@ -48,7 +47,7 @@ class TimestampCacheEntry implements CacheEntry
*
* This method allow Doctrine\Common\Cache\PhpFileCache compatibility
*
* @param array $values array containing property values
* @param array<string,float> $values array containing property values
*
* @return TimestampCacheEntry
*/

View File

@@ -22,9 +22,6 @@ namespace Doctrine\ORM\Cache;
/**
* A key that identifies a timestamped space.
*
* @since 2.5
* @author Fabio B. Silva <fabio.bat.silva@gmail.com>
*/
class TimestampCacheKey extends CacheKey
{

View File

@@ -20,20 +20,13 @@
namespace Doctrine\ORM\Cache;
/**
* @since 2.5
* @author Fabio B. Silva <fabio.bat.silva@gmail.com>
*/
use function microtime;
class TimestampQueryCacheValidator implements QueryCacheValidator
{
/**
* @var TimestampRegion
*/
/** @var TimestampRegion */
private $timestampRegion;
/**
* @param TimestampRegion $timestampRegion
*/
public function __construct(TimestampRegion $timestampRegion)
{
$this->timestampRegion = $timestampRegion;
@@ -48,20 +41,14 @@ class TimestampQueryCacheValidator implements QueryCacheValidator
return false;
}
if ($key->lifetime == 0) {
if ($key->lifetime === 0) {
return true;
}
return ($entry->time + $key->lifetime) > microtime(true);
return $entry->time + $key->lifetime > microtime(true);
}
/**
* @param QueryCacheKey $key
* @param QueryCacheEntry $entry
*
* @return bool
*/
private function regionUpdated(QueryCacheKey $key, QueryCacheEntry $entry)
private function regionUpdated(QueryCacheKey $key, QueryCacheEntry $entry): bool
{
if ($key->timestampKey === null) {
return false;

View File

@@ -22,18 +22,15 @@ namespace Doctrine\ORM\Cache;
/**
* Defines the contract for a cache region which will specifically be used to store entity "update timestamps".
*
* @since 2.5
* @author Fabio B. Silva <fabio.bat.silva@gmail.com>
*/
interface TimestampRegion extends Region
{
/**
* Update an specific key into the cache region.
*
* @param \Doctrine\ORM\Cache\CacheKey $key The key of the item to update the timestamp.
* @param CacheKey $key The key of the item to update the timestamp.
*
* @throws \Doctrine\ORM\Cache\LockException Indicates a problem accessing the region.
* @throws LockException Indicates a problem accessing the region.
*/
public function update(CacheKey $key);
}

View File

@@ -1,4 +1,5 @@
<?php
/*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
@@ -25,7 +26,10 @@ use Doctrine\Common\Annotations\CachedReader;
use Doctrine\Common\Annotations\SimpleAnnotationReader;
use Doctrine\Common\Cache\ArrayCache;
use Doctrine\Common\Cache\Cache as CacheDriver;
use Doctrine\Common\Cache\Psr6\CacheAdapter;
use Doctrine\Common\Cache\Psr6\DoctrineProvider;
use Doctrine\Common\Proxy\AbstractProxyFactory;
use Doctrine\Deprecations\Deprecation;
use Doctrine\ORM\Cache\CacheConfiguration;
use Doctrine\ORM\Mapping\ClassMetadataFactory;
use Doctrine\ORM\Mapping\DefaultEntityListenerResolver;
@@ -35,23 +39,23 @@ use Doctrine\ORM\Mapping\Driver\AnnotationDriver;
use Doctrine\ORM\Mapping\EntityListenerResolver;
use Doctrine\ORM\Mapping\NamingStrategy;
use Doctrine\ORM\Mapping\QuoteStrategy;
use Doctrine\ORM\Query\ResultSetMapping;
use Doctrine\ORM\Repository\DefaultRepositoryFactory;
use Doctrine\ORM\Repository\RepositoryFactory;
use Doctrine\Persistence\Mapping\Driver\MappingDriver;
use Doctrine\Persistence\ObjectRepository;
use function interface_exists;
use Psr\Cache\CacheItemPoolInterface;
use ReflectionClass;
use function class_exists;
use function strtolower;
use function trim;
/**
* Configuration container for all configuration options of Doctrine.
* It combines all configuration options from DBAL & ORM.
*
* Internal note: When adding a new configuration option just write a getter/setter pair.
*
* @since 2.0
* @author Benjamin Eberlei <kontakt@beberlei.de>
* @author Guilherme Blanco <guilhermeblanco@hotmail.com>
* @author Jonathan Wage <jonwage@gmail.com>
* @author Roman Borschel <roman@code-factory.org>
*/
class Configuration extends \Doctrine\DBAL\Configuration
{
@@ -70,38 +74,36 @@ class Configuration extends \Doctrine\DBAL\Configuration
/**
* 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
*
* @return string|null
*/
public function getProxyDir()
{
return isset($this->_attributes['proxyDir'])
? $this->_attributes['proxyDir']
: null;
return $this->_attributes['proxyDir'] ?? null;
}
/**
* 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
*
* @return int Possible values are constants of Doctrine\Common\Proxy\AbstractProxyFactory.
*/
public function getAutoGenerateProxyClasses()
{
return isset($this->_attributes['autoGenerateProxyClasses'])
? $this->_attributes['autoGenerateProxyClasses']
: AbstractProxyFactory::AUTOGENERATE_ALWAYS;
return $this->_attributes['autoGenerateProxyClasses'] ?? AbstractProxyFactory::AUTOGENERATE_ALWAYS;
}
/**
* Sets the strategy for automatically generating proxy classes.
*
* @param boolean|int $autoGenerate Possible values are constants of Doctrine\Common\Proxy\AbstractProxyFactory.
* True is converted to AUTOGENERATE_ALWAYS, false to AUTOGENERATE_NEVER.
* @param bool|int $autoGenerate Possible values are constants of Doctrine\Common\Proxy\AbstractProxyFactory.
* True is converted to AUTOGENERATE_ALWAYS, false to AUTOGENERATE_NEVER.
*
* @return void
*/
@@ -113,16 +115,15 @@ class Configuration extends \Doctrine\DBAL\Configuration
/**
* 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
*
* @return string|null
*/
public function getProxyNamespace()
{
return isset($this->_attributes['proxyNamespace'])
? $this->_attributes['proxyNamespace']
: null;
return $this->_attributes['proxyNamespace'] ?? null;
}
/**
@@ -140,8 +141,6 @@ class Configuration extends \Doctrine\DBAL\Configuration
/**
* Sets the cache driver implementation that is used for metadata caching.
*
* @param MappingDriver $driverImpl
*
* @return void
*
* @todo Force parameter to be a Closure to ensure lazy evaluation
@@ -156,8 +155,8 @@ class Configuration extends \Doctrine\DBAL\Configuration
* Adds a new default annotation driver with a correctly configured annotation reader. If $useSimpleAnnotationReader
* is true, the notation `@Entity` will work, otherwise, the notation `@ORM\Entity` will be supported.
*
* @param array $paths
* @param bool $useSimpleAnnotationReader
* @param bool $useSimpleAnnotationReader
* @psalm-param string|list<string> $paths
*
* @return AnnotationDriver
*/
@@ -169,13 +168,16 @@ class Configuration extends \Doctrine\DBAL\Configuration
// Register the ORM Annotations in the AnnotationRegistry
$reader = new SimpleAnnotationReader();
$reader->addNamespace('Doctrine\ORM\Mapping');
$cachedReader = new CachedReader($reader, new ArrayCache());
} else {
$reader = new AnnotationReader();
}
return new AnnotationDriver($cachedReader, (array) $paths);
if (class_exists(ArrayCache::class)) {
$reader = new CachedReader($reader, new ArrayCache());
}
return new AnnotationDriver(
new CachedReader(new AnnotationReader(), new ArrayCache()),
$reader,
(array) $paths
);
}
@@ -204,7 +206,7 @@ class Configuration extends \Doctrine\DBAL\Configuration
*/
public function getEntityNamespace($entityNamespaceAlias)
{
if ( ! isset($this->_attributes['entityNamespaces'][$entityNamespaceAlias])) {
if (! isset($this->_attributes['entityNamespaces'][$entityNamespaceAlias])) {
throw ORMException::unknownEntityNamespace($entityNamespaceAlias);
}
@@ -214,7 +216,7 @@ class Configuration extends \Doctrine\DBAL\Configuration
/**
* Sets the entity alias map.
*
* @param array $entityNamespaces
* @psalm-param array<string, string> $entityNamespaces
*
* @return void
*/
@@ -226,7 +228,7 @@ class Configuration extends \Doctrine\DBAL\Configuration
/**
* Retrieves the list of registered entity namespace aliases.
*
* @return array
* @psalm-return array<string, string>
*/
public function getEntityNamespaces()
{
@@ -242,28 +244,22 @@ class Configuration extends \Doctrine\DBAL\Configuration
*/
public function getMetadataDriverImpl()
{
return isset($this->_attributes['metadataDriverImpl'])
? $this->_attributes['metadataDriverImpl']
: null;
return $this->_attributes['metadataDriverImpl'] ?? null;
}
/**
* Gets the cache driver implementation that is used for the query cache (SQL cache).
*
* @return \Doctrine\Common\Cache\Cache|null
* @return CacheDriver|null
*/
public function getQueryCacheImpl()
{
return isset($this->_attributes['queryCacheImpl'])
? $this->_attributes['queryCacheImpl']
: null;
return $this->_attributes['queryCacheImpl'] ?? null;
}
/**
* Sets the cache driver implementation that is used for the query cache (SQL cache).
*
* @param \Doctrine\Common\Cache\Cache $cacheImpl
*
* @return void
*/
public function setQueryCacheImpl(CacheDriver $cacheImpl)
@@ -274,20 +270,16 @@ class Configuration extends \Doctrine\DBAL\Configuration
/**
* Gets the cache driver implementation that is used for the hydration cache (SQL cache).
*
* @return \Doctrine\Common\Cache\Cache|null
* @return CacheDriver|null
*/
public function getHydrationCacheImpl()
{
return isset($this->_attributes['hydrationCacheImpl'])
? $this->_attributes['hydrationCacheImpl']
: null;
return $this->_attributes['hydrationCacheImpl'] ?? null;
}
/**
* Sets the cache driver implementation that is used for the hydration cache (SQL cache).
*
* @param \Doctrine\Common\Cache\Cache $cacheImpl
*
* @return void
*/
public function setHydrationCacheImpl(CacheDriver $cacheImpl)
@@ -298,25 +290,55 @@ class Configuration extends \Doctrine\DBAL\Configuration
/**
* Gets the cache driver implementation that is used for metadata caching.
*
* @return \Doctrine\Common\Cache\Cache|null
* @deprecated Deprecated in favor of getMetadataCache
*
* @return CacheDriver|null
*/
public function getMetadataCacheImpl()
{
return isset($this->_attributes['metadataCacheImpl'])
? $this->_attributes['metadataCacheImpl']
: null;
Deprecation::trigger(
'doctrine/orm',
'https://github.com/doctrine/orm/issues/8650',
'Method %s() is deprecated and will be removed in Doctrine ORM 3.0. Use getMetadataCache() instead.',
__METHOD__
);
if (isset($this->_attributes['metadataCacheImpl'])) {
return $this->_attributes['metadataCacheImpl'];
}
return isset($this->_attributes['metadataCache']) ? DoctrineProvider::wrap($this->_attributes['metadataCache']) : null;
}
/**
* Sets the cache driver implementation that is used for metadata caching.
*
* @param \Doctrine\Common\Cache\Cache $cacheImpl
* @deprecated Deprecated in favor of setMetadataCache
*
* @return void
*/
public function setMetadataCacheImpl(CacheDriver $cacheImpl)
{
Deprecation::trigger(
'doctrine/orm',
'https://github.com/doctrine/orm/issues/8650',
'Method %s() is deprecated and will be removed in Doctrine ORM 3.0. Use setMetadataCache() instead.',
__METHOD__
);
$this->_attributes['metadataCacheImpl'] = $cacheImpl;
$this->_attributes['metadataCache'] = CacheAdapter::wrap($cacheImpl);
}
public function getMetadataCache(): ?CacheItemPoolInterface
{
return $this->_attributes['metadataCache'] ?? null;
}
public function setMetadataCache(CacheItemPoolInterface $cache): void
{
$this->_attributes['metadataCache'] = $cache;
$this->_attributes['metadataCacheImpl'] = DoctrineProvider::wrap($cache);
}
/**
@@ -343,7 +365,7 @@ class Configuration extends \Doctrine\DBAL\Configuration
*/
public function getNamedQuery($name)
{
if ( ! isset($this->_attributes['namedQueries'][$name])) {
if (! isset($this->_attributes['namedQueries'][$name])) {
throw ORMException::namedQueryNotFound($name);
}
@@ -369,14 +391,17 @@ class Configuration extends \Doctrine\DBAL\Configuration
*
* @param string $name The name of the query.
*
* @return array A tuple with the first element being the SQL string and the second
* element being the ResultSetMapping.
* @psalm-return array{string, ResultSetMapping} A tuple with the first
* element being the SQL
* string and the second
* element being the
* ResultSetMapping.
*
* @throws ORMException
*/
public function getNamedNativeQuery($name)
{
if ( ! isset($this->_attributes['namedNativeQueries'][$name])) {
if (! isset($this->_attributes['namedNativeQueries'][$name])) {
throw ORMException::namedNativeQueryNotFound($name);
}
@@ -396,7 +421,7 @@ class Configuration extends \Doctrine\DBAL\Configuration
{
$queryCacheImpl = $this->getQueryCacheImpl();
if ( ! $queryCacheImpl) {
if (! $queryCacheImpl) {
throw ORMException::queryCacheNotConfigured();
}
@@ -404,19 +429,19 @@ class Configuration extends \Doctrine\DBAL\Configuration
throw ORMException::queryCacheUsesNonPersistentCache($queryCacheImpl);
}
$metadataCacheImpl = $this->getMetadataCacheImpl();
if ($this->getAutoGenerateProxyClasses()) {
throw ORMException::proxyClassesAlwaysRegenerating();
}
if ( ! $metadataCacheImpl) {
if (! $this->getMetadataCache()) {
throw ORMException::metadataCacheNotConfigured();
}
$metadataCacheImpl = $this->getMetadataCacheImpl();
if ($metadataCacheImpl instanceof ArrayCache) {
throw ORMException::metadataCacheUsesNonPersistentCache($metadataCacheImpl);
}
if ($this->getAutoGenerateProxyClasses()) {
throw ORMException::proxyClassesAlwaysRegenerating();
}
}
/**
@@ -448,9 +473,7 @@ class Configuration extends \Doctrine\DBAL\Configuration
{
$name = strtolower($name);
return isset($this->_attributes['customStringFunctions'][$name])
? $this->_attributes['customStringFunctions'][$name]
: null;
return $this->_attributes['customStringFunctions'][$name] ?? null;
}
/**
@@ -461,7 +484,8 @@ class Configuration extends \Doctrine\DBAL\Configuration
*
* Any previously added string functions are discarded.
*
* @param array $functions The map of custom DQL string functions.
* @psalm-param array<string, class-string> $functions The map of custom
* DQL string functions.
*
* @return void
*/
@@ -501,9 +525,7 @@ class Configuration extends \Doctrine\DBAL\Configuration
{
$name = strtolower($name);
return isset($this->_attributes['customNumericFunctions'][$name])
? $this->_attributes['customNumericFunctions'][$name]
: null;
return $this->_attributes['customNumericFunctions'][$name] ?? null;
}
/**
@@ -514,7 +536,8 @@ class Configuration extends \Doctrine\DBAL\Configuration
*
* Any previously added numeric functions are discarded.
*
* @param array $functions The map of custom DQL numeric functions.
* @psalm-param array<string, class-string> $functions The map of custom
* DQL numeric functions.
*
* @return void
*/
@@ -534,10 +557,9 @@ class Configuration extends \Doctrine\DBAL\Configuration
*
* @param string $name Function name.
* @param string|callable $className Class name or a callable that returns the function.
* @psalm-param class-string|callable $className
*
* @return void
*
* @psalm-param class-string|callable $className
*/
public function addCustomDatetimeFunction($name, $className)
{
@@ -550,16 +572,13 @@ class Configuration extends \Doctrine\DBAL\Configuration
* @param string $name
*
* @return string|null
*
* @psalm-return ?class-string $name
*/
public function getCustomDatetimeFunction($name)
{
$name = strtolower($name);
return isset($this->_attributes['customDatetimeFunctions'][$name])
? $this->_attributes['customDatetimeFunctions'][$name]
: null;
return $this->_attributes['customDatetimeFunctions'][$name] ?? null;
}
/**
@@ -571,10 +590,9 @@ class Configuration extends \Doctrine\DBAL\Configuration
* Any previously added date/time functions are discarded.
*
* @param array $functions The map of custom DQL date/time functions.
* @psalm-param array<string, string> $functions
*
* @return void
*
* @psalm-param array<string, string> $functions
*/
public function setCustomDatetimeFunctions(array $functions)
{
@@ -586,7 +604,7 @@ class Configuration extends \Doctrine\DBAL\Configuration
/**
* Sets the custom hydrator modes in one pass.
*
* @param array $modes An array of ($modeName => $hydrator).
* @param array<string, class-string> $modes An array of ($modeName => $hydrator).
*
* @return void
*/
@@ -605,21 +623,18 @@ class Configuration extends \Doctrine\DBAL\Configuration
* @param string $modeName The hydration mode name.
*
* @return string|null The hydrator class name.
*
* @psalm-return ?class-string
*/
public function getCustomHydrationMode($modeName)
{
return isset($this->_attributes['customHydrationModes'][$modeName])
? $this->_attributes['customHydrationModes'][$modeName]
: null;
return $this->_attributes['customHydrationModes'][$modeName] ?? null;
}
/**
* Adds a custom hydration mode.
*
* @param string $modeName The hydration mode name.
* @param string $hydrator The hydrator class name.
* @psalm-param class-string $hydrator The hydrator class name.
*
* @return void
*/
@@ -632,10 +647,9 @@ class Configuration extends \Doctrine\DBAL\Configuration
* Sets a class metadata factory.
*
* @param string $cmfName
* @psalm-param class-string $cmfName
*
* @return void
*
* @psalm-param class-string $cmfName
*/
public function setClassMetadataFactoryName($cmfName)
{
@@ -644,12 +658,11 @@ class Configuration extends \Doctrine\DBAL\Configuration
/**
* @return string
*
* @psalm-return class-string
*/
public function getClassMetadataFactoryName()
{
if ( ! isset($this->_attributes['classMetadataFactoryName'])) {
if (! isset($this->_attributes['classMetadataFactoryName'])) {
$this->_attributes['classMetadataFactoryName'] = ClassMetadataFactory::class;
}
@@ -661,6 +674,8 @@ class Configuration extends \Doctrine\DBAL\Configuration
*
* @param string $name The name of the filter.
* @param string $className The class name of the filter.
*
* @return void
*/
public function addFilter($name, $className)
{
@@ -674,21 +689,16 @@ class Configuration extends \Doctrine\DBAL\Configuration
*
* @return string|null The class name of the filter, or null if it is not
* defined.
*
* @psalm-return ?class-string
*/
public function getFilterClassName($name)
{
return isset($this->_attributes['filters'][$name])
? $this->_attributes['filters'][$name]
: null;
return $this->_attributes['filters'][$name] ?? null;
}
/**
* Sets default repository class.
*
* @since 2.2
*
* @param string $className
*
* @return void
@@ -697,9 +707,9 @@ class Configuration extends \Doctrine\DBAL\Configuration
*/
public function setDefaultRepositoryClassName($className)
{
$reflectionClass = new \ReflectionClass($className);
$reflectionClass = new ReflectionClass($className);
if ( ! $reflectionClass->implementsInterface(ObjectRepository::class)) {
if (! $reflectionClass->implementsInterface(ObjectRepository::class)) {
throw ORMException::invalidEntityRepository($className);
}
@@ -709,26 +719,17 @@ class Configuration extends \Doctrine\DBAL\Configuration
/**
* Get default repository class.
*
* @since 2.2
*
* @return string
*
* @psalm-return class-string
*/
public function getDefaultRepositoryClassName()
{
return isset($this->_attributes['defaultRepositoryClassName'])
? $this->_attributes['defaultRepositoryClassName']
: EntityRepository::class;
return $this->_attributes['defaultRepositoryClassName'] ?? EntityRepository::class;
}
/**
* Sets naming strategy.
*
* @since 2.3
*
* @param NamingStrategy $namingStrategy
*
* @return void
*/
public function setNamingStrategy(NamingStrategy $namingStrategy)
@@ -739,13 +740,11 @@ class Configuration extends \Doctrine\DBAL\Configuration
/**
* Gets naming strategy..
*
* @since 2.3
*
* @return NamingStrategy
*/
public function getNamingStrategy()
{
if ( ! isset($this->_attributes['namingStrategy'])) {
if (! isset($this->_attributes['namingStrategy'])) {
$this->_attributes['namingStrategy'] = new DefaultNamingStrategy();
}
@@ -755,10 +754,6 @@ class Configuration extends \Doctrine\DBAL\Configuration
/**
* Sets quote strategy.
*
* @since 2.3
*
* @param \Doctrine\ORM\Mapping\QuoteStrategy $quoteStrategy
*
* @return void
*/
public function setQuoteStrategy(QuoteStrategy $quoteStrategy)
@@ -769,13 +764,11 @@ class Configuration extends \Doctrine\DBAL\Configuration
/**
* Gets quote strategy.
*
* @since 2.3
*
* @return \Doctrine\ORM\Mapping\QuoteStrategy
* @return QuoteStrategy
*/
public function getQuoteStrategy()
{
if ( ! isset($this->_attributes['quoteStrategy'])) {
if (! isset($this->_attributes['quoteStrategy'])) {
$this->_attributes['quoteStrategy'] = new DefaultQuoteStrategy();
}
@@ -785,8 +778,7 @@ class Configuration extends \Doctrine\DBAL\Configuration
/**
* Set the entity listener resolver.
*
* @since 2.4
* @param \Doctrine\ORM\Mapping\EntityListenerResolver $resolver
* @return void
*/
public function setEntityListenerResolver(EntityListenerResolver $resolver)
{
@@ -796,12 +788,11 @@ class Configuration extends \Doctrine\DBAL\Configuration
/**
* Get the entity listener resolver.
*
* @since 2.4
* @return \Doctrine\ORM\Mapping\EntityListenerResolver
* @return EntityListenerResolver
*/
public function getEntityListenerResolver()
{
if ( ! isset($this->_attributes['entityListenerResolver'])) {
if (! isset($this->_attributes['entityListenerResolver'])) {
$this->_attributes['entityListenerResolver'] = new DefaultEntityListenerResolver();
}
@@ -811,8 +802,7 @@ class Configuration extends \Doctrine\DBAL\Configuration
/**
* Set the entity repository factory.
*
* @since 2.4
* @param \Doctrine\ORM\Repository\RepositoryFactory $repositoryFactory
* @return void
*/
public function setRepositoryFactory(RepositoryFactory $repositoryFactory)
{
@@ -822,45 +812,32 @@ class Configuration extends \Doctrine\DBAL\Configuration
/**
* Get the entity repository factory.
*
* @since 2.4
* @return \Doctrine\ORM\Repository\RepositoryFactory
* @return RepositoryFactory
*/
public function getRepositoryFactory()
{
return isset($this->_attributes['repositoryFactory'])
? $this->_attributes['repositoryFactory']
: new DefaultRepositoryFactory();
return $this->_attributes['repositoryFactory'] ?? new DefaultRepositoryFactory();
}
/**
* @since 2.5
*
* @return boolean
* @return bool
*/
public function isSecondLevelCacheEnabled()
{
return isset($this->_attributes['isSecondLevelCacheEnabled'])
? $this->_attributes['isSecondLevelCacheEnabled']
: false;
return $this->_attributes['isSecondLevelCacheEnabled'] ?? false;
}
/**
* @since 2.5
*
* @param boolean $flag
* @param bool $flag
*
* @return void
*/
public function setSecondLevelCacheEnabled($flag = true)
{
$this->_attributes['isSecondLevelCacheEnabled'] = (boolean) $flag;
$this->_attributes['isSecondLevelCacheEnabled'] = (bool) $flag;
}
/**
* @since 2.5
*
* @param \Doctrine\ORM\Cache\CacheConfiguration $cacheConfig
*
* @return void
*/
public function setSecondLevelCacheConfiguration(CacheConfiguration $cacheConfig)
@@ -869,39 +846,33 @@ class Configuration extends \Doctrine\DBAL\Configuration
}
/**
* @since 2.5
*
* @return \Doctrine\ORM\Cache\CacheConfiguration|null
* @return CacheConfiguration|null
*/
public function getSecondLevelCacheConfiguration()
{
if ( ! isset($this->_attributes['secondLevelCacheConfiguration']) && $this->isSecondLevelCacheEnabled()) {
if (! isset($this->_attributes['secondLevelCacheConfiguration']) && $this->isSecondLevelCacheEnabled()) {
$this->_attributes['secondLevelCacheConfiguration'] = new CacheConfiguration();
}
return isset($this->_attributes['secondLevelCacheConfiguration'])
? $this->_attributes['secondLevelCacheConfiguration']
: null;
return $this->_attributes['secondLevelCacheConfiguration'] ?? null;
}
/**
* Returns query hints, which will be applied to every query in application
*
* @since 2.5
*
* @return array
* @psalm-return array<string, mixed>
*/
public function getDefaultQueryHints()
{
return isset($this->_attributes['defaultQueryHints']) ? $this->_attributes['defaultQueryHints'] : [];
return $this->_attributes['defaultQueryHints'] ?? [];
}
/**
* Sets array of query hints, which will be applied to every query in application
*
* @since 2.5
* @psalm-param array<string, mixed> $defaultQueryHints
*
* @param array $defaultQueryHints
* @return void
*/
public function setDefaultQueryHints(array $defaultQueryHints)
{
@@ -911,26 +882,22 @@ class Configuration extends \Doctrine\DBAL\Configuration
/**
* Gets the value of a default query hint. If the hint name is not recognized, FALSE is returned.
*
* @since 2.5
*
* @param string $name The name of the hint.
*
* @return mixed The value of the hint or FALSE, if the hint name is not recognized.
*/
public function getDefaultQueryHint($name)
{
return isset($this->_attributes['defaultQueryHints'][$name])
? $this->_attributes['defaultQueryHints'][$name]
: false;
return $this->_attributes['defaultQueryHints'][$name] ?? false;
}
/**
* Sets a default query hint. If the hint name is not recognized, it is silently ignored.
*
* @since 2.5
*
* @param string $name The name of the hint.
* @param mixed $value The value of the hint.
*
* @return void
*/
public function setDefaultQueryHint($name, $value)
{

View File

@@ -1,4 +1,5 @@
<?php
/*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
@@ -19,26 +20,18 @@
namespace Doctrine\ORM\Decorator;
use Doctrine\ORM\Query\ResultSetMapping;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\Query\ResultSetMapping;
use Doctrine\Persistence\ObjectManagerDecorator;
/**
* Base class for EntityManager decorators
*
* @since 2.4
* @author Lars Strojny <lars@strojny.net
*/
abstract class EntityManagerDecorator extends ObjectManagerDecorator implements EntityManagerInterface
{
/**
* @var EntityManagerInterface
*/
/** @var EntityManagerInterface */
protected $wrapped;
/**
* @param EntityManagerInterface $wrapped
*/
public function __construct(EntityManagerInterface $wrapped)
{
$this->wrapped = $wrapped;

View File

@@ -1,4 +1,5 @@
<?php
/*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
@@ -19,21 +20,38 @@
namespace Doctrine\ORM;
use BadMethodCallException;
use Doctrine\Common\Cache\Psr6\CacheAdapter;
use Doctrine\Common\Cache\Psr6\DoctrineProvider;
use Doctrine\Common\EventManager;
use Doctrine\Common\Util\ClassUtils;
use Doctrine\DBAL\Connection;
use Doctrine\DBAL\DriverManager;
use Doctrine\DBAL\LockMode;
use Doctrine\Deprecations\Deprecation;
use Doctrine\ORM\Mapping\ClassMetadata;
use Doctrine\ORM\Query\ResultSetMapping;
use Doctrine\ORM\Mapping\ClassMetadataFactory;
use Doctrine\ORM\Proxy\ProxyFactory;
use Doctrine\ORM\Query\Expr;
use Doctrine\ORM\Query\FilterCollection;
use Doctrine\Common\Util\ClassUtils;
use Doctrine\ORM\Query\ResultSetMapping;
use Doctrine\ORM\Repository\RepositoryFactory;
use Doctrine\Persistence\Mapping\MappingException;
use Doctrine\Persistence\ObjectRepository;
use InvalidArgumentException;
use Throwable;
use function array_keys;
use function call_user_func;
use function get_class;
use function gettype;
use function is_array;
use function is_callable;
use function is_object;
use function is_string;
use function ltrim;
use const E_USER_DEPRECATED;
use function trigger_error;
use function method_exists;
use function sprintf;
/**
* The EntityManager is the central access point to ORM functionality.
@@ -59,68 +77,62 @@ use function trigger_error;
* is not a valid extension point for the EntityManager. Instead you
* should take a look at the {@see \Doctrine\ORM\Decorator\EntityManagerDecorator}
* and wrap your entity manager in a decorator.
*
* @since 2.0
* @author Benjamin Eberlei <kontakt@beberlei.de>
* @author Guilherme Blanco <guilhermeblanco@hotmail.com>
* @author Jonathan Wage <jonwage@gmail.com>
* @author Roman Borschel <roman@code-factory.org>
*/
/* final */class EntityManager implements EntityManagerInterface
{
/**
* The used Configuration.
*
* @var \Doctrine\ORM\Configuration
* @var Configuration
*/
private $config;
/**
* The database connection used by the EntityManager.
*
* @var \Doctrine\DBAL\Connection
* @var Connection
*/
private $conn;
/**
* The metadata factory, used to retrieve the ORM metadata of entity classes.
*
* @var \Doctrine\ORM\Mapping\ClassMetadataFactory
* @var ClassMetadataFactory
*/
private $metadataFactory;
/**
* The UnitOfWork used to coordinate object-level transactions.
*
* @var \Doctrine\ORM\UnitOfWork
* @var UnitOfWork
*/
private $unitOfWork;
/**
* The event manager that is the central point of the event system.
*
* @var \Doctrine\Common\EventManager
* @var EventManager
*/
private $eventManager;
/**
* The proxy factory used to create dynamic proxies.
*
* @var \Doctrine\ORM\Proxy\ProxyFactory
* @var ProxyFactory
*/
private $proxyFactory;
/**
* The repository factory used to create dynamic repositories.
*
* @var \Doctrine\ORM\Repository\RepositoryFactory
* @var RepositoryFactory
*/
private $repositoryFactory;
/**
* The expression builder instance used to generate query expressions.
*
* @var \Doctrine\ORM\Query\Expr
* @var Expr
*/
private $expressionBuilder;
@@ -134,34 +146,29 @@ use function trigger_error;
/**
* Collection of query filters.
*
* @var \Doctrine\ORM\Query\FilterCollection
* @var FilterCollection
*/
private $filterCollection;
/**
* @var \Doctrine\ORM\Cache The second level cache regions API.
*/
/** @var Cache The second level cache regions API. */
private $cache;
/**
* Creates a new EntityManager that operates on the given database connection
* and uses the given Configuration and EventManager implementations.
*
* @param \Doctrine\DBAL\Connection $conn
* @param \Doctrine\ORM\Configuration $config
* @param \Doctrine\Common\EventManager $eventManager
*/
protected function __construct(Connection $conn, Configuration $config, EventManager $eventManager)
{
$this->conn = $conn;
$this->config = $config;
$this->eventManager = $eventManager;
$this->conn = $conn;
$this->config = $config;
$this->eventManager = $eventManager;
$metadataFactoryClassName = $config->getClassMetadataFactoryName();
$this->metadataFactory = new $metadataFactoryClassName;
$this->metadataFactory = new $metadataFactoryClassName();
$this->metadataFactory->setEntityManager($this);
$this->metadataFactory->setCacheDriver($this->config->getMetadataCacheImpl());
$this->configureMetadataCache();
$this->repositoryFactory = $config->getRepositoryFactory();
$this->unitOfWork = new UnitOfWork($this);
@@ -173,9 +180,9 @@ use function trigger_error;
);
if ($config->isSecondLevelCacheEnabled()) {
$cacheConfig = $config->getSecondLevelCacheConfiguration();
$cacheFactory = $cacheConfig->getCacheFactory();
$this->cache = $cacheFactory->createCache($this);
$cacheConfig = $config->getSecondLevelCacheConfiguration();
$cacheFactory = $cacheConfig->getCacheFactory();
$this->cache = $cacheFactory->createCache($this);
}
}
@@ -190,7 +197,7 @@ use function trigger_error;
/**
* Gets the metadata factory used to gather the metadata of classes.
*
* @return \Doctrine\ORM\Mapping\ClassMetadataFactory
* @return ClassMetadataFactory
*/
public function getMetadataFactory()
{
@@ -203,7 +210,7 @@ use function trigger_error;
public function getExpressionBuilder()
{
if ($this->expressionBuilder === null) {
$this->expressionBuilder = new Query\Expr;
$this->expressionBuilder = new Query\Expr();
}
return $this->expressionBuilder;
@@ -230,8 +237,8 @@ use function trigger_error;
*/
public function transactional($func)
{
if (!is_callable($func)) {
throw new \InvalidArgumentException('Expected argument of type "callable", got "' . gettype($func) . '"');
if (! is_callable($func)) {
throw new InvalidArgumentException('Expected argument of type "callable", got "' . gettype($func) . '"');
}
$this->conn->beginTransaction();
@@ -279,9 +286,7 @@ use function trigger_error;
*
* Internal note: Performance-sensitive method.
*
* @param string $className
*
* @return \Doctrine\ORM\Mapping\ClassMetadata
* {@inheritDoc}
*/
public function getClassMetadata($className)
{
@@ -295,7 +300,7 @@ use function trigger_error;
{
$query = new Query($this);
if ( ! empty($dql)) {
if (! empty($dql)) {
$query->setDQL($dql);
}
@@ -349,20 +354,22 @@ use function trigger_error;
* If an entity is explicitly passed to this method only this entity and
* the cascade-persist semantics + scheduled inserts/removals are synchronized.
*
* @param null|object|array $entity
* @param object|mixed[]|null $entity
*
* @return void
*
* @throws \Doctrine\ORM\OptimisticLockException If a version check on an entity that
* makes use of optimistic locking fails.
* @throws OptimisticLockException If a version check on an entity that
* makes use of optimistic locking fails.
* @throws ORMException
*/
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
Deprecation::trigger(
'doctrine/orm',
'https://github.com/doctrine/orm/issues/8459',
'Calling %s() with any arguments to flush specific entities is deprecated and will not be supported in Doctrine ORM 3.0.',
__METHOD__
);
}
@@ -374,15 +381,17 @@ use function trigger_error;
/**
* Finds an Entity by its identifier.
*
* @param string $className The class name of the entity to find.
* @param mixed $id The identity of the entity to find.
* @param integer|null $lockMode One of the \Doctrine\DBAL\LockMode::* constants
* or NULL if no specific lock mode should be used
* during the search.
* @param integer|null $lockVersion The version of the entity to find when using
* optimistic locking.
* @param string $className The class name of the entity to find.
* @param mixed $id The identity of the entity to find.
* @param int|null $lockMode One of the \Doctrine\DBAL\LockMode::* constants
* or NULL if no specific lock mode should be used
* during the search.
* @param int|null $lockVersion The version of the entity to find when using
* optimistic locking.
* @psalm-param class-string<T> $className
*
* @return object|null The entity instance or NULL if the entity can not be found.
* @psalm-return ?T
*
* @throws OptimisticLockException
* @throws ORMInvalidArgumentException
@@ -390,8 +399,6 @@ use function trigger_error;
* @throws ORMException
*
* @template T
* @psalm-param class-string<T> $entityName
* @psalm-return ?T
*/
public function find($className, $id, $lockMode = null, $lockVersion = null)
{
@@ -401,7 +408,7 @@ use function trigger_error;
$this->checkLockRequirements($lockMode, $class);
}
if ( ! is_array($id)) {
if (! is_array($id)) {
if ($class->isIdentifierComposite) {
throw ORMInvalidArgumentException::invalidCompositeIdentifier();
}
@@ -422,7 +429,7 @@ use function trigger_error;
$sortedId = [];
foreach ($class->identifier as $identifier) {
if ( ! isset($id[$identifier])) {
if (! isset($id[$identifier])) {
throw ORMException::missingIdentifierField($class->name, $identifier);
}
@@ -436,20 +443,22 @@ use function trigger_error;
$unitOfWork = $this->getUnitOfWork();
$entity = $unitOfWork->tryGetById($sortedId, $class->rootEntityName);
// Check identity map first
if (($entity = $unitOfWork->tryGetById($sortedId, $class->rootEntityName)) !== false) {
if ( ! ($entity instanceof $class->name)) {
if ($entity !== false) {
if (! ($entity instanceof $class->name)) {
return null;
}
switch (true) {
case LockMode::OPTIMISTIC === $lockMode:
case $lockMode === LockMode::OPTIMISTIC:
$this->lock($entity, $lockMode, $lockVersion);
break;
case LockMode::NONE === $lockMode:
case LockMode::PESSIMISTIC_READ === $lockMode:
case LockMode::PESSIMISTIC_WRITE === $lockMode:
case $lockMode === LockMode::NONE:
case $lockMode === LockMode::PESSIMISTIC_READ:
case $lockMode === LockMode::PESSIMISTIC_WRITE:
$persister = $unitOfWork->getEntityPersister($class->name);
$persister->refresh($sortedId, $entity, $lockMode);
break;
@@ -461,15 +470,15 @@ use function trigger_error;
$persister = $unitOfWork->getEntityPersister($class->name);
switch (true) {
case LockMode::OPTIMISTIC === $lockMode:
case $lockMode === LockMode::OPTIMISTIC:
$entity = $persister->load($sortedId);
$unitOfWork->lock($entity, $lockMode, $lockVersion);
return $entity;
case LockMode::PESSIMISTIC_READ === $lockMode:
case LockMode::PESSIMISTIC_WRITE === $lockMode:
case $lockMode === LockMode::PESSIMISTIC_READ:
case $lockMode === LockMode::PESSIMISTIC_WRITE:
return $persister->load($sortedId, null, null, [], $lockMode);
default:
@@ -484,14 +493,14 @@ use function trigger_error;
{
$class = $this->metadataFactory->getMetadataFor(ltrim($entityName, '\\'));
if ( ! is_array($id)) {
if (! is_array($id)) {
$id = [$class->identifier[0] => $id];
}
$sortedId = [];
foreach ($class->identifier as $identifier) {
if ( ! isset($id[$identifier])) {
if (! isset($id[$identifier])) {
throw ORMException::missingIdentifierField($class->name, $identifier);
}
@@ -503,9 +512,11 @@ use function trigger_error;
throw ORMException::unrecognizedIdentifierFields($class->name, array_keys($id));
}
$entity = $this->unitOfWork->tryGetById($sortedId, $class->rootEntityName);
// Check identity map first, if its already in there just return it.
if (($entity = $this->unitOfWork->tryGetById($sortedId, $class->rootEntityName)) !== false) {
return ($entity instanceof $class->name) ? $entity : null;
if ($entity !== false) {
return $entity instanceof $class->name ? $entity : null;
}
if ($class->subClasses) {
@@ -526,12 +537,14 @@ use function trigger_error;
{
$class = $this->metadataFactory->getMetadataFor(ltrim($entityName, '\\'));
$entity = $this->unitOfWork->tryGetById($identifier, $class->rootEntityName);
// Check identity map first, if its already in there just return it.
if (($entity = $this->unitOfWork->tryGetById($identifier, $class->rootEntityName)) !== false) {
return ($entity instanceof $class->name) ? $entity : null;
if ($entity !== false) {
return $entity instanceof $class->name ? $entity : null;
}
if ( ! is_array($identifier)) {
if (! is_array($identifier)) {
$identifier = [$class->identifier[0] => $identifier];
}
@@ -559,19 +572,21 @@ use function trigger_error;
*/
public function clear($entityName = null)
{
if (null !== $entityName && ! is_string($entityName)) {
if ($entityName !== null && ! 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
Deprecation::trigger(
'doctrine/orm',
'https://github.com/doctrine/orm/issues/8460',
'Calling %s() with any arguments to clear specific entities is deprecated and will not be supported in Doctrine ORM 3.0.',
__METHOD__
);
}
$this->unitOfWork->clear(
null === $entityName
$entityName === null
? null
: $this->metadataFactory->getMetadataFor($entityName)->getName()
);
@@ -605,7 +620,7 @@ use function trigger_error;
*/
public function persist($entity)
{
if ( ! is_object($entity)) {
if (! is_object($entity)) {
throw ORMInvalidArgumentException::invalidObject('EntityManager#persist()', $entity);
}
@@ -629,7 +644,7 @@ use function trigger_error;
*/
public function remove($entity)
{
if ( ! is_object($entity)) {
if (! is_object($entity)) {
throw ORMInvalidArgumentException::invalidObject('EntityManager#remove()', $entity);
}
@@ -651,7 +666,7 @@ use function trigger_error;
*/
public function refresh($entity)
{
if ( ! is_object($entity)) {
if (! is_object($entity)) {
throw ORMInvalidArgumentException::invalidObject('EntityManager#refresh()', $entity);
}
@@ -672,14 +687,10 @@ use function trigger_error;
* @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)) {
if (! is_object($entity)) {
throw ORMInvalidArgumentException::invalidObject('EntityManager#detach()', $entity);
}
@@ -691,20 +702,25 @@ use function trigger_error;
* of this EntityManager and returns the managed copy of the entity.
* The entity passed to merge will not become associated/managed with this EntityManager.
*
* @deprecated 2.7 This method is being removed from the ORM and won't have any replacement
*
* @param object $entity The detached entity to merge into the persistence context.
*
* @return object The managed copy of the 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);
Deprecation::trigger(
'doctrine/orm',
'https://github.com/doctrine/orm/issues/8461',
'Method %s() is deprecated and will be removed in Doctrine ORM 3.0.',
__METHOD__
);
if ( ! is_object($entity)) {
if (! is_object($entity)) {
throw ORMInvalidArgumentException::invalidObject('EntityManager#merge()', $entity);
}
@@ -718,9 +734,14 @@ use function trigger_error;
*/
public function copy($entity, $deep = false)
{
@trigger_error('Method ' . __METHOD__ . '() is deprecated and will be removed in Doctrine ORM 3.0.', E_USER_DEPRECATED);
Deprecation::trigger(
'doctrine/orm',
'https://github.com/doctrine/orm/issues/8462',
'Method %s() is deprecated and will be removed in Doctrine ORM 3.0.',
__METHOD__
);
throw new \BadMethodCallException("Not implemented.");
throw new BadMethodCallException('Not implemented.');
}
/**
@@ -735,12 +756,12 @@ use function trigger_error;
* Gets the repository for an entity class.
*
* @param string $entityName The name of the entity.
* @psalm-param class-string<T> $entityName
*
* @return ObjectRepository|EntityRepository The repository class.
* @psalm-return EntityRepository<T>
*
* @template T
* @psalm-param class-string<T> $entityName
* @psalm-return EntityRepository<T>
*/
public function getRepository($entityName)
{
@@ -752,7 +773,7 @@ use function trigger_error;
*
* @param object $entity
*
* @return boolean TRUE if this EntityManager currently manages the given entity, FALSE otherwise.
* @return bool TRUE if this EntityManager currently manages the given entity, FALSE otherwise.
*/
public function contains($entity)
{
@@ -780,11 +801,9 @@ use function trigger_error;
/**
* Throws an exception if the EntityManager is closed or currently not active.
*
* @return void
*
* @throws ORMException If the EntityManager is closed.
*/
private function errorIfClosed()
private function errorIfClosed(): void
{
if ($this->closed) {
throw ORMException::entityManagerClosed();
@@ -796,7 +815,7 @@ use function trigger_error;
*/
public function isOpen()
{
return (!$this->closed);
return ! $this->closed;
}
/**
@@ -837,7 +856,9 @@ use function trigger_error;
return new Internal\Hydration\SimpleObjectHydrator($this);
default:
if (($class = $this->config->getCustomHydrationMode($hydrationMode)) !== null) {
$class = $this->config->getCustomHydrationMode($hydrationMode);
if ($class !== null) {
return new $class($this);
}
}
@@ -864,18 +885,18 @@ use function trigger_error;
/**
* Factory method to create EntityManager instances.
*
* @param array|Connection $connection An array with the connection parameters or an existing Connection instance.
* @param Configuration $config The Configuration instance to use.
* @param EventManager $eventManager The EventManager instance to use.
* @param array<string, mixed>|Connection $connection An array with the connection parameters or an existing Connection instance.
* @param Configuration $config The Configuration instance to use.
* @param EventManager $eventManager The EventManager instance to use.
*
* @return EntityManager The created EntityManager.
*
* @throws \InvalidArgumentException
* @throws InvalidArgumentException
* @throws ORMException
*/
public static function create($connection, Configuration $config, EventManager $eventManager = null)
public static function create($connection, Configuration $config, ?EventManager $eventManager = null)
{
if ( ! $config->getMetadataDriverImpl()) {
if (! $config->getMetadataDriverImpl()) {
throw ORMException::missingMappingDriverImpl();
}
@@ -887,23 +908,23 @@ use function trigger_error;
/**
* Factory method to create Connection instances.
*
* @param array|Connection $connection An array with the connection parameters or an existing Connection instance.
* @param Configuration $config The Configuration instance to use.
* @param EventManager $eventManager The EventManager instance to use.
* @param array<string, mixed>|Connection $connection An array with the connection parameters or an existing Connection instance.
* @param Configuration $config The Configuration instance to use.
* @param EventManager $eventManager The EventManager instance to use.
*
* @return Connection
*
* @throws \InvalidArgumentException
* @throws InvalidArgumentException
* @throws ORMException
*/
protected static function createConnection($connection, Configuration $config, EventManager $eventManager = null)
protected static function createConnection($connection, Configuration $config, ?EventManager $eventManager = null)
{
if (is_array($connection)) {
return DriverManager::getConnection($connection, $config, $eventManager ?: new EventManager());
}
if ( ! $connection instanceof Connection) {
throw new \InvalidArgumentException(
if (! $connection instanceof Connection) {
throw new InvalidArgumentException(
sprintf(
'Invalid $connection argument of type %s given%s.',
is_object($connection) ? get_class($connection) : gettype($connection),
@@ -924,7 +945,7 @@ use function trigger_error;
*/
public function getFilters()
{
if (null === $this->filterCollection) {
if ($this->filterCollection === null) {
$this->filterCollection = new FilterCollection($this);
}
@@ -936,7 +957,7 @@ use function trigger_error;
*/
public function isFiltersStateClean()
{
return null === $this->filterCollection || $this->filterCollection->isClean();
return $this->filterCollection === null || $this->filterCollection->isClean();
}
/**
@@ -944,12 +965,10 @@ use function trigger_error;
*/
public function hasFilters()
{
return null !== $this->filterCollection;
return $this->filterCollection !== null;
}
/**
* @param int $lockMode
* @param ClassMetadata $class
* @throws OptimisticLockException
* @throws TransactionRequiredException
*/
@@ -957,15 +976,54 @@ use function trigger_error;
{
switch ($lockMode) {
case LockMode::OPTIMISTIC:
if (!$class->isVersioned) {
if (! $class->isVersioned) {
throw OptimisticLockException::notVersioned($class->name);
}
break;
case LockMode::PESSIMISTIC_READ:
case LockMode::PESSIMISTIC_WRITE:
if (!$this->getConnection()->isTransactionActive()) {
if (! $this->getConnection()->isTransactionActive()) {
throw TransactionRequiredException::transactionRequired();
}
}
}
private function configureMetadataCache(): void
{
$metadataCache = $this->config->getMetadataCache();
if (! $metadataCache) {
$this->configureLegacyMetadataCache();
return;
}
// We have a PSR-6 compatible metadata factory. Use cache directly
if (method_exists($this->metadataFactory, 'setCache')) {
$this->metadataFactory->setCache($metadataCache);
return;
}
// Wrap PSR-6 cache to provide doctrine/cache interface
$this->metadataFactory->setCacheDriver(DoctrineProvider::wrap($metadataCache));
}
private function configureLegacyMetadataCache(): void
{
$metadataCache = $this->config->getMetadataCacheImpl();
if (! $metadataCache) {
return;
}
// Metadata factory is not PSR-6 compatible. Use cache directly
if (! method_exists($this->metadataFactory, 'setCache')) {
$this->metadataFactory->setCacheDriver($metadataCache);
return;
}
// Wrap doctrine/cache to provide PSR-6 interface
$this->metadataFactory->setCache(CacheAdapter::wrap($metadataCache));
}
}

View File

@@ -1,4 +1,5 @@
<?php
/*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
@@ -19,30 +20,46 @@
namespace Doctrine\ORM;
use BadMethodCallException;
use DateTimeInterface;
use Doctrine\Common\EventManager;
use Doctrine\DBAL\Connection;
use Doctrine\ORM\Internal\Hydration\AbstractHydrator;
use Doctrine\ORM\Proxy\ProxyFactory;
use Doctrine\ORM\Query\Expr;
use Doctrine\ORM\Query\FilterCollection;
use Doctrine\ORM\Query\ResultSetMapping;
use Doctrine\Persistence\ObjectManager;
/**
* EntityManager interface
*
* @since 2.4
* @author Lars Strojny <lars@strojny.net>
*
* @method Mapping\ClassMetadata getClassMetadata($className)
* @method Mapping\ClassMetadataFactory getMetadataFactory()
*/
interface EntityManagerInterface extends ObjectManager
{
/**
* {@inheritdoc}
*
* @psalm-param class-string<T> $className
*
* @psalm-return EntityRepository<T>
*
* @template T
*/
public function getRepository($className);
/**
* Returns the cache API for managing the second level cache regions or NULL if the cache is not enabled.
*
* @return \Doctrine\ORM\Cache|null
* @return Cache|null
*/
public function getCache();
/**
* Gets the database connection object used by the EntityManager.
*
* @return \Doctrine\DBAL\Connection
* @return Connection
*/
public function getConnection();
@@ -58,7 +75,7 @@ interface EntityManagerInterface extends ObjectManager
* ->where($expr->orX($expr->eq('u.id', 1), $expr->eq('u.id', 2)));
* </code>
*
* @return \Doctrine\ORM\Query\Expr
* @return Expr
*/
public function getExpressionBuilder();
@@ -149,14 +166,14 @@ interface EntityManagerInterface extends ObjectManager
*
* @param string $entityName The name of the entity type.
* @param mixed $id The entity identifier.
* @psalm-param class-string<T> $entityName
*
* @return object|null The entity reference.
* @psalm-return ?T
*
* @throws ORMException
*
* @template T
* @psalm-param class-string<T> $entityName
* @psalm-return ?T
*/
public function getReference($entityName, $id);
@@ -196,21 +213,21 @@ interface EntityManagerInterface extends ObjectManager
*
* @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.
* @param object $entity The entity to copy.
* @param bool $deep FALSE for a shallow copy, TRUE for a deep copy.
*
* @return object The new entity.
*
* @throws \BadMethodCallException
* @throws BadMethodCallException
*/
public function copy($entity, $deep = false);
/**
* Acquire a lock on the given entity.
*
* @param object $entity
* @param int $lockMode
* @param int|null $lockVersion
* @param object $entity
* @param int $lockMode
* @param int|DateTimeInterface|null $lockVersion
*
* @return void
*
@@ -222,7 +239,7 @@ interface EntityManagerInterface extends ObjectManager
/**
* Gets the EventManager used by the EntityManager.
*
* @return \Doctrine\Common\EventManager
* @return EventManager
*/
public function getEventManager();
@@ -248,17 +265,17 @@ interface EntityManagerInterface extends ObjectManager
public function getUnitOfWork();
/**
* Gets a hydrator for the given hydration mode.
*
* This method caches the hydrator instances which is used for all queries that don't
* selectively iterate over the result.
*
* @deprecated
*
* @param string|int $hydrationMode
*
* @return \Doctrine\ORM\Internal\Hydration\AbstractHydrator
*/
* Gets a hydrator for the given hydration mode.
*
* This method caches the hydrator instances which is used for all queries that don't
* selectively iterate over the result.
*
* @deprecated
*
* @param string|int $hydrationMode
*
* @return AbstractHydrator
*/
public function getHydrator($hydrationMode);
/**
@@ -266,7 +283,7 @@ interface EntityManagerInterface extends ObjectManager
*
* @param string|int $hydrationMode
*
* @return \Doctrine\ORM\Internal\Hydration\AbstractHydrator
* @return AbstractHydrator
*
* @throws ORMException
*/
@@ -275,28 +292,40 @@ interface EntityManagerInterface extends ObjectManager
/**
* Gets the proxy factory used by the EntityManager to create entity proxies.
*
* @return \Doctrine\ORM\Proxy\ProxyFactory
* @return ProxyFactory
*/
public function getProxyFactory();
/**
* Gets the enabled filters.
*
* @return \Doctrine\ORM\Query\FilterCollection The active filter collection.
* @return FilterCollection The active filter collection.
*/
public function getFilters();
/**
* Checks whether the state of the filter collection is clean.
*
* @return boolean True, if the filter collection is clean.
* @return bool True, if the filter collection is clean.
*/
public function isFiltersStateClean();
/**
* Checks whether the Entity Manager has filters.
*
* @return boolean True, if the EM has a filter collection.
* @return bool True, if the EM has a filter collection.
*/
public function hasFilters();
/**
* {@inheritDoc}
*
* @psalm-param string|class-string<T> $className
*
* @return Mapping\ClassMetadata
* @psalm-return Mapping\ClassMetadata<T>
*
* @template T of object
*/
public function getClassMetadata($className);
}

View File

@@ -1,4 +1,5 @@
<?php
/*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
@@ -19,11 +20,11 @@
namespace Doctrine\ORM;
use function implode;
use function sprintf;
/**
* Exception thrown when a Proxy fails to retrieve an Entity result.
*
* @author robo
* @since 2.0
*/
class EntityNotFoundException extends ORMException
{
@@ -43,9 +44,21 @@ class EntityNotFoundException extends ORMException
$ids[] = $key . '(' . $value . ')';
}
return new self(
'Entity of type \'' . $className . '\'' . ($ids ? ' for IDs ' . implode(', ', $ids) : '') . ' was not found'
);
}
/**
* Instance for which no identifier can be found
*
* @psalm-param class-string $className
*/
public static function noIdentifierFound(string $className): self
{
return new self(sprintf(
'Unable to find "%s" entity identifier associated with the UnitOfWork',
$className
));
}
}

View File

@@ -1,4 +1,5 @@
<?php
/*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
@@ -19,15 +20,22 @@
namespace Doctrine\ORM;
use BadMethodCallException;
use Doctrine\Common\Collections\Collection;
use Doctrine\Common\Collections\Criteria;
use Doctrine\Common\Collections\Selectable;
use Doctrine\Deprecations\Deprecation;
use Doctrine\Inflector\Inflector;
use Doctrine\Inflector\InflectorFactory;
use Doctrine\ORM\Mapping\ClassMetadata;
use Doctrine\ORM\Query\ResultSetMappingBuilder;
use Doctrine\Persistence\ObjectRepository;
use const E_USER_DEPRECATED;
use function array_slice;
use function lcfirst;
use function trigger_error;
use function sprintf;
use function strpos;
use function substr;
/**
* An EntityRepository serves as a repository for entities with generic as well as
@@ -36,31 +44,19 @@ use function trigger_error;
* This class is designed for inheritance and users can subclass this class to
* write their own repositories with business-specific methods to locate entities.
*
* @since 2.0
* @author Benjamin Eberlei <kontakt@beberlei.de>
* @author Guilherme Blanco <guilhermeblanco@hotmail.com>
* @author Jonathan Wage <jonwage@gmail.com>
* @author Roman Borschel <roman@code-factory.org>
*
* @template T
* @template-implements Selectable<int,T>
* @template-implements ObjectRepository<T>
*/
class EntityRepository implements ObjectRepository, Selectable
{
/**
* @var string
*/
/** @var string */
protected $_entityName;
/**
* @var EntityManager
*/
/** @var EntityManager */
protected $_em;
/**
* @var \Doctrine\ORM\Mapping\ClassMetadata
*/
/** @var ClassMetadata */
protected $_class;
/** @var Inflector */
@@ -69,7 +65,7 @@ class EntityRepository implements ObjectRepository, Selectable
/**
* Initializes a new <tt>EntityRepository</tt>.
*
* @psalm-param Mapping\ClassMetadata<T>
* @psalm-param Mapping\ClassMetadata $class
*/
public function __construct(EntityManagerInterface $em, Mapping\ClassMetadata $class)
{
@@ -113,26 +109,46 @@ class EntityRepository implements ObjectRepository, Selectable
/**
* Creates a new Query instance based on a predefined metadata named query.
*
* @deprecated
*
* @param string $queryName
*
* @return Query
*/
public function createNamedQuery($queryName)
{
Deprecation::trigger(
'doctrine/orm',
'https://github.com/doctrine/orm/issues/8592',
'Named Queries are deprecated, here "%s" on entity %s. Move the query logic into EntityRepository',
$queryName,
$this->_class->name
);
return $this->_em->createQuery($this->_class->getNamedQuery($queryName));
}
/**
* Creates a native SQL query.
*
* @deprecated
*
* @param string $queryName
*
* @return NativeQuery
*/
public function createNativeNamedQuery($queryName)
{
$queryMapping = $this->_class->getNamedNativeQuery($queryName);
$rsm = new Query\ResultSetMappingBuilder($this->_em);
Deprecation::trigger(
'doctrine/orm',
'https://github.com/doctrine/orm/issues/8592',
'Named Native Queries are deprecated, here "%s" on entity %s. Move the query logic into EntityRepository',
$queryName,
$this->_class->name
);
$queryMapping = $this->_class->getNamedNativeQuery($queryName);
$rsm = new Query\ResultSetMappingBuilder($this->_em);
$rsm->addNamedNativeQueryMapping($this->_class, $queryMapping);
return $this->_em->createNativeQuery($queryMapping['query'], $rsm);
@@ -141,13 +157,18 @@ class EntityRepository implements ObjectRepository, Selectable
/**
* Clears the repository, causing all managed entities to become detached.
*
* @return void
*
* @deprecated 2.8 This method is being removed from the ORM and won't have any replacement
*
* @return void
*/
public function clear()
{
@trigger_error('Method ' . __METHOD__ . '() is deprecated and will be removed in Doctrine ORM 3.0.', E_USER_DEPRECATED);
Deprecation::trigger(
'doctrine/orm',
'https://github.com/doctrine/orm/issues/8460',
'Calling %s() is deprecated and will not be supported in Doctrine ORM 3.0.',
__METHOD__
);
$this->_em->clear($this->_class->rootEntityName);
}
@@ -162,7 +183,6 @@ class EntityRepository implements ObjectRepository, Selectable
* @param int|null $lockVersion The lock version.
*
* @return object|null The entity instance or NULL if the entity can not be found.
*
* @psalm-return ?T
*/
public function find($id, $lockMode = null, $lockVersion = null)
@@ -173,9 +193,7 @@ class EntityRepository implements ObjectRepository, Selectable
/**
* Finds all entities in the repository.
*
* @return array The entities.
*
* @psalm-return list<T>
* @psalm-return list<T> The entities.
*/
public function findAll()
{
@@ -185,16 +203,14 @@ class EntityRepository implements ObjectRepository, Selectable
/**
* Finds entities by a set of criteria.
*
* @param array $criteria
* @param array|null $orderBy
* @param int|null $limit
* @param int|null $offset
* @param int|null $limit
* @param int|null $offset
* @psalm-param array<string, mixed> $criteria
* @psalm-param array<string, string>|null $orderBy
*
* @return array The objects.
*
* @psalm-return list<T>
* @psalm-return list<T> The objects.
*/
public function findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
public function findBy(array $criteria, ?array $orderBy = null, $limit = null, $offset = null)
{
$persister = $this->_em->getUnitOfWork()->getEntityPersister($this->_entityName);
@@ -204,14 +220,13 @@ class EntityRepository implements ObjectRepository, Selectable
/**
* Finds a single entity by a set of criteria.
*
* @param array $criteria
* @param array|null $orderBy
* @psalm-param array<string, mixed> $criteria
* @psalm-param array<string, string>|null $orderBy
*
* @return object|null The entity instance or NULL if the entity can not be found.
*
* @psalm-return ?T
*/
public function findOneBy(array $criteria, array $orderBy = null)
public function findOneBy(array $criteria, ?array $orderBy = null)
{
$persister = $this->_em->getUnitOfWork()->getEntityPersister($this->_entityName);
@@ -221,11 +236,11 @@ class EntityRepository implements ObjectRepository, Selectable
/**
* Counts entities by a set of criteria.
*
* @todo Add this method to `ObjectRepository` interface in the next major release
*
* @param array $criteria
* @psalm-param array<string, mixed> $criteria
*
* @return int The cardinality of the objects that match the given criteria.
*
* @todo Add this method to `ObjectRepository` interface in the next major release
*/
public function count(array $criteria)
{
@@ -236,31 +251,32 @@ class EntityRepository implements ObjectRepository, Selectable
* Adds support for magic method calls.
*
* @param string $method
* @param array $arguments
* @psalm-param list<mixed> $arguments
*
* @return mixed The returned value from the resolved method.
*
* @throws ORMException
* @throws \BadMethodCallException If the method called is invalid
* @throws BadMethodCallException If the method called is invalid.
*/
public function __call($method, $arguments)
{
if (0 === strpos($method, 'findBy')) {
if (strpos($method, 'findBy') === 0) {
return $this->resolveMagicCall('findBy', substr($method, 6), $arguments);
}
if (0 === strpos($method, 'findOneBy')) {
if (strpos($method, 'findOneBy') === 0) {
return $this->resolveMagicCall('findOneBy', substr($method, 9), $arguments);
}
if (0 === strpos($method, 'countBy')) {
if (strpos($method, 'countBy') === 0) {
return $this->resolveMagicCall('count', substr($method, 7), $arguments);
}
throw new \BadMethodCallException(
"Undefined method '$method'. The method name must start with ".
"either findBy, findOneBy or countBy!"
);
throw new BadMethodCallException(sprintf(
'Undefined method "%s". The method name must start with ' .
'either findBy, findOneBy or countBy!',
$method
));
}
/**
@@ -299,11 +315,8 @@ class EntityRepository implements ObjectRepository, Selectable
* Select all elements from a selectable that match the expression and
* return a new collection containing these elements.
*
* @param \Doctrine\Common\Collections\Criteria $criteria
*
* @return \Doctrine\Common\Collections\Collection
*
* @psalm-return \Doctrine\Common\Collections\Collection<int, T>
* @return LazyCriteriaCollection
* @psalm-return Collection<int, T>
*/
public function matching(Criteria $criteria)
{
@@ -315,15 +328,15 @@ class EntityRepository implements ObjectRepository, Selectable
/**
* 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
* @param string $method The method to call
* @param string $by The property name used as condition
* @psalm-param list<mixed> $arguments The arguments to pass at method call
*
* @return mixed
*
* @throws ORMException If the method called is invalid or the requested field/association does not exist.
*/
private function resolveMagicCall($method, $by, array $arguments)
private function resolveMagicCall(string $method, string $by, array $arguments)
{
if (! $arguments) {
throw ORMException::findByRequiresParameter($method . $by);

View File

@@ -1,4 +1,5 @@
<?php
/*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
@@ -19,6 +20,7 @@
namespace Doctrine\ORM\Event;
use Doctrine\ORM\EntityManager;
use Doctrine\Persistence\Event\LifecycleEventArgs as BaseLifecycleEventArgs;
/**
@@ -26,9 +28,6 @@ use Doctrine\Persistence\Event\LifecycleEventArgs as BaseLifecycleEventArgs;
* of entities.
*
* @link www.doctrine-project.org
* @since 2.0
* @author Roman Borschel <roman@code-factory.de>
* @author Benjamin Eberlei <kontakt@beberlei.de>
*/
class LifecycleEventArgs extends BaseLifecycleEventArgs
{
@@ -45,7 +44,7 @@ class LifecycleEventArgs extends BaseLifecycleEventArgs
/**
* Retrieves associated EntityManager.
*
* @return \Doctrine\ORM\EntityManager
* @return EntityManager
*/
public function getEntityManager()
{

View File

@@ -1,4 +1,5 @@
<?php
/*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
@@ -20,38 +21,33 @@
namespace Doctrine\ORM\Event;
use Doctrine\Common\EventArgs;
use Doctrine\Common\EventManager;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\Mapping\ClassMetadata;
use Doctrine\ORM\Mapping\EntityListenerResolver;
/**
* A method invoker based on entity lifecycle.
*
* @author Fabio B. Silva <fabio.bat.silva@gmail.com>
* @since 2.4
*/
class ListenersInvoker
{
const INVOKE_NONE = 0;
const INVOKE_LISTENERS = 1;
const INVOKE_CALLBACKS = 2;
const INVOKE_MANAGER = 4;
public const INVOKE_NONE = 0;
public const INVOKE_LISTENERS = 1;
public const INVOKE_CALLBACKS = 2;
public const INVOKE_MANAGER = 4;
/**
* @var \Doctrine\ORM\Mapping\EntityListenerResolver The Entity listener resolver.
*/
/** @var EntityListenerResolver The Entity listener resolver. */
private $resolver;
/**
* The EventManager used for dispatching events.
*
* @var \Doctrine\Common\EventManager
* @var EventManager
*/
private $eventManager;
/**
* Initializes a new ListenersInvoker instance.
*
* @param EntityManagerInterface $em
*/
public function __construct(EntityManagerInterface $em)
{
@@ -62,10 +58,10 @@ class ListenersInvoker
/**
* Get the subscribed event systems
*
* @param \Doctrine\ORM\Mapping\ClassMetadata $metadata The entity metadata.
* @param string $eventName The entity lifecycle event.
* @param ClassMetadata $metadata The entity metadata.
* @param string $eventName The entity lifecycle event.
*
* @return integer Bitmask of subscribed event systems.
* @return int Bitmask of subscribed event systems.
*/
public function getSubscribedSystems(ClassMetadata $metadata, $eventName)
{
@@ -89,11 +85,13 @@ class ListenersInvoker
/**
* Dispatches the lifecycle event of the given entity.
*
* @param \Doctrine\ORM\Mapping\ClassMetadata $metadata The entity metadata.
* @param string $eventName The entity lifecycle event.
* @param object $entity The Entity on which the event occurred.
* @param \Doctrine\Common\EventArgs $event The Event args.
* @param integer $invoke Bitmask to invoke listeners.
* @param ClassMetadata $metadata The entity metadata.
* @param string $eventName The entity lifecycle event.
* @param object $entity The Entity on which the event occurred.
* @param EventArgs $event The Event args.
* @param int $invoke Bitmask to invoke listeners.
*
* @return void
*/
public function invoke(ClassMetadata $metadata, $eventName, $entity, EventArgs $event, $invoke)
{
@@ -105,9 +103,9 @@ class ListenersInvoker
if ($invoke & self::INVOKE_LISTENERS) {
foreach ($metadata->entityListeners[$eventName] as $listener) {
$class = $listener['class'];
$method = $listener['method'];
$instance = $this->resolver->resolve($class);
$class = $listener['class'];
$method = $listener['method'];
$instance = $this->resolver->resolve($class);
$instance->$method($entity, $event);
}

View File

@@ -1,4 +1,5 @@
<?php
/*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
@@ -19,25 +20,22 @@
namespace Doctrine\ORM\Event;
use Doctrine\ORM\EntityManager;
use Doctrine\ORM\Mapping\ClassMetadata;
use Doctrine\Persistence\Event\LoadClassMetadataEventArgs as BaseLoadClassMetadataEventArgs;
/**
* Class that holds event arguments for a loadMetadata event.
*
* @author Jonathan H. Wage <jonwage@gmail.com>
* @since 2.0
*
* Note: method annotations are used instead of method overrides (due to BC policy)
*
* @method __construct(\Doctrine\ORM\Mapping\ClassMetadata $classMetadata, \Doctrine\ORM\EntityManager $objectManager)
* @method \Doctrine\ORM\Mapping\ClassMetadata getClassMetadata()
* @method __construct(ClassMetadata $classMetadata, EntityManager $objectManager)
* @method ClassMetadata getClassMetadata()
*/
class LoadClassMetadataEventArgs extends BaseLoadClassMetadataEventArgs
{
/**
* Retrieve associated EntityManager.
*
* @return \Doctrine\ORM\EntityManager
* @return EntityManager
*/
public function getEntityManager()
{

View File

@@ -1,4 +1,5 @@
<?php
/*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
@@ -22,34 +23,23 @@ namespace Doctrine\ORM\Event;
use Doctrine\Persistence\Event\ManagerEventArgs;
use Doctrine\Persistence\Mapping\ClassMetadata;
use Doctrine\Persistence\ObjectManager;
use function interface_exists;
/**
* Class that holds event arguments for a `onClassMetadataNotFound` event.
*
* This object is mutable by design, allowing callbacks having access to it to set the
* found metadata in it, and therefore "cancelling" a `onClassMetadataNotFound` event
*
* @author Marco Pivetta <ocramius@gmail.com>
* @since 2.5
*/
class OnClassMetadataNotFoundEventArgs extends ManagerEventArgs
{
/**
* @var string
*/
/** @var string */
private $className;
/**
* @var ClassMetadata|null
*/
/** @var ClassMetadata|null */
private $foundMetadata;
/**
* Constructor.
*
* @param string $className
* @param ObjectManager $objectManager
* @param string $className
*/
public function __construct($className, ObjectManager $objectManager)
{
@@ -59,9 +49,9 @@ class OnClassMetadataNotFoundEventArgs extends ManagerEventArgs
}
/**
* @param ClassMetadata|null $classMetadata
* @return void
*/
public function setFoundMetadata(ClassMetadata $classMetadata = null)
public function setFoundMetadata(?ClassMetadata $classMetadata = null)
{
$this->foundMetadata = $classMetadata;
}

View File

@@ -1,4 +1,5 @@
<?php
/*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
@@ -19,34 +20,24 @@
namespace Doctrine\ORM\Event;
use Doctrine\Common\EventArgs;
use Doctrine\ORM\EntityManagerInterface;
/**
* Provides event arguments for the onClear event.
*
* @license http://www.opensource.org/licenses/mit-license.php MIT
* @link www.doctrine-project.org
* @since 2.0
* @author Roman Borschel <roman@code-factory.de>
* @author Benjamin Eberlei <kontakt@beberlei.de>
*/
class OnClearEventArgs extends \Doctrine\Common\EventArgs
class OnClearEventArgs extends EventArgs
{
/**
* @var EntityManagerInterface
*/
/** @var EntityManagerInterface */
private $em;
/**
* @var string|null
*/
/** @var string|null */
private $entityClass;
/**
* Constructor.
*
* @param EntityManagerInterface $em
* @param string|null $entityClass Optional entity class.
* @param string|null $entityClass Optional entity class.
*/
public function __construct(EntityManagerInterface $em, $entityClass = null)
{
@@ -57,7 +48,7 @@ class OnClearEventArgs extends \Doctrine\Common\EventArgs
/**
* Retrieves associated EntityManager.
*
* @return \Doctrine\ORM\EntityManager
* @return EntityManagerInterface
*/
public function getEntityManager()
{
@@ -81,6 +72,6 @@ class OnClearEventArgs extends \Doctrine\Common\EventArgs
*/
public function clearsAllEntities()
{
return ($this->entityClass === null);
return $this->entityClass === null;
}
}

View File

@@ -1,4 +1,5 @@
<?php
/*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
@@ -25,24 +26,13 @@ use Doctrine\ORM\EntityManagerInterface;
/**
* Provides event arguments for the preFlush event.
*
* @license http://www.opensource.org/licenses/mit-license.php MIT
* @link www.doctrine-project.org
* @since 2.0
* @author Roman Borschel <roman@code-factory.de>
* @author Benjamin Eberlei <kontakt@beberlei.de>
*/
class OnFlushEventArgs extends EventArgs
{
/**
* @var EntityManagerInterface
*/
/** @var EntityManagerInterface */
private $em;
/**
* Constructor.
*
* @param EntityManagerInterface $em
*/
public function __construct(EntityManagerInterface $em)
{
$this->em = $em;
@@ -51,11 +41,10 @@ class OnFlushEventArgs extends EventArgs
/**
* Retrieve associated EntityManager.
*
* @return \Doctrine\ORM\EntityManager
* @return EntityManagerInterface
*/
public function getEntityManager()
{
return $this->em;
}
}

View File

@@ -1,4 +1,5 @@
<?php
/*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
@@ -16,31 +17,23 @@
* and is licensed under the MIT license. For more information, see
* <http://www.doctrine-project.org>.
*/
namespace Doctrine\ORM\Event;
use Doctrine\Common\EventArgs;
use Doctrine\ORM\EntityManager;
use Doctrine\ORM\EntityManagerInterface;
/**
* Provides event arguments for the postFlush event.
*
* @license http://www.opensource.org/licenses/mit-license.php MIT
* @link www.doctrine-project.org
* @since 2.0
* @author Daniel Freudenberger <df@rebuy.de>
*/
class PostFlushEventArgs extends EventArgs
{
/**
* @var \Doctrine\ORM\EntityManager
*/
/** @var EntityManager */
private $em;
/**
* Constructor.
*
* @param EntityManagerInterface $em
*/
public function __construct(EntityManagerInterface $em)
{
$this->em = $em;
@@ -49,7 +42,7 @@ class PostFlushEventArgs extends EventArgs
/**
* Retrieves associated EntityManager.
*
* @return \Doctrine\ORM\EntityManager
* @return EntityManager
*/
public function getEntityManager()
{

View File

@@ -1,4 +1,5 @@
<?php
/*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
@@ -20,36 +21,26 @@
namespace Doctrine\ORM\Event;
use Doctrine\Common\EventArgs;
use Doctrine\ORM\EntityManager;
use Doctrine\ORM\EntityManagerInterface;
/**
* Provides event arguments for the preFlush event.
*
* @license http://www.opensource.org/licenses/mit-license.php MIT
* @link www.doctrine-project.com
* @since 2.0
* @author Roman Borschel <roman@code-factory.de>
* @author Benjamin Eberlei <kontakt@beberlei.de>
*/
class PreFlushEventArgs extends EventArgs
{
/**
* @var \Doctrine\ORM\EntityManager
*/
/** @var EntityManager */
private $em;
/**
* Constructor.
*
* @param EntityManagerInterface $em
*/
public function __construct(EntityManagerInterface $em)
{
$this->em = $em;
}
/**
* @return \Doctrine\ORM\EntityManager
* @return EntityManager
*/
public function getEntityManager()
{

View File

@@ -1,4 +1,5 @@
<?php
/*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
@@ -20,28 +21,22 @@
namespace Doctrine\ORM\Event;
use Doctrine\ORM\EntityManagerInterface;
use InvalidArgumentException;
use function get_class;
use function sprintf;
/**
* Class that holds event arguments for a preInsert/preUpdate event.
*
* @author Guilherme Blanco <guilehrmeblanco@hotmail.com>
* @author Roman Borschel <roman@code-factory.org>
* @author Benjamin Eberlei <kontakt@beberlei.de>
* @since 2.0
*/
class PreUpdateEventArgs extends LifecycleEventArgs
{
/**
* @var array
*/
/** @var array<string,array<int,mixed>> */
private $entityChangeSet;
/**
* Constructor.
*
* @param object $entity
* @param EntityManagerInterface $em
* @param array $changeSet
* @param object $entity
* @param array<string,array<int,mixed>> $changeSet
*/
public function __construct($entity, EntityManagerInterface $em, array &$changeSet)
{
@@ -53,7 +48,7 @@ class PreUpdateEventArgs extends LifecycleEventArgs
/**
* Retrieves entity changeset.
*
* @return array
* @return array<string,array<int,mixed>>
*/
public function getEntityChangeSet()
{
@@ -65,7 +60,7 @@ class PreUpdateEventArgs extends LifecycleEventArgs
*
* @param string $field
*
* @return boolean
* @return bool
*/
public function hasChangedField($field)
{
@@ -118,16 +113,12 @@ class PreUpdateEventArgs extends LifecycleEventArgs
/**
* Asserts the field exists in changeset.
*
* @param string $field
*
* @return void
*
* @throws \InvalidArgumentException
* @throws InvalidArgumentException
*/
private function assertValidField($field)
private function assertValidField(string $field): void
{
if ( ! isset($this->entityChangeSet[$field])) {
throw new \InvalidArgumentException(sprintf(
if (! isset($this->entityChangeSet[$field])) {
throw new InvalidArgumentException(sprintf(
'Field "%s" is not a valid field of the entity "%s" in PreUpdateEventArgs.',
$field,
get_class($this->getEntity())

View File

@@ -1,4 +1,5 @@
<?php
/*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
@@ -23,9 +24,6 @@ namespace Doctrine\ORM;
* Container for all ORM events.
*
* This class cannot be instantiated.
*
* @author Roman Borschel <roman@code-factory.org>
* @since 2.0
*/
final class Events
{
@@ -41,30 +39,24 @@ final class Events
* EntityManager remove operation for that entity is executed.
*
* This is an entity lifecycle event.
*
* @var string
*/
const preRemove = 'preRemove';
public const preRemove = 'preRemove';
/**
* The postRemove event occurs for an entity after the entity has
* been deleted. It will be invoked after the database delete operations.
*
* This is an entity lifecycle event.
*
* @var string
*/
const postRemove = 'postRemove';
public const postRemove = 'postRemove';
/**
* The prePersist event occurs for a given entity before the respective
* EntityManager persist operation for that entity is executed.
*
* This is an entity lifecycle event.
*
* @var string
*/
const prePersist = 'prePersist';
public const prePersist = 'prePersist';
/**
* The postPersist event occurs for an entity after the entity has
@@ -72,30 +64,24 @@ final class Events
* Generated primary key values are available in the postPersist event.
*
* This is an entity lifecycle event.
*
* @var string
*/
const postPersist = 'postPersist';
public const postPersist = 'postPersist';
/**
* The preUpdate event occurs before the database update operations to
* entity data.
*
* This is an entity lifecycle event.
*
* @var string
*/
const preUpdate = 'preUpdate';
public const preUpdate = 'preUpdate';
/**
* The postUpdate event occurs after the database update operations to
* entity data.
*
* This is an entity lifecycle event.
*
* @var string
*/
const postUpdate = 'postUpdate';
public const postUpdate = 'postUpdate';
/**
* The postLoad event occurs for an entity after the entity has been loaded
@@ -107,33 +93,27 @@ final class Events
* or event handler.
*
* This is an entity lifecycle event.
*
* @var string
*/
const postLoad = 'postLoad';
public const postLoad = 'postLoad';
/**
* The loadClassMetadata event occurs after the mapping metadata for a class
* has been loaded from a mapping source (annotations/xml/yaml).
*
* @var string
*/
const loadClassMetadata = 'loadClassMetadata';
public const loadClassMetadata = 'loadClassMetadata';
/**
* The onClassMetadataNotFound event occurs whenever loading metadata for a class
* failed.
*
* @var string
*/
const onClassMetadataNotFound = 'onClassMetadataNotFound';
public const onClassMetadataNotFound = 'onClassMetadataNotFound';
/**
* The preFlush event occurs when the EntityManager#flush() operation is invoked,
* but before any changes to managed entities have been calculated. This event is
* always raised right after EntityManager#flush() call.
*/
const preFlush = 'preFlush';
public const preFlush = 'preFlush';
/**
* The onFlush event occurs when the EntityManager#flush() operation is invoked,
@@ -141,10 +121,8 @@ final class Events
* actual database operations are executed. The event is only raised if there is
* actually something to do for the underlying UnitOfWork. If nothing needs to be done,
* the onFlush event is not raised.
*
* @var string
*/
const onFlush = 'onFlush';
public const onFlush = 'onFlush';
/**
* The postFlush event occurs when the EntityManager#flush() operation is invoked and
@@ -152,16 +130,12 @@ final class Events
* actually something to do for the underlying UnitOfWork. If nothing needs to be done,
* the postFlush event is not raised. The event won't be raised if an error occurs during the
* flush operation.
*
* @var string
*/
const postFlush = 'postFlush';
public const postFlush = 'postFlush';
/**
* The onClear event occurs when the EntityManager#clear() operation is invoked,
* after all references to entities have been removed from the unit of work.
*
* @var string
*/
const onClear = 'onClear';
public const onClear = 'onClear';
}

Some files were not shown because too many files have changed in this diff Show More