Compare commits

..

85 Commits
2.8.2 ... 2.8.3

Author SHA1 Message Date
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
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
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
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
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
Grégoire Paris
3580517aac Manually fix cs 2021-03-01 21:49:10 +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
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
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
454 changed files with 4592 additions and 2406 deletions

View File

@@ -7,7 +7,7 @@
"versions": [
{
"name": "3.0",
"branchName": "master",
"branchName": "3.0.x",
"slug": "latest",
"upcoming": true
},

View File

@@ -2,11 +2,16 @@ 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"
@@ -28,16 +31,9 @@ jobs:
- name: "Install dependencies with Composer"
uses: "ramsey/composer-install@v1"
with:
dependency-versions: "highest"
- name: "Install diff-sniffer"
run: "wget https://github.com/diff-sniffer/diff-sniffer/releases/download/0.5.1/diff-sniffer.phar"
- name: "Fetch head branch"
run: "git remote set-branches --add origin $GITHUB_BASE_REF && git fetch origin $GITHUB_BASE_REF"
- name: "Run diff-sniffer"
run: "php diff-sniffer.phar origin/$GITHUB_BASE_REF...$GITHUB_SHA --report=checkstyle | cs2pr"
- name: "Run phpcbf"
run: "vendor/bin/phpcbf"
# https://github.com/doctrine/.github/issues/3
- name: "Run PHP_CodeSniffer"
run: "vendor/bin/phpcs -q --no-colors --report=checkstyle | cs2pr"

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

@@ -5,6 +5,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

@@ -51,12 +51,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

@@ -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

@@ -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()":

View File

@@ -112,7 +112,7 @@ abstract class AbstractQuery
/**
* The map of query hints.
*
* @var array
* @psalm-var array<string, mixed>
*/
protected $_hints = [];
@@ -796,7 +796,7 @@ abstract class AbstractQuery
*
* Alias for execute(null, HYDRATE_ARRAY).
*
* @return array<int,mixed>
* @return mixed[]
*/
public function getArrayResult()
{
@@ -808,7 +808,7 @@ abstract class AbstractQuery
*
* Alias for execute(null, HYDRATE_SCALAR).
*
* @return array<int,mixed>
* @return mixed[]
*/
public function getScalarResult()
{

View File

@@ -428,7 +428,7 @@ class DefaultQueryCache implements QueryCache
* @param mixed $value
* @param array<mixed> $path
*
* @return array<object>|object|null
* @return mixed
*/
private function getAssociationPathValue($value, array $path)
{

View File

@@ -59,7 +59,7 @@ class FileLockRegion implements ConcurrentRegion
/** @var string */
private $directory;
/** @var int */
/** @psalm-var numeric-string */
private $lockLifetime;
/**

View File

@@ -36,6 +36,7 @@ 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;
@@ -149,10 +150,11 @@ 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
*
* @return AnnotationDriver
*
* @psalm-param string|list<string> $paths
*/
public function newDefaultAnnotationDriver($paths = [], $useSimpleAnnotationReader = true)
{
@@ -207,9 +209,9 @@ class Configuration extends \Doctrine\DBAL\Configuration
/**
* Sets the entity alias map.
*
* @param array $entityNamespaces
*
* @return void
*
* @psalm-param array<string, string> $entityNamespaces
*/
public function setEntityNamespaces(array $entityNamespaces)
{
@@ -219,7 +221,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()
{
@@ -348,10 +350,13 @@ 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.
*
* @throws ORMException
*
* @psalm-return array{string, ResultSetMapping} A tuple with the first
* element being the SQL
* string and the second
* element being the
* ResultSetMapping.
*/
public function getNamedNativeQuery($name)
{
@@ -439,9 +444,10 @@ class Configuration extends \Doctrine\DBAL\Configuration
*
* Any previously added string functions are discarded.
*
* @param array $functions The map of custom DQL string functions.
*
* @return void
*
* @psalm-param array<string, class-string> $functions The map of custom
* DQL string functions.
*/
public function setCustomStringFunctions(array $functions)
{
@@ -491,9 +497,10 @@ class Configuration extends \Doctrine\DBAL\Configuration
*
* Any previously added numeric functions are discarded.
*
* @param array $functions The map of custom DQL numeric functions.
*
* @return void
*
* @psalm-param array<string, class-string> $functions The map of custom
* DQL numeric functions.
*/
public function setCustomNumericFunctions(array $functions)
{
@@ -561,7 +568,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
*/
@@ -592,9 +599,10 @@ class Configuration extends \Doctrine\DBAL\Configuration
* Adds a custom hydration mode.
*
* @param string $modeName The hydration mode name.
* @param string $hydrator The hydrator class name.
*
* @return void
*
* @psalm-param class-string $hydrator The hydrator class name.
*/
public function addCustomHydrationMode($modeName, $hydrator)
{
@@ -816,7 +824,7 @@ class Configuration extends \Doctrine\DBAL\Configuration
/**
* Returns query hints, which will be applied to every query in application
*
* @return array
* @psalm-return array<string, mixed>
*/
public function getDefaultQueryHints()
{
@@ -826,7 +834,7 @@ class Configuration extends \Doctrine\DBAL\Configuration
/**
* Sets array of query hints, which will be applied to every query in application
*
* @param array $defaultQueryHints
* @psalm-param array<string, mixed> $defaultQueryHints
*/
public function setDefaultQueryHints(array $defaultQueryHints)
{

View File

@@ -21,6 +21,7 @@
namespace Doctrine\ORM;
use BadMethodCallException;
use DateTimeInterface;
use Doctrine\Common\EventManager;
use Doctrine\DBAL\Connection;
use Doctrine\ORM\Internal\Hydration\AbstractHydrator;
@@ -213,9 +214,9 @@ interface EntityManagerInterface extends ObjectManager
/**
* 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
*

View File

@@ -171,9 +171,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()
{
@@ -183,14 +181,12 @@ 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
*
* @return array The objects.
*
* @psalm-return list<T>
* @psalm-param array<string, mixed> $criteria
* @psalm-param list<string>|null $orderBy
* @psalm-return list<T> The objects.
*/
public function findBy(array $criteria, ?array $orderBy = null, $limit = null, $offset = null)
{
@@ -202,11 +198,10 @@ class EntityRepository implements ObjectRepository, Selectable
/**
* Finds a single entity by a set of criteria.
*
* @param array $criteria
* @param array|null $orderBy
*
* @return object|null The entity instance or NULL if the entity can not be found.
*
* @psalm-param array<string, mixed> $criteria
* @psalm-param array<string, string>|null $orderBy
* @psalm-return ?T
*/
public function findOneBy(array $criteria, ?array $orderBy = null)
@@ -219,10 +214,9 @@ class EntityRepository implements ObjectRepository, Selectable
/**
* Counts entities by a set of criteria.
*
* @param array $criteria
*
* @return int The cardinality of the objects that match the given criteria.
*
* @psalm-param array<string, mixed> $criteria
* @todo Add this method to `ObjectRepository` interface in the next major release
*/
public function count(array $criteria)
@@ -234,12 +228,13 @@ class EntityRepository implements ObjectRepository, Selectable
* Adds support for magic method calls.
*
* @param string $method
* @param array $arguments
*
* @return mixed The returned value from the resolved method.
*
* @throws ORMException
* @throws BadMethodCallException If the method called is invalid.
*
* @psalm-param list<mixed> $arguments
*/
public function __call($method, $arguments)
{
@@ -298,8 +293,6 @@ class EntityRepository implements ObjectRepository, Selectable
* Select all elements from a selectable that match the expression and
* return a new collection containing these elements.
*
* @return Collection
*
* @psalm-return Collection<int, T>
*/
public function matching(Criteria $criteria)
@@ -312,15 +305,16 @@ 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
* @param string $method The method to call
* @param string $by The property name used as condition
*
* @return mixed
*
* @throws ORMException If the method called is invalid or the requested field/association does not exist.
*
* @psalm-param list<mixed> $arguments The arguments to pass at method call
*/
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

@@ -20,7 +20,7 @@
namespace Doctrine\ORM\Internal\Hydration;
use Doctrine\DBAL\Driver\Statement;
use Doctrine\DBAL\Driver\ResultStatement;
use Doctrine\DBAL\FetchMode;
use Doctrine\DBAL\Platforms\AbstractPlatform;
use Doctrine\DBAL\Types\Type;
@@ -79,28 +79,28 @@ abstract class AbstractHydrator
/**
* Local ClassMetadata cache to avoid going to the EntityManager all the time.
*
* @var array
* @var array<string, ClassMetadata>
*/
protected $_metadataCache = [];
/**
* The cache used during row-by-row hydration.
*
* @var array
* @var array<string, mixed[]|null>
*/
protected $_cache = [];
/**
* The statement that provides the data to hydrate.
*
* @var Statement
* @var ResultStatement
*/
protected $_stmt;
/**
* The query hints.
*
* @var array
* @var array<string, mixed>
*/
protected $_hints;
@@ -123,9 +123,10 @@ abstract class AbstractHydrator
*
* @param object $stmt
* @param object $resultSetMapping
* @param array $hints
*
* @return IterableResult
*
* @psalm-param array<string, mixed> $hints
*/
public function iterate($stmt, $resultSetMapping, array $hints = [])
{
@@ -150,11 +151,11 @@ abstract class AbstractHydrator
/**
* Initiates a row-by-row hydration.
*
* @param mixed[] $hints
*
* @return iterable<mixed>
*
* @psalm-param array<string, mixed> $hints
*/
public function toIterable(Statement $stmt, ResultSetMapping $resultSetMapping, array $hints = []): iterable
public function toIterable(ResultStatement $stmt, ResultSetMapping $resultSetMapping, array $hints = []): iterable
{
$this->_stmt = $stmt;
$this->_rsm = $resultSetMapping;
@@ -194,9 +195,10 @@ abstract class AbstractHydrator
*
* @param object $stmt
* @param object $resultSetMapping
* @param array $hints
*
* @return array
* @return mixed[]
*
* @psalm-param array<string, string> $hints
*/
public function hydrateAll($stmt, $resultSetMapping, array $hints = [])
{
@@ -205,12 +207,13 @@ abstract class AbstractHydrator
$this->_hints = $hints;
$this->_em->getEventManager()->addEventListener([Events::onClear], $this);
$this->prepare();
$result = $this->hydrateAllData();
$this->cleanup();
try {
$result = $this->hydrateAllData();
} finally {
$this->cleanup();
}
return $result;
}
@@ -318,15 +321,15 @@ abstract class AbstractHydrator
* field names during this procedure as well as any necessary conversions on
* the values applied. Scalar values are kept in a specific key 'scalars'.
*
* @param mixed[] $data SQL Result Row.
* @param array &$id Dql-Alias => ID-Hash.
* @param array &$nonemptyComponents Does this DQL-Alias has at least one non NULL value?
* @param mixed[] $data SQL Result Row.
*
* @return array<string, array<string, mixed>> An array with all the fields
* (name => value) of the data
* row, grouped by their
* component alias.
*
* @psalm-param array<string, string> $id Dql-Alias => ID-Hash.
* @psalm-param array<string, bool> $nonemptyComponents Does this DQL-Alias has at least one non NULL value?
* @psalm-return array{
* data: array<array-key, array>,
* newObjects?: array<array-key, array{
@@ -341,7 +344,8 @@ abstract class AbstractHydrator
$rowData = ['data' => []];
foreach ($data as $key => $value) {
if (($cacheKeyInfo = $this->hydrateColumnInfo($key)) === null) {
$cacheKeyInfo = $this->hydrateColumnInfo($key);
if ($cacheKeyInfo === null) {
continue;
}
@@ -410,16 +414,16 @@ abstract class AbstractHydrator
* values according to their types. The resulting row has the same number
* of elements as before.
*
* @param array $data
*
* @return array The processed row.
* @psalm-param array<string, mixed> $data
* @psalm-return array<string, mixed> The processed row.
*/
protected function gatherScalarRowData(&$data)
{
$rowData = [];
foreach ($data as $key => $value) {
if (($cacheKeyInfo = $this->hydrateColumnInfo($key)) === null) {
$cacheKeyInfo = $this->hydrateColumnInfo($key);
if ($cacheKeyInfo === null) {
continue;
}
@@ -445,7 +449,7 @@ abstract class AbstractHydrator
*
* @param string $key Column name
*
* @return array|null
* @psalm-return array<string, mixed>|null
*/
protected function hydrateColumnInfo($key)
{

View File

@@ -43,8 +43,12 @@ class HydrationException extends ORMException
*/
public static function parentObjectOfRelationNotFound($alias, $parentAlias)
{
return new self("The parent object of entity result with alias '$alias' was not found."
. " The parent alias is '$parentAlias'.");
return new self(sprintf(
"The parent object of entity result with alias '%s' was not found."
. " The parent alias is '%s'.",
$alias,
$parentAlias
));
}
/**
@@ -96,9 +100,10 @@ class HydrationException extends ORMException
/**
* @param string $discrValue
* @param array $discrMap
*
* @return HydrationException
*
* @psalm-param array<string, string> $discrMap
*/
public static function invalidDiscriminatorValue($discrValue, $discrMap)
{

View File

@@ -68,7 +68,7 @@ class IterableResult implements Iterator
/**
* Gets the next set of results.
*
* @return array|false
* @return mixed[]|false
*/
public function next()
{

View File

@@ -222,12 +222,13 @@ class ObjectHydrator extends AbstractHydrator
/**
* Gets an entity instance.
*
* @param array $data The instance data.
* @param string $dqlAlias The DQL alias of the entity's class.
*
* @return object The entity.
*
* @throws HydrationException
*
* @psalm-param array<string, mixed> $data The instance data.
*/
private function getEntity(array $data, $dqlAlias)
{
@@ -273,16 +274,16 @@ class ObjectHydrator extends AbstractHydrator
/**
* @param string $className
* @param array $data
*
* @return mixed
*
* @psalm-param array<string, mixed> $data
*/
private function getEntityFromIdentityMap($className, array $data)
{
// TODO: Abstract this code and UnitOfWork::createEntity() equivalent?
$class = $this->_metadataCache[$className];
/** @var ClassMetadata $class */
if ($class->isIdentifierComposite) {
$idHash = '';
@@ -317,8 +318,8 @@ class ObjectHydrator extends AbstractHydrator
* level of the hydrated result. A typical example are the objects of the type
* specified by the FROM clause in a DQL query.
*
* @param array $row The data of the row to process.
* @param array $result The result array to fill.
* @param mixed[] $row The data of the row to process.
* @param mixed[] $result The result array to fill.
*
* @return void
*/
@@ -397,7 +398,8 @@ class ObjectHydrator extends AbstractHydrator
if (! $indexExists || ! $indexIsValid) {
if (isset($this->existingCollections[$collKey])) {
// Collection exists, only look for the element in the identity map.
if ($element = $this->getEntityFromIdentityMap($entityName, $data)) {
$element = $this->getEntityFromIdentityMap($entityName, $data);
if ($element) {
$this->resultPointers[$dqlAlias] = $element;
} else {
unset($this->resultPointers[$dqlAlias]);

View File

@@ -96,7 +96,8 @@ class SimpleObjectHydrator extends AbstractHydrator
$discrColumnName = $this->_platform->getSQLResultCasing($this->class->discriminatorColumn['name']);
// Find mapped discriminator column from the result set.
if ($metaMappingDiscrColumnName = array_search($discrColumnName, $this->_rsm->metaMappings)) {
$metaMappingDiscrColumnName = array_search($discrColumnName, $this->_rsm->metaMappings);
if ($metaMappingDiscrColumnName) {
$discrColumnName = $metaMappingDiscrColumnName;
}

View File

@@ -137,10 +137,11 @@ class ClassMetadataBuilder
/**
* Adds Index.
*
* @param array $columns
* @param string $name
*
* @return static
*
* @psalm-param list<string> $columns
*/
public function addIndex(array $columns, $name)
{
@@ -156,10 +157,11 @@ class ClassMetadataBuilder
/**
* Adds Unique Constraint.
*
* @param array $columns
* @param string $name
*
* @return static
*
* @psalm-param list<string> $columns
*/
public function addUniqueConstraint(array $columns, $name)
{
@@ -297,9 +299,10 @@ class ClassMetadataBuilder
*
* @param string $name
* @param string $type
* @param array $mapping
*
* @return static
*
* @psalm-param array<string, mixed> $mapping
*/
public function addField($name, $type, array $mapping = [])
{

View File

@@ -28,9 +28,9 @@ namespace Doctrine\ORM\Mapping\Builder;
class OneToManyAssociationBuilder extends AssociationBuilder
{
/**
* @param array $fieldNames
*
* @return static
*
* @psalm-param list<string> $fieldNames
*/
public function setOrderBy(array $fieldNames)
{

View File

@@ -41,6 +41,7 @@ use ReflectionClass;
use ReflectionException;
use function array_map;
use function assert;
use function class_exists;
use function count;
use function end;
@@ -119,8 +120,6 @@ class ClassMetadataFactory extends AbstractClassMetadataFactory
*/
protected function doLoadMetadata($class, $parent, $rootEntityFound, array $nonSuperclassParents)
{
/** @var ClassMetadata $class */
/** @var ClassMetadata $parent */
if ($parent) {
$class->setInheritanceType($parent->inheritanceType);
$class->setDiscriminatorColumn($parent->discriminatorColumn);
@@ -728,7 +727,7 @@ class ClassMetadataFactory extends AbstractClassMetadataFactory
*/
protected function wakeupReflection(ClassMetadataInterface $class, ReflectionService $reflService)
{
/** @var ClassMetadata $class */
assert($class instanceof ClassMetadata);
$class->wakeupReflection($reflService);
}
@@ -737,7 +736,7 @@ class ClassMetadataFactory extends AbstractClassMetadataFactory
*/
protected function initializeReflection(ClassMetadataInterface $class, ReflectionService $reflService)
{
/** @var ClassMetadata $class */
assert($class instanceof ClassMetadata);
$class->initializeReflection($reflService);
}

View File

@@ -297,28 +297,28 @@ class ClassMetadataInfo implements ClassMetadata
/**
* READ-ONLY: The names of the parent classes (ancestors).
*
* @var array
* @psalm-var list<class-string>
*/
public $parentClasses = [];
/**
* READ-ONLY: The names of all subclasses (descendants).
*
* @var array
* @psalm-var list<class-string>
*/
public $subClasses = [];
/**
* READ-ONLY: The names of all embedded classes based on properties.
*
* @var array
* @psalm-var array<string, mixed[]>
*/
public $embeddedClasses = [];
/**
* READ-ONLY: The named queries allowed to be called directly from Repository.
*
* @var array
* @psalm-var array<string, array<string, mixed>>
*/
public $namedQueries = [];
@@ -335,7 +335,7 @@ class ClassMetadataInfo implements ClassMetadata
* )
* </pre>
*
* @var array
* @psalm-var array<string, array<string, mixed>>
*/
public $namedNativeQueries = [];
@@ -351,7 +351,11 @@ class ClassMetadataInfo implements ClassMetadata
* )
* </pre>
*
* @var array
* @psalm-var array<string, array{
* name: string,
* entities: mixed[],
* columns: mixed[]
* }>
*/
public $sqlResultSetMappings = [];
@@ -359,7 +363,7 @@ class ClassMetadataInfo implements ClassMetadata
* READ-ONLY: The field names of all fields that are part of the identifier/primary key
* of the mapped entity class.
*
* @var array
* @psalm-var list<string>
*/
public $identifier = [];
@@ -416,8 +420,23 @@ class ClassMetadataInfo implements ClassMetadata
* - <b>'unique'</b> (string, optional, schema-only)
* Whether a unique constraint should be generated for the column.
*
* @var array
* @psalm-var array<string, array{type: string, fieldName: string, columnName: string, inherited: class-string}>
* @psalm-var array<string, array{
* type: string,
* fieldName: string,
* columnName?: string,
* length?: int,
* id?: bool,
* nullable?: bool,
* columnDefinition?: string,
* precision?: int,
* scale?: int,
* unique?: string,
* inherited?: class-string,
* originalClass?: class-string,
* originalField?: string,
* quoted?: bool,
* requireSQLConversion?: bool,
* }>
*/
public $fieldMappings = [];
@@ -425,7 +444,7 @@ class ClassMetadataInfo implements ClassMetadata
* READ-ONLY: An array of field names. Used to look up field names from column names.
* Keys are column names and values are field names.
*
* @var array
* @psalm-var array<string, string>
*/
public $fieldNames = [];
@@ -468,7 +487,7 @@ class ClassMetadataInfo implements ClassMetadata
* READ-ONLY: The definition of the discriminator column used in JOINED and SINGLE_TABLE
* inheritance mappings.
*
* @var array
* @psalm-var array<string, mixed>
*/
public $discriminatorColumn;
@@ -481,21 +500,21 @@ class ClassMetadataInfo implements ClassMetadata
* indexes => array
* uniqueConstraints => array
*
* @var array
* @psalm-var array<string, mixed>
*/
public $table;
/**
* READ-ONLY: The registered lifecycle callbacks for entities of this class.
*
* @var array[]
* @psalm-var array<string, list<string>>
*/
public $lifecycleCallbacks = [];
/**
* READ-ONLY: The registered entity listeners.
*
* @var array
* @psalm-var array<string, list<array{class: class-string, method: string}>>
*/
public $entityListeners = [];
@@ -552,7 +571,7 @@ class ClassMetadataInfo implements ClassMetadata
* )
* </pre>
*
* @var array
* @psalm-var array<string, array<string, mixed>>
*/
public $associationMappings = [];
@@ -593,7 +612,7 @@ class ClassMetadataInfo implements ClassMetadata
* )
* </code>
*
* @var array
* @psalm-var array<string, mixed>
* @todo Merge with tableGeneratorDefinition into generic generatorDefinition
*/
public $sequenceGeneratorDefinition;
@@ -602,7 +621,7 @@ class ClassMetadataInfo implements ClassMetadata
* READ-ONLY: The definition of the table generator of this class. Only used for the
* TABLE generation strategy.
*
* @var array
* @var array<string, mixed>
* @todo Merge with tableGeneratorDefinition into generic generatorDefinition
*/
public $tableGeneratorDefinition;
@@ -729,7 +748,7 @@ class ClassMetadataInfo implements ClassMetadata
*
* @param object $entity
*
* @return array
* @return array<string|int, mixed>
*/
public function getIdentifierValues($entity)
{
@@ -761,10 +780,10 @@ class ClassMetadataInfo implements ClassMetadata
* Populates the entity identifier of an entity.
*
* @param object $entity
* @param array $id
*
* @return void
*
* @psalm-param array<string, mixed> $id
* @todo Rename to assignIdentifier()
*/
public function setIdentifierValues($entity, array $id)
@@ -1083,9 +1102,9 @@ class ClassMetadataInfo implements ClassMetadata
}
/**
* @param array $cache
*
* @return void
*
* @psalm-param array{usage?: mixed, region?: mixed} $cache
*/
public function enableCache(array $cache)
{
@@ -1102,9 +1121,10 @@ class ClassMetadataInfo implements ClassMetadata
/**
* @param string $fieldName
* @param array $cache
*
* @return void
*
* @psalm-param array{usage?: mixed, region?: mixed} $cache
*/
public function enableAssociationCache($fieldName, array $cache)
{
@@ -1117,7 +1137,7 @@ class ClassMetadataInfo implements ClassMetadata
*
* @return mixed[]
*
* @psalm-param array{usage: mixed, region: mixed} $cache
* @psalm-param array{usage?: mixed, region?: mixed} $cache
* @psalm-return array{usage: mixed, region: mixed}
*/
public function getAssociationCacheDefaults($fieldName, array $cache)
@@ -1244,9 +1264,9 @@ class ClassMetadataInfo implements ClassMetadata
*
* @param string $fieldName The field name.
*
* @return array The field mapping.
*
* @throws MappingException
*
* @psalm-return array<string, mixed> The field mapping.
*/
public function getFieldMapping($fieldName)
{
@@ -1265,9 +1285,9 @@ class ClassMetadataInfo implements ClassMetadata
* @param string $fieldName The field name that represents the association in
* the object model.
*
* @return array The mapping.
*
* @throws MappingException
*
* @psalm-return array<string, mixed> The mapping.
*/
public function getAssociationMapping($fieldName)
{
@@ -1281,7 +1301,7 @@ class ClassMetadataInfo implements ClassMetadata
/**
* Gets all association mappings of the class.
*
* @return array
* @psalm-return array<string, array<string, mixed>>
*/
public function getAssociationMappings()
{
@@ -1324,7 +1344,7 @@ class ClassMetadataInfo implements ClassMetadata
/**
* Gets all named queries of the class.
*
* @return array
* @psalm-return array<string, mixed>
*/
public function getNamedQueries()
{
@@ -1338,9 +1358,9 @@ class ClassMetadataInfo implements ClassMetadata
*
* @param string $queryName The query name.
*
* @return array
*
* @throws MappingException
*
* @psalm-return array<string, mixed>
*/
public function getNamedNativeQuery($queryName)
{
@@ -1354,7 +1374,7 @@ class ClassMetadataInfo implements ClassMetadata
/**
* Gets all named native queries of the class.
*
* @return array
* @psalm-return array<string, array<string, mixed>>
*/
public function getNamedNativeQueries()
{
@@ -1368,9 +1388,9 @@ class ClassMetadataInfo implements ClassMetadata
*
* @param string $name The result set mapping name.
*
* @return array
*
* @throws MappingException
*
* @psalm-return array<string, mixed>
*/
public function getSqlResultSetMapping($name)
{
@@ -1384,7 +1404,7 @@ class ClassMetadataInfo implements ClassMetadata
/**
* Gets all sql result set mappings of the class.
*
* @return array
* @psalm-return array<string, array<string, mixed>>
*/
public function getSqlResultSetMappings()
{
@@ -1394,11 +1414,11 @@ class ClassMetadataInfo implements ClassMetadata
/**
* Validates & completes the given field mapping.
*
* @param array $mapping The field mapping to validate & complete.
*
* @return void
*
* @throws MappingException
*
* @psalm-param array<string, mixed> $mapping The field mapping to validate & complete.
*/
protected function _validateAndCompleteFieldMapping(array &$mapping)
{
@@ -1459,12 +1479,11 @@ class ClassMetadataInfo implements ClassMetadata
* Validates & completes the basic mapping information that is common to all
* association mappings (one-to-one, many-ot-one, one-to-many, many-to-many).
*
* @param array $mapping The mapping.
*
* @return mixed[] The updated mapping.
*
* @throws MappingException If something is wrong with the mapping.
*
* @psalm-param array<string, mixed> $mapping The mapping.
* @psalm-return array{
* mappedBy: mixed,
* inversedBy: mixed,
@@ -1478,7 +1497,8 @@ class ClassMetadataInfo implements ClassMetadata
* isCascadePersist: bool,
* isCascadeRefresh: bool,
* isCascadeMerge: bool,
* isCascadeDetach: bool
* isCascadeDetach: bool,
* ?orphanRemoval: bool
* }
*/
protected function _validateAndCompleteAssociationMapping(array $mapping)
@@ -1597,13 +1617,12 @@ class ClassMetadataInfo implements ClassMetadata
/**
* Validates & completes a one-to-one association mapping.
*
* @param array $mapping The mapping to validate & complete.
*
* @return mixed[] The validated & completed mapping.
*
* @throws RuntimeException
* @throws MappingException
*
* @psalm-param array<string, mixed> $mapping The mapping to validate & complete.
* @psalm-return array{isOwningSide: mixed, orphanRemoval: bool, isCascadeRemove: bool}
*/
protected function _validateAndCompleteOneToOneMapping(array $mapping)
@@ -1688,13 +1707,12 @@ class ClassMetadataInfo implements ClassMetadata
/**
* Validates & completes a one-to-many association mapping.
*
* @param array $mapping The mapping to validate and complete.
*
* @return mixed[] The validated and completed mapping.
*
* @throws MappingException
* @throws InvalidArgumentException
*
* @psalm-param array<string, mixed> $mapping The mapping to validate and complete.
* @psalm-return array{
* mappedBy: mixed,
* inversedBy: mixed,
@@ -1732,12 +1750,11 @@ class ClassMetadataInfo implements ClassMetadata
/**
* Validates & completes a many-to-many association mapping.
*
* @param array $mapping The mapping to validate & complete.
*
* @return mixed[] The validated & completed mapping.
*
* @throws InvalidArgumentException
*
* @psalm-param array<string, mixed> $mapping The mapping to validate & complete.
* @psalm-return array{isOwningSide: mixed, orphanRemoval: bool}
*/
protected function _validateAndCompleteManyToManyMapping(array $mapping)
@@ -1884,9 +1901,9 @@ class ClassMetadataInfo implements ClassMetadata
* Sets the mapped identifier/primary key fields of this class.
* Mainly used by the ClassMetadataFactory to assign inherited identifiers.
*
* @param array $identifier
*
* @return void
*
* @psalm-param list<mixed> $identifier
*/
public function setIdentifier(array $identifier)
{
@@ -1913,10 +1930,9 @@ class ClassMetadataInfo implements ClassMetadata
/**
* Gets an array containing all the column names.
*
* @param array|null $fieldNames
*
* @return mixed[]
*
* @psalm-param list<string>|null $fieldNames
* @psalm-return list<string>
*/
public function getColumnNames(?array $fieldNames = null)
@@ -1931,7 +1947,7 @@ class ClassMetadataInfo implements ClassMetadata
/**
* Returns an array with all the identifier column names.
*
* @return array
* @psalm-return list<string>
*/
public function getIdentifierColumnNames()
{
@@ -2135,9 +2151,9 @@ class ClassMetadataInfo implements ClassMetadata
/**
* Sets the mapped subclasses of this class.
*
* @param array $subclasses The names of all mapped subclasses.
*
* @return void
*
* @psalm-param list<string> $subclasses The names of all mapped subclasses.
*/
public function setSubclasses(array $subclasses)
{
@@ -2151,9 +2167,9 @@ class ClassMetadataInfo implements ClassMetadata
* Assumes that the class names in the passed array are in the order:
* directParent -> directParentParent -> directParentParentParent ... -> root.
*
* @param array $classNames
*
* @return void
*
* @psalm-param list<class-string> $classNames
*/
public function setParentClasses(array $classNames)
{
@@ -2175,7 +2191,7 @@ class ClassMetadataInfo implements ClassMetadata
*/
public function setInheritanceType($type)
{
if (! $this->_isInheritanceType($type)) {
if (! $this->isInheritanceType($type)) {
throw MappingException::invalidInheritanceType($this->name, $type);
}
@@ -2186,11 +2202,12 @@ class ClassMetadataInfo implements ClassMetadata
* Sets the association to override association mapping of property for an entity relationship.
*
* @param string $fieldName
* @param array $overrideMapping
*
* @return void
*
* @throws MappingException
*
* @psalm-param array<string, mixed> $overrideMapping
*/
public function setAssociationOverride($fieldName, array $overrideMapping)
{
@@ -2251,11 +2268,12 @@ class ClassMetadataInfo implements ClassMetadata
* Sets the override for a mapped field.
*
* @param string $fieldName
* @param array $overrideMapping
*
* @return void
*
* @throws MappingException
*
* @psalm-param array<string, mixed> $overrideMapping
*/
public function setAttributeOverride($fieldName, array $overrideMapping)
{
@@ -2329,6 +2347,11 @@ class ClassMetadataInfo implements ClassMetadata
return isset($this->associationMappings[$fieldName]['inherited']);
}
/**
* @param string $fieldName
*
* @return bool
*/
public function isInheritedEmbeddedClass($fieldName)
{
return isset($this->embeddedClasses[$fieldName]['inherited']);
@@ -2358,9 +2381,9 @@ class ClassMetadataInfo implements ClassMetadata
*
* If a key is omitted, the current value is kept.
*
* @param array $table The table description.
*
* @return void
*
* @psalm-param array<string, mixed> $table The table description.
*/
public function setPrimaryTable(array $table)
{
@@ -2406,7 +2429,7 @@ class ClassMetadataInfo implements ClassMetadata
*
* @return bool TRUE if the given type identifies an inheritance type, FALSe otherwise.
*/
private function _isInheritanceType($type)
private function isInheritanceType($type)
{
return $type === self::INHERITANCE_TYPE_NONE ||
$type === self::INHERITANCE_TYPE_SINGLE_TABLE ||
@@ -2417,11 +2440,11 @@ class ClassMetadataInfo implements ClassMetadata
/**
* Adds a mapped field to the class.
*
* @param array $mapping The field mapping.
*
* @return void
*
* @throws MappingException
*
* @psalm-param array<string, mixed> $mapping The field mapping.
*/
public function mapField(array $mapping)
{
@@ -2436,11 +2459,11 @@ class ClassMetadataInfo implements ClassMetadata
* Adds an association mapping without completing/validating it.
* This is mainly used to add inherited association mappings to derived classes.
*
* @param array $mapping
*
* @return void
*
* @throws MappingException
*
* @psalm-param array<string, mixed> $mapping
*/
public function addInheritedAssociationMapping(array $mapping/*, $owningClassName = null*/)
{
@@ -2456,9 +2479,9 @@ class ClassMetadataInfo implements ClassMetadata
* Adds a field mapping without completing/validating it.
* This is mainly used to add inherited field mappings to derived classes.
*
* @param array $fieldMapping
*
* @return void
*
* @psalm-param array<string, mixed> $fieldMapping
*/
public function addInheritedFieldMapping(array $fieldMapping)
{
@@ -2471,11 +2494,11 @@ class ClassMetadataInfo implements ClassMetadata
* INTERNAL:
* Adds a named query to this class.
*
* @param array $queryMapping
*
* @return void
*
* @throws MappingException
*
* @psalm-param array<string, mixed> $queryMapping
*/
public function addNamedQuery(array $queryMapping)
{
@@ -2506,11 +2529,11 @@ class ClassMetadataInfo implements ClassMetadata
* INTERNAL:
* Adds a named native query to this class.
*
* @param array $queryMapping
*
* @return void
*
* @throws MappingException
*
* @psalm-param array<string, mixed> $queryMapping
*/
public function addNamedNativeQuery(array $queryMapping)
{
@@ -2549,11 +2572,11 @@ class ClassMetadataInfo implements ClassMetadata
* INTERNAL:
* Adds a sql result set mapping to this class.
*
* @param array $resultMapping
*
* @return void
*
* @throws MappingException
*
* @psalm-param array<string, mixed> $resultMapping
*/
public function addSqlResultSetMapping(array $resultMapping)
{
@@ -2607,7 +2630,7 @@ class ClassMetadataInfo implements ClassMetadata
/**
* Adds a one-to-one mapping.
*
* @param array $mapping The mapping.
* @param array<string, mixed> $mapping The mapping.
*
* @return void
*/
@@ -2623,9 +2646,9 @@ class ClassMetadataInfo implements ClassMetadata
/**
* Adds a one-to-many mapping.
*
* @param array $mapping The mapping.
*
* @return void
*
* @psalm-param array<string, mixed> $mapping The mapping.
*/
public function mapOneToMany(array $mapping)
{
@@ -2639,9 +2662,9 @@ class ClassMetadataInfo implements ClassMetadata
/**
* Adds a many-to-one mapping.
*
* @param array $mapping The mapping.
*
* @return void
*
* @psalm-param array<string, mixed> $mapping The mapping.
*/
public function mapManyToOne(array $mapping)
{
@@ -2656,9 +2679,9 @@ class ClassMetadataInfo implements ClassMetadata
/**
* Adds a many-to-many mapping.
*
* @param array $mapping The mapping.
*
* @return void
*
* @psalm-param array<string, mixed> $mapping The mapping.
*/
public function mapManyToMany(array $mapping)
{
@@ -2672,11 +2695,11 @@ class ClassMetadataInfo implements ClassMetadata
/**
* Stores the association mapping.
*
* @param array $assocMapping
*
* @return void
*
* @throws MappingException
*
* @psalm-param array<string, mixed> $assocMapping
*/
protected function _storeAssociationMapping(array $assocMapping)
{
@@ -2736,7 +2759,7 @@ class ClassMetadataInfo implements ClassMetadata
*
* @param string $event
*
* @return array
* @psalm-return list<string>
*/
public function getLifecycleCallbacks($event)
{
@@ -2764,9 +2787,9 @@ class ClassMetadataInfo implements ClassMetadata
* Sets the lifecycle callbacks for entities of this class.
* Any previously registered callbacks are overwritten.
*
* @param array $callbacks
*
* @return void
*
* @psalm-param array<string, list<string>> $callbacks
*/
public function setLifecycleCallbacks(array $callbacks)
{
@@ -2811,11 +2834,11 @@ class ClassMetadataInfo implements ClassMetadata
*
* @see getDiscriminatorColumn()
*
* @param array $columnDef
*
* @return void
*
* @throws MappingException
*
* @psalm-param array<string, mixed> $columnDef
*/
public function setDiscriminatorColumn($columnDef)
{
@@ -2848,9 +2871,9 @@ class ClassMetadataInfo implements ClassMetadata
* Sets the discriminator values used by this class.
* Used for JOINED and SINGLE_TABLE inheritance mapping strategies.
*
* @param array $map
*
* @return void
*
* @psalm-param array<string, class-string> $map
*/
public function setDiscriminatorMap(array $map)
{
@@ -2863,11 +2886,12 @@ class ClassMetadataInfo implements ClassMetadata
* Adds one entry of the discriminator map with a new class and corresponding name.
*
* @param string $name
* @param string $className
*
* @return void
*
* @throws MappingException
*
* @psalm-param class-string $className
*/
public function addDiscriminatorMapClass($name, $className)
{
@@ -3047,9 +3071,9 @@ class ClassMetadataInfo implements ClassMetadata
/**
* Sets definition.
*
* @param array $definition
*
* @return void
*
* @psalm-param array<string, string> $definition
*/
public function setCustomGeneratorDefinition(array $definition)
{
@@ -3069,11 +3093,11 @@ class ClassMetadataInfo implements ClassMetadata
* )
* </code>
*
* @param array $definition
*
* @return void
*
* @throws MappingException
*
* @psalm-param array<string, string> $definition
*/
public function setSequenceGeneratorDefinition(array $definition)
{
@@ -3101,11 +3125,11 @@ class ClassMetadataInfo implements ClassMetadata
* Sets the version field mapping used for versioning. Sets the default
* value to use depending on the column type.
*
* @param array $mapping The version field mapping array.
*
* @return void
*
* @throws MappingException
*
* @psalm-param array<string, mixed> $mapping The version field mapping array.
*/
public function setVersionMapping(array &$mapping)
{
@@ -3203,7 +3227,7 @@ class ClassMetadataInfo implements ClassMetadata
*
* @param AbstractPlatform $platform
*
* @return array
* @psalm-return list<string>
*/
public function getQuotedIdentifierColumnNames($platform)
{
@@ -3305,7 +3329,7 @@ class ClassMetadataInfo implements ClassMetadata
/**
* @param string $targetClass
*
* @return array
* @psalm-return array<string, array<string, mixed>>
*/
public function getAssociationsByTargetClass($targetClass)
{
@@ -3357,11 +3381,11 @@ class ClassMetadataInfo implements ClassMetadata
/**
* Map Embedded Class
*
* @param array $mapping
*
* @return void
*
* @throws MappingException
*
* @psalm-param array<string, mixed> $mapping
*/
public function mapEmbedded(array $mapping)
{
@@ -3407,11 +3431,9 @@ class ClassMetadataInfo implements ClassMetadata
}
/**
* @param string $fieldName
*
* @throws MappingException
*/
private function assertFieldNotMapped($fieldName)
private function assertFieldNotMapped(string $fieldName): void
{
if (
isset($this->fieldMappings[$fieldName]) ||
@@ -3450,7 +3472,8 @@ class ClassMetadataInfo implements ClassMetadata
$sequencePrefix = $tableName;
// Prepend the schema name to the table name if there is one
if ($schemaName = $this->getSchemaName()) {
$schemaName = $this->getSchemaName();
if ($schemaName) {
$sequencePrefix = $schemaName . '.' . $tableName;
if (! $platform->supportsSchemas() && $platform->canEmulateSchemas()) {
@@ -3462,9 +3485,9 @@ class ClassMetadataInfo implements ClassMetadata
}
/**
* @param array $mapping
* @psalm-param array<string, mixed> $mapping
*/
private function assertMappingOrderBy(array $mapping)
private function assertMappingOrderBy(array $mapping): void
{
if (isset($mapping['orderBy']) && ! is_array($mapping['orderBy'])) {
throw new InvalidArgumentException("'orderBy' is expected to be an array, not " . gettype($mapping['orderBy']));

View File

@@ -25,7 +25,6 @@ use Doctrine\ORM\Events;
use Doctrine\ORM\Id\TableGenerator;
use Doctrine\ORM\Mapping;
use Doctrine\ORM\Mapping\Builder\EntityListenerBuilder;
use Doctrine\ORM\Mapping\ClassMetadataInfo;
use Doctrine\ORM\Mapping\MappingException;
use Doctrine\Persistence\Mapping\ClassMetadata;
use Doctrine\Persistence\Mapping\Driver\AnnotationDriver as AbstractAnnotationDriver;
@@ -60,7 +59,6 @@ class AnnotationDriver extends AbstractAnnotationDriver
*/
public function loadMetadataForClass($className, ClassMetadata $metadata)
{
/** @var ClassMetadataInfo $metadata */
$class = $metadata->getReflectionClass();
if (! $class) {
@@ -299,7 +297,8 @@ class AnnotationDriver extends AbstractAnnotationDriver
$mapping['fieldName'] = $property->getName();
// Evaluate @Cache annotation
if (($cacheAnnot = $this->reader->getPropertyAnnotation($property, Mapping\Cache::class)) !== null) {
$cacheAnnot = $this->reader->getPropertyAnnotation($property, Mapping\Cache::class);
if ($cacheAnnot !== null) {
$mapping['cache'] = $metadata->getAssociationCacheDefaults(
$mapping['fieldName'],
[
@@ -312,7 +311,8 @@ class AnnotationDriver extends AbstractAnnotationDriver
// Check for JoinColumn/JoinColumns annotations
$joinColumns = [];
if ($joinColumnAnnot = $this->reader->getPropertyAnnotation($property, Mapping\JoinColumn::class)) {
$joinColumnAnnot = $this->reader->getPropertyAnnotation($property, Mapping\JoinColumn::class);
if ($joinColumnAnnot) {
$joinColumns[] = $this->joinColumnToArray($joinColumnAnnot);
} else {
$joinColumnsAnnot = $this->reader->getPropertyAnnotation($property, Mapping\JoinColumns::class);
@@ -325,18 +325,21 @@ class AnnotationDriver extends AbstractAnnotationDriver
// Field can only be annotated with one of:
// @Column, @OneToOne, @OneToMany, @ManyToOne, @ManyToMany
if ($columnAnnot = $this->reader->getPropertyAnnotation($property, Mapping\Column::class)) {
$columnAnnot = $this->reader->getPropertyAnnotation($property, Mapping\Column::class);
if ($columnAnnot) {
if ($columnAnnot->type === null) {
throw MappingException::propertyTypeIsRequired($className, $property->getName());
}
$mapping = $this->columnToArray($property->getName(), $columnAnnot);
if ($idAnnot = $this->reader->getPropertyAnnotation($property, Mapping\Id::class)) {
$idAnnot = $this->reader->getPropertyAnnotation($property, Mapping\Id::class);
if ($idAnnot) {
$mapping['id'] = true;
}
if ($generatedValueAnnot = $this->reader->getPropertyAnnotation($property, Mapping\GeneratedValue::class)) {
$generatedValueAnnot = $this->reader->getPropertyAnnotation($property, Mapping\GeneratedValue::class);
if ($generatedValueAnnot) {
$metadata->setIdGeneratorType(constant('Doctrine\ORM\Mapping\ClassMetadata::GENERATOR_TYPE_' . $generatedValueAnnot->strategy));
}
@@ -347,7 +350,8 @@ class AnnotationDriver extends AbstractAnnotationDriver
$metadata->mapField($mapping);
// Check for SequenceGenerator/TableGenerator definition
if ($seqGeneratorAnnot = $this->reader->getPropertyAnnotation($property, Mapping\SequenceGenerator::class)) {
$seqGeneratorAnnot = $this->reader->getPropertyAnnotation($property, Mapping\SequenceGenerator::class);
if ($seqGeneratorAnnot) {
$metadata->setSequenceGeneratorDefinition(
[
'sequenceName' => $seqGeneratorAnnot->sequenceName,
@@ -483,8 +487,9 @@ class AnnotationDriver extends AbstractAnnotationDriver
}
/**
* @param mixed[] $mapping
* @param mixed[] $joinColumns
*
* @psalm-param array<string, mixed> $mapping
*/
private function loadRelationShipMapping(
ReflectionProperty $property,

View File

@@ -60,7 +60,7 @@ class DatabaseDriver implements MappingDriver
/** @var mixed[] */
private $classToTableNames = [];
/** @var mixed[] */
/** @psalm-var array<string, Table> */
private $manyToManyTables = [];
/** @var mixed[] */
@@ -145,10 +145,10 @@ class DatabaseDriver implements MappingDriver
/**
* Sets tables manually instead of relying on the reverse engineering capabilities of SchemaManager.
*
* @param array $entityTables
* @param array $manyToManyTables
*
* @return void
*
* @psalm-param list<Table> $entityTables
* @psalm-param list<Table> $manyToManyTables
*/
public function setTables($entityTables, $manyToManyTables)
{
@@ -384,8 +384,6 @@ class DatabaseDriver implements MappingDriver
*
* @param string $tableName
*
* @return array
*
* @psalm-return array{
* fieldName: string,
* columnName: string,
@@ -439,12 +437,14 @@ class DatabaseDriver implements MappingDriver
}
// Comment
if (($comment = $column->getComment()) !== null) {
$comment = $column->getComment();
if ($comment !== null) {
$fieldMapping['options']['comment'] = $comment;
}
// Default
if (($default = $column->getDefault()) !== null) {
$default = $column->getDefault();
if ($default !== null) {
$fieldMapping['options']['default'] = $default;
}

View File

@@ -23,7 +23,6 @@ namespace Doctrine\ORM\Mapping\Driver;
use Doctrine\Common\Collections\Criteria;
use Doctrine\ORM\Mapping\Builder\EntityListenerBuilder;
use Doctrine\ORM\Mapping\ClassMetadata as Metadata;
use Doctrine\ORM\Mapping\ClassMetadataInfo;
use Doctrine\ORM\Mapping\MappingException;
use Doctrine\Persistence\Mapping\ClassMetadata;
use Doctrine\Persistence\Mapping\Driver\FileDriver;
@@ -63,7 +62,6 @@ class XmlDriver extends FileDriver
*/
public function loadMetadataForClass($className, ClassMetadata $metadata)
{
/** @var ClassMetadataInfo $metadata */
$xmlRoot = $this->getElement($className);
assert($xmlRoot instanceof SimpleXMLElement);
@@ -221,7 +219,7 @@ class XmlDriver extends FileDriver
}
if (isset($indexXml->options)) {
$index['options'] = $this->_parseOptions($indexXml->options->children());
$index['options'] = $this->parseOptions($indexXml->options->children());
}
if (isset($indexXml['name'])) {
@@ -239,7 +237,7 @@ class XmlDriver extends FileDriver
$unique = ['columns' => explode(',', (string) $uniqueXml['columns'])];
if (isset($uniqueXml->options)) {
$unique['options'] = $this->_parseOptions($uniqueXml->options->children());
$unique['options'] = $this->parseOptions($uniqueXml->options->children());
}
if (isset($uniqueXml['name'])) {
@@ -251,7 +249,7 @@ class XmlDriver extends FileDriver
}
if (isset($xmlRoot->options)) {
$metadata->table['options'] = $this->_parseOptions($xmlRoot->options->children());
$metadata->table['options'] = $this->parseOptions($xmlRoot->options->children());
}
// The mapping assignment is done in 2 times as a bug might occurs on some php/xml lib versions
@@ -329,7 +327,7 @@ class XmlDriver extends FileDriver
}
if (isset($idElement->options)) {
$mapping['options'] = $this->_parseOptions($idElement->options->children());
$mapping['options'] = $this->parseOptions($idElement->options->children());
}
$metadata->mapField($mapping);
@@ -400,7 +398,7 @@ class XmlDriver extends FileDriver
}
if (isset($oneToOneElement->cascade)) {
$mapping['cascade'] = $this->_getCascadeMappings($oneToOneElement->cascade);
$mapping['cascade'] = $this->getCascadeMappings($oneToOneElement->cascade);
}
if (isset($oneToOneElement['orphan-removal'])) {
@@ -430,7 +428,7 @@ class XmlDriver extends FileDriver
}
if (isset($oneToManyElement->cascade)) {
$mapping['cascade'] = $this->_getCascadeMappings($oneToManyElement->cascade);
$mapping['cascade'] = $this->getCascadeMappings($oneToManyElement->cascade);
}
if (isset($oneToManyElement['orphan-removal'])) {
@@ -496,7 +494,7 @@ class XmlDriver extends FileDriver
$mapping['joinColumns'] = $joinColumns;
if (isset($manyToOneElement->cascade)) {
$mapping['cascade'] = $this->_getCascadeMappings($manyToOneElement->cascade);
$mapping['cascade'] = $this->getCascadeMappings($manyToOneElement->cascade);
}
// Evaluate second level cache
@@ -552,7 +550,7 @@ class XmlDriver extends FileDriver
}
if (isset($manyToManyElement->cascade)) {
$mapping['cascade'] = $this->_getCascadeMappings($manyToManyElement->cascade);
$mapping['cascade'] = $this->getCascadeMappings($manyToManyElement->cascade);
}
if (isset($manyToManyElement->{'order-by'})) {
@@ -683,13 +681,13 @@ class XmlDriver extends FileDriver
*
* @return mixed[] The options array.
*/
private function _parseOptions(SimpleXMLElement $options)
private function parseOptions(SimpleXMLElement $options)
{
$array = [];
foreach ($options as $option) {
if ($option->count()) {
$value = $this->_parseOptions($option->children());
$value = $this->parseOptions($option->children());
} else {
$value = (string) $option;
}
@@ -814,7 +812,7 @@ class XmlDriver extends FileDriver
}
if (isset($fieldMapping->options)) {
$mapping['options'] = $this->_parseOptions($fieldMapping->options->children());
$mapping['options'] = $this->parseOptions($fieldMapping->options->children());
}
return $mapping;
@@ -855,7 +853,7 @@ class XmlDriver extends FileDriver
*
* @psalm-return list<string>
*/
private function _getCascadeMappings(SimpleXMLElement $cascadeElement)
private function getCascadeMappings(SimpleXMLElement $cascadeElement)
{
$cascades = [];
foreach ($cascadeElement->children() as $action) {

View File

@@ -22,7 +22,6 @@ namespace Doctrine\ORM\Mapping\Driver;
use Doctrine\ORM\Mapping\Builder\EntityListenerBuilder;
use Doctrine\ORM\Mapping\ClassMetadata as Metadata;
use Doctrine\ORM\Mapping\ClassMetadataInfo;
use Doctrine\ORM\Mapping\MappingException;
use Doctrine\Persistence\Mapping\ClassMetadata;
use Doctrine\Persistence\Mapping\Driver\FileDriver;
@@ -71,7 +70,6 @@ class YamlDriver extends FileDriver
*/
public function loadMetadataForClass($className, ClassMetadata $metadata)
{
/** @var ClassMetadataInfo $metadata */
$element = $this->getElement($className);
if ($element['type'] === 'entity') {
@@ -691,10 +689,17 @@ class YamlDriver extends FileDriver
* Constructs a joinColumn mapping array based on the information
* found in the given join column element.
*
* @param array $joinColumnElement The array join column element.
*
* @return mixed[] The mapping array.
*
* @psalm-param array{
* referencedColumnName?: mixed,
* name?: mixed,
* fieldName?: mixed,
* unique?: mixed,
* nullable?: mixed,
* onDelete?: mixed,
* columnDefinition?: mixed
* } $joinColumnElement The array join column element.
* @psalm-return array{
* referencedColumnName?: string,
* name?: string,
@@ -705,7 +710,7 @@ class YamlDriver extends FileDriver
* columnDefinition?: mixed
* }
*/
private function joinColumnToArray($joinColumnElement)
private function joinColumnToArray(array $joinColumnElement): array
{
$joinColumn = [];
if (isset($joinColumnElement['referencedColumnName'])) {
@@ -742,11 +747,19 @@ class YamlDriver extends FileDriver
/**
* Parses the given column as array.
*
* @param string $fieldName
* @param array $column
*
* @return mixed[]
*
* @psalm-param array{
* type?: string,
* column?: string,
* precision?: mixed,
* scale?: mixed,
* unique?: mixed,
* options?: mixed,
* nullable?: mixed,
* version?: mixed,
* columnDefinition?: mixed
* }|null $column
* @psalm-return array{
* fieldName: string,
* type?: string,
@@ -761,7 +774,7 @@ class YamlDriver extends FileDriver
* columnDefinition?: mixed
* }
*/
private function columnToArray($fieldName, $column)
private function columnToArray(string $fieldName, ?array $column): array
{
$mapping = ['fieldName' => $fieldName];

View File

@@ -32,7 +32,7 @@ interface EntityListenerResolver
*
* @return void
*/
function clear($className = null);
public function clear($className = null);
/**
* Returns a entity listener instance for the given identifier.
@@ -41,12 +41,12 @@ interface EntityListenerResolver
*
* @return object An entity listener
*/
function resolve($className);
public function resolve($className);
/**
* Register a entity listener instance.
*
* @param object $object An entity listener
*/
function register($object);
public function register($object);
}

View File

@@ -34,7 +34,7 @@ interface NamingStrategy
*
* @return string A table name.
*/
function classToTableName($className);
public function classToTableName($className);
/**
* Returns a column name for a property.
@@ -44,7 +44,7 @@ interface NamingStrategy
*
* @return string A column name.
*/
function propertyToColumnName($propertyName, $className = null);
public function propertyToColumnName($propertyName, $className = null);
/**
* Returns a column name for an embedded property.
@@ -56,14 +56,14 @@ interface NamingStrategy
*
* @return string
*/
function embeddedFieldToColumnName($propertyName, $embeddedColumnName, $className = null, $embeddedClassName = null);
public function embeddedFieldToColumnName($propertyName, $embeddedColumnName, $className = null, $embeddedClassName = null);
/**
* Returns the default reference column name.
*
* @return string A column name.
*/
function referenceColumnName();
public function referenceColumnName();
/**
* Returns a join column name for a property.
@@ -72,7 +72,7 @@ interface NamingStrategy
*
* @return string A join column name.
*/
function joinColumnName($propertyName);
public function joinColumnName($propertyName);
/**
* Returns a join table name.
@@ -83,7 +83,7 @@ interface NamingStrategy
*
* @return string A join table name.
*/
function joinTableName($sourceEntity, $targetEntity, $propertyName = null);
public function joinTableName($sourceEntity, $targetEntity, $propertyName = null);
/**
* Returns the foreign key column name for the given parameters.
@@ -93,5 +93,5 @@ interface NamingStrategy
*
* @return string A join column name.
*/
function joinKeyColumnName($entityName, $referencedColumnName = null);
public function joinKeyColumnName($entityName, $referencedColumnName = null);
}

View File

@@ -82,7 +82,7 @@ interface QuoteStrategy
/**
* Gets the (possibly quoted) identifier column names for safe use in an SQL statement.
*
* @return array
* @psalm-return list<string>
*/
public function getIdentifierColumnNames(ClassMetadata $class, AbstractPlatform $platform);

View File

@@ -91,7 +91,8 @@ final class ReflectionPropertiesGetter
$classes[] = $currentClass;
$parentClassName = null;
if ($parentClass = $currentClass->getParentClass()) {
$parentClass = $currentClass->getParentClass();
if ($parentClass) {
$parentClassName = $parentClass->getName();
}
}

View File

@@ -122,10 +122,11 @@ class ORMInvalidArgumentException extends InvalidArgumentException
}
/**
* @param array $associationMapping
* @param object $entry
*
* @return ORMInvalidArgumentException
*
* @psalm-param array<string, string> $associationMapping
*/
public static function newEntityFoundThroughRelationship(array $associationMapping, $entry)
{
@@ -133,10 +134,11 @@ class ORMInvalidArgumentException extends InvalidArgumentException
}
/**
* @param array $assoc
* @param object $entry
*
* @return ORMInvalidArgumentException
*
* @psalm-param array<string, string> $assoc
*/
public static function detachedEntityFoundThroughRelationship(array $assoc, $entry)
{
@@ -252,19 +254,16 @@ class ORMInvalidArgumentException extends InvalidArgumentException
/**
* Helper method to show an object as string.
*
* @param object $obj
*/
private static function objToStr($obj): string
private static function objToStr(object $obj): string
{
return method_exists($obj, '__toString') ? (string) $obj : get_class($obj) . '@' . spl_object_hash($obj);
}
/**
* @param array $associationMapping
* @param object $entity
* @psalm-param array<string,string> $associationMapping
*/
private static function newEntityFoundThroughRelationshipMessage(array $associationMapping, $entity): string
private static function newEntityFoundThroughRelationshipMessage(array $associationMapping, object $entity): string
{
return 'A new entity was found through the relationship \''
. $associationMapping['sourceEntity'] . '#' . $associationMapping['fieldName'] . '\' that was not'

View File

@@ -20,7 +20,7 @@
namespace Doctrine\ORM;
use DateTime;
use DateTimeInterface;
/**
* An OptimisticLockException is thrown when a version check on an object
@@ -70,8 +70,8 @@ class OptimisticLockException extends ORMException
*/
public static function lockFailedVersionMismatch($entity, $expectedLockVersion, $actualLockVersion)
{
$expectedLockVersion = $expectedLockVersion instanceof DateTime ? $expectedLockVersion->getTimestamp() : $expectedLockVersion;
$actualLockVersion = $actualLockVersion instanceof DateTime ? $actualLockVersion->getTimestamp() : $actualLockVersion;
$expectedLockVersion = $expectedLockVersion instanceof DateTimeInterface ? $expectedLockVersion->getTimestamp() : $expectedLockVersion;
$actualLockVersion = $actualLockVersion instanceof DateTimeInterface ? $actualLockVersion->getTimestamp() : $actualLockVersion;
return new self('The optimistic lock failed, version ' . $expectedLockVersion . ' was expected, but is actually ' . $actualLockVersion, $entity);
}

View File

@@ -45,6 +45,11 @@ use function spl_object_hash;
* entities from the collection, only the links in the relation table are removed (on flush).
* Similarly, if you remove entities from a collection that is part of a one-many
* mapping this will only result in the nulling out of the foreign keys on flush.
*
* @phpstan-template TKey
* @psalm-template TKey of array-key
* @psalm-template T
* @template-implements Collection<TKey,T>
*/
final class PersistentCollection extends AbstractLazyCollection implements Selectable
{
@@ -52,7 +57,7 @@ final class PersistentCollection extends AbstractLazyCollection implements Selec
* A snapshot of the collection at the moment it was fetched from the database.
* This is used to create a diff of the collection at commit time.
*
* @var array
* @psalm-var array<string|int, mixed>
*/
private $snapshot = [];
@@ -67,7 +72,7 @@ final class PersistentCollection extends AbstractLazyCollection implements Selec
* The association mapping the collection belongs to.
* This is currently either a OneToManyMapping or a ManyToManyMapping.
*
* @var array
* @psalm-var array<string, mixed>
*/
private $association;
@@ -104,9 +109,10 @@ final class PersistentCollection extends AbstractLazyCollection implements Selec
/**
* Creates a new persistent collection.
*
* @param EntityManagerInterface $em The EntityManager the collection will be associated with.
* @param ClassMetadata $class The class descriptor of the entity type of this collection.
* @param Collection $collection The collection elements.
* @param EntityManagerInterface $em The EntityManager the collection will be associated with.
* @param ClassMetadata $class The class descriptor of the entity type of this collection.
*
* @psalm-param Collection<TKey, T> $collection The collection elements.
*/
public function __construct(EntityManagerInterface $em, $class, Collection $collection)
{
@@ -122,9 +128,10 @@ final class PersistentCollection extends AbstractLazyCollection implements Selec
* describes the association between the owner and the elements of the collection.
*
* @param object $entity
* @param array $assoc
*
* @return void
*
* @psalm-param array<string, mixed> $assoc
*/
public function setOwner($entity, array $assoc)
{
@@ -239,7 +246,7 @@ final class PersistentCollection extends AbstractLazyCollection implements Selec
* INTERNAL:
* Returns the last snapshot of the elements in the collection.
*
* @return array The last snapshot of the elements.
* @psalm-return array<string|int, mixed> The last snapshot of the elements.
*/
public function getSnapshot()
{
@@ -250,14 +257,14 @@ final class PersistentCollection extends AbstractLazyCollection implements Selec
* INTERNAL:
* getDeleteDiff
*
* @return array
* @return mixed[]
*/
public function getDeleteDiff()
{
return array_udiff_assoc(
$this->snapshot,
$this->collection->toArray(),
static function ($a, $b) {
static function ($a, $b): int {
return $a === $b ? 0 : 1;
}
);
@@ -267,14 +274,14 @@ final class PersistentCollection extends AbstractLazyCollection implements Selec
* INTERNAL:
* getInsertDiff
*
* @return array
* @return mixed[]
*/
public function getInsertDiff()
{
return array_udiff_assoc(
$this->collection->toArray(),
$this->snapshot,
static function ($a, $b) {
static function ($a, $b): int {
return $a === $b ? 0 : 1;
}
);
@@ -283,7 +290,7 @@ final class PersistentCollection extends AbstractLazyCollection implements Selec
/**
* INTERNAL: Gets the association mapping of the collection.
*
* @return array
* @psalm-return array<string, mixed>
*/
public function getMapping()
{
@@ -616,7 +623,7 @@ final class PersistentCollection extends AbstractLazyCollection implements Selec
* @param int $offset
* @param int|null $length
*
* @return array
* @psalm-return array<TKey,T>
*/
public function slice($offset, $length = null)
{
@@ -660,7 +667,7 @@ final class PersistentCollection extends AbstractLazyCollection implements Selec
* Selects all elements from a selectable that match the expression and
* return a new collection containing these elements.
*
* @return Collection
* @return Collection<TKey, T>
*
* @throws RuntimeException
*/
@@ -699,7 +706,7 @@ final class PersistentCollection extends AbstractLazyCollection implements Selec
/**
* Retrieves the wrapped Collection instance.
*
* @return Collection
* @return Collection<TKey, T>
*/
public function unwrap()
{

View File

@@ -57,7 +57,7 @@ interface CollectionPersister
* @param int $offset
* @param int $length
*
* @return array
* @return mixed[]
*/
public function slice(PersistentCollection $collection, $offset, $length = null);
@@ -91,7 +91,7 @@ interface CollectionPersister
/**
* Loads association entities matching the given Criteria object.
*
* @return array
* @return mixed[]
*/
public function loadCriteria(PersistentCollection $collection, Criteria $criteria);
}

View File

@@ -298,12 +298,11 @@ class ManyToManyPersister extends AbstractCollectionPersister
* have to join in the actual entities table leading to additional
* JOIN.
*
* @param array $mapping Array containing mapping information.
*
* @return string[] ordered tuple:
* - JOIN condition to add to the SQL
* - WHERE condition to add to the SQL
*
* @psalm-param array<string, mixed> $mapping Array containing mapping information.
* @psalm-return array{0: string, 1: string}
*/
public function getFilterSql($mapping)
@@ -337,7 +336,8 @@ class ManyToManyPersister extends AbstractCollectionPersister
$filterClauses = [];
foreach ($this->em->getFilters()->getEnabledFilters() as $filter) {
if ($filterExpr = $filter->addFilterConstraint($targetEntity, $targetTableAlias)) {
$filterExpr = $filter->addFilterConstraint($targetEntity, $targetTableAlias);
if ($filterExpr) {
$filterClauses[] = '(' . $filterExpr . ')';
}
}
@@ -350,10 +350,9 @@ class ManyToManyPersister extends AbstractCollectionPersister
/**
* Generate ON condition
*
* @param array $mapping
*
* @return string[]
*
* @psalm-param array<string, mixed> $mapping
* @psalm-return list<string>
*/
protected function getOnConditionSQL($mapping)
@@ -373,7 +372,7 @@ class ManyToManyPersister extends AbstractCollectionPersister
$joinColumnName = $this->quoteStrategy->getJoinColumnName($joinColumn, $targetClass, $this->platform);
$refColumnName = $this->quoteStrategy->getReferencedJoinColumnName($joinColumn, $targetClass, $this->platform);
$conditions[] = ' t.' . $joinColumnName . ' = ' . 'te.' . $refColumnName;
$conditions[] = ' t.' . $joinColumnName . ' = te.' . $refColumnName;
}
return $conditions;
@@ -466,8 +465,6 @@ class ManyToManyPersister extends AbstractCollectionPersister
*
* @param mixed $element
*
* @return array
*
* @psalm-return list<mixed>
*/
protected function getDeleteRowSQLParameters(PersistentCollection $collection, $element)
@@ -518,8 +515,6 @@ class ManyToManyPersister extends AbstractCollectionPersister
*
* @param mixed $element
*
* @return array
*
* @psalm-return list<mixed>
*/
protected function getInsertRowSQLParameters(PersistentCollection $collection, $element)
@@ -577,7 +572,7 @@ class ManyToManyPersister extends AbstractCollectionPersister
* @param string $key
* @param bool $addFilters Whether the filter SQL should be included or not.
*
* @return array ordered vector:
* @return mixed[] ordered vector:
* - quoted join table name
* - where clauses to be added for filtering
* - parameters to be bound for filtering
@@ -663,7 +658,7 @@ class ManyToManyPersister extends AbstractCollectionPersister
* @param object $element
* @param bool $addFilters Whether the filter SQL should be included or not.
*
* @return array ordered vector:
* @return mixed[] ordered vector:
* - quoted join table name
* - where clauses to be added for filtering
* - parameters to be bound for filtering
@@ -730,7 +725,7 @@ class ManyToManyPersister extends AbstractCollectionPersister
* Expands Criteria Parameters by walking the expressions and grabbing all
* parameters and types from it.
*
* @return array
* @return mixed[][]
*/
private function expandCriteriaParameters(Criteria $criteria)
{

View File

@@ -145,7 +145,7 @@ class BasicEntityPersister implements EntityPersister
/**
* Queued inserts.
*
* @var array
* @psalm-var array<string, object>
*/
protected $queuedInserts = [];
@@ -313,8 +313,8 @@ class BasicEntityPersister implements EntityPersister
* by the preceding INSERT statement and assigns it back in to the
* entities version field.
*
* @param object $entity
* @param array $id
* @param object $entity
* @param mixed[] $id
*
* @return void
*/
@@ -359,6 +359,8 @@ class BasicEntityPersister implements EntityPersister
}
/**
* @param mixed[] $id
*
* @return int[]|null[]|string[]
*
* @psalm-return list<(int|string|null)>
@@ -398,7 +400,7 @@ class BasicEntityPersister implements EntityPersister
$this->updateTable($entity, $quotedTableName, $data, $isVersioned);
if ($isVersioned) {
$id = $this->em->getUnitOfWork()->getEntityIdentifier($entity);
$id = $this->class->getIdentifierValues($entity);
$this->assignDefaultVersionValue($entity, $id);
}
@@ -974,17 +976,18 @@ class BasicEntityPersister implements EntityPersister
}
/**
* @param array $assoc
* @param object $sourceEntity
* @param int|null $offset
* @param int|null $limit
*
* @return \Doctrine\DBAL\Driver\Statement
*
* @throws MappingException
*
* @psalm-param array<string, mixed> $assoc
*/
private function getManyToManyStatement(array $assoc, $sourceEntity, $offset = null, $limit = null)
{
private function getManyToManyStatement(
array $assoc,
object $sourceEntity,
?int $offset = null,
?int $limit = null
) {
$this->switchPersisterContext($offset, $limit);
$sourceClass = $this->em->getClassMetadata($assoc['sourceEntity']);
@@ -1137,12 +1140,11 @@ class BasicEntityPersister implements EntityPersister
/**
* Gets the ORDER BY SQL snippet for ordered collections.
*
* @param array $orderBy
* @param string $baseTableAlias
*
* @throws ORMException
*
* @psalm-param array<string, string> $orderBy
*/
final protected function getOrderBySQL(array $orderBy, $baseTableAlias): string
final protected function getOrderBySQL(array $orderBy, string $baseTableAlias): string
{
$orderByList = [];
@@ -1286,7 +1288,8 @@ class BasicEntityPersister implements EntityPersister
}
// Add filter SQL
if ($filterSql = $this->generateFilterConditionSQL($eagerEntity, $tableAlias)) {
$filterSql = $this->generateFilterConditionSQL($eagerEntity, $tableAlias);
if ($filterSql) {
$joinCondition[] = $filterSql;
}
} else {
@@ -1347,9 +1350,9 @@ class BasicEntityPersister implements EntityPersister
* Gets the SQL join fragment used when selecting entities from a
* many-to-many association.
*
* @param array $manyToMany
*
* @return string
*
* @psalm-param array<string, mixed> $manyToMany
*/
protected function getSelectManyToManyJoinSQL(array $manyToMany)
{
@@ -1657,13 +1660,13 @@ class BasicEntityPersister implements EntityPersister
/**
* Builds the left-hand-side of a where condition statement.
*
* @param string $field
* @param array|null $assoc
* @param string $field
*
* @return string[]
*
* @throws ORMException
*
* @psalm-param array<string, mixed>|null $assoc
* @psalm-return list<string>
*/
private function getSelectConditionStatementColumnSQL($field, $assoc = null)
@@ -1726,10 +1729,10 @@ class BasicEntityPersister implements EntityPersister
* Subclasses are supposed to override this method if they intend to change
* or alter the criteria by which entities are selected.
*
* @param array $criteria
* @param array|null $assoc
*
* @return string
*
* @psalm-param array<string, mixed> $criteria
* @psalm-param array<string, mixed>|null $assoc
*/
protected function getSelectConditionSQL(array $criteria, $assoc = null)
{
@@ -1767,12 +1770,13 @@ class BasicEntityPersister implements EntityPersister
/**
* Builds criteria and execute SQL statement to fetch the one to many entities from.
*
* @param array $assoc
* @param object $sourceEntity
* @param int|null $offset
* @param int|null $limit
*
* @return Statement
*
* @psalm-param array<string, mixed> $assoc
*/
private function getOneToManyStatement(array $assoc, $sourceEntity, $offset = null, $limit = null)
{
@@ -1932,7 +1936,7 @@ class BasicEntityPersister implements EntityPersister
*
* @param mixed $value
*
* @return array
* @return array{mixed}
*/
private function getValues($value)
{
@@ -2005,7 +2009,8 @@ class BasicEntityPersister implements EntityPersister
$types = array_merge($types, $criteriaTypes);
}
if ($filterSql = $this->generateFilterConditionSQL($this->class, $alias)) {
$filterSql = $this->generateFilterConditionSQL($this->class, $alias);
if ($filterSql) {
$sql .= ' AND ' . $filterSql;
}
@@ -2015,9 +2020,9 @@ class BasicEntityPersister implements EntityPersister
/**
* Generates the appropriate join SQL for the given join column.
*
* @param array $joinColumns The join columns definition of an association.
*
* @return string LEFT JOIN if one of the columns is nullable, INNER JOIN otherwise.
*
* @psalm-param array<array<string, mixed>> $joinColumns The join columns definition of an association.
*/
protected function getJoinSQLForJoinColumns($joinColumns)
{
@@ -2054,7 +2059,8 @@ class BasicEntityPersister implements EntityPersister
$filterClauses = [];
foreach ($this->em->getFilters()->getEnabledFilters() as $filter) {
if ('' !== $filterExpr = $filter->addFilterConstraint($targetEntity, $targetTableAlias)) {
$filterExpr = $filter->addFilterConstraint($targetEntity, $targetTableAlias);
if ($filterExpr !== '') {
$filterClauses[] = '(' . $filterExpr . ')';
}
}

View File

@@ -74,7 +74,7 @@ class CachedPersisterContext
/**
* Map from class names (FQCN) to the corresponding generated SQL table aliases.
*
* @var array
* @var array<class-string, string>
*/
public $sqlTableAliases = [];

View File

@@ -47,7 +47,7 @@ interface EntityPersister
/**
* Get all queued inserts.
*
* @return array
* @psalm-return array<string, object>
*/
public function getInserts();
@@ -89,14 +89,14 @@ interface EntityPersister
*
* @param string[] $criteria
*
* @return array
* @psalm-return array{list<mixed>, list<int|string|null>}
*/
public function expandParameters($criteria);
/**
* Expands Criteria Parameters by walking the expressions and grabbing all parameters and types from it.
*
* @return array
* @psalm-return array{list<mixed>, list<int|string|null>}
*/
public function expandCriteriaParameters(Criteria $criteria);
@@ -105,10 +105,11 @@ interface EntityPersister
*
* @param string $field
* @param mixed $value
* @param array|null $assoc
* @param string|null $comparison
*
* @return string
*
* @psalm-param array<string, mixed>|null $assoc
*/
public function getSelectConditionStatementSQL($field, $value, $assoc = null, $comparison = null);
@@ -128,8 +129,12 @@ interface EntityPersister
*
* If no inserts are queued, invoking this method is a NOOP.
*
* @return array An array of any generated post-insert IDs. This will be an empty array
* if the entity class does not use the IDENTITY generation strategy.
* @psalm-return list<array{
* generatedId: int,
* entity: object
* }> An array of any generated post-insert IDs. This will be
* an empty array if the entity class does not use the
* IDENTITY generation strategy.
*/
public function executeInserts();
@@ -182,30 +187,42 @@ interface EntityPersister
/**
* Loads an entity by a list of field criteria.
*
* @param array $criteria The criteria by which to load the entity.
* @param object|null $entity The entity to load the data into. If not specified, a new entity is created.
* @param array|null $assoc The association that connects the entity to load to another entity, if any.
* @param array $hints Hints for entity creation.
* @param int|null $lockMode One of the \Doctrine\DBAL\LockMode::* constants
* or NULL if no specific lock mode should be used
* for loading the entity.
* @param int|null $limit Limit number of results.
* @param array|null $orderBy Criteria to order by.
*
* @return object|null The loaded and managed entity instance or NULL if the entity can not be found.
*
* @psalm-param array<string, mixed> $hints Hints for entity creation.
* @psalm-param array<string, mixed> $criteria The criteria by which
* to load the entity.
* @psalm-param array<string, mixed>|null $assoc The association that
* connects the entity to
* load to another entity,
* if any.
* @psalm-param array<string, string>|null $orderBy Criteria to order by.
* @todo Check identity map? loadById method? Try to guess whether $criteria is the id?
*/
public function load(array $criteria, $entity = null, $assoc = null, array $hints = [], $lockMode = null, $limit = null, ?array $orderBy = null);
public function load(
array $criteria,
$entity = null,
$assoc = null,
array $hints = [],
$lockMode = null,
$limit = null,
?array $orderBy = null
);
/**
* Loads an entity by identifier.
*
* @param array $identifier The entity identifier.
* @param object|null $entity The entity to load the data into. If not specified, a new entity is created.
* @param object|null $entity The entity to load the data into. If not specified, a new entity is created.
*
* @return object The loaded and managed entity instance or NULL if the entity can not be found.
*
* @psalm-param array<string, mixed> $identifier The entity identifier.
* @todo Check parameters
*/
public function loadById(array $identifier, $entity = null);
@@ -214,104 +231,111 @@ interface EntityPersister
* Loads an entity of this persister's mapped class as part of a single-valued
* association from another entity.
*
* @param array $assoc The association to load.
* @param object $sourceEntity The entity that owns the association (not necessarily the "owning side").
* @param array $identifier The identifier of the entity to load. Must be provided if
* the association to load represents the owning side, otherwise
* the identifier is derived from the $sourceEntity.
*
* @return object The loaded and managed entity instance or NULL if the entity can not be found.
*
* @throws MappingException
*
* @psalm-param array<string, mixed> $identifier The identifier of the entity to load. Must be provided if
* the association to load represents the owning side, otherwise
* the identifier is derived from the $sourceEntity.
* @psalm-param array<string, mixed> $assoc The association to load.
*/
public function loadOneToOneEntity(array $assoc, $sourceEntity, array $identifier = []);
/**
* Refreshes a managed entity.
*
* @param array $id The identifier of the entity as an associative array from
* column or field names to values.
* @param object $entity The entity to refresh.
* @param int|null $lockMode One of the \Doctrine\DBAL\LockMode::* constants
* or NULL if no specific lock mode should be used
* for refreshing the managed entity.
*
* @return void
*
* @psalm-param array<string, mixed> $id The identifier of the entity as an
* associative array from column or
* field names to values.
*/
public function refresh(array $id, $entity, $lockMode = null);
/**
* Loads Entities matching the given Criteria object.
*
* @return array
* @return mixed[]
*/
public function loadCriteria(Criteria $criteria);
/**
* Loads a list of entities by a list of field criteria.
*
* @param array $criteria
* @param array|null $orderBy
* @param int|null $limit
* @param int|null $offset
* @param int|null $limit
* @param int|null $offset
*
* @return array
* @psalm-param list<string>|null $orderBy
* @psalm-param array<string, mixed> $criteria
*/
public function loadAll(array $criteria = [], ?array $orderBy = null, $limit = null, $offset = null);
/**
* Gets (sliced or full) elements of the given collection.
*
* @param array $assoc
* @param object $sourceEntity
* @param int|null $offset
* @param int|null $limit
*
* @return array
* @return mixed[]
*
* @psalm-param array<string, mixed> $assoc
*/
public function getManyToManyCollection(array $assoc, $sourceEntity, $offset = null, $limit = null);
/**
* Loads a collection of entities of a many-to-many association.
*
* @param array $assoc The association mapping of the association being loaded.
* @param object $sourceEntity The entity that owns the collection.
* @param PersistentCollection $collection The collection to fill.
*
* @return array
* @return mixed[]
*
* @psalm-param array<string, mixed> $assoc The association mapping of the association being loaded.
*/
public function loadManyToManyCollection(array $assoc, $sourceEntity, PersistentCollection $collection);
/**
* Loads a collection of entities in a one-to-many association.
*
* @param array $assoc
* @param object $sourceEntity
* @param PersistentCollection $collection The collection to load/fill.
*
* @return array
* @return mixed
*
* @psalm-param array<string, mixed> $assoc
*/
public function loadOneToManyCollection(array $assoc, $sourceEntity, PersistentCollection $collection);
/**
* Locks all rows of this entity matching the given criteria with the specified pessimistic lock mode.
*
* @param array $criteria
* @param int $lockMode One of the Doctrine\DBAL\LockMode::* constants.
* @param int $lockMode One of the Doctrine\DBAL\LockMode::* constants.
*
* @return void
*
* @psalm-param array<string, mixed> $criteria
*/
public function lock(array $criteria, $lockMode);
/**
* Returns an array with (sliced or full list) of elements in the specified collection.
*
* @param array $assoc
* @param object $sourceEntity
* @param int|null $offset
* @param int|null $limit
*
* @return array
* @return mixed[]
*
* @psalm-param array<string, mixed> $assoc
*/
public function getOneToManyCollection(array $assoc, $sourceEntity, $offset = null, $limit = null);

View File

@@ -22,7 +22,6 @@ namespace Doctrine\ORM\Persisters\Entity;
use Doctrine\Common\Collections\Criteria;
use Doctrine\DBAL\LockMode;
use Doctrine\DBAL\Statement;
use Doctrine\DBAL\Types\Type;
use Doctrine\ORM\Mapping\ClassMetadata;
use Doctrine\ORM\Utility\PersisterHelper;
@@ -43,14 +42,14 @@ class JoinedSubclassPersister extends AbstractEntityInheritancePersister
* Map that maps column names to the table names that own them.
* This is mainly a temporary cache, used during a single request.
*
* @var array
* @psalm-var array<string, string>
*/
private $owningTableMap = [];
/**
* Map of table to quoted table names.
*
* @var array
* @psalm-var array<string, string>
*/
private $quotedTableMap = [];
@@ -192,7 +191,6 @@ class JoinedSubclassPersister extends AbstractEntityInheritancePersister
// Execute inserts on subtables.
// The order doesn't matter because all child tables link to the root table via FK.
foreach ($subTableStmts as $tableName => $stmt) {
/** @var Statement $stmt */
$paramIndex = 1;
$data = $insertData[$tableName] ?? [];
@@ -234,7 +232,8 @@ class JoinedSubclassPersister extends AbstractEntityInheritancePersister
return;
}
if (($isVersioned = $this->class->isVersioned) === false) {
$isVersioned = $this->class->isVersioned;
if ($isVersioned === false) {
return;
}
@@ -319,8 +318,12 @@ class JoinedSubclassPersister extends AbstractEntityInheritancePersister
? $this->getSelectConditionCriteriaSQL($criteria)
: $this->getSelectConditionSQL($criteria, $assoc);
$filterSql = $this->generateFilterConditionSQL(
$this->em->getClassMetadata($this->class->rootEntityName),
$this->getSQLTableAlias($this->class->rootEntityName)
);
// If the current class in the root entity, add the filters
if ($filterSql = $this->generateFilterConditionSQL($this->em->getClassMetadata($this->class->rootEntityName), $this->getSQLTableAlias($this->class->rootEntityName))) {
if ($filterSql) {
$conditionSql .= $conditionSql
? ' AND ' . $filterSql
: $filterSql;

View File

@@ -103,13 +103,13 @@ class SqlValueVisitor extends ExpressionVisitor
switch ($comparison->getOperator()) {
case Comparison::CONTAINS:
return "%{$value}%";
return '%' . $value . '%';
case Comparison::STARTS_WITH:
return "{$value}%";
return $value . '%';
case Comparison::ENDS_WITH:
return "%{$value}";
return '%' . $value;
default:
return $value;

View File

@@ -28,7 +28,6 @@ use Doctrine\Common\Proxy\ProxyGenerator;
use Doctrine\Common\Util\ClassUtils;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\EntityNotFoundException;
use Doctrine\ORM\Mapping\ClassMetadataInfo;
use Doctrine\ORM\Persisters\Entity\EntityPersister;
use Doctrine\ORM\UnitOfWork;
use Doctrine\ORM\Utility\IdentifierFlattener;
@@ -85,7 +84,6 @@ class ProxyFactory extends AbstractProxyFactory
*/
protected function skipClass(ClassMetadata $metadata)
{
/** @var ClassMetadataInfo $metadata */
return $metadata->isMappedSuperclass
|| $metadata->isEmbeddedClass
|| $metadata->getReflectionClass()->isAbstract();

View File

@@ -258,7 +258,7 @@ final class Query extends AbstractQuery
return $this->parserResult;
}
$hash = $this->_getQueryCacheId();
$hash = $this->getQueryCacheId();
$cached = $this->expireQueryCache ? false : $queryCache->fetch($hash);
if ($cached instanceof ParserResult) {
@@ -756,10 +756,8 @@ final class Query extends AbstractQuery
/**
* Generate a cache id for the query cache - reusing the Result-Cache-Id generator.
*
* @return string
*/
protected function _getQueryCacheId()
protected function getQueryCacheId(): string
{
ksort($this->_hints);

View File

@@ -27,6 +27,7 @@ namespace Doctrine\ORM\Query\AST;
*/
class CollectionMemberExpression extends Node
{
/** @var mixed */
public $entityExpression;
/** @var PathExpression */

View File

@@ -20,6 +20,7 @@
namespace Doctrine\ORM\Query\AST\Functions;
use Doctrine\ORM\Query\AST\Node;
use Doctrine\ORM\Query\Lexer;
use Doctrine\ORM\Query\Parser;
use Doctrine\ORM\Query\SqlWalker;
@@ -31,7 +32,10 @@ use Doctrine\ORM\Query\SqlWalker;
*/
class BitAndFunction extends FunctionNode
{
/** @var Node */
public $firstArithmetic;
/** @var Node */
public $secondArithmetic;
/**

View File

@@ -20,6 +20,7 @@
namespace Doctrine\ORM\Query\AST\Functions;
use Doctrine\ORM\Query\AST\Node;
use Doctrine\ORM\Query\Lexer;
use Doctrine\ORM\Query\Parser;
use Doctrine\ORM\Query\SqlWalker;
@@ -31,7 +32,10 @@ use Doctrine\ORM\Query\SqlWalker;
*/
class BitOrFunction extends FunctionNode
{
/** @var Node */
public $firstArithmetic;
/** @var Node */
public $secondArithmetic;
/**

View File

@@ -20,6 +20,7 @@
namespace Doctrine\ORM\Query\AST\Functions;
use Doctrine\ORM\Query\AST\Node;
use Doctrine\ORM\Query\Lexer;
use Doctrine\ORM\Query\Parser;
use Doctrine\ORM\Query\SqlWalker;
@@ -33,10 +34,13 @@ use function call_user_func_array;
*/
class ConcatFunction extends FunctionNode
{
/** @var Node */
public $firstStringPrimary;
/** @var Node */
public $secondStringPrimary;
/** @psalm-var list<Node> */
public $concatExpressions = [];
/**

View File

@@ -20,6 +20,7 @@
namespace Doctrine\ORM\Query\AST\Functions;
use Doctrine\ORM\Query\AST\Node;
use Doctrine\ORM\Query\Lexer;
use Doctrine\ORM\Query\Parser;
use Doctrine\ORM\Query\SqlWalker;
@@ -31,7 +32,10 @@ use Doctrine\ORM\Query\SqlWalker;
*/
class DateDiffFunction extends FunctionNode
{
/** @var Node */
public $date1;
/** @var Node */
public $date2;
/**

View File

@@ -21,6 +21,7 @@
namespace Doctrine\ORM\Query\AST\Functions;
use Doctrine\DBAL\Types\Type;
use Doctrine\ORM\Query\AST\Node;
use Doctrine\ORM\Query\AST\TypedExpression;
use Doctrine\ORM\Query\Lexer;
use Doctrine\ORM\Query\Parser;
@@ -33,6 +34,7 @@ use Doctrine\ORM\Query\SqlWalker;
*/
class LengthFunction extends FunctionNode implements TypedExpression
{
/** @var Node */
public $stringPrimary;
/**

View File

@@ -20,6 +20,7 @@
namespace Doctrine\ORM\Query\AST\Functions;
use Doctrine\ORM\Query\AST\Node;
use Doctrine\ORM\Query\AST\SimpleArithmeticExpression;
use Doctrine\ORM\Query\Lexer;
use Doctrine\ORM\Query\Parser;
@@ -32,7 +33,10 @@ use Doctrine\ORM\Query\SqlWalker;
*/
class LocateFunction extends FunctionNode
{
/** @var Node */
public $firstStringPrimary;
/** @var Node */
public $secondStringPrimary;
/** @var SimpleArithmeticExpression|bool */

View File

@@ -20,6 +20,7 @@
namespace Doctrine\ORM\Query\AST\Functions;
use Doctrine\ORM\Query\AST\Node;
use Doctrine\ORM\Query\Lexer;
use Doctrine\ORM\Query\Parser;
use Doctrine\ORM\Query\SqlWalker;
@@ -31,6 +32,7 @@ use Doctrine\ORM\Query\SqlWalker;
*/
class LowerFunction extends FunctionNode
{
/** @psalm-var Node */
public $stringPrimary;
/**

View File

@@ -20,6 +20,7 @@
namespace Doctrine\ORM\Query\AST\Functions;
use Doctrine\ORM\Query\AST\Node;
use Doctrine\ORM\Query\AST\SimpleArithmeticExpression;
use Doctrine\ORM\Query\Lexer;
use Doctrine\ORM\Query\Parser;
@@ -32,6 +33,7 @@ use Doctrine\ORM\Query\SqlWalker;
*/
class SubstringFunction extends FunctionNode
{
/** @var Node */
public $stringPrimary;
/** @var SimpleArithmeticExpression */

View File

@@ -20,6 +20,7 @@
namespace Doctrine\ORM\Query\AST\Functions;
use Doctrine\ORM\Query\AST\Node;
use Doctrine\ORM\Query\Lexer;
use Doctrine\ORM\Query\Parser;
use Doctrine\ORM\Query\SqlWalker;
@@ -31,6 +32,7 @@ use Doctrine\ORM\Query\SqlWalker;
*/
class UpperFunction extends FunctionNode
{
/** @var Node */
public $stringPrimary;
/**

View File

@@ -23,6 +23,7 @@ namespace Doctrine\ORM\Query\Exec;
use Doctrine\DBAL\Cache\QueryCacheProfile;
use Doctrine\DBAL\Connection;
use Doctrine\DBAL\Driver\Statement;
use Doctrine\DBAL\Types\Type;
/**
* Base class for SQL statement executors.
@@ -70,11 +71,13 @@ abstract class AbstractSqlExecutor
/**
* Executes all sql statements.
*
* @param Connection $conn The database connection that is used to execute the queries.
* @param array $params The parameters.
* @param array $types The parameter types.
* @param Connection $conn The database connection that is used to execute the queries.
*
* @return Statement
*
* @psalm-param array<int, mixed>|array<string, mixed> $params The parameters.
* @psalm-param array<int, int|string|Type|null>|
* array<string, int|string|Type|null> $types The parameter types.
*/
abstract public function execute(Connection $conn, array $params, array $types);
}

View File

@@ -457,7 +457,7 @@ class Expr
foreach ($y as &$literal) {
if (! ($literal instanceof Expr\Literal)) {
$literal = $this->_quoteLiteral($literal);
$literal = $this->quoteLiteral($literal);
}
}
}
@@ -482,7 +482,7 @@ class Expr
foreach ($y as &$literal) {
if (! ($literal instanceof Expr\Literal)) {
$literal = $this->_quoteLiteral($literal);
$literal = $this->quoteLiteral($literal);
}
}
}
@@ -617,17 +617,15 @@ class Expr
*/
public function literal($literal)
{
return new Expr\Literal($this->_quoteLiteral($literal));
return new Expr\Literal($this->quoteLiteral($literal));
}
/**
* Quotes a literal value, if necessary, according to the DQL syntax.
*
* @param mixed $literal The literal value.
*
* @return string
*/
private function _quoteLiteral($literal)
private function quoteLiteral($literal): string
{
if (is_numeric($literal) && ! is_string($literal)) {
return (string) $literal;

View File

@@ -38,8 +38,11 @@ class Andx extends Composite
self::class,
];
/** @psalm-var list<string|Comparison|Func|Orx|self> */
protected $parts = [];
/**
* @return array
* @psalm-return list<string|Comparison|Func|Orx|self>
*/
public function getParts()
{

View File

@@ -45,10 +45,10 @@ abstract class Base
/** @var string */
protected $postSeparator = ')';
/** @var string[] */
/** @psalm-var list<class-string> */
protected $allowedClasses = [];
/** @var mixed[] */
/** @psalm-var list<string|object> */
protected $parts = [];
/**
@@ -60,9 +60,9 @@ abstract class Base
}
/**
* @param array $args
*
* @return static
*
* @psalm-param list<string|object> $args
*/
public function addMultiple($args = [])
{

View File

@@ -22,7 +22,7 @@ namespace Doctrine\ORM\Query\Expr;
use function implode;
use function is_object;
use function stripos;
use function preg_match;
/**
* Expression class for building DQL and parts.
@@ -63,7 +63,7 @@ class Composite extends Base
}
// Fixes DDC-1237: User may have added a where item containing nested expression (with "OR" or "AND")
if (stripos($queryPart, ' OR ') !== false || stripos($queryPart, ' AND ') !== false) {
if (preg_match('/\s(OR|AND)\s/', $queryPart)) {
return $this->preSeparator . $queryPart . $this->postSeparator;
}

View File

@@ -39,7 +39,8 @@ class Func
* Creates a function, with the given argument.
*
* @param string $name
* @param array $arguments
*
* @psalm-param list<mixed> $arguments
*/
public function __construct($name, $arguments)
{
@@ -56,7 +57,7 @@ class Func
}
/**
* @return array
* @psalm-return list<mixed>
*/
public function getArguments()
{

View File

@@ -33,8 +33,11 @@ class GroupBy extends Base
/** @var string */
protected $postSeparator = '';
/** @psalm-var list<string> */
protected $parts = [];
/**
* @return array
* @psalm-return list<string>
*/
public function getParts()
{

View File

@@ -33,8 +33,11 @@ class Literal extends Base
/** @var string */
protected $postSeparator = '';
/** @psalm-var list<string> */
protected $parts = [];
/**
* @return array
* @psalm-return list<string>
*/
public function getParts()
{

View File

@@ -42,7 +42,7 @@ class OrderBy
/** @var string[] */
protected $allowedClasses = [];
/** @var mixed[] */
/** @psalm-var list<string> */
protected $parts = [];
/**
@@ -77,7 +77,7 @@ class OrderBy
}
/**
* @return array
* @psalm-return list<string>
*/
public function getParts()
{

View File

@@ -38,8 +38,11 @@ class Orx extends Composite
self::class,
];
/** @psalm-var list<string|Comparison|Func|Andx|self> */
protected $parts = [];
/**
* @return array
* @psalm-return list<string|Comparison|Func|Andx|self>
*/
public function getParts()
{

View File

@@ -36,8 +36,11 @@ class Select extends Base
/** @var string[] */
protected $allowedClasses = [Func::class];
/** @psalm-var list<string|Func> */
protected $parts = [];
/**
* @return array
* @psalm-return list<string|Func>
*/
public function getParts()
{

View File

@@ -48,7 +48,7 @@ abstract class SQLFilter
/**
* Parameters for the filter.
*
* @var array
* @psalm-var array<string, array{value: string, type: string|null}>
*/
private $parameters = [];

View File

@@ -52,6 +52,7 @@ use Doctrine\ORM\Query\AST\JoinAssociationPathExpression;
use Doctrine\ORM\Query\AST\LikeExpression;
use Doctrine\ORM\Query\AST\Literal;
use Doctrine\ORM\Query\AST\NewObjectExpression;
use Doctrine\ORM\Query\AST\Node;
use Doctrine\ORM\Query\AST\NullComparisonExpression;
use Doctrine\ORM\Query\AST\NullIfExpression;
use Doctrine\ORM\Query\AST\OrderByClause;
@@ -104,10 +105,9 @@ class Parser
/**
* READ-ONLY: Maps BUILT-IN string function names to AST class names.
*
* @var array
* @psalm-var array<string, class-string<Functions\FunctionNode>>
*/
private static $_STRING_FUNCTIONS = [
private static $stringFunctions = [
'concat' => Functions\ConcatFunction::class,
'substring' => Functions\SubstringFunction::class,
'trim' => Functions\TrimFunction::class,
@@ -119,10 +119,9 @@ class Parser
/**
* READ-ONLY: Maps BUILT-IN numeric function names to AST class names.
*
* @var array
* @psalm-var array<string, class-string<Functions\FunctionNode>>
*/
private static $_NUMERIC_FUNCTIONS = [
private static $numericFunctions = [
'length' => Functions\LengthFunction::class,
'locate' => Functions\LocateFunction::class,
'abs' => Functions\AbsFunction::class,
@@ -144,10 +143,9 @@ class Parser
/**
* READ-ONLY: Maps BUILT-IN datetime function names to AST class names.
*
* @var array
* @psalm-var array<string, class-string<Functions\FunctionNode>>
*/
private static $_DATETIME_FUNCTIONS = [
private static $datetimeFunctions = [
'current_date' => Functions\CurrentDateFunction::class,
'current_time' => Functions\CurrentTimeFunction::class,
'current_timestamp' => Functions\CurrentTimestampFunction::class,
@@ -160,19 +158,19 @@ class Parser
* and still need to be validated.
*/
/** @var array */
/** @psalm-var list<array{token: mixed, expression: mixed, nestingLevel: int}> */
private $deferredIdentificationVariables = [];
/** @var array */
/** @psalm-var list<array{token: mixed, expression: mixed, nestingLevel: int}> */
private $deferredPartialObjectExpressions = [];
/** @var array */
/** @psalm-var list<array{token: mixed, expression: mixed, nestingLevel: int}> */
private $deferredPathExpressions = [];
/** @var array */
/** @psalm-var list<array{token: mixed, expression: mixed, nestingLevel: int}> */
private $deferredResultVariables = [];
/** @var array */
/** @psalm-var list<array{token: mixed, expression: mixed, nestingLevel: int}> */
private $deferredNewObjectExpressions = [];
/**
@@ -206,7 +204,7 @@ class Parser
/**
* Map of declared query components in the parsed query.
*
* @var array
* @psalm-var array<string, array<string, mixed>>
*/
private $queryComponents = [];
@@ -220,7 +218,7 @@ class Parser
/**
* Any additional custom tree walkers that modify the AST.
*
* @var array
* @psalm-var list<class-string<TreeWalker>>
*/
private $customTreeWalkers = [];
@@ -231,7 +229,7 @@ class Parser
*/
private $customOutputWalker;
/** @var array */
/** @psalm-var list<AST\SelectExpression> */
private $identVariableExpressions = [];
/**
@@ -263,9 +261,9 @@ class Parser
/**
* Adds a custom tree walker for modifying the AST.
*
* @param string $className
*
* @return void
*
* @psalm-param class-string $className
*/
public function addCustomTreeWalker($className)
{
@@ -412,11 +410,13 @@ class Parser
{
$AST = $this->getAST();
if (($customWalkers = $this->query->getHint(Query::HINT_CUSTOM_TREE_WALKERS)) !== false) {
$customWalkers = $this->query->getHint(Query::HINT_CUSTOM_TREE_WALKERS);
if ($customWalkers !== false) {
$this->customTreeWalkers = $customWalkers;
}
if (($customOutputWalker = $this->query->getHint(Query::HINT_CUSTOM_OUTPUT_WALKER)) !== false) {
$customOutputWalker = $this->query->getHint(Query::HINT_CUSTOM_OUTPUT_WALKER);
if ($customOutputWalker !== false) {
$this->customOutputWalker = $customOutputWalker;
}
@@ -490,12 +490,13 @@ class Parser
/**
* Generates a new syntax error.
*
* @param string $expected Expected string.
* @param array|null $token Got token.
* @param string $expected Expected string.
*
* @return void
*
* @throws QueryException
*
* @psalm-param array<string, mixed>|null $token Got token.
*/
public function syntaxError($expected = '', $token = null)
{
@@ -505,7 +506,7 @@ class Parser
$tokenPos = $token['position'] ?? '-1';
$message = "line 0, col {$tokenPos}: Error: ";
$message = sprintf('line 0, col %d: Error: ', $tokenPos);
$message .= $expected !== '' ? sprintf('Expected %s, got ', $expected) : 'Unexpected ';
$message .= $this->lexer->lookahead === null ? 'end of string.' : sprintf("'%s'", $token['value']);
@@ -515,12 +516,13 @@ class Parser
/**
* Generates a new semantical error.
*
* @param string $message Optional message.
* @param array|null $token Optional token.
* @param string $message Optional message.
*
* @return void
*
* @throws QueryException
*
* @psalm-param array<string, mixed>|null $token Optional token.
*/
public function semanticalError($message = '', $token = null)
{
@@ -552,9 +554,9 @@ class Parser
*
* @param bool $resetPeek Reset peek after finding the closing parenthesis.
*
* @return array
* @psalm-return array<string, mixed>| null
*/
private function peekBeyondClosingParenthesis($resetPeek = true)
private function peekBeyondClosingParenthesis(bool $resetPeek = true)
{
$token = $this->lexer->peek();
$numUnmatched = 1;
@@ -586,11 +588,9 @@ class Parser
/**
* Checks if the given token indicates a mathematical operator.
*
* @param array $token
*
* @return bool TRUE if the token is a mathematical operator, FALSE otherwise.
* @psalm-param array<string, mixed> $token
*/
private function isMathOperator($token)
private function isMathOperator($token): bool
{
return $token !== null && in_array($token['type'], [Lexer::T_PLUS, Lexer::T_MINUS, Lexer::T_DIVIDE, Lexer::T_MULTIPLY]);
}
@@ -600,7 +600,7 @@ class Parser
*
* @return bool TRUE if the next-next tokens start a function, FALSE otherwise.
*/
private function isFunction()
private function isFunction(): bool
{
$lookaheadType = $this->lexer->lookahead['type'];
$peek = $this->lexer->peek();
@@ -613,32 +613,34 @@ class Parser
/**
* Checks whether the given token type indicates an aggregate function.
*
* @param int $tokenType
*
* @return bool TRUE if the token type is an aggregate function, FALSE otherwise.
*
* @psalm-param Lexer::T_* $tokenType
*/
private function isAggregateFunction($tokenType)
private function isAggregateFunction(int $tokenType): bool
{
return in_array($tokenType, [Lexer::T_AVG, Lexer::T_MIN, Lexer::T_MAX, Lexer::T_SUM, Lexer::T_COUNT]);
return in_array(
$tokenType,
[Lexer::T_AVG, Lexer::T_MIN, Lexer::T_MAX, Lexer::T_SUM, Lexer::T_COUNT]
);
}
/**
* Checks whether the current lookahead token of the lexer has the type T_ALL, T_ANY or T_SOME.
*
* @return bool
*/
private function isNextAllAnySome()
private function isNextAllAnySome(): bool
{
return in_array($this->lexer->lookahead['type'], [Lexer::T_ALL, Lexer::T_ANY, Lexer::T_SOME]);
return in_array(
$this->lexer->lookahead['type'],
[Lexer::T_ALL, Lexer::T_ANY, Lexer::T_SOME]
);
}
/**
* Validates that the given <tt>IdentificationVariable</tt> is semantically correct.
* It must exist in query components list.
*
* @return void
*/
private function processDeferredIdentificationVariables()
private function processDeferredIdentificationVariables(): void
{
foreach ($this->deferredIdentificationVariables as $deferredItem) {
$identVariable = $deferredItem['expression'];
@@ -673,12 +675,8 @@ class Parser
/**
* Validates that the given <tt>NewObjectExpression</tt>.
*
* @param SelectStatement $AST
*
* @return void
*/
private function processDeferredNewObjectExpressions($AST)
private function processDeferredNewObjectExpressions(SelectStatement $AST): void
{
foreach ($this->deferredNewObjectExpressions as $deferredItem) {
$expression = $deferredItem['expression'];
@@ -721,10 +719,8 @@ class Parser
/**
* Validates that the given <tt>PartialObjectExpression</tt> is semantically correct.
* It must exist in query components list.
*
* @return void
*/
private function processDeferredPartialObjectExpressions()
private function processDeferredPartialObjectExpressions(): void
{
foreach ($this->deferredPartialObjectExpressions as $deferredItem) {
$expr = $deferredItem['expression'];
@@ -762,10 +758,8 @@ class Parser
/**
* Validates that the given <tt>ResultVariable</tt> is semantically correct.
* It must exist in query components list.
*
* @return void
*/
private function processDeferredResultVariables()
private function processDeferredResultVariables(): void
{
foreach ($this->deferredResultVariables as $deferredItem) {
$resultVariable = $deferredItem['expression'];
@@ -806,10 +800,8 @@ class Parser
* StateFieldPathExpression ::= IdentificationVariable "." StateField
* SingleValuedAssociationPathExpression ::= IdentificationVariable "." SingleValuedAssociationField
* CollectionValuedPathExpression ::= IdentificationVariable "." CollectionValuedAssociationField
*
* @return void
*/
private function processDeferredPathExpressions()
private function processDeferredPathExpressions(): void
{
foreach ($this->deferredPathExpressions as $deferredItem) {
$pathExpression = $deferredItem['expression'];
@@ -817,7 +809,8 @@ class Parser
$qComp = $this->queryComponents[$pathExpression->identificationVariable];
$class = $qComp['metadata'];
if (($field = $pathExpression->field) === null) {
$field = $pathExpression->field;
if ($field === null) {
$field = $pathExpression->field = $class->identifier[0];
}
@@ -875,10 +868,7 @@ class Parser
}
}
/**
* @return void
*/
private function processRootEntityAliasSelected()
private function processRootEntityAliasSelected(): void
{
if (! count($this->identVariableExpressions)) {
return;
@@ -1008,7 +998,10 @@ class Parser
$exists = isset($this->queryComponents[$aliasIdentVariable]);
if ($exists) {
$this->semanticalError("'$aliasIdentVariable' is already defined.", $this->lexer->token);
$this->semanticalError(
sprintf("'%s' is already defined.", $aliasIdentVariable),
$this->lexer->token
);
}
return $aliasIdentVariable;
@@ -1050,7 +1043,10 @@ class Parser
private function validateAbstractSchemaName($schemaName)
{
if (! (class_exists($schemaName, true) || interface_exists($schemaName, true))) {
$this->semanticalError("Class '$schemaName' is not defined.", $this->lexer->token);
$this->semanticalError(
sprintf("Class '%s' is not defined.", $schemaName),
$this->lexer->token
);
}
}
@@ -1067,7 +1063,10 @@ class Parser
$exists = isset($this->queryComponents[$resultVariable]);
if ($exists) {
$this->semanticalError("'$resultVariable' is already defined.", $this->lexer->token);
$this->semanticalError(
sprintf("'%s' is already defined.", $resultVariable),
$this->lexer->token
);
}
return $resultVariable;
@@ -2573,6 +2572,8 @@ class Parser
* InExpression | NullComparisonExpression | ExistsExpression |
* EmptyCollectionComparisonExpression | CollectionMemberExpression |
* InstanceOfExpression
*
* @return Node
*/
public function SimpleConditionalExpression()
{
@@ -2868,7 +2869,8 @@ class Parser
{
$sign = null;
if (($isPlus = $this->lexer->isNextToken(Lexer::T_PLUS)) || $this->lexer->isNextToken(Lexer::T_MINUS)) {
$isPlus = $this->lexer->isNextToken(Lexer::T_PLUS);
if ($isPlus || $this->lexer->isNextToken(Lexer::T_MINUS)) {
$this->match($isPlus ? Lexer::T_PLUS : Lexer::T_MINUS);
$sign = $isPlus;
}
@@ -2889,6 +2891,8 @@ class Parser
* | FunctionsReturningNumerics | AggregateExpression | FunctionsReturningStrings
* | FunctionsReturningDatetime | IdentificationVariable | ResultVariable
* | InputParameter | CaseExpression
*
* @return Node|string
*/
public function ArithmeticPrimary()
{
@@ -2970,6 +2974,8 @@ class Parser
/**
* StringPrimary ::= StateFieldPathExpression | string | InputParameter | FunctionsReturningStrings | AggregateExpression | CaseExpression
*
* @return Node
*/
public function StringPrimary()
{
@@ -3449,13 +3455,13 @@ class Parser
case $customFunctionDeclaration !== null:
return $customFunctionDeclaration;
case isset(self::$_STRING_FUNCTIONS[$funcName]):
case isset(self::$stringFunctions[$funcName]):
return $this->FunctionsReturningStrings();
case isset(self::$_NUMERIC_FUNCTIONS[$funcName]):
case isset(self::$numericFunctions[$funcName]):
return $this->FunctionsReturningNumerics();
case isset(self::$_DATETIME_FUNCTIONS[$funcName]):
case isset(self::$datetimeFunctions[$funcName]):
return $this->FunctionsReturningDatetime();
default:
@@ -3508,7 +3514,7 @@ class Parser
public function FunctionsReturningNumerics()
{
$funcNameLower = strtolower($this->lexer->lookahead['value']);
$funcClass = self::$_NUMERIC_FUNCTIONS[$funcNameLower];
$funcClass = self::$numericFunctions[$funcNameLower];
$function = new $funcClass($funcNameLower);
$function->parse($this);
@@ -3547,7 +3553,7 @@ class Parser
public function FunctionsReturningDatetime()
{
$funcNameLower = strtolower($this->lexer->lookahead['value']);
$funcClass = self::$_DATETIME_FUNCTIONS[$funcNameLower];
$funcClass = self::$datetimeFunctions[$funcNameLower];
$function = new $funcClass($funcNameLower);
$function->parse($this);
@@ -3587,7 +3593,7 @@ class Parser
public function FunctionsReturningStrings()
{
$funcNameLower = strtolower($this->lexer->lookahead['value']);
$funcClass = self::$_STRING_FUNCTIONS[$funcNameLower];
$funcClass = self::$stringFunctions[$funcNameLower];
$function = new $funcClass($funcNameLower);
$function->parse($this);

View File

@@ -47,7 +47,7 @@ class ParserResult
/**
* The mappings of DQL parameter names/positions to SQL parameter positions.
*
* @var array
* @psalm-var array<string|int, list<int>>
*/
private $_parameterMappings = [];
@@ -119,7 +119,7 @@ class ParserResult
/**
* Gets all DQL to SQL parameter mappings.
*
* @return array The parameter mappings.
* @psalm-return array<int|string, list<int>> The parameter mappings.
*/
public function getParameterMappings()
{
@@ -131,7 +131,7 @@ class ParserResult
*
* @param string|int $dqlPosition The name or position of the DQL parameter.
*
* @return array The positions of the corresponding SQL parameters.
* @psalm-return list<int> The positions of the corresponding SQL parameters.
*/
public function getSqlParameterPositions($dqlPosition)
{

View File

@@ -161,13 +161,13 @@ class QueryException extends ORMException
*/
public static function invalidLiteral($literal)
{
return new self("Invalid literal '$literal'");
return new self("Invalid literal '" . $literal . "'");
}
/**
* @param array $assoc
*
* @return QueryException
*
* @psalm-param array<string, string> $assoc
*/
public static function iterateWithFetchJoinCollectionNotAllowed($assoc)
{
@@ -190,9 +190,9 @@ class QueryException extends ORMException
}
/**
* @param array $assoc
*
* @return QueryException
*
* @psalm-param array<string, string> $assoc
*/
public static function overwritingJoinConditionsNotYetSupported($assoc)
{
@@ -215,9 +215,9 @@ class QueryException extends ORMException
}
/**
* @param array $assoc
*
* @return QueryException
*
* @psalm-param array<string, string> $assoc
*/
public static function iterateWithFetchJoinNotAllowed($assoc)
{

View File

@@ -69,7 +69,7 @@ class QueryExpressionVisitor extends ExpressionVisitor
* Gets bound parameters.
* Filled after {@link dispach()}.
*
* @return Collection
* @return Collection<int, mixed>
*/
public function getParameters()
{

View File

@@ -57,7 +57,7 @@ class ResultSetMapping
* Maps alias names to class names.
*
* @ignore
* @var array
* @psalm-var array<string, class-string>
*/
public $aliasMap = [];
@@ -65,7 +65,7 @@ class ResultSetMapping
* Maps alias names to related association field names.
*
* @ignore
* @var array
* @psalm-var array<string, string>
*/
public $relationMap = [];
@@ -73,7 +73,7 @@ class ResultSetMapping
* Maps alias names to parent alias names.
*
* @ignore
* @var array
* @psalm-var array<string, string>
*/
public $parentAliasMap = [];
@@ -81,7 +81,7 @@ class ResultSetMapping
* Maps column names in the result set to field names for each class.
*
* @ignore
* @var array
* @psalm-var array<string, string>
*/
public $fieldMappings = [];
@@ -89,7 +89,7 @@ class ResultSetMapping
* Maps column names in the result set to the alias/field name to use in the mapped result.
*
* @ignore
* @var array
* @psalm-var array<string, string>
*/
public $scalarMappings = [];
@@ -97,7 +97,7 @@ class ResultSetMapping
* Maps column names in the result set to the alias/field type to use in the mapped result.
*
* @ignore
* @var array
* @psalm-var array<string, string>
*/
public $typeMappings = [];
@@ -105,7 +105,7 @@ class ResultSetMapping
* Maps entities in the result set to the alias name to use in the mapped result.
*
* @ignore
* @var array
* @psalm-var array<string, string|null>
*/
public $entityMappings = [];
@@ -113,7 +113,7 @@ class ResultSetMapping
* Maps column names of meta columns (foreign keys, discriminator columns, ...) to field names.
*
* @ignore
* @var array
* @psalm-var array<string, string>
*/
public $metaMappings = [];
@@ -121,7 +121,7 @@ class ResultSetMapping
* Maps column names in the result set to the alias they belong to.
*
* @ignore
* @var array
* @psalm-var array<string, string>
*/
public $columnOwnerMap = [];
@@ -129,7 +129,7 @@ class ResultSetMapping
* List of columns in the result set that are used as discriminator columns.
*
* @ignore
* @var array
* @psalm-var array<string, string>
*/
public $discriminatorColumns = [];
@@ -137,7 +137,7 @@ class ResultSetMapping
* Maps alias names to field names that should be used for indexing.
*
* @ignore
* @var array
* @psalm-var array<string, string>
*/
public $indexByMap = [];
@@ -145,35 +145,35 @@ class ResultSetMapping
* Map from column names to class names that declare the field the column is mapped to.
*
* @ignore
* @var array
* @psalm-var array<string, class-string>
*/
public $declaringClasses = [];
/**
* This is necessary to hydrate derivate foreign keys correctly.
*
* @var array
* @psalm-var array<string, array<string, bool>>
*/
public $isIdentifierColumn = [];
/**
* Maps column names in the result set to field names for each new object expression.
*
* @var array
* @psalm-var array<string, array<string, mixed>>
*/
public $newObjectMappings = [];
/**
* Maps metadata parameter names to the metadata attribute.
*
* @var array
* @psalm-var array<int|string, string>
*/
public $metadataParameterMapping = [];
/**
* Contains query parameter names to be resolved as discriminator values
*
* @var array
* @psalm-var array<string, string>
*/
public $discriminatorParameters = [];
@@ -528,7 +528,7 @@ class ResultSetMapping
}
/**
* @return array
* @psalm-return array<string, class-string>
*/
public function getAliasMap()
{

View File

@@ -84,12 +84,13 @@ class ResultSetMappingBuilder extends ResultSetMapping
/**
* Adds a root entity and all of its fields to the result set.
*
* @param string $class The class name of the root entity.
* @param string $alias The unique alias to use for the root entity.
* @param array $renamedColumns Columns that have been renamed (tableColumnName => queryColumnName).
* @param int|null $renameMode One of the COLUMN_RENAMING_* constants or array for BC reasons (CUSTOM).
* @param string $class The class name of the root entity.
* @param string $alias The unique alias to use for the root entity.
* @param int|null $renameMode One of the COLUMN_RENAMING_* constants or array for BC reasons (CUSTOM).
*
* @return void
*
* @psalm-param array<string, string> $renamedColumns Columns that have been renamed (tableColumnName => queryColumnName).
*/
public function addRootEntityFromClassMetadata($class, $alias, $renamedColumns = [], $renameMode = null)
{
@@ -103,15 +104,16 @@ class ResultSetMappingBuilder extends ResultSetMapping
/**
* Adds a joined entity and all of its fields to the result set.
*
* @param string $class The class name of the joined entity.
* @param string $alias The unique alias to use for the joined entity.
* @param string $parentAlias The alias of the entity result that is the parent of this joined result.
* @param string $relation The association field that connects the parent entity result
* with the joined entity result.
* @param array $renamedColumns Columns that have been renamed (tableColumnName => queryColumnName).
* @param int|null $renameMode One of the COLUMN_RENAMING_* constants or array for BC reasons (CUSTOM).
* @param string $class The class name of the joined entity.
* @param string $alias The unique alias to use for the joined entity.
* @param string $parentAlias The alias of the entity result that is the parent of this joined result.
* @param string $relation The association field that connects the parent entity result
* with the joined entity result.
* @param int|null $renameMode One of the COLUMN_RENAMING_* constants or array for BC reasons (CUSTOM).
*
* @return void
*
* @psalm-param array<string, string> $renamedColumns Columns that have been renamed (tableColumnName => queryColumnName).
*/
public function addJoinedEntityFromClassMetadata($class, $alias, $parentAlias, $relation, $renamedColumns = [], $renameMode = null)
{
@@ -127,11 +129,12 @@ class ResultSetMappingBuilder extends ResultSetMapping
*
* @param string $class
* @param string $alias
* @param array $columnAliasMap
*
* @return void
*
* @throws InvalidArgumentException
*
* @psalm-param array<string, string> $columnAliasMap
*/
protected function addAllClassFields($class, $alias, $columnAliasMap = [])
{
@@ -179,7 +182,7 @@ class ResultSetMappingBuilder extends ResultSetMapping
}
}
private function isInheritanceSupported(ClassMetadataInfo $classMetadata)
private function isInheritanceSupported(ClassMetadataInfo $classMetadata): bool
{
if (
$classMetadata->isInheritanceTypeSingleTable()
@@ -196,9 +199,10 @@ class ResultSetMappingBuilder extends ResultSetMapping
*
* @param string $columnName
* @param int $mode
* @param array $customRenameColumns
*
* @return string
*
* @psalm-param array<string, string> $customRenameColumns
*/
private function getColumnAlias($columnName, $mode, array $customRenameColumns)
{
@@ -221,10 +225,10 @@ class ResultSetMappingBuilder extends ResultSetMapping
*
* @param string $className
* @param int $mode
* @param array $customRenameColumns
*
* @return string[]
*
* @psalm-param array<string, string> $customRenameColumns
* @psalm-return array<array-key, string>
*/
private function getColumnAliasMap($className, $mode, array $customRenameColumns)
@@ -426,9 +430,9 @@ class ResultSetMappingBuilder extends ResultSetMapping
* Works only for all the entity results. The select parts for scalar
* expressions have to be written manually.
*
* @param array $tableAliases
*
* @return string
*
* @psalm-param array<string, string> $tableAliases
*/
public function generateSelectClause($tableAliases = [])
{

View File

@@ -122,43 +122,49 @@ class SqlWalker implements TreeWalker
/**
* Map from result variable names to their SQL column alias names.
*
* @var array
* @psalm-var array<string, string|list<string>>
*/
private $scalarResultAliasMap = [];
/**
* Map from Table-Alias + Column-Name to OrderBy-Direction.
*
* @var array
* @var array<string, string>
*/
private $orderedColumnsMap = [];
/**
* Map from DQL-Alias + Field-Name to SQL Column Alias.
*
* @var array
* @var array<string, array<string, string>>
*/
private $scalarFields = [];
/**
* Map of all components/classes that appear in the DQL query.
*
* @var array
* @psalm-var array<string, array{metadata: ClassMetadata, token: array, relation: mixed[], parent: string}>
* @psalm-var array<string, array{
* metadata: ClassMetadata,
* parent: string,
* relation: mixed[],
* map: mixed,
* nestingLevel: int,
* token: array
* }>
*/
private $queryComponents;
/**
* A list of classes that appear in non-scalar SelectExpressions.
*
* @var array
* @psalm-var list<array{class: ClassMetadata, dqlAlias: string, resultAlias: string}>
*/
private $selectedClasses = [];
/**
* The DQL alias of the root class of the currently traversed query.
*
* @var array
* @psalm-var list<string>
*/
private $rootAliases = [];
@@ -234,9 +240,14 @@ class SqlWalker implements TreeWalker
*
* @param string $dqlAlias The DQL alias.
*
* @return array
*
* @psalm-return array{metadata: ClassMetadata}
* @psalm-return array{
* metadata: ClassMetadata,
* parent: string,
* relation: mixed[],
* map: mixed,
* nestingLevel: int,
* token: array
* }
*/
public function getQueryComponent($dqlAlias)
{
@@ -350,8 +361,10 @@ class SqlWalker implements TreeWalker
*
* @return string The SQL.
*/
private function _generateClassTableInheritanceJoins($class, $dqlAlias)
{
private function generateClassTableInheritanceJoins(
ClassMetadata $class,
string $dqlAlias
): string {
$sql = '';
$baseTableAlias = $this->getSQLTableAlias($class->getTableName(), $dqlAlias);
@@ -372,11 +385,9 @@ class SqlWalker implements TreeWalker
}
// Add filters on the root class
if ($filterSql = $this->generateFilterConditionSQL($parentClass, $tableAlias)) {
$sqlParts[] = $filterSql;
}
$sqlParts[] = $this->generateFilterConditionSQL($parentClass, $tableAlias);
$sql .= implode(' AND ', $sqlParts);
$sql .= implode(' AND ', array_filter($sqlParts));
}
// Ignore subclassing inclusion if partial objects is disallowed
@@ -403,10 +414,7 @@ class SqlWalker implements TreeWalker
return $sql;
}
/**
* @return string
*/
private function _generateOrderedCollectionOrderByItems()
private function generateOrderedCollectionOrderByItems(): string
{
$orderedColumns = [];
@@ -444,11 +452,9 @@ class SqlWalker implements TreeWalker
/**
* Generates a discriminator column SQL condition for the class with the given DQL alias.
*
* @param array $dqlAliases List of root DQL aliases to inspect for discriminator restrictions.
*
* @return string
* @psalm-param list<string> $dqlAliases List of root DQL aliases to inspect for discriminator restrictions.
*/
private function _generateDiscriminatorColumnConditionSQL(array $dqlAliases)
private function generateDiscriminatorColumnConditionSQL(array $dqlAliases): string
{
$sqlParts = [];
@@ -490,8 +496,10 @@ class SqlWalker implements TreeWalker
*
* @return string The SQL query part to add to a query.
*/
private function generateFilterConditionSQL(ClassMetadata $targetEntity, $targetTableAlias)
{
private function generateFilterConditionSQL(
ClassMetadata $targetEntity,
string $targetTableAlias
): string {
if (! $this->em->hasFilters()) {
return '';
}
@@ -519,7 +527,8 @@ class SqlWalker implements TreeWalker
$filterClauses = [];
foreach ($this->em->getFilters()->getEnabledFilters() as $filter) {
if ('' !== $filterExpr = $filter->addFilterConstraint($targetEntity, $targetTableAlias)) {
$filterExpr = $filter->addFilterConstraint($targetEntity, $targetTableAlias);
if ($filterExpr !== '') {
$filterClauses[] = '(' . $filterExpr . ')';
}
}
@@ -551,7 +560,7 @@ class SqlWalker implements TreeWalker
$sql .= $this->walkOrderByClause($AST->orderByClause);
}
$orderBySql = $this->_generateOrderedCollectionOrderByItems();
$orderBySql = $this->generateOrderedCollectionOrderByItems();
if (! $AST->orderByClause && $orderBySql) {
$sql .= ' ORDER BY ' . $orderBySql;
}
@@ -659,7 +668,6 @@ class SqlWalker implements TreeWalker
{
$sql = '';
/** @var Query\AST\PathExpression $pathExpr */
switch ($pathExpr->type) {
case AST\PathExpression::TYPE_STATE_FIELD:
$fieldName = $pathExpr->field;
@@ -920,7 +928,7 @@ class SqlWalker implements TreeWalker
return $sql;
}
$classTableInheritanceJoins = $this->_generateClassTableInheritanceJoins($class, $dqlAlias);
$classTableInheritanceJoins = $this->generateClassTableInheritanceJoins($class, $dqlAlias);
if (! $buildNestedJoins) {
return $sql . $classTableInheritanceJoins;
@@ -988,7 +996,7 @@ class SqlWalker implements TreeWalker
}
// Apply remaining inheritance restrictions
$discrSql = $this->_generateDiscriminatorColumnConditionSQL([$joinedDqlAlias]);
$discrSql = $this->generateDiscriminatorColumnConditionSQL([$joinedDqlAlias]);
if ($discrSql) {
$conditions[] = $discrSql;
@@ -1043,7 +1051,7 @@ class SqlWalker implements TreeWalker
}
// Apply remaining inheritance restrictions
$discrSql = $this->_generateDiscriminatorColumnConditionSQL([$joinedDqlAlias]);
$discrSql = $this->generateDiscriminatorColumnConditionSQL([$joinedDqlAlias]);
if ($discrSql) {
$conditions[] = $discrSql;
@@ -1070,7 +1078,7 @@ class SqlWalker implements TreeWalker
$withCondition = $condExpr === null ? '' : ('(' . $this->walkConditionalExpression($condExpr) . ')');
if ($targetClass->isInheritanceTypeJoined()) {
$ctiJoins = $this->_generateClassTableInheritanceJoins($targetClass, $joinedDqlAlias);
$ctiJoins = $this->generateClassTableInheritanceJoins($targetClass, $joinedDqlAlias);
// If we have WITH condition, we need to build nested joins for target class table and cti joins
if ($withCondition) {
$sql .= '(' . $targetTableJoin['table'] . $ctiJoins . ') ON ' . $targetTableJoin['condition'];
@@ -1111,7 +1119,8 @@ class SqlWalker implements TreeWalker
{
$orderByItems = array_map([$this, 'walkOrderByItem'], $orderByClause->orderByItems);
if (($collectionOrderByItems = $this->_generateOrderedCollectionOrderByItems()) !== '') {
$collectionOrderByItems = $this->generateOrderedCollectionOrderByItems();
if ($collectionOrderByItems !== '') {
$orderByItems = array_merge($orderByItems, (array) $collectionOrderByItems);
}
@@ -1177,7 +1186,7 @@ class SqlWalker implements TreeWalker
$sql .= $this->generateRangeVariableDeclarationSQL($joinDeclaration, ! $isUnconditionalJoin);
// Apply remaining inheritance restrictions
$discrSql = $this->_generateDiscriminatorColumnConditionSQL([$dqlAlias]);
$discrSql = $this->generateDiscriminatorColumnConditionSQL([$dqlAlias]);
if ($discrSql) {
$conditions[] = $discrSql;
@@ -1803,7 +1812,7 @@ class SqlWalker implements TreeWalker
public function walkWhereClause($whereClause)
{
$condSql = $whereClause !== null ? $this->walkConditionalExpression($whereClause->conditionalExpression) : '';
$discrSql = $this->_generateDiscriminatorColumnConditionSQL($this->rootAliases);
$discrSql = $this->generateDiscriminatorColumnConditionSQL($this->rootAliases);
if ($this->em->hasFilters()) {
$filterClauses = [];
@@ -1811,7 +1820,8 @@ class SqlWalker implements TreeWalker
$class = $this->queryComponents[$dqlAlias]['metadata'];
$tableAlias = $this->getSQLTableAlias($class->table['name'], $dqlAlias);
if ($filterExpr = $this->generateFilterConditionSQL($class, $tableAlias)) {
$filterExpr = $this->generateFilterConditionSQL($class, $tableAlias);
if ($filterExpr) {
$filterClauses[] = $filterExpr;
}
}
@@ -2205,8 +2215,11 @@ class SqlWalker implements TreeWalker
$parameter = $this->query->getParameter($inputParam->name);
if ($parameter && Type::hasType($type = $parameter->getType())) {
return Type::getType($type)->convertToDatabaseValueSQL('?', $this->platform);
if ($parameter) {
$type = $parameter->getType();
if (Type::hasType($type)) {
return Type::getType($type)->convertToDatabaseValueSQL('?', $this->platform);
}
}
return '?';

View File

@@ -21,6 +21,7 @@
namespace Doctrine\ORM\Query;
use Doctrine\ORM\AbstractQuery;
use Doctrine\ORM\Mapping\ClassMetadata;
/**
* Interface for walkers of DQL ASTs (abstract syntax trees).
@@ -41,7 +42,14 @@ interface TreeWalker
*
* @return array<string, array<string, mixed>>
*
* @psalm-var array<string, array{metadata: ClassMetadata, token: array, relation: mixed[], parent: string}>
* @psalm-return array<string, array{
* metadata: ClassMetadata,
* parent: string,
* relation: mixed[],
* map: mixed,
* nestingLevel: int,
* token: array
* }>
*/
public function getQueryComponents();

View File

@@ -21,13 +21,14 @@
namespace Doctrine\ORM\Query;
use Doctrine\ORM\AbstractQuery;
use Doctrine\ORM\Mapping\ClassMetadata;
use function array_diff;
use function array_keys;
/**
* An adapter implementation of the TreeWalker interface. The methods in this class
* are empty. This class exists as convenience for creating tree walkers.
* are empty. This class exists as convenience for creating tree walkers.
*/
abstract class TreeWalkerAdapter implements TreeWalker
{
@@ -48,7 +49,14 @@ abstract class TreeWalkerAdapter implements TreeWalker
/**
* The query components of the original query (the "symbol table") that was produced by the Parser.
*
* @var array
* @psalm-var array<string, array{
* metadata: ClassMetadata,
* parent: string,
* relation: mixed[],
* map: mixed,
* nestingLevel: int,
* token: array
* }>
*/
private $_queryComponents;
@@ -85,7 +93,7 @@ abstract class TreeWalkerAdapter implements TreeWalker
}
/**
* @return array
* {@inheritDoc}
*/
protected function _getQueryComponents()
{

View File

@@ -20,7 +20,7 @@
namespace Doctrine\ORM\Query;
use Doctrine\ORM\AbstractQuery;
use Doctrine\ORM\Mapping\ClassMetadata;
use function array_diff;
use function array_keys;
@@ -40,31 +40,25 @@ class TreeWalkerChain implements TreeWalker
*/
private $_walkers;
/**
* The original Query.
*
* @var AbstractQuery
*/
private $_query;
/**
* The ParserResult of the original query that was produced by the Parser.
*
* @var ParserResult
*/
private $_parserResult;
/**
* The query components of the original query (the "symbol table") that was produced by the Parser.
*
* @var array
* @var array<string, array<string, mixed>>
* @psalm-var array<string, array{
* metadata: ClassMetadata,
* parent: string,
* relation: mixed[],
* map: mixed,
* nestingLevel: int,
* token: array
* }>
*/
private $_queryComponents;
/**
* Returns the internal queryComponents array.
*
* @return array
* {@inheritDoc}
*/
public function getQueryComponents()
{
@@ -92,8 +86,6 @@ class TreeWalkerChain implements TreeWalker
*/
public function __construct($query, $parserResult, array $queryComponents)
{
$this->_query = $query;
$this->_parserResult = $parserResult;
$this->_queryComponents = $queryComponents;
$this->_walkers = new TreeWalkerChainIterator($this, $query, $parserResult);
}

View File

@@ -71,7 +71,7 @@ class QueryBuilder
/**
* The array of DQL parts collected.
*
* @var array
* @psalm-var array<string, mixed>
*/
private $_dqlParts = [
'distinct' => false,
@@ -130,7 +130,7 @@ class QueryBuilder
/**
* Keeps root entity alias names for join entities.
*
* @var array
* @psalm-var array<string, string>
*/
private $joinRootAliases = [];
@@ -327,16 +327,16 @@ class QueryBuilder
switch ($this->_type) {
case self::DELETE:
$dql = $this->_getDQLForDelete();
$dql = $this->getDQLForDelete();
break;
case self::UPDATE:
$dql = $this->_getDQLForUpdate();
$dql = $this->getDQLForUpdate();
break;
case self::SELECT:
default:
$dql = $this->_getDQLForSelect();
$dql = $this->getDQLForSelect();
break;
}
@@ -693,11 +693,12 @@ class QueryBuilder
* The available parts are: 'select', 'from', 'join', 'set', 'where',
* 'groupBy', 'having' and 'orderBy'.
*
* @param string $dqlPartName The DQL part name.
* @param object|array $dqlPart An Expr object.
* @param bool $append Whether to append (true) or replace (false).
* @param string $dqlPartName The DQL part name.
* @param bool $append Whether to append (true) or replace (false).
*
* @return self
*
* @psalm-param string|object|list<string>|array{join: array<int|string, object>} $dqlPart An Expr object.
*/
public function add($dqlPartName, $dqlPart, $append = false)
{
@@ -1325,7 +1326,8 @@ class QueryBuilder
$visitor = new QueryExpressionVisitor($this->getAllAliases());
if ($whereExpression = $criteria->getWhereExpression()) {
$whereExpression = $criteria->getWhereExpression();
if ($whereExpression) {
$this->andWhere($visitor->dispatch($whereExpression));
foreach ($visitor->getParameters() as $parameter) {
$this->parameters->add($parameter);
@@ -1351,11 +1353,13 @@ class QueryBuilder
}
// Overwrite limits only if they was set in criteria
if (($firstResult = $criteria->getFirstResult()) !== null) {
$firstResult = $criteria->getFirstResult();
if ($firstResult !== null) {
$this->setFirstResult($firstResult);
}
if (($maxResults = $criteria->getMaxResults()) !== null) {
$maxResults = $criteria->getMaxResults();
if ($maxResults !== null) {
$this->setMaxResults($maxResults);
}
@@ -1377,7 +1381,7 @@ class QueryBuilder
/**
* Gets all query parts.
*
* @return array $dqlParts
* @psalm-return array<string, mixed> $dqlParts
*/
public function getDQLParts()
{
@@ -1387,34 +1391,34 @@ class QueryBuilder
/**
* @return string
*/
private function _getDQLForDelete()
private function getDQLForDelete()
{
return 'DELETE'
. $this->_getReducedDQLQueryPart('from', ['pre' => ' ', 'separator' => ', '])
. $this->_getReducedDQLQueryPart('where', ['pre' => ' WHERE '])
. $this->_getReducedDQLQueryPart('orderBy', ['pre' => ' ORDER BY ', 'separator' => ', ']);
. $this->getReducedDQLQueryPart('from', ['pre' => ' ', 'separator' => ', '])
. $this->getReducedDQLQueryPart('where', ['pre' => ' WHERE '])
. $this->getReducedDQLQueryPart('orderBy', ['pre' => ' ORDER BY ', 'separator' => ', ']);
}
/**
* @return string
*/
private function _getDQLForUpdate()
private function getDQLForUpdate()
{
return 'UPDATE'
. $this->_getReducedDQLQueryPart('from', ['pre' => ' ', 'separator' => ', '])
. $this->_getReducedDQLQueryPart('set', ['pre' => ' SET ', 'separator' => ', '])
. $this->_getReducedDQLQueryPart('where', ['pre' => ' WHERE '])
. $this->_getReducedDQLQueryPart('orderBy', ['pre' => ' ORDER BY ', 'separator' => ', ']);
. $this->getReducedDQLQueryPart('from', ['pre' => ' ', 'separator' => ', '])
. $this->getReducedDQLQueryPart('set', ['pre' => ' SET ', 'separator' => ', '])
. $this->getReducedDQLQueryPart('where', ['pre' => ' WHERE '])
. $this->getReducedDQLQueryPart('orderBy', ['pre' => ' ORDER BY ', 'separator' => ', ']);
}
/**
* @return string
*/
private function _getDQLForSelect()
private function getDQLForSelect()
{
$dql = 'SELECT'
. ($this->_dqlParts['distinct'] === true ? ' DISTINCT' : '')
. $this->_getReducedDQLQueryPart('select', ['pre' => ' ', 'separator' => ', ']);
. $this->getReducedDQLQueryPart('select', ['pre' => ' ', 'separator' => ', ']);
$fromParts = $this->getDQLPart('from');
$joinParts = $this->getDQLPart('join');
@@ -1438,21 +1442,18 @@ class QueryBuilder
}
$dql .= implode(', ', $fromClauses)
. $this->_getReducedDQLQueryPart('where', ['pre' => ' WHERE '])
. $this->_getReducedDQLQueryPart('groupBy', ['pre' => ' GROUP BY ', 'separator' => ', '])
. $this->_getReducedDQLQueryPart('having', ['pre' => ' HAVING '])
. $this->_getReducedDQLQueryPart('orderBy', ['pre' => ' ORDER BY ', 'separator' => ', ']);
. $this->getReducedDQLQueryPart('where', ['pre' => ' WHERE '])
. $this->getReducedDQLQueryPart('groupBy', ['pre' => ' GROUP BY ', 'separator' => ', '])
. $this->getReducedDQLQueryPart('having', ['pre' => ' HAVING '])
. $this->getReducedDQLQueryPart('orderBy', ['pre' => ' ORDER BY ', 'separator' => ', ']);
return $dql;
}
/**
* @param string $queryPartName
* @param array $options
*
* @return string
* @psalm-param array<string, mixed> $options
*/
private function _getReducedDQLQueryPart($queryPartName, $options = [])
private function getReducedDQLQueryPart(string $queryPartName, array $options = []): string
{
$queryPart = $this->getDQLPart($queryPartName);
@@ -1468,9 +1469,9 @@ class QueryBuilder
/**
* Resets DQL parts.
*
* @param array|null $parts
*
* @return self
*
* @psalm-param list<string>|null $parts
*/
public function resetDQLParts($parts = null)
{

View File

@@ -110,7 +110,8 @@ EOT
$databaseDriver
);
if (($namespace = $input->getOption('namespace')) !== null) {
$namespace = $input->getOption('namespace');
if ($namespace !== null) {
$databaseDriver->setNamespace($namespace);
}
}
@@ -151,7 +152,8 @@ EOT
$entityGenerator->setNumSpaces((int) $input->getOption('num-spaces'));
if (($extend = $input->getOption('extend')) !== null) {
$extend = $input->getOption('extend');
if ($extend !== null) {
$entityGenerator->setClassToExtend($extend);
}
}

View File

@@ -130,7 +130,8 @@ EOT
$entityGenerator->setNumSpaces((int) $input->getOption('num-spaces'));
$entityGenerator->setBackupExisting(! $input->getOption('no-backup'));
if (($extend = $input->getOption('extend')) !== null) {
$extend = $input->getOption('extend');
if ($extend !== null) {
$entityGenerator->setClassToExtend($extend);
}

View File

@@ -72,7 +72,8 @@ class GenerateProxiesCommand extends Command
$metadatas = MetadataFilter::filter($metadatas, $input->getOption('filter'));
// Process destination directory
if (($destPath = $input->getArgument('dest-path')) === null) {
$destPath = $input->getArgument('dest-path');
if ($destPath === null) {
$destPath = $em->getConfiguration()->getProxyDir();
}

View File

@@ -268,10 +268,9 @@ EOT
/**
* Format the association mappings
*
* @param array $propertyMappings
*
* @return string[][]
*
* @psalm-param array<string, array<string, mixed>> $propertyMappings
* @psalm-return list<array{0: string, 1: string}>
*/
private function formatMappings(array $propertyMappings): array
@@ -292,10 +291,9 @@ EOT
/**
* Format the entity listeners
*
* @param array $entityListeners
*
* @return string[]
*
* @psalm-param list<object> $entityListeners
* @psalm-return array{0: string, 1: string}
*/
private function formatEntityListeners(array $entityListeners): array

View File

@@ -35,6 +35,7 @@ use function assert;
use function constant;
use function defined;
use function is_numeric;
use function sprintf;
use function str_replace;
use function strtoupper;
@@ -71,7 +72,8 @@ class RunDqlCommand extends Command
$em = $this->getHelper('em')->getEntityManager();
assert($em instanceof EntityManagerInterface);
if (($dql = $input->getArgument('dql')) === null) {
$dql = $input->getArgument('dql');
if ($dql === null) {
throw new RuntimeException("Argument 'dql' is required in order to execute this command correctly.");
}
@@ -85,14 +87,16 @@ class RunDqlCommand extends Command
$hydrationMode = 'Doctrine\ORM\Query::HYDRATE_' . strtoupper(str_replace('-', '_', $hydrationModeName));
if (! defined($hydrationMode)) {
throw new RuntimeException(
"Hydration mode '$hydrationModeName' does not exist. It should be either: object. array, scalar or single-scalar."
);
throw new RuntimeException(sprintf(
"Hydration mode '%s' does not exist. It should be either: object. array, scalar or single-scalar.",
$hydrationModeName
));
}
$query = $em->createQuery($dql);
if (($firstResult = $input->getOption('first-result')) !== null) {
$firstResult = $input->getOption('first-result');
if ($firstResult !== null) {
if (! is_numeric($firstResult)) {
throw new LogicException("Option 'first-result' must contain an integer value");
}
@@ -100,7 +104,8 @@ class RunDqlCommand extends Command
$query->setFirstResult((int) $firstResult);
}
if (($maxResult = $input->getOption('max-result')) !== null) {
$maxResult = $input->getOption('max-result');
if ($maxResult !== null) {
if (! is_numeric($maxResult)) {
throw new LogicException("Option 'max-result' must contain an integer value");
}

View File

@@ -20,7 +20,7 @@
namespace Doctrine\ORM\Tools\Console\Command\SchemaTool;
use Doctrine\ORM\EntityManager;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\Tools\SchemaTool;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
@@ -53,7 +53,7 @@ abstract class AbstractCommand extends Command
$emHelper = $this->getHelper('em');
$em = $emHelper->getEntityManager();
assert($em instanceof EntityManager);
assert($em instanceof EntityManagerInterface);
$metadatas = $em->getMetadataFactory()->getAllMetadata();

View File

@@ -63,22 +63,25 @@ class ValidateSchemaCommand extends Command
if ($input->getOption('skip-mapping')) {
$ui->text('<comment>[SKIPPED] The mapping was not checked.</comment>');
} elseif ($errors = $validator->validateMapping()) {
foreach ($errors as $className => $errorMessages) {
$ui->text(
sprintf(
'<error>[FAIL]</error> The entity-class <comment>%s</comment> mapping is invalid:',
$className
)
);
$ui->listing($errorMessages);
$ui->newLine();
}
++$exit;
} else {
$ui->success('The mapping files are correct.');
$errors = $validator->validateMapping();
if ($errors) {
foreach ($errors as $className => $errorMessages) {
$ui->text(
sprintf(
'<error>[FAIL]</error> The entity-class <comment>%s</comment> mapping is invalid:',
$className
)
);
$ui->listing($errorMessages);
$ui->newLine();
}
++$exit;
} else {
$ui->success('The mapping files are correct.');
}
}
$ui->section('Database');

View File

@@ -79,7 +79,7 @@ class MetadataFilter extends FilterIterator implements Countable
$metadata = $it->current();
foreach ($this->filter as $filter) {
$pregResult = preg_match("/$filter/", $metadata->name);
$pregResult = preg_match('/' . $filter . '/', $metadata->name);
if ($pregResult === false) {
throw new RuntimeException(

View File

@@ -59,7 +59,7 @@ class ConvertDoctrine1Schema
* Constructor passes the directory or array of directories
* to convert the Doctrine 1 schema files from.
*
* @param array $from
* @psalm-param list<string>|string $from
*/
public function __construct($from)
{
@@ -97,12 +97,9 @@ class ConvertDoctrine1Schema
}
/**
* @param string $className
* @param array $mappingInformation
*
* @return ClassMetadataInfo
* @param mixed[] $mappingInformation
*/
private function convertToClassMetadataInfo($className, $mappingInformation)
private function convertToClassMetadataInfo(string $className, $mappingInformation): ClassMetadataInfo
{
$metadata = new ClassMetadataInfo($className);
@@ -115,12 +112,9 @@ class ConvertDoctrine1Schema
}
/**
* @param string $className
* @param mixed[] $model
*
* @return void
*/
private function convertTableName($className, array $model, ClassMetadataInfo $metadata)
private function convertTableName(string $className, array $model, ClassMetadataInfo $metadata): void
{
if (isset($model['tableName']) && $model['tableName']) {
$e = explode('.', $model['tableName']);

View File

@@ -139,6 +139,8 @@ class EntityGenerator
/**
* Number of spaces to use for indention in generated code.
*
* @var int
*/
protected $numSpaces = 4;
@@ -204,7 +206,7 @@ class EntityGenerator
/**
* Hash-map for handle types.
*
* @var array
* @psalm-var array<Type::*, string>
*/
protected $typeAlias = [
Type::DATETIMETZ => '\DateTime',
@@ -227,7 +229,7 @@ class EntityGenerator
/**
* Hash-map to handle generator types string.
*
* @var array
* @psalm-var array<ClassMetadataInfo::GENERATOR_TYPE_*, string>
*/
protected static $generatorStrategyMap = [
ClassMetadataInfo::GENERATOR_TYPE_AUTO => 'AUTO',
@@ -242,7 +244,7 @@ class EntityGenerator
/**
* Hash-map to handle the change tracking policy string.
*
* @var array
* @psalm-var array<ClassMetadataInfo::CHANGETRACKING_*, string>
*/
protected static $changeTrackingPolicyMap = [
ClassMetadataInfo::CHANGETRACKING_DEFERRED_IMPLICIT => 'DEFERRED_IMPLICIT',
@@ -253,7 +255,7 @@ class EntityGenerator
/**
* Hash-map to handle the inheritance type string.
*
* @var array
* @psalm-var array<ClassMetadataInfo::INHERITANCE_TYPE_*, string>
*/
protected static $inheritanceTypeMap = [
ClassMetadataInfo::INHERITANCE_TYPE_NONE => 'NONE',
@@ -381,10 +383,11 @@ public function __construct(<params>)
/**
* Generates and writes entity classes for the given array of ClassMetadataInfo instances.
*
* @param array $metadatas
* @param string $outputDirectory
*
* @return void
*
* @psalm-param list<ClassMetadataInfo> $metadatas
*/
public function generate(array $metadatas, $outputDirectory)
{
@@ -1040,7 +1043,8 @@ public function __construct(<params>)
];
foreach ($methods as $method) {
if ($code = $this->$method($metadata)) {
$code = $this->$method($metadata);
if ($code) {
$lines[] = ' * ' . $code;
}
}
@@ -1111,9 +1115,10 @@ public function __construct(<params>)
/**
* @param string $constraintName
* @param array $constraints
*
* @return string
*
* @psalm-param array<string, array<string, mixed>> $constraints
*/
protected function generateTableConstraints($constraintName, array $constraints)
{
@@ -1194,14 +1199,23 @@ public function __construct(<params>)
if (
(! $metadata->isEmbeddedClass || ! $this->embeddablesImmutable)
&& (! isset($fieldMapping['id']) || ! $fieldMapping['id'] || $metadata->generatorType === ClassMetadataInfo::GENERATOR_TYPE_NONE)
&& $code = $this->generateEntityStubMethod($metadata, 'set', $fieldMapping['fieldName'], $fieldMapping['type'], $nullableField)
) {
$methods[] = $code;
$methods[] = $this->generateEntityStubMethod(
$metadata,
'set',
$fieldMapping['fieldName'],
$fieldMapping['type'],
$nullableField
);
}
if ($code = $this->generateEntityStubMethod($metadata, 'get', $fieldMapping['fieldName'], $fieldMapping['type'], $nullableField)) {
$methods[] = $code;
}
$methods[] = $this->generateEntityStubMethod(
$metadata,
'get',
$fieldMapping['fieldName'],
$fieldMapping['type'],
$nullableField
);
}
foreach ($metadata->embeddedClasses as $fieldName => $embeddedClass) {
@@ -1210,48 +1224,71 @@ public function __construct(<params>)
}
if (! $metadata->isEmbeddedClass || ! $this->embeddablesImmutable) {
if ($code = $this->generateEntityStubMethod($metadata, 'set', $fieldName, $embeddedClass['class'])) {
$methods[] = $code;
}
$methods[] = $this->generateEntityStubMethod(
$metadata,
'set',
$fieldName,
$embeddedClass['class']
);
}
if ($code = $this->generateEntityStubMethod($metadata, 'get', $fieldName, $embeddedClass['class'])) {
$methods[] = $code;
}
$methods[] = $this->generateEntityStubMethod(
$metadata,
'get',
$fieldName,
$embeddedClass['class']
);
}
foreach ($metadata->associationMappings as $associationMapping) {
if ($associationMapping['type'] & ClassMetadataInfo::TO_ONE) {
$nullable = $this->isAssociationIsNullable($associationMapping) ? 'null' : null;
if ($code = $this->generateEntityStubMethod($metadata, 'set', $associationMapping['fieldName'], $associationMapping['targetEntity'], $nullable)) {
$methods[] = $code;
}
$nullable = $this->isAssociationIsNullable($associationMapping) ? 'null' : null;
$methods[] = $this->generateEntityStubMethod(
$metadata,
'set',
$associationMapping['fieldName'],
$associationMapping['targetEntity'],
$nullable
);
if ($code = $this->generateEntityStubMethod($metadata, 'get', $associationMapping['fieldName'], $associationMapping['targetEntity'], $nullable)) {
$methods[] = $code;
}
$methods[] = $this->generateEntityStubMethod(
$metadata,
'get',
$associationMapping['fieldName'],
$associationMapping['targetEntity'],
$nullable
);
} elseif ($associationMapping['type'] & ClassMetadataInfo::TO_MANY) {
if ($code = $this->generateEntityStubMethod($metadata, 'add', $associationMapping['fieldName'], $associationMapping['targetEntity'])) {
$methods[] = $code;
}
$methods[] = $this->generateEntityStubMethod(
$metadata,
'add',
$associationMapping['fieldName'],
$associationMapping['targetEntity']
);
if ($code = $this->generateEntityStubMethod($metadata, 'remove', $associationMapping['fieldName'], $associationMapping['targetEntity'])) {
$methods[] = $code;
}
$methods[] = $this->generateEntityStubMethod(
$metadata,
'remove',
$associationMapping['fieldName'],
$associationMapping['targetEntity']
);
if ($code = $this->generateEntityStubMethod($metadata, 'get', $associationMapping['fieldName'], Collection::class)) {
$methods[] = $code;
}
$methods[] = $this->generateEntityStubMethod(
$metadata,
'get',
$associationMapping['fieldName'],
Collection::class
);
}
}
return implode("\n\n", $methods);
return implode("\n\n", array_filter($methods));
}
/**
* @param array $associationMapping
*
* @return bool
*
* @psalm-param array<string, mixed> $associationMapping
*/
protected function isAssociationIsNullable(array $associationMapping)
{
@@ -1453,9 +1490,9 @@ public function __construct(<params>)
}
/**
* @param array $joinColumn
*
* @return string
*
* @psalm-param array<string, mixed> $joinColumn
*/
protected function generateJoinColumnAnnotation(array $joinColumn)
{
@@ -1510,7 +1547,8 @@ public function __construct(<params>)
if (isset($associationMapping['id']) && $associationMapping['id']) {
$lines[] = $this->spaces . ' * @' . $this->annotationsPrefix . 'Id';
if ($generatorType = $this->getIdGeneratorTypeString($metadata->generatorType)) {
$generatorType = $this->getIdGeneratorTypeString($metadata->generatorType);
if ($generatorType) {
$lines[] = $this->spaces . ' * @' . $this->annotationsPrefix . 'GeneratedValue(strategy="' . $generatorType . '")';
}
}
@@ -1596,7 +1634,8 @@ public function __construct(<params>)
$joinColumnsLines = [];
foreach ($associationMapping['joinColumns'] as $joinColumn) {
if ($joinColumnAnnot = $this->generateJoinColumnAnnotation($joinColumn)) {
$joinColumnAnnot = $this->generateJoinColumnAnnotation($joinColumn);
if ($joinColumnAnnot) {
$joinColumnsLines[] = $this->spaces . ' * ' . $joinColumnAnnot;
}
}
@@ -1738,7 +1777,8 @@ public function __construct(<params>)
if (isset($fieldMapping['id']) && $fieldMapping['id']) {
$lines[] = $this->spaces . ' * @' . $this->annotationsPrefix . 'Id';
if ($generatorType = $this->getIdGeneratorTypeString($metadata->generatorType)) {
$generatorType = $this->getIdGeneratorTypeString($metadata->generatorType);
if ($generatorType) {
$lines[] = $this->spaces . ' * @' . $this->annotationsPrefix . 'GeneratedValue(strategy="' . $generatorType . '")';
}
@@ -1772,9 +1812,9 @@ public function __construct(<params>)
}
/**
* @param array $embeddedClass
*
* @return string
*
* @psalm-param array<string, mixed> $embeddedClass
*/
protected function generateEmbeddedPropertyDocBlock(array $embeddedClass)
{
@@ -1893,11 +1933,9 @@ public function __construct(<params>)
}
/**
* @param array $fieldMapping
*
* @return string|null
* @psalm-param array<string, mixed> $fieldMapping
*/
private function nullableFieldExpression(array $fieldMapping)
private function nullableFieldExpression(array $fieldMapping): ?string
{
if (isset($fieldMapping['nullable']) && $fieldMapping['nullable'] === true) {
return 'null';
@@ -1909,11 +1947,9 @@ public function __construct(<params>)
/**
* Exports (nested) option elements.
*
* @param array $options
*
* @return string
* @psalm-param array<string, mixed> $options
*/
private function exportTableOptions(array $options)
private function exportTableOptions(array $options): string
{
$optionsStr = [];

View File

@@ -48,8 +48,10 @@ use const E_USER_DEPRECATED;
*/
class EntityRepositoryGenerator
{
/** @psalm-var class-string */
private $repositoryName;
/** @var string */
protected static $_template =
'<?php

View File

@@ -20,6 +20,7 @@
namespace Doctrine\ORM\Tools\Export\Driver;
use Doctrine\ORM\Mapping\ClassMetadata;
use Doctrine\ORM\Mapping\ClassMetadataInfo;
use Doctrine\ORM\Tools\Export\ExportException;
@@ -44,7 +45,7 @@ use const E_USER_DEPRECATED;
*/
abstract class AbstractExporter
{
/** @var mixed[] */
/** @var ClassMetadata[] */
protected $_metadata = [];
/** @var string|null */
@@ -85,11 +86,11 @@ abstract class AbstractExporter
abstract public function exportClassMetadata(ClassMetadataInfo $metadata);
/**
* Sets the array of ClassMetadataInfo instances to export.
*
* @param array $metadata
* Sets the array of ClassMetadata instances to export.
*
* @return void
*
* @psalm-param list<ClassMetadata> $metadata
*/
public function setMetadata(array $metadata)
{
@@ -139,7 +140,8 @@ abstract class AbstractExporter
foreach ($this->_metadata as $metadata) {
// In case output is returned, write it to a file, skip otherwise
if ($output = $this->exportClassMetadata($metadata)) {
$output = $this->exportClassMetadata($metadata);
if ($output) {
$path = $this->_generateOutputPath($metadata);
$dir = dirname($path);
if (! is_dir($dir)) {

View File

@@ -87,7 +87,7 @@ class PhpExporter extends AbstractExporter
if ($metadata->lifecycleCallbacks) {
foreach ($metadata->lifecycleCallbacks as $event => $callbacks) {
foreach ($callbacks as $callback) {
$lines[] = "\$metadata->addLifecycleCallback('$callback', '$event');";
$lines[] = sprintf("\$metadata->addLifecycleCallback('%s', '%s');", $callback, $event);
}
}
}

View File

@@ -48,7 +48,7 @@ class XmlExporter extends AbstractExporter
*/
public function exportClassMetadata(ClassMetadataInfo $metadata)
{
$xml = new SimpleXmlElement('<?xml version="1.0" encoding="utf-8"?><doctrine-mapping ' .
$xml = new SimpleXMLElement('<?xml version="1.0" encoding="utf-8"?><doctrine-mapping ' .
'xmlns="http://doctrine-project.org/schemas/orm/doctrine-mapping" ' .
'xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" ' .
'xsi:schemaLocation="http://doctrine-project.org/schemas/orm/doctrine-mapping https://www.doctrine-project.org/schemas/orm/doctrine-mapping.xsd" />');
@@ -179,7 +179,8 @@ class XmlExporter extends AbstractExporter
$idXml->addAttribute('association-key', 'true');
}
if ($idGeneratorType = $this->_getIdGeneratorTypeString($metadata->generatorType)) {
$idGeneratorType = $this->_getIdGeneratorTypeString($metadata->generatorType);
if ($idGeneratorType) {
$generatorXml = $idXml->addChild('generator');
$generatorXml->addAttribute('strategy', $idGeneratorType);
@@ -405,7 +406,7 @@ class XmlExporter extends AbstractExporter
$this->processEntityListeners($metadata, $root);
return $this->_asXml($xml);
return $this->asXml($xml);
}
/**
@@ -447,7 +448,7 @@ class XmlExporter extends AbstractExporter
$sequenceGeneratorXml->addAttribute('initial-value', $sequenceDefinition['initialValue']);
}
private function _asXml(SimpleXMLElement $simpleXml): string
private function asXml(SimpleXMLElement $simpleXml): string
{
$dom = new DOMDocument('1.0', 'UTF-8');
$dom->loadXML($simpleXml->asXML());

View File

@@ -65,11 +65,13 @@ class YamlExporter extends AbstractExporter
$array['inheritanceType'] = $this->_getInheritanceTypeString($inheritanceType);
}
if ($column = $metadata->discriminatorColumn) {
$column = $metadata->discriminatorColumn;
if ($column) {
$array['discriminatorColumn'] = $column;
}
if ($map = $metadata->discriminatorMap) {
$map = $metadata->discriminatorMap;
if ($map) {
$array['discriminatorMap'] = $map;
}
@@ -241,6 +243,10 @@ class YamlExporter extends AbstractExporter
return Yaml::dump($array, $inline);
}
/**
* @psalm-param array<string, mixed> $array
* @psalm-return array<string, mixed>&array{entityListeners: array<class-string, array<string, array{string}>>}
*/
private function processEntityListeners(ClassMetadataInfo $metadata, array $array): array
{
if (count($metadata->entityListeners) === 0) {
@@ -256,8 +262,16 @@ class YamlExporter extends AbstractExporter
return $array;
}
private function processEntityListenerConfig(array $array, array $entityListenerConfig, string $event): array
{
/**
* @psalm-param array{entityListeners: array<class-string, array<string, array{string}>>} $array
* @psalm-param list<array{class: class-string, method: string}> $entityListenerConfig
* @psalm-return array{entityListeners: array<class-string, array<string, array{string}>>}
*/
private function processEntityListenerConfig(
array $array,
array $entityListenerConfig,
string $event
): array {
foreach ($entityListenerConfig as $entityListener) {
if (! isset($array['entityListeners'][$entityListener['class']])) {
$array['entityListeners'][$entityListener['class']] = [];

View File

@@ -22,6 +22,8 @@ namespace Doctrine\ORM\Tools\Export;
use Doctrine\ORM\ORMException;
use function sprintf;
/**
* @deprecated 2.7 This class is being removed from the ORM and won't have any replacement
*/
@@ -34,7 +36,10 @@ class ExportException extends ORMException
*/
public static function invalidExporterDriverType($type)
{
return new self("The specified export driver '$type' does not exist");
return new self(sprintf(
"The specified export driver '%s' does not exist",
$type
));
}
/**
@@ -44,7 +49,10 @@ class ExportException extends ORMException
*/
public static function invalidMappingDriverType($type)
{
return new self("The mapping driver '$type' does not exist");
return new self(sprintf(
"The mapping driver '%s' does not exist",
$type
));
}
/**

View File

@@ -477,7 +477,7 @@ class LimitSubqueryOutputWalker extends SqlWalker
/**
* getter for $orderByPathExpressions
*
* @return array
* @return mixed[]
*/
public function getOrderByPathExpressions()
{

View File

@@ -132,7 +132,7 @@ class Paginator implements Countable, IteratorAggregate
/**
* {@inheritdoc}
*
* @return ArrayIterator<mixed, T>
* @psalm-return ArrayIterator<array-key, T>
*/
public function getIterator()
{

View File

@@ -58,9 +58,10 @@ class ResolveTargetEntityListener implements EventSubscriber
*
* @param string $originalEntity
* @param string $newEntity
* @param array $mapping
*
* @return void
*
* @psalm-param array<string, mixed> $mapping
*/
public function addResolveTargetEntity($originalEntity, $newEntity, array $mapping)
{

View File

@@ -87,11 +87,11 @@ class SchemaTool
/**
* Creates the database schema for the given array of ClassMetadata instances.
*
* @param array $classes
*
* @return void
*
* @throws ToolsException
*
* @psalm-param list<ClassMetadata> $classes
*/
public function createSchema(array $classes)
{
@@ -111,9 +111,9 @@ class SchemaTool
* Gets the list of DDL statements that are required to create the database schema for
* the given list of ClassMetadata instances.
*
* @param array $classes
*
* @return string[] The SQL statements needed to create the schema for the classes.
*
* @psalm-param list<ClassMetadata> $classes
*/
public function getCreateSchemaSql(array $classes)
{
@@ -125,13 +125,12 @@ class SchemaTool
/**
* Detects instances of ClassMetadata that don't need to be processed in the SchemaTool context.
*
* @param ClassMetadata $class
* @param array $processedClasses
*
* @return bool
* @psalm-param array<string, bool> $processedClasses
*/
private function processingNotRequired($class, array $processedClasses)
{
private function processingNotRequired(
ClassMetadata $class,
array $processedClasses
): bool {
return isset($processedClasses[$class->name]) ||
$class->isMappedSuperclass ||
$class->isEmbeddedClass ||
@@ -141,11 +140,11 @@ class SchemaTool
/**
* Creates a Schema instance from a given set of metadata classes.
*
* @param array $classes
*
* @return Schema
*
* @throws ORMException
*
* @psalm-param list<ClassMetadata> $classes
*/
public function getSchemaFromMetadata(array $classes)
{
@@ -162,7 +161,6 @@ class SchemaTool
$blacklistedFks = [];
foreach ($classes as $class) {
assert($class instanceof ClassMetadata);
if ($this->processingNotRequired($class, $processedClasses)) {
continue;
}
@@ -432,13 +430,15 @@ class SchemaTool
/**
* Creates a column definition as required by the DBAL from an ORM field mapping definition.
*
* @param ClassMetadata $class The class that owns the field mapping.
* @param array $mapping The field mapping.
* @param ClassMetadata $class The class that owns the field mapping.
*
* @return void
* @psalm-param array<string, mixed> $mapping The field mapping.
*/
private function gatherColumn($class, array $mapping, Table $table)
{
private function gatherColumn(
ClassMetadata $class,
array $mapping,
Table $table
): void {
$columnName = $this->quoteStrategy->getColumnName($mapping['fieldName'], $class, $this->platform);
$columnType = $mapping['type'];
@@ -500,18 +500,21 @@ class SchemaTool
* Gathers the SQL for properly setting up the relations of the given class.
* This includes the SQL for foreign key constraints and join tables.
*
* @param ClassMetadata $class
* @param Table $table
* @param Schema $schema
* @param array $addedFks
* @param array $blacklistedFks
*
* @return void
*
* @throws ORMException
*
* @psalm-param array<string, array{
* foreignTableName: string,
* foreignColumns: list<string>
* }> $addedFks
* @psalm-param array<string, bool> $blacklistedFks
*/
private function gatherRelationsSql($class, $table, $schema, &$addedFks, &$blacklistedFks)
{
private function gatherRelationsSql(
ClassMetadata $class,
Table $table,
Schema $schema,
array &$addedFks,
array &$blacklistedFks
): void {
foreach ($class->associationMappings as $id => $mapping) {
if (isset($mapping['inherited']) && ! in_array($id, $class->identifier, true)) {
continue;
@@ -580,12 +583,9 @@ class SchemaTool
*
* TODO: Is there any way to make this code more pleasing?
*
* @param ClassMetadata $class
* @param string $referencedColumnName
*
* @return array (ClassMetadata, referencedFieldName)
* @psalm-return array{ClassMetadata, string}|null
*/
private function getDefiningClass($class, $referencedColumnName)
private function getDefiningClass(ClassMetadata $class, string $referencedColumnName): ?array
{
$referencedFieldName = $class->getFieldName($referencedColumnName);
@@ -614,27 +614,26 @@ class SchemaTool
/**
* Gathers columns and fk constraints that are required for one part of relationship.
*
* @param array $joinColumns
* @param Table $theJoinTable
* @param ClassMetadata $class
* @param array $mapping
* @param array $primaryKeyColumns
* @param array $addedFks
* @param array $blacklistedFks
*
* @return void
*
* @throws ORMException
*
* @psalm-param array<string, mixed> $joinColumns
* @psalm-param array<string, mixed> $mapping
* @psalm-param list<string> $primaryKeyColumns
* @psalm-param array<string, array{
* foreignTableName: string,
* foreignColumns: list<string>
* }> $addedFks
* @psalm-param array<string,bool> $blacklistedFks
*/
private function gatherRelationJoinColumns(
$joinColumns,
$theJoinTable,
$class,
$mapping,
&$primaryKeyColumns,
&$addedFks,
&$blacklistedFks
) {
array $joinColumns,
Table $theJoinTable,
ClassMetadata $class,
array $mapping,
array &$primaryKeyColumns,
array &$addedFks,
array &$blacklistedFks
): void {
$localColumns = [];
$foreignColumns = [];
$fkOptions = [];
@@ -764,9 +763,9 @@ class SchemaTool
* In any way when an exception is thrown it is suppressed since drop was
* issued for all classes of the schema and some probably just don't exist.
*
* @param array $classes
*
* @return void
*
* @psalm-param list<ClassMetadata> $classes
*/
public function dropSchema(array $classes)
{
@@ -816,9 +815,9 @@ class SchemaTool
/**
* Gets SQL to drop the tables defined by the passed classes.
*
* @param array $classes
*
* @return string[]
*
* @psalm-param list<ClassMetadata> $classes
*/
public function getDropSchemaSQL(array $classes)
{
@@ -849,7 +848,6 @@ class SchemaTool
}
foreach ($schema->getTables() as $table) {
/** @var Table $sequence */
if ($table->hasPrimaryKey()) {
$columns = $table->getPrimaryKey()->getColumns();
if (count($columns) === 1) {

View File

@@ -58,7 +58,7 @@ class SchemaValidator
* 2. Check if "mappedBy" and "inversedBy" are consistent to each other.
* 3. Check if "referencedColumnName" attributes are really pointing to primary key columns.
*
* @return array
* @psalm-return array<string, list<string>>
*/
public function validateMapping()
{
@@ -67,7 +67,8 @@ class SchemaValidator
$classes = $cmf->getAllMetadata();
foreach ($classes as $class) {
if ($ce = $this->validateClass($class)) {
$ce = $this->validateClass($class);
if ($ce) {
$errors[$class->name] = $ce;
}
}

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