Cambio textos FAQS seccion registro

This commit is contained in:
kquiroz
2023-08-17 19:45:01 -04:00
parent f4795ceacc
commit 84904eca6a
2102 changed files with 225 additions and 496829 deletions

View File

@@ -1,19 +0,0 @@
Copyright (c) 2006-2013 Doctrine Project
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@@ -1,24 +0,0 @@
⚠️ PHP 8 introduced
[attributes](https://www.php.net/manual/en/language.attributes.overview.php),
which are a native replacement for annotations. As such, this library is
considered feature complete, and should receive exclusively bugfixes and
security fixes.
# Doctrine Annotations
[![Build Status](https://github.com/doctrine/annotations/workflows/Continuous%20Integration/badge.svg?label=build)](https://github.com/doctrine/persistence/actions)
[![Dependency Status](https://www.versioneye.com/package/php--doctrine--annotations/badge.png)](https://www.versioneye.com/package/php--doctrine--annotations)
[![Reference Status](https://www.versioneye.com/php/doctrine:annotations/reference_badge.svg)](https://www.versioneye.com/php/doctrine:annotations/references)
[![Total Downloads](https://poser.pugx.org/doctrine/annotations/downloads.png)](https://packagist.org/packages/doctrine/annotations)
[![Latest Stable Version](https://img.shields.io/packagist/v/doctrine/annotations.svg?label=stable)](https://packagist.org/packages/doctrine/annotations)
Docblock Annotations Parser library (extracted from [Doctrine Common](https://github.com/doctrine/common)).
## Documentation
See the [doctrine-project website](https://www.doctrine-project.org/projects/doctrine-annotations/en/latest/index.html).
## Contributing
When making a pull request, make sure your changes follow the
[Coding Standard Guidelines](https://www.doctrine-project.org/projects/doctrine-coding-standard/en/current/reference/index.html#introduction).

View File

@@ -1,72 +0,0 @@
{
"name": "doctrine/annotations",
"description": "Docblock Annotations Parser",
"license": "MIT",
"type": "library",
"keywords": [
"annotations",
"docblock",
"parser"
],
"authors": [
{
"name": "Guilherme Blanco",
"email": "guilhermeblanco@gmail.com"
},
{
"name": "Roman Borschel",
"email": "roman@code-factory.org"
},
{
"name": "Benjamin Eberlei",
"email": "kontakt@beberlei.de"
},
{
"name": "Jonathan Wage",
"email": "jonwage@gmail.com"
},
{
"name": "Johannes Schmitt",
"email": "schmittjoh@gmail.com"
}
],
"homepage": "https://www.doctrine-project.org/projects/annotations.html",
"require": {
"php": "^7.1 || ^8.0",
"ext-tokenizer": "*",
"doctrine/lexer": "^1 || ^2",
"psr/cache": "^1 || ^2 || ^3"
},
"require-dev": {
"doctrine/cache": "^1.11 || ^2.0",
"doctrine/coding-standard": "^9 || ^10",
"phpstan/phpstan": "~1.4.10 || ^1.8.0",
"phpunit/phpunit": "^7.5 || ^8.5 || ^9.5",
"symfony/cache": "^4.4 || ^5.4 || ^6",
"vimeo/psalm": "^4.10"
},
"suggest": {
"php": "PHP 8.0 or higher comes with attributes, a native replacement for annotations"
},
"autoload": {
"psr-4": {
"Doctrine\\Common\\Annotations\\": "lib/Doctrine/Common/Annotations"
}
},
"autoload-dev": {
"psr-4": {
"Doctrine\\Performance\\Common\\Annotations\\": "tests/Doctrine/Performance/Common/Annotations",
"Doctrine\\Tests\\Common\\Annotations\\": "tests/Doctrine/Tests/Common/Annotations"
},
"files": [
"tests/Doctrine/Tests/Common/Annotations/Fixtures/functions.php",
"tests/Doctrine/Tests/Common/Annotations/Fixtures/SingleClassLOC1000.php"
]
},
"config": {
"allow-plugins": {
"dealerdirect/phpcodesniffer-composer-installer": true
},
"sort-packages": true
}
}

View File

@@ -1,252 +0,0 @@
Handling Annotations
====================
There are several different approaches to handling annotations in PHP.
Doctrine Annotations maps docblock annotations to PHP classes. Because
not all docblock annotations are used for metadata purposes a filter is
applied to ignore or skip classes that are not Doctrine annotations.
Take a look at the following code snippet:
.. code-block:: php
namespace MyProject\Entities;
use Doctrine\ORM\Mapping AS ORM;
use Symfony\Component\Validator\Constraints AS Assert;
/**
* @author Benjamin Eberlei
* @ORM\Entity
* @MyProject\Annotations\Foobarable
*/
class User
{
/**
* @ORM\Id @ORM\Column @ORM\GeneratedValue
* @dummy
* @var int
*/
private $id;
/**
* @ORM\Column(type="string")
* @Assert\NotEmpty
* @Assert\Email
* @var string
*/
private $email;
}
In this snippet you can see a variety of different docblock annotations:
- Documentation annotations such as ``@var`` and ``@author``. These
annotations are ignored and never considered for throwing an
exception due to wrongly used annotations.
- Annotations imported through use statements. The statement ``use
Doctrine\ORM\Mapping AS ORM`` makes all classes under that namespace
available as ``@ORM\ClassName``. Same goes for the import of
``@Assert``.
- The ``@dummy`` annotation. It is not a documentation annotation and
not ignored. For Doctrine Annotations it is not entirely clear how
to handle this annotation. Depending on the configuration an exception
(unknown annotation) will be thrown when parsing this annotation.
- The fully qualified annotation ``@MyProject\Annotations\Foobarable``.
This is transformed directly into the given class name.
How are these annotations loaded? From looking at the code you could
guess that the ORM Mapping, Assert Validation and the fully qualified
annotation can just be loaded using
the defined PHP autoloaders. This is not the case however: For error
handling reasons every check for class existence inside the
``AnnotationReader`` sets the second parameter $autoload
of ``class_exists($name, $autoload)`` to false. To work flawlessly the
``AnnotationReader`` requires silent autoloaders which many autoloaders are
not. Silent autoloading is NOT part of the `PSR-0 specification
<https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-0.md>`_
for autoloading.
This is why Doctrine Annotations uses its own autoloading mechanism
through a global registry. If you are wondering about the annotation
registry being global, there is no other way to solve the architectural
problems of autoloading annotation classes in a straightforward fashion.
Additionally if you think about PHP autoloading then you recognize it is
a global as well.
To anticipate the configuration section, making the above PHP class work
with Doctrine Annotations requires this setup:
.. code-block:: php
use Doctrine\Common\Annotations\AnnotationReader;
use Doctrine\Common\Annotations\AnnotationRegistry;
AnnotationRegistry::registerFile("/path/to/doctrine/lib/Doctrine/ORM/Mapping/Driver/DoctrineAnnotations.php");
AnnotationRegistry::registerAutoloadNamespace("Symfony\Component\Validator\Constraint", "/path/to/symfony/src");
AnnotationRegistry::registerAutoloadNamespace("MyProject\Annotations", "/path/to/myproject/src");
$reader = new AnnotationReader();
AnnotationReader::addGlobalIgnoredName('dummy');
The second block with the annotation registry calls registers all the
three different annotation namespaces that are used.
Doctrine Annotations saves all its annotations in a single file, that is
why ``AnnotationRegistry#registerFile`` is used in contrast to
``AnnotationRegistry#registerAutoloadNamespace`` which creates a PSR-0
compatible loading mechanism for class to file names.
In the third block, we create the actual ``AnnotationReader`` instance.
Note that we also add ``dummy`` to the global list of ignored
annotations for which we do not throw exceptions. Setting this is
necessary in our example case, otherwise ``@dummy`` would trigger an
exception to be thrown during the parsing of the docblock of
``MyProject\Entities\User#id``.
Setup and Configuration
-----------------------
To use the annotations library is simple, you just need to create a new
``AnnotationReader`` instance:
.. code-block:: php
$reader = new \Doctrine\Common\Annotations\AnnotationReader();
This creates a simple annotation reader with no caching other than in
memory (in php arrays). Since parsing docblocks can be expensive you
should cache this process by using a caching reader.
To cache annotations, you can create a ``Doctrine\Common\Annotations\PsrCachedReader``.
This reader decorates the original reader and stores all annotations in a PSR-6
cache:
.. code-block:: php
use Doctrine\Common\Annotations\AnnotationReader;
use Doctrine\Common\Annotations\PsrCachedReader;
$cache = ... // instantiate a PSR-6 Cache pool
$reader = new PsrCachedReader(
new AnnotationReader(),
$cache,
$debug = true
);
The ``debug`` flag is used here as well to invalidate the cache files
when the PHP class with annotations changed and should be used during
development.
.. warning ::
The ``AnnotationReader`` works and caches under the
assumption that all annotations of a doc-block are processed at
once. That means that annotation classes that do not exist and
aren't loaded and cannot be autoloaded (using the
AnnotationRegistry) would never be visible and not accessible if a
cache is used unless the cache is cleared and the annotations
requested again, this time with all annotations defined.
By default the annotation reader returns a list of annotations with
numeric indexes. If you want your annotations to be indexed by their
class name you can wrap the reader in an ``IndexedReader``:
.. code-block:: php
use Doctrine\Common\Annotations\AnnotationReader;
use Doctrine\Common\Annotations\IndexedReader;
$reader = new IndexedReader(new AnnotationReader());
.. warning::
You should never wrap the indexed reader inside a cached reader,
only the other way around. This way you can re-use the cache with
indexed or numeric keys, otherwise your code may experience failures
due to caching in a numerical or indexed format.
Registering Annotations
~~~~~~~~~~~~~~~~~~~~~~~
As explained in the introduction, Doctrine Annotations uses its own
autoloading mechanism to determine if a given annotation has a
corresponding PHP class that can be autoloaded. For annotation
autoloading you have to configure the
``Doctrine\Common\Annotations\AnnotationRegistry``. There are three
different mechanisms to configure annotation autoloading:
- Calling ``AnnotationRegistry#registerFile($file)`` to register a file
that contains one or more annotation classes.
- Calling ``AnnotationRegistry#registerNamespace($namespace, $dirs =
null)`` to register that the given namespace contains annotations and
that their base directory is located at the given $dirs or in the
include path if ``NULL`` is passed. The given directories should *NOT*
be the directory where classes of the namespace are in, but the base
directory of the root namespace. The AnnotationRegistry uses a
namespace to directory separator approach to resolve the correct path.
- Calling ``AnnotationRegistry#registerLoader($callable)`` to register
an autoloader callback. The callback accepts the class as first and
only parameter and has to return ``true`` if the corresponding file
was found and included.
.. note::
Loaders have to fail silently, if a class is not found even if it
matches for example the namespace prefix of that loader. Never is a
loader to throw a warning or exception if the loading failed
otherwise parsing doc block annotations will become a huge pain.
A sample loader callback could look like:
.. code-block:: php
use Doctrine\Common\Annotations\AnnotationRegistry;
use Symfony\Component\ClassLoader\UniversalClassLoader;
AnnotationRegistry::registerLoader(function($class) {
$file = str_replace("\\", DIRECTORY_SEPARATOR, $class) . ".php";
if (file_exists("/my/base/path/" . $file)) {
// file_exists() makes sure that the loader fails silently
require "/my/base/path/" . $file;
}
});
$loader = new UniversalClassLoader();
AnnotationRegistry::registerLoader(array($loader, "loadClass"));
Ignoring missing exceptions
~~~~~~~~~~~~~~~~~~~~~~~~~~~
By default an exception is thrown from the ``AnnotationReader`` if an
annotation was found that:
- is not part of the list of ignored "documentation annotations";
- was not imported through a use statement;
- is not a fully qualified class that exists.
You can disable this behavior for specific names if your docblocks do
not follow strict requirements:
.. code-block:: php
$reader = new \Doctrine\Common\Annotations\AnnotationReader();
AnnotationReader::addGlobalIgnoredName('foo');
PHP Imports
~~~~~~~~~~~
By default the annotation reader parses the use-statement of a php file
to gain access to the import rules and register them for the annotation
processing. Only if you are using PHP Imports can you validate the
correct usage of annotations and throw exceptions if you misspelled an
annotation. This mechanism is enabled by default.
To ease the upgrade path, we still allow you to disable this mechanism.
Note however that we will remove this in future versions:
.. code-block:: php
$reader = new \Doctrine\Common\Annotations\AnnotationReader();
$reader->setEnabledPhpImports(false);

View File

@@ -1,443 +0,0 @@
Custom Annotation Classes
=========================
If you want to define your own annotations, you just have to group them
in a namespace and register this namespace in the ``AnnotationRegistry``.
Annotation classes have to contain a class-level docblock with the text
``@Annotation``:
.. code-block:: php
namespace MyCompany\Annotations;
/** @Annotation */
class Bar
{
// some code
}
Inject annotation values
------------------------
The annotation parser checks if the annotation constructor has arguments,
if so then it will pass the value array, otherwise it will try to inject
values into public properties directly:
.. code-block:: php
namespace MyCompany\Annotations;
/**
* @Annotation
*
* Some Annotation using a constructor
*/
class Bar
{
private $foo;
public function __construct(array $values)
{
$this->foo = $values['foo'];
}
}
/**
* @Annotation
*
* Some Annotation without a constructor
*/
class Foo
{
public $bar;
}
Optional: Constructors with Named Parameters
--------------------------------------------
Starting with Annotations v1.11 a new annotation instantiation strategy
is available that aims at compatibility of Annotation classes with the PHP 8
attribute feature. You need to declare a constructor with regular parameter
names that match the named arguments in the annotation syntax.
To enable this feature, you can tag your annotation class with
``@NamedArgumentConstructor`` (available from v1.12) or implement the
``Doctrine\Common\Annotations\NamedArgumentConstructorAnnotation`` interface
(available from v1.11 and deprecated as of v1.12).
When using the ``@NamedArgumentConstructor`` tag, the first argument of the
constructor is considered as the default one.
Usage with the ``@NamedArgumentConstructor`` tag
.. code-block:: php
namespace MyCompany\Annotations;
/**
* @Annotation
* @NamedArgumentConstructor
*/
class Bar implements NamedArgumentConstructorAnnotation
{
private $foo;
public function __construct(string $foo)
{
$this->foo = $foo;
}
}
/** Usable with @Bar(foo="baz") */
/** Usable with @Bar("baz") */
In combination with PHP 8's constructor property promotion feature
you can simplify this to:
.. code-block:: php
namespace MyCompany\Annotations;
/**
* @Annotation
* @NamedArgumentConstructor
*/
class Bar implements NamedArgumentConstructorAnnotation
{
public function __construct(private string $foo) {}
}
Usage with the
``Doctrine\Common\Annotations\NamedArgumentConstructorAnnotation``
interface (v1.11, deprecated as of v1.12):
.. code-block:: php
namespace MyCompany\Annotations;
use Doctrine\Common\Annotations\NamedArgumentConstructorAnnotation;
/** @Annotation */
class Bar implements NamedArgumentConstructorAnnotation
{
private $foo;
public function __construct(private string $foo) {}
}
/** Usable with @Bar(foo="baz") */
Annotation Target
-----------------
``@Target`` indicates the kinds of class elements to which an annotation
type is applicable. Then you could define one or more targets:
- ``CLASS`` Allowed in class docblocks
- ``PROPERTY`` Allowed in property docblocks
- ``METHOD`` Allowed in the method docblocks
- ``FUNCTION`` Allowed in function dockblocks
- ``ALL`` Allowed in class, property, method and function docblocks
- ``ANNOTATION`` Allowed inside other annotations
If the annotations is not allowed in the current context, an
``AnnotationException`` is thrown.
.. code-block:: php
namespace MyCompany\Annotations;
/**
* @Annotation
* @Target({"METHOD","PROPERTY"})
*/
class Bar
{
// some code
}
/**
* @Annotation
* @Target("CLASS")
*/
class Foo
{
// some code
}
Attribute types
---------------
The annotation parser checks the given parameters using the phpdoc
annotation ``@var``, The data type could be validated using the ``@var``
annotation on the annotation properties or using the ``@Attributes`` and
``@Attribute`` annotations.
If the data type does not match you get an ``AnnotationException``
.. code-block:: php
namespace MyCompany\Annotations;
/**
* @Annotation
* @Target({"METHOD","PROPERTY"})
*/
class Bar
{
/** @var mixed */
public $mixed;
/** @var boolean */
public $boolean;
/** @var bool */
public $bool;
/** @var float */
public $float;
/** @var string */
public $string;
/** @var integer */
public $integer;
/** @var array */
public $array;
/** @var SomeAnnotationClass */
public $annotation;
/** @var array<integer> */
public $arrayOfIntegers;
/** @var array<SomeAnnotationClass> */
public $arrayOfAnnotations;
}
/**
* @Annotation
* @Target({"METHOD","PROPERTY"})
* @Attributes({
* @Attribute("stringProperty", type = "string"),
* @Attribute("annotProperty", type = "SomeAnnotationClass"),
* })
*/
class Foo
{
public function __construct(array $values)
{
$this->stringProperty = $values['stringProperty'];
$this->annotProperty = $values['annotProperty'];
}
// some code
}
Annotation Required
-------------------
``@Required`` indicates that the field must be specified when the
annotation is used. If it is not used you get an ``AnnotationException``
stating that this value can not be null.
Declaring a required field:
.. code-block:: php
/**
* @Annotation
* @Target("ALL")
*/
class Foo
{
/** @Required */
public $requiredField;
}
Usage:
.. code-block:: php
/** @Foo(requiredField="value") */
public $direction; // Valid
/** @Foo */
public $direction; // Required field missing, throws an AnnotationException
Enumerated values
-----------------
- An annotation property marked with ``@Enum`` is a field that accepts a
fixed set of scalar values.
- You should use ``@Enum`` fields any time you need to represent fixed
values.
- The annotation parser checks the given value and throws an
``AnnotationException`` if the value does not match.
Declaring an enumerated property:
.. code-block:: php
/**
* @Annotation
* @Target("ALL")
*/
class Direction
{
/**
* @Enum({"NORTH", "SOUTH", "EAST", "WEST"})
*/
public $value;
}
Annotation usage:
.. code-block:: php
/** @Direction("NORTH") */
public $direction; // Valid value
/** @Direction("NORTHEAST") */
public $direction; // Invalid value, throws an AnnotationException
Constants
---------
The use of constants and class constants is available on the annotations
parser.
The following usages are allowed:
.. code-block:: php
namespace MyCompany\Entity;
use MyCompany\Annotations\Foo;
use MyCompany\Annotations\Bar;
use MyCompany\Entity\SomeClass;
/**
* @Foo(PHP_EOL)
* @Bar(Bar::FOO)
* @Foo({SomeClass::FOO, SomeClass::BAR})
* @Bar({SomeClass::FOO_KEY = SomeClass::BAR_VALUE})
*/
class User
{
}
Be careful with constants and the cache !
.. note::
The cached reader will not re-evaluate each time an annotation is
loaded from cache. When a constant is changed the cache must be
cleaned.
Usage
-----
Using the library API is simple. Using the annotations described in the
previous section, you can now annotate other classes with your
annotations:
.. code-block:: php
namespace MyCompany\Entity;
use MyCompany\Annotations\Foo;
use MyCompany\Annotations\Bar;
/**
* @Foo(bar="foo")
* @Bar(foo="bar")
*/
class User
{
}
Now we can write a script to get the annotations above:
.. code-block:: php
$reflClass = new ReflectionClass('MyCompany\Entity\User');
$classAnnotations = $reader->getClassAnnotations($reflClass);
foreach ($classAnnotations AS $annot) {
if ($annot instanceof \MyCompany\Annotations\Foo) {
echo $annot->bar; // prints "foo";
} else if ($annot instanceof \MyCompany\Annotations\Bar) {
echo $annot->foo; // prints "bar";
}
}
You have a complete API for retrieving annotation class instances from a
class, property or method docblock:
Reader API
~~~~~~~~~~
Access all annotations of a class
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
.. code-block:: php
public function getClassAnnotations(\ReflectionClass $class);
Access one annotation of a class
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
.. code-block:: php
public function getClassAnnotation(\ReflectionClass $class, $annotationName);
Access all annotations of a method
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
.. code-block:: php
public function getMethodAnnotations(\ReflectionMethod $method);
Access one annotation of a method
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
.. code-block:: php
public function getMethodAnnotation(\ReflectionMethod $method, $annotationName);
Access all annotations of a property
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
.. code-block:: php
public function getPropertyAnnotations(\ReflectionProperty $property);
Access one annotation of a property
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
.. code-block:: php
public function getPropertyAnnotation(\ReflectionProperty $property, $annotationName);
Access all annotations of a function
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
.. code-block:: php
public function getFunctionAnnotations(\ReflectionFunction $property);
Access one annotation of a function
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
.. code-block:: php
public function getFunctionAnnotation(\ReflectionFunction $property, $annotationName);

View File

@@ -1,110 +0,0 @@
Deprecation notice
==================
PHP 8 introduced `attributes
<https://www.php.net/manual/en/language.attributes.overview.php>`_,
which are a native replacement for annotations. As such, this library is
considered feature complete, and should receive exclusively bugfixes and
security fixes.
Introduction
============
Doctrine Annotations allows to implement custom annotation
functionality for PHP classes and functions.
.. code-block:: php
class Foo
{
/**
* @MyAnnotation(myProperty="value")
*/
private $bar;
}
Annotations aren't implemented in PHP itself which is why this component
offers a way to use the PHP doc-blocks as a place for the well known
annotation syntax using the ``@`` char.
Annotations in Doctrine are used for the ORM configuration to build the
class mapping, but it can be used in other projects for other purposes
too.
Installation
============
You can install the Annotation component with composer:
.. code-block::
  $ composer require doctrine/annotations
Create an annotation class
==========================
An annotation class is a representation of the later used annotation
configuration in classes. The annotation class of the previous example
looks like this:
.. code-block:: php
/**
* @Annotation
*/
final class MyAnnotation
{
public $myProperty;
}
The annotation class is declared as an annotation by ``@Annotation``.
:ref:`Read more about custom annotations. <custom>`
Reading annotations
===================
The access to the annotations happens by reflection of the class or function
containing them. There are multiple reader-classes implementing the
``Doctrine\Common\Annotations\Reader`` interface, that can access the
annotations of a class. A common one is
``Doctrine\Common\Annotations\AnnotationReader``:
.. code-block:: php
use Doctrine\Common\Annotations\AnnotationReader;
use Doctrine\Common\Annotations\AnnotationRegistry;
// Deprecated and will be removed in 2.0 but currently needed
AnnotationRegistry::registerLoader('class_exists');
$reflectionClass = new ReflectionClass(Foo::class);
$property = $reflectionClass->getProperty('bar');
$reader = new AnnotationReader();
$myAnnotation = $reader->getPropertyAnnotation(
$property,
MyAnnotation::class
);
echo $myAnnotation->myProperty; // result: "value"
Note that ``AnnotationRegistry::registerLoader('class_exists')`` only works
if you already have an autoloader configured (i.e. composer autoloader).
Otherwise, :ref:`please take a look to the other annotation autoload mechanisms <annotations>`.
A reader has multiple methods to access the annotations of a class or
function.
:ref:`Read more about handling annotations. <annotations>`
IDE Support
-----------
Some IDEs already provide support for annotations:
- Eclipse via the `Symfony2 Plugin <https://github.com/pulse00/Symfony-2-Eclipse-Plugin>`_
- PhpStorm via the `PHP Annotations Plugin <https://plugins.jetbrains.com/plugin/7320-php-annotations>`_ or the `Symfony Plugin <https://plugins.jetbrains.com/plugin/7219-symfony-support>`_
.. _Read more about handling annotations.: annotations
.. _Read more about custom annotations.: custom

View File

@@ -1,6 +0,0 @@
.. toctree::
:depth: 3
index
annotations
custom

View File

@@ -1,57 +0,0 @@
<?php
namespace Doctrine\Common\Annotations;
use BadMethodCallException;
use function sprintf;
/**
* Annotations class.
*/
class Annotation
{
/**
* Value property. Common among all derived classes.
*
* @var mixed
*/
public $value;
/** @param array<string, mixed> $data Key-value for properties to be defined in this class. */
final public function __construct(array $data)
{
foreach ($data as $key => $value) {
$this->$key = $value;
}
}
/**
* Error handler for unknown property accessor in Annotation class.
*
* @param string $name Unknown property name.
*
* @throws BadMethodCallException
*/
public function __get($name)
{
throw new BadMethodCallException(
sprintf("Unknown property '%s' on annotation '%s'.", $name, static::class)
);
}
/**
* Error handler for unknown property mutator in Annotation class.
*
* @param string $name Unknown property name.
* @param mixed $value Property value.
*
* @throws BadMethodCallException
*/
public function __set($name, $value)
{
throw new BadMethodCallException(
sprintf("Unknown property '%s' on annotation '%s'.", $name, static::class)
);
}
}

View File

@@ -1,21 +0,0 @@
<?php
namespace Doctrine\Common\Annotations\Annotation;
/**
* Annotation that can be used to signal to the parser
* to check the attribute type during the parsing process.
*
* @Annotation
*/
final class Attribute
{
/** @var string */
public $name;
/** @var string */
public $type;
/** @var bool */
public $required = false;
}

View File

@@ -1,15 +0,0 @@
<?php
namespace Doctrine\Common\Annotations\Annotation;
/**
* Annotation that can be used to signal to the parser
* to check the types of all declared attributes during the parsing process.
*
* @Annotation
*/
final class Attributes
{
/** @var array<Attribute> */
public $value;
}

View File

@@ -1,69 +0,0 @@
<?php
namespace Doctrine\Common\Annotations\Annotation;
use InvalidArgumentException;
use function get_class;
use function gettype;
use function in_array;
use function is_object;
use function is_scalar;
use function sprintf;
/**
* Annotation that can be used to signal to the parser
* to check the available values during the parsing process.
*
* @Annotation
* @Attributes({
* @Attribute("value", required = true, type = "array"),
* @Attribute("literal", required = false, type = "array")
* })
*/
final class Enum
{
/** @phpstan-var list<scalar> */
public $value;
/**
* Literal target declaration.
*
* @var mixed[]
*/
public $literal;
/**
* @phpstan-param array{literal?: mixed[], value: list<scalar>} $values
*
* @throws InvalidArgumentException
*/
public function __construct(array $values)
{
if (! isset($values['literal'])) {
$values['literal'] = [];
}
foreach ($values['value'] as $var) {
if (! is_scalar($var)) {
throw new InvalidArgumentException(sprintf(
'@Enum supports only scalar values "%s" given.',
is_object($var) ? get_class($var) : gettype($var)
));
}
}
foreach ($values['literal'] as $key => $var) {
if (! in_array($key, $values['value'])) {
throw new InvalidArgumentException(sprintf(
'Undefined enumerator value "%s" for literal "%s".',
$key,
$var
));
}
}
$this->value = $values['value'];
$this->literal = $values['literal'];
}
}

View File

@@ -1,43 +0,0 @@
<?php
namespace Doctrine\Common\Annotations\Annotation;
use RuntimeException;
use function is_array;
use function is_string;
use function json_encode;
use function sprintf;
/**
* Annotation that can be used to signal to the parser to ignore specific
* annotations during the parsing process.
*
* @Annotation
*/
final class IgnoreAnnotation
{
/** @phpstan-var list<string> */
public $names;
/**
* @phpstan-param array{value: string|list<string>} $values
*
* @throws RuntimeException
*/
public function __construct(array $values)
{
if (is_string($values['value'])) {
$values['value'] = [$values['value']];
}
if (! is_array($values['value'])) {
throw new RuntimeException(sprintf(
'@IgnoreAnnotation expects either a string name, or an array of strings, but got %s.',
json_encode($values['value'])
));
}
$this->names = $values['value'];
}
}

View File

@@ -1,13 +0,0 @@
<?php
namespace Doctrine\Common\Annotations\Annotation;
/**
* Annotation that indicates that the annotated class should be constructed with a named argument call.
*
* @Annotation
* @Target("CLASS")
*/
final class NamedArgumentConstructor
{
}

View File

@@ -1,13 +0,0 @@
<?php
namespace Doctrine\Common\Annotations\Annotation;
/**
* Annotation that can be used to signal to the parser
* to check if that attribute is required during the parsing process.
*
* @Annotation
*/
final class Required
{
}

View File

@@ -1,101 +0,0 @@
<?php
namespace Doctrine\Common\Annotations\Annotation;
use InvalidArgumentException;
use function array_keys;
use function get_class;
use function gettype;
use function implode;
use function is_array;
use function is_object;
use function is_string;
use function sprintf;
/**
* Annotation that can be used to signal to the parser
* to check the annotation target during the parsing process.
*
* @Annotation
*/
final class Target
{
public const TARGET_CLASS = 1;
public const TARGET_METHOD = 2;
public const TARGET_PROPERTY = 4;
public const TARGET_ANNOTATION = 8;
public const TARGET_FUNCTION = 16;
public const TARGET_ALL = 31;
/** @var array<string, int> */
private static $map = [
'ALL' => self::TARGET_ALL,
'CLASS' => self::TARGET_CLASS,
'METHOD' => self::TARGET_METHOD,
'PROPERTY' => self::TARGET_PROPERTY,
'FUNCTION' => self::TARGET_FUNCTION,
'ANNOTATION' => self::TARGET_ANNOTATION,
];
/** @phpstan-var list<string> */
public $value;
/**
* Targets as bitmask.
*
* @var int
*/
public $targets;
/**
* Literal target declaration.
*
* @var string
*/
public $literal;
/**
* @phpstan-param array{value?: string|list<string>} $values
*
* @throws InvalidArgumentException
*/
public function __construct(array $values)
{
if (! isset($values['value'])) {
$values['value'] = null;
}
if (is_string($values['value'])) {
$values['value'] = [$values['value']];
}
if (! is_array($values['value'])) {
throw new InvalidArgumentException(
sprintf(
'@Target expects either a string value, or an array of strings, "%s" given.',
is_object($values['value']) ? get_class($values['value']) : gettype($values['value'])
)
);
}
$bitmask = 0;
foreach ($values['value'] as $literal) {
if (! isset(self::$map[$literal])) {
throw new InvalidArgumentException(
sprintf(
'Invalid Target "%s". Available targets: [%s]',
$literal,
implode(', ', array_keys(self::$map))
)
);
}
$bitmask |= self::$map[$literal];
}
$this->targets = $bitmask;
$this->value = $values['value'];
$this->literal = implode(', ', $this->value);
}
}

View File

@@ -1,167 +0,0 @@
<?php
namespace Doctrine\Common\Annotations;
use Exception;
use Throwable;
use function get_class;
use function gettype;
use function implode;
use function is_object;
use function sprintf;
/**
* Description of AnnotationException
*/
class AnnotationException extends Exception
{
/**
* Creates a new AnnotationException describing a Syntax error.
*
* @param string $message Exception message
*
* @return AnnotationException
*/
public static function syntaxError($message)
{
return new self('[Syntax Error] ' . $message);
}
/**
* Creates a new AnnotationException describing a Semantical error.
*
* @param string $message Exception message
*
* @return AnnotationException
*/
public static function semanticalError($message)
{
return new self('[Semantical Error] ' . $message);
}
/**
* Creates a new AnnotationException describing an error which occurred during
* the creation of the annotation.
*
* @param string $message
*
* @return AnnotationException
*/
public static function creationError($message, ?Throwable $previous = null)
{
return new self('[Creation Error] ' . $message, 0, $previous);
}
/**
* Creates a new AnnotationException describing a type error.
*
* @param string $message
*
* @return AnnotationException
*/
public static function typeError($message)
{
return new self('[Type Error] ' . $message);
}
/**
* Creates a new AnnotationException describing a constant semantical error.
*
* @param string $identifier
* @param string $context
*
* @return AnnotationException
*/
public static function semanticalErrorConstants($identifier, $context = null)
{
return self::semanticalError(sprintf(
"Couldn't find constant %s%s.",
$identifier,
$context ? ', ' . $context : ''
));
}
/**
* Creates a new AnnotationException describing an type error of an attribute.
*
* @param string $attributeName
* @param string $annotationName
* @param string $context
* @param string $expected
* @param mixed $actual
*
* @return AnnotationException
*/
public static function attributeTypeError($attributeName, $annotationName, $context, $expected, $actual)
{
return self::typeError(sprintf(
'Attribute "%s" of @%s declared on %s expects %s, but got %s.',
$attributeName,
$annotationName,
$context,
$expected,
is_object($actual) ? 'an instance of ' . get_class($actual) : gettype($actual)
));
}
/**
* Creates a new AnnotationException describing an required error of an attribute.
*
* @param string $attributeName
* @param string $annotationName
* @param string $context
* @param string $expected
*
* @return AnnotationException
*/
public static function requiredError($attributeName, $annotationName, $context, $expected)
{
return self::typeError(sprintf(
'Attribute "%s" of @%s declared on %s expects %s. This value should not be null.',
$attributeName,
$annotationName,
$context,
$expected
));
}
/**
* Creates a new AnnotationException describing a invalid enummerator.
*
* @param string $attributeName
* @param string $annotationName
* @param string $context
* @param mixed $given
* @phpstan-param list<string> $available
*
* @return AnnotationException
*/
public static function enumeratorError($attributeName, $annotationName, $context, $available, $given)
{
return new self(sprintf(
'[Enum Error] Attribute "%s" of @%s declared on %s accepts only [%s], but got %s.',
$attributeName,
$annotationName,
$context,
implode(', ', $available),
is_object($given) ? get_class($given) : $given
));
}
/** @return AnnotationException */
public static function optimizerPlusSaveComments()
{
return new self(
'You have to enable opcache.save_comments=1 or zend_optimizerplus.save_comments=1.'
);
}
/** @return AnnotationException */
public static function optimizerPlusLoadComments()
{
return new self(
'You have to enable opcache.load_comments=1 or zend_optimizerplus.load_comments=1.'
);
}
}

View File

@@ -1,389 +0,0 @@
<?php
namespace Doctrine\Common\Annotations;
use Doctrine\Common\Annotations\Annotation\IgnoreAnnotation;
use Doctrine\Common\Annotations\Annotation\Target;
use ReflectionClass;
use ReflectionFunction;
use ReflectionMethod;
use ReflectionProperty;
use function array_merge;
use function class_exists;
use function extension_loaded;
use function ini_get;
/**
* A reader for docblock annotations.
*/
class AnnotationReader implements Reader
{
/**
* Global map for imports.
*
* @var array<string, class-string>
*/
private static $globalImports = [
'ignoreannotation' => Annotation\IgnoreAnnotation::class,
];
/**
* A list with annotations that are not causing exceptions when not resolved to an annotation class.
*
* The names are case sensitive.
*
* @var array<string, true>
*/
private static $globalIgnoredNames = ImplicitlyIgnoredAnnotationNames::LIST;
/**
* A list with annotations that are not causing exceptions when not resolved to an annotation class.
*
* The names are case sensitive.
*
* @var array<string, true>
*/
private static $globalIgnoredNamespaces = [];
/**
* Add a new annotation to the globally ignored annotation names with regard to exception handling.
*
* @param string $name
*/
public static function addGlobalIgnoredName($name)
{
self::$globalIgnoredNames[$name] = true;
}
/**
* Add a new annotation to the globally ignored annotation namespaces with regard to exception handling.
*
* @param string $namespace
*/
public static function addGlobalIgnoredNamespace($namespace)
{
self::$globalIgnoredNamespaces[$namespace] = true;
}
/**
* Annotations parser.
*
* @var DocParser
*/
private $parser;
/**
* Annotations parser used to collect parsing metadata.
*
* @var DocParser
*/
private $preParser;
/**
* PHP parser used to collect imports.
*
* @var PhpParser
*/
private $phpParser;
/**
* In-memory cache mechanism to store imported annotations per class.
*
* @psalm-var array<'class'|'function', array<string, array<string, class-string>>>
*/
private $imports = [];
/**
* In-memory cache mechanism to store ignored annotations per class.
*
* @psalm-var array<'class'|'function', array<string, array<string, true>>>
*/
private $ignoredAnnotationNames = [];
/**
* Initializes a new AnnotationReader.
*
* @throws AnnotationException
*/
public function __construct(?DocParser $parser = null)
{
if (
extension_loaded('Zend Optimizer+') && (ini_get('zend_optimizerplus.save_comments') === '0' ||
ini_get('opcache.save_comments') === '0')
) {
throw AnnotationException::optimizerPlusSaveComments();
}
if (extension_loaded('Zend OPcache') && ini_get('opcache.save_comments') === 0) {
throw AnnotationException::optimizerPlusSaveComments();
}
// Make sure that the IgnoreAnnotation annotation is loaded
class_exists(IgnoreAnnotation::class);
$this->parser = $parser ?: new DocParser();
$this->preParser = new DocParser();
$this->preParser->setImports(self::$globalImports);
$this->preParser->setIgnoreNotImportedAnnotations(true);
$this->preParser->setIgnoredAnnotationNames(self::$globalIgnoredNames);
$this->phpParser = new PhpParser();
}
/**
* {@inheritDoc}
*/
public function getClassAnnotations(ReflectionClass $class)
{
$this->parser->setTarget(Target::TARGET_CLASS);
$this->parser->setImports($this->getImports($class));
$this->parser->setIgnoredAnnotationNames($this->getIgnoredAnnotationNames($class));
$this->parser->setIgnoredAnnotationNamespaces(self::$globalIgnoredNamespaces);
return $this->parser->parse($class->getDocComment(), 'class ' . $class->getName());
}
/**
* {@inheritDoc}
*/
public function getClassAnnotation(ReflectionClass $class, $annotationName)
{
$annotations = $this->getClassAnnotations($class);
foreach ($annotations as $annotation) {
if ($annotation instanceof $annotationName) {
return $annotation;
}
}
return null;
}
/**
* {@inheritDoc}
*/
public function getPropertyAnnotations(ReflectionProperty $property)
{
$class = $property->getDeclaringClass();
$context = 'property ' . $class->getName() . '::$' . $property->getName();
$this->parser->setTarget(Target::TARGET_PROPERTY);
$this->parser->setImports($this->getPropertyImports($property));
$this->parser->setIgnoredAnnotationNames($this->getIgnoredAnnotationNames($class));
$this->parser->setIgnoredAnnotationNamespaces(self::$globalIgnoredNamespaces);
return $this->parser->parse($property->getDocComment(), $context);
}
/**
* {@inheritDoc}
*/
public function getPropertyAnnotation(ReflectionProperty $property, $annotationName)
{
$annotations = $this->getPropertyAnnotations($property);
foreach ($annotations as $annotation) {
if ($annotation instanceof $annotationName) {
return $annotation;
}
}
return null;
}
/**
* {@inheritDoc}
*/
public function getMethodAnnotations(ReflectionMethod $method)
{
$class = $method->getDeclaringClass();
$context = 'method ' . $class->getName() . '::' . $method->getName() . '()';
$this->parser->setTarget(Target::TARGET_METHOD);
$this->parser->setImports($this->getMethodImports($method));
$this->parser->setIgnoredAnnotationNames($this->getIgnoredAnnotationNames($class));
$this->parser->setIgnoredAnnotationNamespaces(self::$globalIgnoredNamespaces);
return $this->parser->parse($method->getDocComment(), $context);
}
/**
* {@inheritDoc}
*/
public function getMethodAnnotation(ReflectionMethod $method, $annotationName)
{
$annotations = $this->getMethodAnnotations($method);
foreach ($annotations as $annotation) {
if ($annotation instanceof $annotationName) {
return $annotation;
}
}
return null;
}
/**
* Gets the annotations applied to a function.
*
* @phpstan-return list<object> An array of Annotations.
*/
public function getFunctionAnnotations(ReflectionFunction $function): array
{
$context = 'function ' . $function->getName();
$this->parser->setTarget(Target::TARGET_FUNCTION);
$this->parser->setImports($this->getImports($function));
$this->parser->setIgnoredAnnotationNames($this->getIgnoredAnnotationNames($function));
$this->parser->setIgnoredAnnotationNamespaces(self::$globalIgnoredNamespaces);
return $this->parser->parse($function->getDocComment(), $context);
}
/**
* Gets a function annotation.
*
* @return object|null The Annotation or NULL, if the requested annotation does not exist.
*/
public function getFunctionAnnotation(ReflectionFunction $function, string $annotationName)
{
$annotations = $this->getFunctionAnnotations($function);
foreach ($annotations as $annotation) {
if ($annotation instanceof $annotationName) {
return $annotation;
}
}
return null;
}
/**
* Returns the ignored annotations for the given class or function.
*
* @param ReflectionClass|ReflectionFunction $reflection
*
* @return array<string, true>
*/
private function getIgnoredAnnotationNames($reflection): array
{
$type = $reflection instanceof ReflectionClass ? 'class' : 'function';
$name = $reflection->getName();
if (isset($this->ignoredAnnotationNames[$type][$name])) {
return $this->ignoredAnnotationNames[$type][$name];
}
$this->collectParsingMetadata($reflection);
return $this->ignoredAnnotationNames[$type][$name];
}
/**
* Retrieves imports for a class or a function.
*
* @param ReflectionClass|ReflectionFunction $reflection
*
* @return array<string, class-string>
*/
private function getImports($reflection): array
{
$type = $reflection instanceof ReflectionClass ? 'class' : 'function';
$name = $reflection->getName();
if (isset($this->imports[$type][$name])) {
return $this->imports[$type][$name];
}
$this->collectParsingMetadata($reflection);
return $this->imports[$type][$name];
}
/**
* Retrieves imports for methods.
*
* @return array<string, class-string>
*/
private function getMethodImports(ReflectionMethod $method)
{
$class = $method->getDeclaringClass();
$classImports = $this->getImports($class);
$traitImports = [];
foreach ($class->getTraits() as $trait) {
if (
! $trait->hasMethod($method->getName())
|| $trait->getFileName() !== $method->getFileName()
) {
continue;
}
$traitImports = array_merge($traitImports, $this->phpParser->parseUseStatements($trait));
}
return array_merge($classImports, $traitImports);
}
/**
* Retrieves imports for properties.
*
* @return array<string, class-string>
*/
private function getPropertyImports(ReflectionProperty $property)
{
$class = $property->getDeclaringClass();
$classImports = $this->getImports($class);
$traitImports = [];
foreach ($class->getTraits() as $trait) {
if (! $trait->hasProperty($property->getName())) {
continue;
}
$traitImports = array_merge($traitImports, $this->phpParser->parseUseStatements($trait));
}
return array_merge($classImports, $traitImports);
}
/**
* Collects parsing metadata for a given class or function.
*
* @param ReflectionClass|ReflectionFunction $reflection
*/
private function collectParsingMetadata($reflection): void
{
$type = $reflection instanceof ReflectionClass ? 'class' : 'function';
$name = $reflection->getName();
$ignoredAnnotationNames = self::$globalIgnoredNames;
$annotations = $this->preParser->parse($reflection->getDocComment(), $type . ' ' . $name);
foreach ($annotations as $annotation) {
if (! ($annotation instanceof IgnoreAnnotation)) {
continue;
}
foreach ($annotation->names as $annot) {
$ignoredAnnotationNames[$annot] = true;
}
}
$this->imports[$type][$name] = array_merge(
self::$globalImports,
$this->phpParser->parseUseStatements($reflection),
[
'__NAMESPACE__' => $reflection->getNamespaceName(),
'self' => $name,
]
);
$this->ignoredAnnotationNames[$type][$name] = $ignoredAnnotationNames;
}
}

View File

@@ -1,190 +0,0 @@
<?php
namespace Doctrine\Common\Annotations;
use function array_key_exists;
use function array_merge;
use function class_exists;
use function in_array;
use function is_file;
use function str_replace;
use function stream_resolve_include_path;
use function strpos;
use const DIRECTORY_SEPARATOR;
final class AnnotationRegistry
{
/**
* A map of namespaces to use for autoloading purposes based on a PSR-0 convention.
*
* Contains the namespace as key and an array of directories as value. If the value is NULL
* the include path is used for checking for the corresponding file.
*
* This autoloading mechanism does not utilize the PHP autoloading but implements autoloading on its own.
*
* @var string[][]|string[]|null[]
*/
private static $autoloadNamespaces = [];
/**
* A map of autoloader callables.
*
* @var callable[]
*/
private static $loaders = [];
/**
* An array of classes which cannot be found
*
* @var null[] indexed by class name
*/
private static $failedToAutoload = [];
/**
* Whenever registerFile() was used. Disables use of standard autoloader.
*
* @var bool
*/
private static $registerFileUsed = false;
public static function reset(): void
{
self::$autoloadNamespaces = [];
self::$loaders = [];
self::$failedToAutoload = [];
self::$registerFileUsed = false;
}
/**
* Registers file.
*
* @deprecated This method is deprecated and will be removed in
* doctrine/annotations 2.0. Annotations will be autoloaded in 2.0.
*/
public static function registerFile(string $file): void
{
self::$registerFileUsed = true;
require_once $file;
}
/**
* Adds a namespace with one or many directories to look for files or null for the include path.
*
* Loading of this namespaces will be done with a PSR-0 namespace loading algorithm.
*
* @deprecated This method is deprecated and will be removed in
* doctrine/annotations 2.0. Annotations will be autoloaded in 2.0.
*
* @phpstan-param string|list<string>|null $dirs
*/
public static function registerAutoloadNamespace(string $namespace, $dirs = null): void
{
self::$autoloadNamespaces[$namespace] = $dirs;
}
/**
* Registers multiple namespaces.
*
* Loading of this namespaces will be done with a PSR-0 namespace loading algorithm.
*
* @deprecated This method is deprecated and will be removed in
* doctrine/annotations 2.0. Annotations will be autoloaded in 2.0.
*
* @param string[][]|string[]|null[] $namespaces indexed by namespace name
*/
public static function registerAutoloadNamespaces(array $namespaces): void
{
self::$autoloadNamespaces = array_merge(self::$autoloadNamespaces, $namespaces);
}
/**
* Registers an autoloading callable for annotations, much like spl_autoload_register().
*
* NOTE: These class loaders HAVE to be silent when a class was not found!
* IMPORTANT: Loaders have to return true if they loaded a class that could contain the searched annotation class.
*
* @deprecated This method is deprecated and will be removed in
* doctrine/annotations 2.0. Annotations will be autoloaded in 2.0.
*/
public static function registerLoader(callable $callable): void
{
// Reset our static cache now that we have a new loader to work with
self::$failedToAutoload = [];
self::$loaders[] = $callable;
}
/**
* Registers an autoloading callable for annotations, if it is not already registered
*
* @deprecated This method is deprecated and will be removed in
* doctrine/annotations 2.0. Annotations will be autoloaded in 2.0.
*/
public static function registerUniqueLoader(callable $callable): void
{
if (in_array($callable, self::$loaders, true)) {
return;
}
self::registerLoader($callable);
}
/**
* Autoloads an annotation class silently.
*/
public static function loadAnnotationClass(string $class): bool
{
if (class_exists($class, false)) {
return true;
}
if (array_key_exists($class, self::$failedToAutoload)) {
return false;
}
foreach (self::$autoloadNamespaces as $namespace => $dirs) {
if (strpos($class, $namespace) !== 0) {
continue;
}
$file = str_replace('\\', DIRECTORY_SEPARATOR, $class) . '.php';
if ($dirs === null) {
$path = stream_resolve_include_path($file);
if ($path) {
require $path;
return true;
}
} else {
foreach ((array) $dirs as $dir) {
if (is_file($dir . DIRECTORY_SEPARATOR . $file)) {
require $dir . DIRECTORY_SEPARATOR . $file;
return true;
}
}
}
}
foreach (self::$loaders as $loader) {
if ($loader($class) === true) {
return true;
}
}
if (
self::$loaders === [] &&
self::$autoloadNamespaces === [] &&
self::$registerFileUsed === false &&
class_exists($class)
) {
return true;
}
self::$failedToAutoload[$class] = null;
return false;
}
}

View File

@@ -1,266 +0,0 @@
<?php
namespace Doctrine\Common\Annotations;
use Doctrine\Common\Cache\Cache;
use ReflectionClass;
use ReflectionMethod;
use ReflectionProperty;
use function array_map;
use function array_merge;
use function assert;
use function filemtime;
use function max;
use function time;
/**
* A cache aware annotation reader.
*
* @deprecated the CachedReader is deprecated and will be removed
* in version 2.0.0 of doctrine/annotations. Please use the
* {@see \Doctrine\Common\Annotations\PsrCachedReader} instead.
*/
final class CachedReader implements Reader
{
/** @var Reader */
private $delegate;
/** @var Cache */
private $cache;
/** @var bool */
private $debug;
/** @var array<string, array<object>> */
private $loadedAnnotations = [];
/** @var int[] */
private $loadedFilemtimes = [];
/** @param bool $debug */
public function __construct(Reader $reader, Cache $cache, $debug = false)
{
$this->delegate = $reader;
$this->cache = $cache;
$this->debug = (bool) $debug;
}
/**
* {@inheritDoc}
*/
public function getClassAnnotations(ReflectionClass $class)
{
$cacheKey = $class->getName();
if (isset($this->loadedAnnotations[$cacheKey])) {
return $this->loadedAnnotations[$cacheKey];
}
$annots = $this->fetchFromCache($cacheKey, $class);
if ($annots === false) {
$annots = $this->delegate->getClassAnnotations($class);
$this->saveToCache($cacheKey, $annots);
}
return $this->loadedAnnotations[$cacheKey] = $annots;
}
/**
* {@inheritDoc}
*/
public function getClassAnnotation(ReflectionClass $class, $annotationName)
{
foreach ($this->getClassAnnotations($class) as $annot) {
if ($annot instanceof $annotationName) {
return $annot;
}
}
return null;
}
/**
* {@inheritDoc}
*/
public function getPropertyAnnotations(ReflectionProperty $property)
{
$class = $property->getDeclaringClass();
$cacheKey = $class->getName() . '$' . $property->getName();
if (isset($this->loadedAnnotations[$cacheKey])) {
return $this->loadedAnnotations[$cacheKey];
}
$annots = $this->fetchFromCache($cacheKey, $class);
if ($annots === false) {
$annots = $this->delegate->getPropertyAnnotations($property);
$this->saveToCache($cacheKey, $annots);
}
return $this->loadedAnnotations[$cacheKey] = $annots;
}
/**
* {@inheritDoc}
*/
public function getPropertyAnnotation(ReflectionProperty $property, $annotationName)
{
foreach ($this->getPropertyAnnotations($property) as $annot) {
if ($annot instanceof $annotationName) {
return $annot;
}
}
return null;
}
/**
* {@inheritDoc}
*/
public function getMethodAnnotations(ReflectionMethod $method)
{
$class = $method->getDeclaringClass();
$cacheKey = $class->getName() . '#' . $method->getName();
if (isset($this->loadedAnnotations[$cacheKey])) {
return $this->loadedAnnotations[$cacheKey];
}
$annots = $this->fetchFromCache($cacheKey, $class);
if ($annots === false) {
$annots = $this->delegate->getMethodAnnotations($method);
$this->saveToCache($cacheKey, $annots);
}
return $this->loadedAnnotations[$cacheKey] = $annots;
}
/**
* {@inheritDoc}
*/
public function getMethodAnnotation(ReflectionMethod $method, $annotationName)
{
foreach ($this->getMethodAnnotations($method) as $annot) {
if ($annot instanceof $annotationName) {
return $annot;
}
}
return null;
}
/**
* Clears loaded annotations.
*
* @return void
*/
public function clearLoadedAnnotations()
{
$this->loadedAnnotations = [];
$this->loadedFilemtimes = [];
}
/**
* Fetches a value from the cache.
*
* @param string $cacheKey The cache key.
*
* @return mixed The cached value or false when the value is not in cache.
*/
private function fetchFromCache($cacheKey, ReflectionClass $class)
{
$data = $this->cache->fetch($cacheKey);
if ($data !== false) {
if (! $this->debug || $this->isCacheFresh($cacheKey, $class)) {
return $data;
}
}
return false;
}
/**
* Saves a value to the cache.
*
* @param string $cacheKey The cache key.
* @param mixed $value The value.
*
* @return void
*/
private function saveToCache($cacheKey, $value)
{
$this->cache->save($cacheKey, $value);
if (! $this->debug) {
return;
}
$this->cache->save('[C]' . $cacheKey, time());
}
/**
* Checks if the cache is fresh.
*
* @param string $cacheKey
*
* @return bool
*/
private function isCacheFresh($cacheKey, ReflectionClass $class)
{
$lastModification = $this->getLastModification($class);
if ($lastModification === 0) {
return true;
}
return $this->cache->fetch('[C]' . $cacheKey) >= $lastModification;
}
/**
* Returns the time the class was last modified, testing traits and parents
*/
private function getLastModification(ReflectionClass $class): int
{
$filename = $class->getFileName();
if (isset($this->loadedFilemtimes[$filename])) {
return $this->loadedFilemtimes[$filename];
}
$parent = $class->getParentClass();
$lastModification = max(array_merge(
[$filename ? filemtime($filename) : 0],
array_map(function (ReflectionClass $reflectionTrait): int {
return $this->getTraitLastModificationTime($reflectionTrait);
}, $class->getTraits()),
array_map(function (ReflectionClass $class): int {
return $this->getLastModification($class);
}, $class->getInterfaces()),
$parent ? [$this->getLastModification($parent)] : []
));
assert($lastModification !== false);
return $this->loadedFilemtimes[$filename] = $lastModification;
}
private function getTraitLastModificationTime(ReflectionClass $reflectionTrait): int
{
$fileName = $reflectionTrait->getFileName();
if (isset($this->loadedFilemtimes[$fileName])) {
return $this->loadedFilemtimes[$fileName];
}
$lastModificationTime = max(array_merge(
[$fileName ? filemtime($fileName) : 0],
array_map(function (ReflectionClass $reflectionTrait): int {
return $this->getTraitLastModificationTime($reflectionTrait);
}, $reflectionTrait->getTraits())
));
assert($lastModificationTime !== false);
return $this->loadedFilemtimes[$fileName] = $lastModificationTime;
}
}

View File

@@ -1,143 +0,0 @@
<?php
namespace Doctrine\Common\Annotations;
use Doctrine\Common\Lexer\AbstractLexer;
use function ctype_alpha;
use function is_numeric;
use function str_replace;
use function stripos;
use function strlen;
use function strpos;
use function strtolower;
use function substr;
/**
* Simple lexer for docblock annotations.
*
* @template-extends AbstractLexer<DocLexer::T_*, string>
*/
final class DocLexer extends AbstractLexer
{
public const T_NONE = 1;
public const T_INTEGER = 2;
public const T_STRING = 3;
public const T_FLOAT = 4;
// All tokens that are also identifiers should be >= 100
public const T_IDENTIFIER = 100;
public const T_AT = 101;
public const T_CLOSE_CURLY_BRACES = 102;
public const T_CLOSE_PARENTHESIS = 103;
public const T_COMMA = 104;
public const T_EQUALS = 105;
public const T_FALSE = 106;
public const T_NAMESPACE_SEPARATOR = 107;
public const T_OPEN_CURLY_BRACES = 108;
public const T_OPEN_PARENTHESIS = 109;
public const T_TRUE = 110;
public const T_NULL = 111;
public const T_COLON = 112;
public const T_MINUS = 113;
/** @var array<string, self::T*> */
protected $noCase = [
'@' => self::T_AT,
',' => self::T_COMMA,
'(' => self::T_OPEN_PARENTHESIS,
')' => self::T_CLOSE_PARENTHESIS,
'{' => self::T_OPEN_CURLY_BRACES,
'}' => self::T_CLOSE_CURLY_BRACES,
'=' => self::T_EQUALS,
':' => self::T_COLON,
'-' => self::T_MINUS,
'\\' => self::T_NAMESPACE_SEPARATOR,
];
/** @var array<string, self::T*> */
protected $withCase = [
'true' => self::T_TRUE,
'false' => self::T_FALSE,
'null' => self::T_NULL,
];
/**
* Whether the next token starts immediately, or if there were
* non-captured symbols before that
*/
public function nextTokenIsAdjacent(): bool
{
return $this->token === null
|| ($this->lookahead !== null
&& ($this->lookahead['position'] - $this->token['position']) === strlen($this->token['value']));
}
/**
* {@inheritdoc}
*/
protected function getCatchablePatterns()
{
return [
'[a-z_\\\][a-z0-9_\:\\\]*[a-z_][a-z0-9_]*',
'(?:[+-]?[0-9]+(?:[\.][0-9]+)*)(?:[eE][+-]?[0-9]+)?',
'"(?:""|[^"])*+"',
];
}
/**
* {@inheritdoc}
*/
protected function getNonCatchablePatterns()
{
return ['\s+', '\*+', '(.)'];
}
/**
* {@inheritdoc}
*/
protected function getType(&$value)
{
$type = self::T_NONE;
if ($value[0] === '"') {
$value = str_replace('""', '"', substr($value, 1, strlen($value) - 2));
return self::T_STRING;
}
if (isset($this->noCase[$value])) {
return $this->noCase[$value];
}
if ($value[0] === '_' || $value[0] === '\\' || ctype_alpha($value[0])) {
return self::T_IDENTIFIER;
}
$lowerValue = strtolower($value);
if (isset($this->withCase[$lowerValue])) {
return $this->withCase[$lowerValue];
}
// Checking numeric value
if (is_numeric($value)) {
return strpos($value, '.') !== false || stripos($value, 'e') !== false
? self::T_FLOAT : self::T_INTEGER;
}
return $type;
}
/** @return array{value: int|string, type:self::T_*|null, position:int} */
public function peek(): ?array
{
$token = parent::peek();
if ($token === null) {
return null;
}
return (array) $token;
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,315 +0,0 @@
<?php
namespace Doctrine\Common\Annotations;
use InvalidArgumentException;
use ReflectionClass;
use ReflectionMethod;
use ReflectionProperty;
use RuntimeException;
use function chmod;
use function file_put_contents;
use function filemtime;
use function gettype;
use function is_dir;
use function is_file;
use function is_int;
use function is_writable;
use function mkdir;
use function rename;
use function rtrim;
use function serialize;
use function sha1;
use function sprintf;
use function strtr;
use function tempnam;
use function uniqid;
use function unlink;
use function var_export;
/**
* File cache reader for annotations.
*
* @deprecated the FileCacheReader is deprecated and will be removed
* in version 2.0.0 of doctrine/annotations. Please use the
* {@see \Doctrine\Common\Annotations\PsrCachedReader} instead.
*/
class FileCacheReader implements Reader
{
/** @var Reader */
private $reader;
/** @var string */
private $dir;
/** @var bool */
private $debug;
/** @phpstan-var array<string, list<object>> */
private $loadedAnnotations = [];
/** @var array<string, string> */
private $classNameHashes = [];
/** @var int */
private $umask;
/**
* @param string $cacheDir
* @param bool $debug
* @param int $umask
*
* @throws InvalidArgumentException
*/
public function __construct(Reader $reader, $cacheDir, $debug = false, $umask = 0002)
{
if (! is_int($umask)) {
throw new InvalidArgumentException(sprintf(
'The parameter umask must be an integer, was: %s',
gettype($umask)
));
}
$this->reader = $reader;
$this->umask = $umask;
if (! is_dir($cacheDir) && ! @mkdir($cacheDir, 0777 & (~$this->umask), true)) {
throw new InvalidArgumentException(sprintf(
'The directory "%s" does not exist and could not be created.',
$cacheDir
));
}
$this->dir = rtrim($cacheDir, '\\/');
$this->debug = $debug;
}
/**
* {@inheritDoc}
*/
public function getClassAnnotations(ReflectionClass $class)
{
if (! isset($this->classNameHashes[$class->name])) {
$this->classNameHashes[$class->name] = sha1($class->name);
}
$key = $this->classNameHashes[$class->name];
if (isset($this->loadedAnnotations[$key])) {
return $this->loadedAnnotations[$key];
}
$path = $this->dir . '/' . strtr($key, '\\', '-') . '.cache.php';
if (! is_file($path)) {
$annot = $this->reader->getClassAnnotations($class);
$this->saveCacheFile($path, $annot);
return $this->loadedAnnotations[$key] = $annot;
}
$filename = $class->getFilename();
if (
$this->debug
&& $filename !== false
&& filemtime($path) < filemtime($filename)
) {
@unlink($path);
$annot = $this->reader->getClassAnnotations($class);
$this->saveCacheFile($path, $annot);
return $this->loadedAnnotations[$key] = $annot;
}
return $this->loadedAnnotations[$key] = include $path;
}
/**
* {@inheritDoc}
*/
public function getPropertyAnnotations(ReflectionProperty $property)
{
$class = $property->getDeclaringClass();
if (! isset($this->classNameHashes[$class->name])) {
$this->classNameHashes[$class->name] = sha1($class->name);
}
$key = $this->classNameHashes[$class->name] . '$' . $property->getName();
if (isset($this->loadedAnnotations[$key])) {
return $this->loadedAnnotations[$key];
}
$path = $this->dir . '/' . strtr($key, '\\', '-') . '.cache.php';
if (! is_file($path)) {
$annot = $this->reader->getPropertyAnnotations($property);
$this->saveCacheFile($path, $annot);
return $this->loadedAnnotations[$key] = $annot;
}
$filename = $class->getFilename();
if (
$this->debug
&& $filename !== false
&& filemtime($path) < filemtime($filename)
) {
@unlink($path);
$annot = $this->reader->getPropertyAnnotations($property);
$this->saveCacheFile($path, $annot);
return $this->loadedAnnotations[$key] = $annot;
}
return $this->loadedAnnotations[$key] = include $path;
}
/**
* {@inheritDoc}
*/
public function getMethodAnnotations(ReflectionMethod $method)
{
$class = $method->getDeclaringClass();
if (! isset($this->classNameHashes[$class->name])) {
$this->classNameHashes[$class->name] = sha1($class->name);
}
$key = $this->classNameHashes[$class->name] . '#' . $method->getName();
if (isset($this->loadedAnnotations[$key])) {
return $this->loadedAnnotations[$key];
}
$path = $this->dir . '/' . strtr($key, '\\', '-') . '.cache.php';
if (! is_file($path)) {
$annot = $this->reader->getMethodAnnotations($method);
$this->saveCacheFile($path, $annot);
return $this->loadedAnnotations[$key] = $annot;
}
$filename = $class->getFilename();
if (
$this->debug
&& $filename !== false
&& filemtime($path) < filemtime($filename)
) {
@unlink($path);
$annot = $this->reader->getMethodAnnotations($method);
$this->saveCacheFile($path, $annot);
return $this->loadedAnnotations[$key] = $annot;
}
return $this->loadedAnnotations[$key] = include $path;
}
/**
* Saves the cache file.
*
* @param string $path
* @param mixed $data
*
* @return void
*/
private function saveCacheFile($path, $data)
{
if (! is_writable($this->dir)) {
throw new InvalidArgumentException(sprintf(
<<<'EXCEPTION'
The directory "%s" is not writable. Both the webserver and the console user need access.
You can manage access rights for multiple users with "chmod +a".
If your system does not support this, check out the acl package.,
EXCEPTION
,
$this->dir
));
}
$tempfile = tempnam($this->dir, uniqid('', true));
if ($tempfile === false) {
throw new RuntimeException(sprintf('Unable to create tempfile in directory: %s', $this->dir));
}
@chmod($tempfile, 0666 & (~$this->umask));
$written = file_put_contents(
$tempfile,
'<?php return unserialize(' . var_export(serialize($data), true) . ');'
);
if ($written === false) {
throw new RuntimeException(sprintf('Unable to write cached file to: %s', $tempfile));
}
@chmod($tempfile, 0666 & (~$this->umask));
if (rename($tempfile, $path) === false) {
@unlink($tempfile);
throw new RuntimeException(sprintf('Unable to rename %s to %s', $tempfile, $path));
}
}
/**
* {@inheritDoc}
*/
public function getClassAnnotation(ReflectionClass $class, $annotationName)
{
$annotations = $this->getClassAnnotations($class);
foreach ($annotations as $annotation) {
if ($annotation instanceof $annotationName) {
return $annotation;
}
}
return null;
}
/**
* {@inheritDoc}
*/
public function getMethodAnnotation(ReflectionMethod $method, $annotationName)
{
$annotations = $this->getMethodAnnotations($method);
foreach ($annotations as $annotation) {
if ($annotation instanceof $annotationName) {
return $annotation;
}
}
return null;
}
/**
* {@inheritDoc}
*/
public function getPropertyAnnotation(ReflectionProperty $property, $annotationName)
{
$annotations = $this->getPropertyAnnotations($property);
foreach ($annotations as $annotation) {
if ($annotation instanceof $annotationName) {
return $annotation;
}
}
return null;
}
/**
* Clears loaded annotations.
*
* @return void
*/
public function clearLoadedAnnotations()
{
$this->loadedAnnotations = [];
}
}

View File

@@ -1,178 +0,0 @@
<?php
declare(strict_types=1);
namespace Doctrine\Common\Annotations;
/**
* A list of annotations that are implicitly ignored during the parsing process.
*
* All names are case sensitive.
*/
final class ImplicitlyIgnoredAnnotationNames
{
private const Reserved = [
'Annotation' => true,
'Attribute' => true,
'Attributes' => true,
/* Can we enable this? 'Enum' => true, */
'Required' => true,
'Target' => true,
'NamedArgumentConstructor' => true,
];
private const WidelyUsedNonStandard = [
'fix' => true,
'fixme' => true,
'override' => true,
];
private const PhpDocumentor1 = [
'abstract' => true,
'access' => true,
'code' => true,
'deprec' => true,
'endcode' => true,
'exception' => true,
'final' => true,
'ingroup' => true,
'inheritdoc' => true,
'inheritDoc' => true,
'magic' => true,
'name' => true,
'private' => true,
'static' => true,
'staticvar' => true,
'staticVar' => true,
'toc' => true,
'tutorial' => true,
'throw' => true,
];
private const PhpDocumentor2 = [
'api' => true,
'author' => true,
'category' => true,
'copyright' => true,
'deprecated' => true,
'example' => true,
'filesource' => true,
'global' => true,
'ignore' => true,
/* Can we enable this? 'index' => true, */
'internal' => true,
'license' => true,
'link' => true,
'method' => true,
'package' => true,
'param' => true,
'property' => true,
'property-read' => true,
'property-write' => true,
'return' => true,
'see' => true,
'since' => true,
'source' => true,
'subpackage' => true,
'throws' => true,
'todo' => true,
'TODO' => true,
'usedby' => true,
'uses' => true,
'var' => true,
'version' => true,
];
private const PHPUnit = [
'author' => true,
'after' => true,
'afterClass' => true,
'backupGlobals' => true,
'backupStaticAttributes' => true,
'before' => true,
'beforeClass' => true,
'codeCoverageIgnore' => true,
'codeCoverageIgnoreStart' => true,
'codeCoverageIgnoreEnd' => true,
'covers' => true,
'coversDefaultClass' => true,
'coversNothing' => true,
'dataProvider' => true,
'depends' => true,
'doesNotPerformAssertions' => true,
'expectedException' => true,
'expectedExceptionCode' => true,
'expectedExceptionMessage' => true,
'expectedExceptionMessageRegExp' => true,
'group' => true,
'large' => true,
'medium' => true,
'preserveGlobalState' => true,
'requires' => true,
'runTestsInSeparateProcesses' => true,
'runInSeparateProcess' => true,
'small' => true,
'test' => true,
'testdox' => true,
'testWith' => true,
'ticket' => true,
'uses' => true,
];
private const PhpCheckStyle = ['SuppressWarnings' => true];
private const PhpStorm = ['noinspection' => true];
private const PEAR = ['package_version' => true];
private const PlainUML = [
'startuml' => true,
'enduml' => true,
];
private const Symfony = ['experimental' => true];
private const PhpCodeSniffer = [
'codingStandardsIgnoreStart' => true,
'codingStandardsIgnoreEnd' => true,
];
private const SlevomatCodingStandard = ['phpcsSuppress' => true];
private const Phan = ['suppress' => true];
private const Rector = ['noRector' => true];
private const StaticAnalysis = [
// PHPStan, Psalm
'extends' => true,
'implements' => true,
'readonly' => true,
'template' => true,
'use' => true,
// Psalm
'pure' => true,
'immutable' => true,
];
public const LIST = self::Reserved
+ self::WidelyUsedNonStandard
+ self::PhpDocumentor1
+ self::PhpDocumentor2
+ self::PHPUnit
+ self::PhpCheckStyle
+ self::PhpStorm
+ self::PEAR
+ self::PlainUML
+ self::Symfony
+ self::SlevomatCodingStandard
+ self::PhpCodeSniffer
+ self::Phan
+ self::Rector
+ self::StaticAnalysis;
private function __construct()
{
}
}

View File

@@ -1,100 +0,0 @@
<?php
namespace Doctrine\Common\Annotations;
use ReflectionClass;
use ReflectionMethod;
use ReflectionProperty;
use function call_user_func_array;
use function get_class;
/**
* Allows the reader to be used in-place of Doctrine's reader.
*/
class IndexedReader implements Reader
{
/** @var Reader */
private $delegate;
public function __construct(Reader $reader)
{
$this->delegate = $reader;
}
/**
* {@inheritDoc}
*/
public function getClassAnnotations(ReflectionClass $class)
{
$annotations = [];
foreach ($this->delegate->getClassAnnotations($class) as $annot) {
$annotations[get_class($annot)] = $annot;
}
return $annotations;
}
/**
* {@inheritDoc}
*/
public function getClassAnnotation(ReflectionClass $class, $annotationName)
{
return $this->delegate->getClassAnnotation($class, $annotationName);
}
/**
* {@inheritDoc}
*/
public function getMethodAnnotations(ReflectionMethod $method)
{
$annotations = [];
foreach ($this->delegate->getMethodAnnotations($method) as $annot) {
$annotations[get_class($annot)] = $annot;
}
return $annotations;
}
/**
* {@inheritDoc}
*/
public function getMethodAnnotation(ReflectionMethod $method, $annotationName)
{
return $this->delegate->getMethodAnnotation($method, $annotationName);
}
/**
* {@inheritDoc}
*/
public function getPropertyAnnotations(ReflectionProperty $property)
{
$annotations = [];
foreach ($this->delegate->getPropertyAnnotations($property) as $annot) {
$annotations[get_class($annot)] = $annot;
}
return $annotations;
}
/**
* {@inheritDoc}
*/
public function getPropertyAnnotation(ReflectionProperty $property, $annotationName)
{
return $this->delegate->getPropertyAnnotation($property, $annotationName);
}
/**
* Proxies all methods to the delegate.
*
* @param string $method
* @param mixed[] $args
*
* @return mixed
*/
public function __call($method, $args)
{
return call_user_func_array([$this->delegate, $method], $args);
}
}

View File

@@ -1,14 +0,0 @@
<?php
namespace Doctrine\Common\Annotations;
/**
* Marker interface for PHP7/PHP8 compatible support
* for named arguments (and constructor property promotion).
*
* @deprecated Implementing this interface is deprecated
* Use the Annotation @NamedArgumentConstructor instead
*/
interface NamedArgumentConstructorAnnotation
{
}

View File

@@ -1,92 +0,0 @@
<?php
namespace Doctrine\Common\Annotations;
use ReflectionClass;
use ReflectionFunction;
use SplFileObject;
use function is_file;
use function method_exists;
use function preg_quote;
use function preg_replace;
/**
* Parses a file for namespaces/use/class declarations.
*/
final class PhpParser
{
/**
* Parses a class.
*
* @deprecated use parseUseStatements instead
*
* @param ReflectionClass $class A <code>ReflectionClass</code> object.
*
* @return array<string, class-string> A list with use statements in the form (Alias => FQN).
*/
public function parseClass(ReflectionClass $class)
{
return $this->parseUseStatements($class);
}
/**
* Parse a class or function for use statements.
*
* @param ReflectionClass|ReflectionFunction $reflection
*
* @psalm-return array<string, string> a list with use statements in the form (Alias => FQN).
*/
public function parseUseStatements($reflection): array
{
if (method_exists($reflection, 'getUseStatements')) {
return $reflection->getUseStatements();
}
$filename = $reflection->getFileName();
if ($filename === false) {
return [];
}
$content = $this->getFileContent($filename, $reflection->getStartLine());
if ($content === null) {
return [];
}
$namespace = preg_quote($reflection->getNamespaceName());
$content = preg_replace('/^.*?(\bnamespace\s+' . $namespace . '\s*[;{].*)$/s', '\\1', $content);
$tokenizer = new TokenParser('<?php ' . $content);
return $tokenizer->parseUseStatements($reflection->getNamespaceName());
}
/**
* Gets the content of the file right up to the given line number.
*
* @param string $filename The name of the file to load.
* @param int $lineNumber The number of lines to read from file.
*
* @return string|null The content of the file or null if the file does not exist.
*/
private function getFileContent($filename, $lineNumber)
{
if (! is_file($filename)) {
return null;
}
$content = '';
$lineCnt = 0;
$file = new SplFileObject($filename);
while (! $file->eof()) {
if ($lineCnt++ === $lineNumber) {
break;
}
$content .= $file->fgets();
}
return $content;
}
}

View File

@@ -1,232 +0,0 @@
<?php
namespace Doctrine\Common\Annotations;
use Psr\Cache\CacheItemPoolInterface;
use ReflectionClass;
use ReflectionMethod;
use ReflectionProperty;
use Reflector;
use function array_map;
use function array_merge;
use function assert;
use function filemtime;
use function max;
use function rawurlencode;
use function time;
/**
* A cache aware annotation reader.
*/
final class PsrCachedReader implements Reader
{
/** @var Reader */
private $delegate;
/** @var CacheItemPoolInterface */
private $cache;
/** @var bool */
private $debug;
/** @var array<string, array<object>> */
private $loadedAnnotations = [];
/** @var int[] */
private $loadedFilemtimes = [];
public function __construct(Reader $reader, CacheItemPoolInterface $cache, bool $debug = false)
{
$this->delegate = $reader;
$this->cache = $cache;
$this->debug = (bool) $debug;
}
/**
* {@inheritDoc}
*/
public function getClassAnnotations(ReflectionClass $class)
{
$cacheKey = $class->getName();
if (isset($this->loadedAnnotations[$cacheKey])) {
return $this->loadedAnnotations[$cacheKey];
}
$annots = $this->fetchFromCache($cacheKey, $class, 'getClassAnnotations', $class);
return $this->loadedAnnotations[$cacheKey] = $annots;
}
/**
* {@inheritDoc}
*/
public function getClassAnnotation(ReflectionClass $class, $annotationName)
{
foreach ($this->getClassAnnotations($class) as $annot) {
if ($annot instanceof $annotationName) {
return $annot;
}
}
return null;
}
/**
* {@inheritDoc}
*/
public function getPropertyAnnotations(ReflectionProperty $property)
{
$class = $property->getDeclaringClass();
$cacheKey = $class->getName() . '$' . $property->getName();
if (isset($this->loadedAnnotations[$cacheKey])) {
return $this->loadedAnnotations[$cacheKey];
}
$annots = $this->fetchFromCache($cacheKey, $class, 'getPropertyAnnotations', $property);
return $this->loadedAnnotations[$cacheKey] = $annots;
}
/**
* {@inheritDoc}
*/
public function getPropertyAnnotation(ReflectionProperty $property, $annotationName)
{
foreach ($this->getPropertyAnnotations($property) as $annot) {
if ($annot instanceof $annotationName) {
return $annot;
}
}
return null;
}
/**
* {@inheritDoc}
*/
public function getMethodAnnotations(ReflectionMethod $method)
{
$class = $method->getDeclaringClass();
$cacheKey = $class->getName() . '#' . $method->getName();
if (isset($this->loadedAnnotations[$cacheKey])) {
return $this->loadedAnnotations[$cacheKey];
}
$annots = $this->fetchFromCache($cacheKey, $class, 'getMethodAnnotations', $method);
return $this->loadedAnnotations[$cacheKey] = $annots;
}
/**
* {@inheritDoc}
*/
public function getMethodAnnotation(ReflectionMethod $method, $annotationName)
{
foreach ($this->getMethodAnnotations($method) as $annot) {
if ($annot instanceof $annotationName) {
return $annot;
}
}
return null;
}
public function clearLoadedAnnotations(): void
{
$this->loadedAnnotations = [];
$this->loadedFilemtimes = [];
}
/** @return mixed[] */
private function fetchFromCache(
string $cacheKey,
ReflectionClass $class,
string $method,
Reflector $reflector
): array {
$cacheKey = rawurlencode($cacheKey);
$item = $this->cache->getItem($cacheKey);
if (($this->debug && ! $this->refresh($cacheKey, $class)) || ! $item->isHit()) {
$this->cache->save($item->set($this->delegate->{$method}($reflector)));
}
return $item->get();
}
/**
* Used in debug mode to check if the cache is fresh.
*
* @return bool Returns true if the cache was fresh, or false if the class
* being read was modified since writing to the cache.
*/
private function refresh(string $cacheKey, ReflectionClass $class): bool
{
$lastModification = $this->getLastModification($class);
if ($lastModification === 0) {
return true;
}
$item = $this->cache->getItem('[C]' . $cacheKey);
if ($item->isHit() && $item->get() >= $lastModification) {
return true;
}
$this->cache->save($item->set(time()));
return false;
}
/**
* Returns the time the class was last modified, testing traits and parents
*/
private function getLastModification(ReflectionClass $class): int
{
$filename = $class->getFileName();
if (isset($this->loadedFilemtimes[$filename])) {
return $this->loadedFilemtimes[$filename];
}
$parent = $class->getParentClass();
$lastModification = max(array_merge(
[$filename ? filemtime($filename) : 0],
array_map(function (ReflectionClass $reflectionTrait): int {
return $this->getTraitLastModificationTime($reflectionTrait);
}, $class->getTraits()),
array_map(function (ReflectionClass $class): int {
return $this->getLastModification($class);
}, $class->getInterfaces()),
$parent ? [$this->getLastModification($parent)] : []
));
assert($lastModification !== false);
return $this->loadedFilemtimes[$filename] = $lastModification;
}
private function getTraitLastModificationTime(ReflectionClass $reflectionTrait): int
{
$fileName = $reflectionTrait->getFileName();
if (isset($this->loadedFilemtimes[$fileName])) {
return $this->loadedFilemtimes[$fileName];
}
$lastModificationTime = max(array_merge(
[$fileName ? filemtime($fileName) : 0],
array_map(function (ReflectionClass $reflectionTrait): int {
return $this->getTraitLastModificationTime($reflectionTrait);
}, $reflectionTrait->getTraits())
));
assert($lastModificationTime !== false);
return $this->loadedFilemtimes[$fileName] = $lastModificationTime;
}
}

View File

@@ -1,80 +0,0 @@
<?php
namespace Doctrine\Common\Annotations;
use ReflectionClass;
use ReflectionMethod;
use ReflectionProperty;
/**
* Interface for annotation readers.
*/
interface Reader
{
/**
* Gets the annotations applied to a class.
*
* @param ReflectionClass $class The ReflectionClass of the class from which
* the class annotations should be read.
*
* @return array<object> An array of Annotations.
*/
public function getClassAnnotations(ReflectionClass $class);
/**
* Gets a class annotation.
*
* @param ReflectionClass $class The ReflectionClass of the class from which
* the class annotations should be read.
* @param class-string<T> $annotationName The name of the annotation.
*
* @return T|null The Annotation or NULL, if the requested annotation does not exist.
*
* @template T
*/
public function getClassAnnotation(ReflectionClass $class, $annotationName);
/**
* Gets the annotations applied to a method.
*
* @param ReflectionMethod $method The ReflectionMethod of the method from which
* the annotations should be read.
*
* @return array<object> An array of Annotations.
*/
public function getMethodAnnotations(ReflectionMethod $method);
/**
* Gets a method annotation.
*
* @param ReflectionMethod $method The ReflectionMethod to read the annotations from.
* @param class-string<T> $annotationName The name of the annotation.
*
* @return T|null The Annotation or NULL, if the requested annotation does not exist.
*
* @template T
*/
public function getMethodAnnotation(ReflectionMethod $method, $annotationName);
/**
* Gets the annotations applied to a property.
*
* @param ReflectionProperty $property The ReflectionProperty of the property
* from which the annotations should be read.
*
* @return array<object> An array of Annotations.
*/
public function getPropertyAnnotations(ReflectionProperty $property);
/**
* Gets a property annotation.
*
* @param ReflectionProperty $property The ReflectionProperty to read the annotations from.
* @param class-string<T> $annotationName The name of the annotation.
*
* @return T|null The Annotation or NULL, if the requested annotation does not exist.
*
* @template T
*/
public function getPropertyAnnotation(ReflectionProperty $property, $annotationName);
}

View File

@@ -1,114 +0,0 @@
<?php
namespace Doctrine\Common\Annotations;
use ReflectionClass;
use ReflectionMethod;
use ReflectionProperty;
/**
* Simple Annotation Reader.
*
* This annotation reader is intended to be used in projects where you have
* full-control over all annotations that are available.
*
* @deprecated Deprecated in favour of using AnnotationReader
*/
class SimpleAnnotationReader implements Reader
{
/** @var DocParser */
private $parser;
/**
* Initializes a new SimpleAnnotationReader.
*/
public function __construct()
{
$this->parser = new DocParser();
$this->parser->setIgnoreNotImportedAnnotations(true);
}
/**
* Adds a namespace in which we will look for annotations.
*
* @param string $namespace
*
* @return void
*/
public function addNamespace($namespace)
{
$this->parser->addNamespace($namespace);
}
/**
* {@inheritDoc}
*/
public function getClassAnnotations(ReflectionClass $class)
{
return $this->parser->parse($class->getDocComment(), 'class ' . $class->getName());
}
/**
* {@inheritDoc}
*/
public function getMethodAnnotations(ReflectionMethod $method)
{
return $this->parser->parse(
$method->getDocComment(),
'method ' . $method->getDeclaringClass()->name . '::' . $method->getName() . '()'
);
}
/**
* {@inheritDoc}
*/
public function getPropertyAnnotations(ReflectionProperty $property)
{
return $this->parser->parse(
$property->getDocComment(),
'property ' . $property->getDeclaringClass()->name . '::$' . $property->getName()
);
}
/**
* {@inheritDoc}
*/
public function getClassAnnotation(ReflectionClass $class, $annotationName)
{
foreach ($this->getClassAnnotations($class) as $annot) {
if ($annot instanceof $annotationName) {
return $annot;
}
}
return null;
}
/**
* {@inheritDoc}
*/
public function getMethodAnnotation(ReflectionMethod $method, $annotationName)
{
foreach ($this->getMethodAnnotations($method) as $annot) {
if ($annot instanceof $annotationName) {
return $annot;
}
}
return null;
}
/**
* {@inheritDoc}
*/
public function getPropertyAnnotation(ReflectionProperty $property, $annotationName)
{
foreach ($this->getPropertyAnnotations($property) as $annot) {
if ($annot instanceof $annotationName) {
return $annot;
}
}
return null;
}
}

View File

@@ -1,206 +0,0 @@
<?php
namespace Doctrine\Common\Annotations;
use function array_merge;
use function count;
use function explode;
use function strtolower;
use function token_get_all;
use const PHP_VERSION_ID;
use const T_AS;
use const T_COMMENT;
use const T_DOC_COMMENT;
use const T_NAME_FULLY_QUALIFIED;
use const T_NAME_QUALIFIED;
use const T_NAMESPACE;
use const T_NS_SEPARATOR;
use const T_STRING;
use const T_USE;
use const T_WHITESPACE;
/**
* Parses a file for namespaces/use/class declarations.
*/
class TokenParser
{
/**
* The token list.
*
* @phpstan-var list<mixed[]>
*/
private $tokens;
/**
* The number of tokens.
*
* @var int
*/
private $numTokens;
/**
* The current array pointer.
*
* @var int
*/
private $pointer = 0;
/** @param string $contents */
public function __construct($contents)
{
$this->tokens = token_get_all($contents);
// The PHP parser sets internal compiler globals for certain things. Annoyingly, the last docblock comment it
// saw gets stored in doc_comment. When it comes to compile the next thing to be include()d this stored
// doc_comment becomes owned by the first thing the compiler sees in the file that it considers might have a
// docblock. If the first thing in the file is a class without a doc block this would cause calls to
// getDocBlock() on said class to return our long lost doc_comment. Argh.
// To workaround, cause the parser to parse an empty docblock. Sure getDocBlock() will return this, but at least
// it's harmless to us.
token_get_all("<?php\n/**\n *\n */");
$this->numTokens = count($this->tokens);
}
/**
* Gets the next non whitespace and non comment token.
*
* @param bool $docCommentIsComment If TRUE then a doc comment is considered a comment and skipped.
* If FALSE then only whitespace and normal comments are skipped.
*
* @return mixed[]|string|null The token if exists, null otherwise.
*/
public function next($docCommentIsComment = true)
{
for ($i = $this->pointer; $i < $this->numTokens; $i++) {
$this->pointer++;
if (
$this->tokens[$i][0] === T_WHITESPACE ||
$this->tokens[$i][0] === T_COMMENT ||
($docCommentIsComment && $this->tokens[$i][0] === T_DOC_COMMENT)
) {
continue;
}
return $this->tokens[$i];
}
return null;
}
/**
* Parses a single use statement.
*
* @return array<string, string> A list with all found class names for a use statement.
*/
public function parseUseStatement()
{
$groupRoot = '';
$class = '';
$alias = '';
$statements = [];
$explicitAlias = false;
while (($token = $this->next())) {
if (! $explicitAlias && $token[0] === T_STRING) {
$class .= $token[1];
$alias = $token[1];
} elseif ($explicitAlias && $token[0] === T_STRING) {
$alias = $token[1];
} elseif (
PHP_VERSION_ID >= 80000 &&
($token[0] === T_NAME_QUALIFIED || $token[0] === T_NAME_FULLY_QUALIFIED)
) {
$class .= $token[1];
$classSplit = explode('\\', $token[1]);
$alias = $classSplit[count($classSplit) - 1];
} elseif ($token[0] === T_NS_SEPARATOR) {
$class .= '\\';
$alias = '';
} elseif ($token[0] === T_AS) {
$explicitAlias = true;
$alias = '';
} elseif ($token === ',') {
$statements[strtolower($alias)] = $groupRoot . $class;
$class = '';
$alias = '';
$explicitAlias = false;
} elseif ($token === ';') {
$statements[strtolower($alias)] = $groupRoot . $class;
break;
} elseif ($token === '{') {
$groupRoot = $class;
$class = '';
} elseif ($token === '}') {
continue;
} else {
break;
}
}
return $statements;
}
/**
* Gets all use statements.
*
* @param string $namespaceName The namespace name of the reflected class.
*
* @return array<string, string> A list with all found use statements.
*/
public function parseUseStatements($namespaceName)
{
$statements = [];
while (($token = $this->next())) {
if ($token[0] === T_USE) {
$statements = array_merge($statements, $this->parseUseStatement());
continue;
}
if ($token[0] !== T_NAMESPACE || $this->parseNamespace() !== $namespaceName) {
continue;
}
// Get fresh array for new namespace. This is to prevent the parser to collect the use statements
// for a previous namespace with the same name. This is the case if a namespace is defined twice
// or if a namespace with the same name is commented out.
$statements = [];
}
return $statements;
}
/**
* Gets the namespace.
*
* @return string The found namespace.
*/
public function parseNamespace()
{
$name = '';
while (
($token = $this->next()) && ($token[0] === T_STRING || $token[0] === T_NS_SEPARATOR || (
PHP_VERSION_ID >= 80000 &&
($token[0] === T_NAME_QUALIFIED || $token[0] === T_NAME_FULLY_QUALIFIED)
))
) {
$name .= $token[1];
}
return $name;
}
/**
* Gets the class name.
*
* @return string The found class name.
*/
public function parseClass()
{
// Namespaces and class names are tokenized the same: T_STRINGs
// separated by T_NS_SEPARATOR so we can use one function to provide
// both.
return $this->parseNamespace();
}
}

View File

@@ -1,15 +0,0 @@
<?xml version="1.0"?>
<psalm
errorLevel="7"
resolveFromConfigFile="true"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="https://getpsalm.org/schema/config"
xsi:schemaLocation="https://getpsalm.org/schema/config vendor/vimeo/psalm/config.xsd"
>
<projectFiles>
<directory name="lib/Doctrine/Common/Annotations" />
<ignoreFiles>
<directory name="vendor" />
</ignoreFiles>
</projectFiles>
</psalm>

View File

@@ -1,60 +0,0 @@
{
"active": true,
"name": "Common",
"slug": "common",
"docsSlug": "doctrine-common",
"versions": [
{
"name": "3.4",
"branchName": "3.4.x",
"slug": "3.4",
"current": true,
"aliases": [
"current",
"stable"
]
},
{
"name": "3.3",
"branchName": "3.3.x",
"slug": "3.3",
"maintained": false
},
{
"name": "3.2",
"branchName": "3.2.x",
"slug": "3.2",
"maintained": false
},
{
"name": "3.1",
"branchName": "3.1.x",
"slug": "3.1",
"maintained": false
},
{
"name": "3.0",
"branchName": "3.0.x",
"slug": "3.0",
"maintained": false
},
{
"name": "2.13",
"branchName": "2.13.x",
"slug": "2.13",
"maintained": false
},
{
"name": "2.12",
"branchName": "2.12.x",
"slug": "2.12",
"maintained": false
},
{
"name": "2.11",
"branchName": "2.11",
"slug": "2.11",
"maintained": false
}
]
}

View File

@@ -1,19 +0,0 @@
Copyright (c) 2006-2015 Doctrine Project
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@@ -1,12 +0,0 @@
# Doctrine Common
[![Build Status](https://github.com/doctrine/common/workflows/Continuous%20Integration/badge.svg)](https://github.com/doctrine/common/actions)
[![codecov](https://codecov.io/gh/doctrine/common/branch/3.1.x/graph/badge.svg)](https://codecov.io/gh/doctrine/common)
The Doctrine Common project is a library that provides extensions to core PHP functionality.
## More resources:
* [Website](https://www.doctrine-project.org/)
* [Documentation](https://www.doctrine-project.org/projects/doctrine-common/en/current/)
* [Downloads](https://github.com/doctrine/common/releases)

View File

@@ -1,39 +0,0 @@
This document details all the possible changes that you should investigate when updating
your project from Doctrine Common 2.0.x to 2.1
## AnnotationReader changes
The annotation reader was heavily refactored between 2.0 and 2.1-RC1. In theory the operation of the new reader should be backwards compatible, but it has to be setup differently to work that way:
$reader = new \Doctrine\Common\Annotations\AnnotationReader();
$reader->setDefaultAnnotationNamespace('Doctrine\ORM\Mapping\\');
// new code necessary starting here
$reader->setIgnoreNotImportedAnnotations(true);
$reader->setEnableParsePhpImports(false);
$reader = new \Doctrine\Common\Annotations\CachedReader(
new \Doctrine\Common\Annotations\IndexedReader($reader), new ArrayCache()
);
## Annotation Base class or @Annotation
Beginning after 2.1-RC2 you have to either extend ``Doctrine\Common\Annotations\Annotation`` or add @Annotation to your annotations class-level docblock, otherwise the class will simply be ignored.
## Removed methods on AnnotationReader
* AnnotationReader::setAutoloadAnnotations()
* AnnotationReader::getAutoloadAnnotations()
* AnnotationReader::isAutoloadAnnotations()
## AnnotationRegistry
Autoloading through the PHP autoloader is removed from the 2.1 AnnotationReader. Instead you have to use the global AnnotationRegistry for loading purposes:
\Doctrine\Common\Annotations\AnnotationRegistry::registerFile($fileWithAnnotations);
\Doctrine\Common\Annotations\AnnotationRegistry::registerAutoloadNamespace($namespace, $dirs = null);
\Doctrine\Common\Annotations\AnnotationRegistry::registerAutoloadNamespaces($namespaces);
\Doctrine\Common\Annotations\AnnotationRegistry::registerLoader($callable);
The $callable for registering a loader accepts a class as first and only parameter and must try to silently autoload it. On success true has to be returned.
The registerAutoloadNamespace function registers a PSR-0 compatible silent autoloader for all classes with the given namespace in the given directories.
If null is passed as directory the include path will be used.

View File

@@ -1,61 +0,0 @@
This document details all the possible changes that you should investigate when
updating your project from Doctrine Common 2.1 to 2.2:
## Annotation Changes
- AnnotationReader::setIgnoreNotImportedAnnotations has been removed, you need to
add ignore annotation names which are supposed to be ignored via
AnnotationReader::addGlobalIgnoredName
- AnnotationReader::setAutoloadAnnotations was deprecated by the AnnotationRegistry
in 2.1 and has been removed in 2.2
- AnnotationReader::setEnableParsePhpImports was added to ease transition to the new
annotation mechanism in 2.1 and is removed in 2.2
- AnnotationReader::isParsePhpImportsEnabled is removed (see above)
- AnnotationReader::setDefaultAnnotationNamespace was deprecated in favor of explicit
configuration in 2.1 and will be removed in 2.2 (for isolated projects where you
have full-control over _all_ available annotations, we offer a dedicated reader
class ``SimpleAnnotationReader``)
- AnnotationReader::setAnnotationCreationFunction was deprecated in 2.1 and will be
removed in 2.2. We only offer two creation mechanisms which cannot be changed
anymore to allow the same reader instance to work with all annotations regardless
of which library they are coming from.
- AnnotationReader::setAnnotationNamespaceAlias was deprecated in 2.1 and will be
removed in 2.2 (see setDefaultAnnotationNamespace)
- If you use a class as annotation which has not the @Annotation marker in it's
class block, we will now throw an exception instead of silently ignoring it. You
can however still achieve the previous behavior using the @IgnoreAnnotation, or
AnnotationReader::addGlobalIgnoredName (the exception message will contain detailed
instructions when you run into this problem).
## Cache Changes
- Renamed old AbstractCache to CacheProvider
- Dropped the support to the following functions of all cache providers:
- CacheProvider::deleteByWildcard
- CacheProvider::deleteByRegEx
- CacheProvider::deleteByPrefix
- CacheProvider::deleteBySuffix
- CacheProvider::deleteAll will not remove ALL entries, it will only mark them as invalid
- CacheProvider::flushAll will remove ALL entries, namespaced or not
- Added support to MemcachedCache
- Added support to WincacheCache
## ClassLoader Changes
- ClassLoader::fileExistsInIncludePath() no longer exists. Use the native stream_resolve_include_path() PHP function

View File

@@ -1,50 +0,0 @@
{
"name": "doctrine/common",
"type": "library",
"description": "PHP Doctrine Common project is a library that provides additional functionality that other Doctrine projects depend on such as better reflection support, proxies and much more.",
"keywords": [
"php",
"common",
"doctrine"
],
"homepage": "https://www.doctrine-project.org/projects/common.html",
"license": "MIT",
"authors": [
{"name": "Guilherme Blanco", "email": "guilhermeblanco@gmail.com"},
{"name": "Roman Borschel", "email": "roman@code-factory.org"},
{"name": "Benjamin Eberlei", "email": "kontakt@beberlei.de"},
{"name": "Jonathan Wage", "email": "jonwage@gmail.com"},
{"name": "Johannes Schmitt", "email": "schmittjoh@gmail.com"},
{"name": "Marco Pivetta", "email": "ocramius@gmail.com"}
],
"require": {
"php": "^7.1 || ^8.0",
"doctrine/persistence": "^2.0 || ^3.0"
},
"require-dev": {
"doctrine/collections": "^1",
"phpstan/phpstan": "^1.4.1",
"phpstan/phpstan-phpunit": "^1",
"phpunit/phpunit": "^7.5.20 || ^8.5 || ^9.0",
"doctrine/coding-standard": "^9.0 || ^10.0",
"squizlabs/php_codesniffer": "^3.0",
"symfony/phpunit-bridge": "^6.1",
"vimeo/psalm": "^4.4"
},
"autoload": {
"psr-4": {
"Doctrine\\Common\\": "src"
}
},
"autoload-dev": {
"psr-4": {
"Doctrine\\Tests\\": "tests"
}
},
"config": {
"allow-plugins": {
"dealerdirect/phpcodesniffer-composer-installer": true,
"composer/package-versions-deprecated": true
}
}
}

View File

@@ -1,10 +0,0 @@
Common Documentation
====================
Welcome to the Doctrine Common Library documentation.
.. toctree::
:depth: 2
:glob:
*

View File

@@ -1,241 +0,0 @@
Class Loading
=============
Class loading is an essential part of any PHP application that
makes heavy use of classes and interfaces. Unfortunately, a lot of
people and projects spend a lot of time and effort on custom and
specialized class loading strategies. It can quickly become a pain
to understand what is going on when using multiple libraries and/or
frameworks, each with its own way to do class loading. Class
loading should be simple and it is an ideal candidate for
convention over configuration.
Overview
--------
The Doctrine Common ClassLoader implements a simple and efficient
approach to class loading that is easy to understand and use. The
implementation is based on the widely used and accepted convention
of mapping namespace and class names to a directory structure. This
approach is used for example by Symfony2, the Zend Framework and of
course, Doctrine.
For example, the following class:
.. code-block:: php
<?php
namespace MyProject\Shipping;
class ShippingStrategy { ... }
resides in the following directory structure:
::
src/
/MyProject
/Shipping
ShippingStrategy.php
Note that the name of "src" or the structure above or beside this
directory is completely arbitrary. "src" could be named "classes"
or "lib" or whatever. The only convention to adhere to is to map
namespaces to directories and classes to files named after the
class name.
Usage
-----
To use a Doctrine Common ClassLoader, you first need to load the
class file containing the ClassLoader. This is the only class file
that actually needs to be loaded explicitly via ``require``. All
other classes will be loaded on demand by the configured class
loaders.
.. code-block:: php
<?php
use Doctrine\Common\ClassLoader;
require '/path/to/Doctrine/Common/ClassLoader.php';
$classLoader = new ClassLoader('MyProject', '/path/to/src');
A ``ClassLoader`` takes two constructor parameters, both optional.
In the normal case both arguments are supplied. The first argument
specifies the namespace prefix this class loader should be
responsible for and the second parameter is the path to the root
directory where the classes can be found according to the
convention mentioned previously.
The class loader in the example above would thus be responsible for
all classes under the 'MyProject' namespace and it would look for
the class files starting at the directory '/path/to/src'.
Also note that the prefix supplied in the first argument need not
be a root namespace but can be an arbitrarily nested namespace as
well. This allows you to even have the sources of subnamespaces
split across different directories. For example, all projects under
the Doctrine umbrella reside in the Doctrine namespace, yet the
sources for each project usually do not reside under a common root
directory. The following is an example of configuring three class
loaders, one for each used Doctrine project:
.. code-block:: php
<?php
use Doctrine\Common\ClassLoader;
require '/path/to/Doctrine/Common/ClassLoader.php';
$commonLoader = new ClassLoader('Doctrine\Common', '/path/to/common/lib');
$dbalLoader = new ClassLoader('Doctrine\DBAL', '/path/to/dbal/lib');
$ormLoader = new ClassLoader('Doctrine\ORM', '/path/to/orm/lib');
$commonLoader->register();
$dbalLoader->register();
$ormLoader->register();
Do not be afraid of using multiple class loaders. Due to the
efficient class loading design you will not incur much overhead
from using many class loaders. Take a look at the implementation of
``ClassLoader#loadClass`` to see how simple and efficient the class
loading is. The iteration over the installed class loaders happens
in C (with the exception of using ``ClassLoader::classExists``).
A ClassLoader can be used in the following other variations,
however, these are rarely used/needed:
- If only the second argument is not supplied, the class loader
will be responsible for the namespace prefix given in the first
argument and it will rely on the PHP include_path.
- If only the first argument is not supplied, the class loader
will be responsible for *all* classes and it will try to look up
*all* classes starting at the directory given as the second
argument.
- If both arguments are not supplied, the class loader will be
responsible for *all* classes and it will rely on the PHP
include_path.
File Extension
--------------
By default, a ClassLoader uses the ``.php`` file extension for all
class files. You can change this behavior, for example to use a
ClassLoader to load classes from a library that uses the
".class.php" convention (but it must nevertheless adhere to the
directory structure convention!):
.. code-block:: php
<?php
$customLoader = new ClassLoader('CustomLib', '/path/to/custom/lib');
$customLoader->setFileExtension('.class.php');
$customLoader->register();
Namespace Separator
-------------------
By default, a ClassLoader uses the ``\`` namespace separator. You
can change this behavior, for example to use a ClassLoader to load
legacy Zend Framework classes that still use the underscore "_"
separator:
.. code-block:: php
<?php
$zend1Loader = new ClassLoader('Zend', '/path/to/zend/lib');
$zend1Loader->setNamespaceSeparator('_');
$zend1Loader->register();
Failing Silently and class_exists
----------------------------------
A lot of class/autoloaders these days try to fail silently when a
class file is not found. For the most part this is necessary in
order to support using ``class_exists('ClassName', true)`` which is
supposed to return a boolean value but triggers autoloading. This
is a bad thing as it basically forces class loaders to fail
silently, which in turn requires costly file_exists or fopen calls
for each class being loaded, even though in at least 99% of the
cases this is not necessary (compare the number of
class_exists(..., true) invocations to the total number of classes
being loaded in a request).
The Doctrine Common ClassLoader does not fail silently, by design.
It therefore does not need any costly checks for file existence. A
ClassLoader is always responsible for all classes with a certain
namespace prefix and if a class is requested to be loaded and can
not be found this is considered to be a fatal error. This also
means that using class_exists(..., true) to check for class
existence when using a Doctrine Common ClassLoader is not possible
but this is not a bad thing. What class\_exists(..., true) actually
means is two things: 1) Check whether the class is already
defined/exists (i.e. class_exists(..., false)) and if not 2) check
whether a class file can be loaded for that class. In the Doctrine
Common ClassLoader the two responsibilities of loading a class and
checking for its existence are separated, which can be observed by
the existence of the two methods ``loadClass`` and
``canLoadClass``. Thereby ``loadClass`` does not invoke
``canLoadClass`` internally, by design. However, you are free to
use it yourself to check whether a class can be loaded and the
following code snippet is thus equivalent to class\_exists(...,
true):
.. code-block:: php
<?php
// Equivalent to if (('Foo', true)) if there is only 1 class loader to check
if (class_exists('Foo', false) || $classLoader->canLoadClass('Foo')) {
// ...
}
The only problem with this is that it is inconvenient as you need
to have a reference to the class loaders around (and there are
often multiple class loaders in use). Therefore, a simpler
alternative exists for the cases in which you really want to ask
all installed class loaders whether they can load the class:
``ClassLoader::classExists($className)``:
.. code-block:: php
<?php
// Equivalent to if (class_exists('Foo', true))
if (ClassLoader::classExists('Foo')) {
// ...
}
This static method can basically be used as a drop-in replacement
for class_exists(..., true). It iterates over all installed class
loaders and asks each of them via ``canLoadClass``, returning early
(with TRUE) as soon as one class loader returns TRUE from
``canLoadClass``. If this sounds like it can potentially be rather
costly then because that is true but it is exactly the same thing
that class_exists(..., true) does under the hood, it triggers a
complete interaction of all class/auto loaders. Checking for class
existence via invoking autoloading was never a cheap thing to do
but now it is more obvious and more importantly, this check is no
longer interleaved with regular class loading, which avoids having
to check each and every class for existence prior to loading it.
The vast majority of classes to be loaded are *not* optional and a
failure to load such a class is, and should be, a fatal error. The
ClassLoader design reflects this.
If you have code that requires the usage of class\_exists(...,
true) or ClassLoader::classExists during normal runtime of the
application (i.e. on each request) try to refactor your design to
avoid it.
Summary
-------
No matter which class loader you prefer to use (Doctrine classes do
not care about how they are loaded), we kindly encourage you to
adhere to the simple convention of mapping namespaces and class
names to a directory structure.
Class loading should be simple, automated and uniform. Time is
better invested in actual application development than in designing
special directory structures, autoloaders and clever caching
strategies for class loading.

View File

@@ -1,58 +0,0 @@
parameters:
phpVersion: 80200
level: 3
paths:
- src
- tests
excludePaths:
- tests/Common/Proxy/InvalidReturnTypeClass.php
- tests/Common/Proxy/InvalidTypeHintClass.php
- tests/Common/Proxy/LazyLoadableObjectWithTypedProperties.php
- tests/Common/Proxy/MagicIssetClassWithInteger.php
- tests/Common/Proxy/NullableNonOptionalHintClass.php
- tests/Common/Proxy/PHP81NeverType.php
- tests/Common/Proxy/PHP81IntersectionTypes.php
- tests/Common/Proxy/Php8UnionTypes.php
- tests/Common/Proxy/Php8StaticType.php
- tests/Common/Proxy/ProxyGeneratorTest.php
- tests/Common/Proxy/ProxyLogicTypedPropertiesTest.php
- tests/Common/Proxy/SerializedClass.php
- tests/Common/Proxy/VariadicTypeHintClass.php
- tests/Common/Proxy/Php71NullableDefaultedNonOptionalHintClass.php
- tests/Common/Proxy/generated
ignoreErrors:
- '#Access to an undefined property Doctrine\\Common\\Proxy\\Proxy::\$publicField#'
-
message: '#^Result of method Doctrine\\Tests\\Common\\Proxy\\LazyLoadableObjectWithVoid::(adding|incrementing)AndReturningVoid\(\) \(void\) is used\.$#'
path: 'tests/Common/Proxy/ProxyLogicVoidReturnTypeTest.php'
-
message: '#^Property Doctrine\\Tests\\Common\\Proxy\\ProxyLogicTest::\$initializerCallbackMock \(callable\(\): mixed&PHPUnit\\Framework\\MockObject\\MockObject\) does not accept PHPUnit\\Framework\\MockObject\\MockObject&stdClass\.$#'
path: 'tests/Common/Proxy/ProxyLogicTest.php'
-
message: '#.*LazyLoadableObject.*#'
paths:
- 'tests/Common/Proxy/ProxyLogicTest.php'
- 'tests/Common/Proxy/ProxyLogicVoidReturnTypeTest.php'
-
message: '#^Instantiated class Doctrine\\Tests\\Common\\ProxyProxy\\__CG__\\Doctrine\\Tests\\Common\\Proxy\\.* not found.$#'
path: 'tests/Common/Proxy/ProxyLogicTest.php'
-
message: '#^Instantiated class Doctrine\\Tests\\Common\\ProxyProxy\\__CG__\\Doctrine\\Tests\\Common\\Proxy\\.* not found.$#'
path: 'tests/Common/Proxy/ProxyLogicVoidReturnTypeTest.php'
-
message: '#^Property Doctrine\\Tests\\Common\\Proxy\\ProxyLogicVoidReturnTypeTest::\$initializerCallbackMock \(callable\(\): mixed&PHPUnit\\Framework\\MockObject\\MockObject\) does not accept PHPUnit\\Framework\\MockObject\\MockObject&stdClass\.$#'
path: 'tests/Common/Proxy/ProxyLogicVoidReturnTypeTest.php'
-
message: '#^Method Doctrine\\Tests\\Common\\Proxy\\MagicIssetClassWithInteger::__isset\(\) should return bool but returns int\.$#'
path: 'tests/Common/Proxy/MagicIssetClassWithInteger.php'
-
message: '#^Access to an undefined property Doctrine\\Tests\\Common\\Proxy\\MagicGetByRefClass\:\:\$nonExisting\.$#'
path: 'tests/Common/Proxy/ProxyMagicMethodsTest.php'
-
message: "#^Class Doctrine\\\\Tests\\\\Common\\\\Proxy\\\\MagicIssetClassWithInteger not found\\.$#"
count: 1
path: tests/Common/Proxy/ProxyMagicMethodsTest.php
includes:
- vendor/phpstan/phpstan-phpunit/extension.neon
- vendor/phpstan/phpstan-phpunit/rules.neon

View File

@@ -1,16 +0,0 @@
<?xml version="1.0"?>
<psalm
errorLevel="8"
resolveFromConfigFile="true"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="https://getpsalm.org/schema/config"
xsi:schemaLocation="https://getpsalm.org/schema/config vendor/vimeo/psalm/config.xsd"
phpVersion="8.1"
>
<projectFiles>
<directory name="src" />
<ignoreFiles>
<file name="src/Proxy/ProxyGenerator.php" />
</ignoreFiles>
</projectFiles>
</psalm>

View File

@@ -1,285 +0,0 @@
<?php
namespace Doctrine\Common;
use function class_exists;
use function interface_exists;
use function is_array;
use function is_file;
use function reset;
use function spl_autoload_functions;
use function spl_autoload_register;
use function spl_autoload_unregister;
use function str_replace;
use function stream_resolve_include_path;
use function strpos;
use function trait_exists;
use function trigger_error;
use const DIRECTORY_SEPARATOR;
use const E_USER_DEPRECATED;
@trigger_error(ClassLoader::class . ' is deprecated.', E_USER_DEPRECATED);
/**
* A <tt>ClassLoader</tt> is an autoloader for class files that can be
* installed on the SPL autoload stack. It is a class loader that either loads only classes
* of a specific namespace or all namespaces and it is suitable for working together
* with other autoloaders in the SPL autoload stack.
*
* If no include path is configured through the constructor or {@link setIncludePath}, a ClassLoader
* relies on the PHP <code>include_path</code>.
*
* @deprecated The ClassLoader is deprecated and will be removed in version 4.0 of doctrine/common.
*/
class ClassLoader
{
/**
* PHP file extension.
*
* @var string
*/
protected $fileExtension = '.php';
/**
* Current namespace.
*
* @var string|null
*/
protected $namespace;
/**
* Current include path.
*
* @var string|null
*/
protected $includePath;
/**
* PHP namespace separator.
*
* @var string
*/
protected $namespaceSeparator = '\\';
/**
* Creates a new <tt>ClassLoader</tt> that loads classes of the
* specified namespace from the specified include path.
*
* If no include path is given, the ClassLoader relies on the PHP include_path.
* If neither a namespace nor an include path is given, the ClassLoader will
* be responsible for loading all classes, thereby relying on the PHP include_path.
*
* @param string|null $ns The namespace of the classes to load.
* @param string|null $includePath The base include path to use.
*/
public function __construct($ns = null, $includePath = null)
{
$this->namespace = $ns;
$this->includePath = $includePath;
}
/**
* Sets the namespace separator used by classes in the namespace of this ClassLoader.
*
* @param string $sep The separator to use.
*
* @return void
*/
public function setNamespaceSeparator($sep)
{
$this->namespaceSeparator = $sep;
}
/**
* Gets the namespace separator used by classes in the namespace of this ClassLoader.
*
* @return string
*/
public function getNamespaceSeparator()
{
return $this->namespaceSeparator;
}
/**
* Sets the base include path for all class files in the namespace of this ClassLoader.
*
* @param string|null $includePath
*
* @return void
*/
public function setIncludePath($includePath)
{
$this->includePath = $includePath;
}
/**
* Gets the base include path for all class files in the namespace of this ClassLoader.
*
* @return string|null
*/
public function getIncludePath()
{
return $this->includePath;
}
/**
* Sets the file extension of class files in the namespace of this ClassLoader.
*
* @param string $fileExtension
*
* @return void
*/
public function setFileExtension($fileExtension)
{
$this->fileExtension = $fileExtension;
}
/**
* Gets the file extension of class files in the namespace of this ClassLoader.
*
* @return string
*/
public function getFileExtension()
{
return $this->fileExtension;
}
/**
* Registers this ClassLoader on the SPL autoload stack.
*
* @return void
*/
public function register()
{
spl_autoload_register([$this, 'loadClass']);
}
/**
* Removes this ClassLoader from the SPL autoload stack.
*
* @return void
*/
public function unregister()
{
spl_autoload_unregister([$this, 'loadClass']);
}
/**
* Loads the given class or interface.
*
* @param string $className The name of the class to load.
* @psalm-param class-string $className
*
* @return bool TRUE if the class has been successfully loaded, FALSE otherwise.
*/
public function loadClass($className)
{
if (self::typeExists($className)) {
return true;
}
if (! $this->canLoadClass($className)) {
return false;
}
require($this->includePath !== null ? $this->includePath . DIRECTORY_SEPARATOR : '')
. str_replace($this->namespaceSeparator, DIRECTORY_SEPARATOR, $className)
. $this->fileExtension;
return self::typeExists($className);
}
/**
* Asks this ClassLoader whether it can potentially load the class (file) with
* the given name.
*
* @param string $className The fully-qualified name of the class.
* @psalm-param class-string $className
*
* @return bool TRUE if this ClassLoader can load the class, FALSE otherwise.
*/
public function canLoadClass($className)
{
if ($this->namespace !== null && strpos($className, $this->namespace . $this->namespaceSeparator) !== 0) {
return false;
}
$file = str_replace($this->namespaceSeparator, DIRECTORY_SEPARATOR, $className) . $this->fileExtension;
if ($this->includePath !== null) {
return is_file($this->includePath . DIRECTORY_SEPARATOR . $file);
}
return stream_resolve_include_path($file) !== false;
}
/**
* Checks whether a class with a given name exists. A class "exists" if it is either
* already defined in the current request or if there is an autoloader on the SPL
* autoload stack that is a) responsible for the class in question and b) is able to
* load a class file in which the class definition resides.
*
* If the class is not already defined, each autoloader in the SPL autoload stack
* is asked whether it is able to tell if the class exists. If the autoloader is
* a <tt>ClassLoader</tt>, {@link canLoadClass} is used, otherwise the autoload
* function of the autoloader is invoked and expected to return a value that
* evaluates to TRUE if the class (file) exists. As soon as one autoloader reports
* that the class exists, TRUE is returned.
*
* Note that, depending on what kinds of autoloaders are installed on the SPL
* autoload stack, the class (file) might already be loaded as a result of checking
* for its existence. This is not the case with a <tt>ClassLoader</tt>, who separates
* these responsibilities.
*
* @param string $className The fully-qualified name of the class.
* @psalm-param class-string $className
*
* @return bool TRUE if the class exists as per the definition given above, FALSE otherwise.
*/
public static function classExists($className)
{
return self::typeExists($className, true);
}
/**
* Gets the <tt>ClassLoader</tt> from the SPL autoload stack that is responsible
* for (and is able to load) the class with the given name.
*
* @param string $className The name of the class.
* @psalm-param class-string $className
*
* @return ClassLoader|null The <tt>ClassLoader</tt> for the class or NULL if no such <tt>ClassLoader</tt> exists.
*/
public static function getClassLoader($className)
{
foreach (spl_autoload_functions() as $loader) {
if (! is_array($loader)) {
continue;
}
$classLoader = reset($loader);
if ($classLoader instanceof ClassLoader && $classLoader->canLoadClass($className)) {
return $classLoader;
}
}
return null;
}
/**
* Checks whether a given type exists
*
* @param string $type
* @param bool $autoload
*
* @return bool
*/
private static function typeExists($type, $autoload = false)
{
return class_exists($type, $autoload)
|| interface_exists($type, $autoload)
|| trait_exists($type, $autoload);
}
}

View File

@@ -1,14 +0,0 @@
<?php
namespace Doctrine\Common;
use Exception;
/**
* Base exception class for package Doctrine\Common.
*
* @deprecated The doctrine/common package is deprecated, please use specific packages and their exceptions instead.
*/
class CommonException extends Exception
{
}

View File

@@ -1,26 +0,0 @@
<?php
namespace Doctrine\Common;
/**
* Comparable interface that allows to compare two value objects to each other for similarity.
*
* @link www.doctrine-project.org
*/
interface Comparable
{
/**
* Compares the current object to the passed $other.
*
* Returns 0 if they are semantically equal, 1 if the other object
* is less than the current one, or -1 if its more than the current one.
*
* This method should not check for identity using ===, only for semantical equality for example
* when two different DateTime instances point to the exact same Date + TZ.
*
* @param mixed $other
*
* @return int
*/
public function compareTo($other);
}

View File

@@ -1,244 +0,0 @@
<?php
namespace Doctrine\Common\Proxy;
use Doctrine\Common\Proxy\Exception\InvalidArgumentException;
use Doctrine\Common\Proxy\Exception\OutOfBoundsException;
use Doctrine\Common\Util\ClassUtils;
use Doctrine\Persistence\Mapping\ClassMetadata;
use Doctrine\Persistence\Mapping\ClassMetadataFactory;
use function class_exists;
use function file_exists;
use function filemtime;
use function in_array;
/**
* Abstract factory for proxy objects.
*/
abstract class AbstractProxyFactory
{
/**
* Never autogenerate a proxy and rely that it was generated by some
* process before deployment.
*/
public const AUTOGENERATE_NEVER = 0;
/**
* Always generates a new proxy in every request.
*
* This is only sane during development.
*/
public const AUTOGENERATE_ALWAYS = 1;
/**
* Autogenerate the proxy class when the proxy file does not exist.
*
* This strategy causes a file_exists() call whenever any proxy is used the
* first time in a request.
*/
public const AUTOGENERATE_FILE_NOT_EXISTS = 2;
/**
* Generate the proxy classes using eval().
*
* This strategy is only sane for development, and even then it gives me
* the creeps a little.
*/
public const AUTOGENERATE_EVAL = 3;
/**
* Autogenerate the proxy class when the proxy file does not exist or
* when the proxied file changed.
*
* This strategy causes a file_exists() call whenever any proxy is used the
* first time in a request. When the proxied file is changed, the proxy will
* be updated.
*/
public const AUTOGENERATE_FILE_NOT_EXISTS_OR_CHANGED = 4;
private const AUTOGENERATE_MODES = [
self::AUTOGENERATE_NEVER,
self::AUTOGENERATE_ALWAYS,
self::AUTOGENERATE_FILE_NOT_EXISTS,
self::AUTOGENERATE_EVAL,
self::AUTOGENERATE_FILE_NOT_EXISTS_OR_CHANGED,
];
/** @var ClassMetadataFactory */
private $metadataFactory;
/** @var ProxyGenerator the proxy generator responsible for creating the proxy classes/files. */
private $proxyGenerator;
/** @var int Whether to automatically (re)generate proxy classes. */
private $autoGenerate;
/** @var ProxyDefinition[] */
private $definitions = [];
/**
* @param bool|int $autoGenerate
*
* @throws InvalidArgumentException When auto generate mode is not valid.
*/
public function __construct(ProxyGenerator $proxyGenerator, ClassMetadataFactory $metadataFactory, $autoGenerate)
{
$this->proxyGenerator = $proxyGenerator;
$this->metadataFactory = $metadataFactory;
$this->autoGenerate = (int) $autoGenerate;
if (! in_array($this->autoGenerate, self::AUTOGENERATE_MODES, true)) {
throw InvalidArgumentException::invalidAutoGenerateMode($autoGenerate);
}
}
/**
* Gets a reference proxy instance for the entity of the given type and identified by
* the given identifier.
*
* @param string $className
* @param array<mixed> $identifier
*
* @return Proxy
*
* @throws OutOfBoundsException
*/
public function getProxy($className, array $identifier)
{
$definition = $this->definitions[$className] ?? $this->getProxyDefinition($className);
$fqcn = $definition->proxyClassName;
$proxy = new $fqcn($definition->initializer, $definition->cloner);
foreach ($definition->identifierFields as $idField) {
if (! isset($identifier[$idField])) {
throw OutOfBoundsException::missingPrimaryKeyValue($className, $idField);
}
$definition->reflectionFields[$idField]->setValue($proxy, $identifier[$idField]);
}
return $proxy;
}
/**
* Generates proxy classes for all given classes.
*
* @param ClassMetadata[] $classes The classes (ClassMetadata instances)
* for which to generate proxies.
* @param string $proxyDir The target directory of the proxy classes. If not specified, the
* directory configured on the Configuration of the EntityManager used
* by this factory is used.
*
* @return int Number of generated proxies.
*/
public function generateProxyClasses(array $classes, $proxyDir = null)
{
$generated = 0;
foreach ($classes as $class) {
if ($this->skipClass($class)) {
continue;
}
$proxyFileName = $this->proxyGenerator->getProxyFileName($class->getName(), $proxyDir);
$this->proxyGenerator->generateProxyClass($class, $proxyFileName);
$generated += 1;
}
return $generated;
}
/**
* Reset initialization/cloning logic for an un-initialized proxy
*
* @return Proxy
*
* @throws InvalidArgumentException
*/
public function resetUninitializedProxy(Proxy $proxy)
{
if ($proxy->__isInitialized()) {
throw InvalidArgumentException::unitializedProxyExpected($proxy);
}
$className = ClassUtils::getClass($proxy);
$definition = $this->definitions[$className] ?? $this->getProxyDefinition($className);
$proxy->__setInitializer($definition->initializer);
$proxy->__setCloner($definition->cloner);
return $proxy;
}
/**
* Get a proxy definition for the given class name.
*
* @param string $className
* @psalm-param class-string $className
*
* @return ProxyDefinition
*/
private function getProxyDefinition($className)
{
$classMetadata = $this->metadataFactory->getMetadataFor($className);
$className = $classMetadata->getName(); // aliases and case sensitivity
$this->definitions[$className] = $this->createProxyDefinition($className);
$proxyClassName = $this->definitions[$className]->proxyClassName;
if (! class_exists($proxyClassName, false)) {
$fileName = $this->proxyGenerator->getProxyFileName($className);
switch ($this->autoGenerate) {
case self::AUTOGENERATE_NEVER:
require $fileName;
break;
case self::AUTOGENERATE_FILE_NOT_EXISTS:
if (! file_exists($fileName)) {
$this->proxyGenerator->generateProxyClass($classMetadata, $fileName);
}
require $fileName;
break;
case self::AUTOGENERATE_ALWAYS:
$this->proxyGenerator->generateProxyClass($classMetadata, $fileName);
require $fileName;
break;
case self::AUTOGENERATE_EVAL:
$this->proxyGenerator->generateProxyClass($classMetadata, false);
break;
case self::AUTOGENERATE_FILE_NOT_EXISTS_OR_CHANGED:
if (! file_exists($fileName) || filemtime($fileName) < filemtime($classMetadata->getReflectionClass()->getFileName())) {
$this->proxyGenerator->generateProxyClass($classMetadata, $fileName);
}
require $fileName;
break;
}
}
return $this->definitions[$className];
}
/**
* Determine if this class should be skipped during proxy generation.
*
* @return bool
*/
abstract protected function skipClass(ClassMetadata $metadata);
/**
* @param string $className
* @psalm-param class-string $className
*
* @return ProxyDefinition
*/
abstract protected function createProxyDefinition($className);
}

View File

@@ -1,99 +0,0 @@
<?php
namespace Doctrine\Common\Proxy;
use Closure;
use Doctrine\Common\Proxy\Exception\InvalidArgumentException;
use function call_user_func;
use function file_exists;
use function is_callable;
use function ltrim;
use function spl_autoload_register;
use function str_replace;
use function strlen;
use function strpos;
use function substr;
use const DIRECTORY_SEPARATOR;
/**
* Special Autoloader for Proxy classes, which are not PSR-0 compliant.
*
* @internal
*/
class Autoloader
{
/**
* Resolves proxy class name to a filename based on the following pattern.
*
* 1. Remove Proxy namespace from class name.
* 2. Remove namespace separators from remaining class name.
* 3. Return PHP filename from proxy-dir with the result from 2.
*
* @param string $proxyDir
* @param string $proxyNamespace
* @param string $className
* @psalm-param class-string $className
*
* @return string
*
* @throws InvalidArgumentException
*/
public static function resolveFile($proxyDir, $proxyNamespace, $className)
{
if (strpos($className, $proxyNamespace) !== 0) {
throw InvalidArgumentException::notProxyClass($className, $proxyNamespace);
}
// remove proxy namespace from class name
$classNameRelativeToProxyNamespace = substr($className, strlen($proxyNamespace));
// remove namespace separators from remaining class name
$fileName = str_replace('\\', '', $classNameRelativeToProxyNamespace);
return $proxyDir . DIRECTORY_SEPARATOR . $fileName . '.php';
}
/**
* Registers and returns autoloader callback for the given proxy dir and namespace.
*
* @param string $proxyDir
* @param string $proxyNamespace
* @param callable|null $notFoundCallback Invoked when the proxy file is not found.
*
* @return Closure
*
* @throws InvalidArgumentException
*/
public static function register($proxyDir, $proxyNamespace, $notFoundCallback = null)
{
$proxyNamespace = ltrim($proxyNamespace, '\\');
if ($notFoundCallback !== null && ! is_callable($notFoundCallback)) {
throw InvalidArgumentException::invalidClassNotFoundCallback($notFoundCallback);
}
$autoloader = static function ($className) use ($proxyDir, $proxyNamespace, $notFoundCallback) {
if ($proxyNamespace === '') {
return;
}
if (strpos($className, $proxyNamespace) !== 0) {
return;
}
$file = Autoloader::resolveFile($proxyDir, $proxyNamespace, $className);
if ($notFoundCallback && ! file_exists($file)) {
call_user_func($notFoundCallback, $proxyDir, $proxyNamespace, $className);
}
require $file;
};
spl_autoload_register($autoloader);
return $autoloader;
}
}

View File

@@ -1,110 +0,0 @@
<?php
namespace Doctrine\Common\Proxy\Exception;
use Doctrine\Persistence\Proxy;
use InvalidArgumentException as BaseInvalidArgumentException;
use function get_class;
use function gettype;
use function is_object;
use function sprintf;
/**
* Proxy Invalid Argument Exception.
*
* @link www.doctrine-project.org
*/
class InvalidArgumentException extends BaseInvalidArgumentException implements ProxyException
{
/** @return self */
public static function proxyDirectoryRequired()
{
return new self('You must configure a proxy directory. See docs for details');
}
/**
* @param string $className
* @param string $proxyNamespace
* @psalm-param class-string $className
*
* @return self
*/
public static function notProxyClass($className, $proxyNamespace)
{
return new self(sprintf('The class "%s" is not part of the proxy namespace "%s"', $className, $proxyNamespace));
}
/**
* @param string $name
*
* @return self
*/
public static function invalidPlaceholder($name)
{
return new self(sprintf('Provided placeholder for "%s" must be either a string or a valid callable', $name));
}
/** @return self */
public static function proxyNamespaceRequired()
{
return new self('You must configure a proxy namespace');
}
/** @return self */
public static function unitializedProxyExpected(Proxy $proxy)
{
return new self(sprintf('Provided proxy of type "%s" must not be initialized.', get_class($proxy)));
}
/**
* @param mixed $callback
*
* @return self
*/
public static function invalidClassNotFoundCallback($callback)
{
$type = is_object($callback) ? get_class($callback) : gettype($callback);
return new self(sprintf('Invalid \$notFoundCallback given: must be a callable, "%s" given', $type));
}
/**
* @param string $className
* @psalm-param class-string $className
*
* @return self
*/
public static function classMustNotBeAbstract($className)
{
return new self(sprintf('Unable to create a proxy for an abstract class "%s".', $className));
}
/**
* @param string $className
* @psalm-param class-string $className
*
* @return self
*/
public static function classMustNotBeFinal($className)
{
return new self(sprintf('Unable to create a proxy for a final class "%s".', $className));
}
/**
* @param string $className
* @psalm-param class-string $className
*
* @return self
*/
public static function classMustNotBeReadOnly($className)
{
return new self(sprintf('Unable to create a proxy for a readonly class "%s".', $className));
}
/** @param mixed $value */
public static function invalidAutoGenerateMode($value): self
{
return new self(sprintf('Invalid auto generate mode "%s" given.', $value));
}
}

View File

@@ -1,27 +0,0 @@
<?php
namespace Doctrine\Common\Proxy\Exception;
use OutOfBoundsException as BaseOutOfBoundsException;
use function sprintf;
/**
* Proxy Invalid Argument Exception.
*
* @link www.doctrine-project.org
*/
class OutOfBoundsException extends BaseOutOfBoundsException implements ProxyException
{
/**
* @param string $className
* @param string $idField
* @psalm-param class-string $className
*
* @return self
*/
public static function missingPrimaryKeyValue($className, $idField)
{
return new self(sprintf('Missing value for primary key %s on %s', $idField, $className));
}
}

View File

@@ -1,12 +0,0 @@
<?php
namespace Doctrine\Common\Proxy\Exception;
/**
* Base exception interface for proxy exceptions.
*
* @link www.doctrine-project.org
*/
interface ProxyException
{
}

View File

@@ -1,72 +0,0 @@
<?php
namespace Doctrine\Common\Proxy\Exception;
use Throwable;
use UnexpectedValueException as BaseUnexpectedValueException;
use function sprintf;
/**
* Proxy Unexpected Value Exception.
*
* @link www.doctrine-project.org
*/
class UnexpectedValueException extends BaseUnexpectedValueException implements ProxyException
{
/**
* @param string $proxyDirectory
*
* @return self
*/
public static function proxyDirectoryNotWritable($proxyDirectory)
{
return new self(sprintf('Your proxy directory "%s" must be writable', $proxyDirectory));
}
/**
* @param string $className
* @param string $methodName
* @param string $parameterName
* @psalm-param class-string $className
*
* @return self
*/
public static function invalidParameterTypeHint(
$className,
$methodName,
$parameterName,
?Throwable $previous = null
) {
return new self(
sprintf(
'The type hint of parameter "%s" in method "%s" in class "%s" is invalid.',
$parameterName,
$methodName,
$className
),
0,
$previous
);
}
/**
* @param string $className
* @param string $methodName
* @psalm-param class-string $className
*
* @return self
*/
public static function invalidReturnTypeHint($className, $methodName, ?Throwable $previous = null)
{
return new self(
sprintf(
'The return type of method "%s" in class "%s" is invalid.',
$methodName,
$className
),
0,
$previous
);
}
}

View File

@@ -1,68 +0,0 @@
<?php
namespace Doctrine\Common\Proxy;
use Closure;
use Doctrine\Persistence\Proxy as BaseProxy;
/**
* Interface for proxy classes.
*
* @template T of object
* @template-extends BaseProxy<T>
*/
interface Proxy extends BaseProxy
{
/**
* Marks the proxy as initialized or not.
*
* @param bool $initialized
*
* @return void
*/
public function __setInitialized($initialized);
/**
* Sets the initializer callback to be used when initializing the proxy. That
* initializer should accept 3 parameters: $proxy, $method and $params. Those
* are respectively the proxy object that is being initialized, the method name
* that triggered initialization and the parameters passed to that method.
*
* @return void
*/
public function __setInitializer(?Closure $initializer = null);
/**
* Retrieves the initializer callback used to initialize the proxy.
*
* @see __setInitializer
*
* @return Closure|null
*/
public function __getInitializer();
/**
* Sets the callback to be used when cloning the proxy. That initializer should accept
* a single parameter, which is the cloned proxy instance itself.
*
* @return void
*/
public function __setCloner(?Closure $cloner = null);
/**
* Retrieves the callback to be used when cloning the proxy.
*
* @see __setCloner
*
* @return Closure|null
*/
public function __getCloner();
/**
* Retrieves the list of lazy loaded properties for a given proxy
*
* @return array<string, mixed> Keys are the property names, and values are the default values
* for those properties.
*/
public function __getLazyProperties();
}

View File

@@ -1,42 +0,0 @@
<?php
namespace Doctrine\Common\Proxy;
use ReflectionProperty;
/**
* Definition structure how to create a proxy.
*/
class ProxyDefinition
{
/** @var string */
public $proxyClassName;
/** @var array<string> */
public $identifierFields;
/** @var ReflectionProperty[] */
public $reflectionFields;
/** @var callable */
public $initializer;
/** @var callable */
public $cloner;
/**
* @param string $proxyClassName
* @param array<string> $identifierFields
* @param array<string, ReflectionProperty> $reflectionFields
* @param callable $initializer
* @param callable $cloner
*/
public function __construct($proxyClassName, array $identifierFields, array $reflectionFields, $initializer, $cloner)
{
$this->proxyClassName = $proxyClassName;
$this->identifierFields = $identifierFields;
$this->reflectionFields = $reflectionFields;
$this->initializer = $initializer;
$this->cloner = $cloner;
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,113 +0,0 @@
<?php
namespace Doctrine\Common\Util;
use Doctrine\Persistence\Proxy;
use ReflectionClass;
use function get_class;
use function get_parent_class;
use function ltrim;
use function rtrim;
use function strrpos;
use function substr;
/**
* Class and reflection related functionality for objects that
* might or not be proxy objects at the moment.
*/
class ClassUtils
{
/**
* Gets the real class name of a class name that could be a proxy.
*
* @param string $className
* @psalm-param class-string<Proxy<T>>|class-string<T> $className
*
* @return string
* @psalm-return class-string<T>
*
* @template T of object
*/
public static function getRealClass($className)
{
$pos = strrpos($className, '\\' . Proxy::MARKER . '\\');
if ($pos === false) {
/** @psalm-var class-string<T> */
return $className;
}
return substr($className, $pos + Proxy::MARKER_LENGTH + 2);
}
/**
* Gets the real class name of an object (even if its a proxy).
*
* @param object $object
* @psalm-param Proxy<T>|T $object
*
* @return string
* @psalm-return class-string<T>
*
* @template T of object
*/
public static function getClass($object)
{
return self::getRealClass(get_class($object));
}
/**
* Gets the real parent class name of a class or object.
*
* @param string $className
* @psalm-param class-string $className
*
* @return string
* @psalm-return class-string
*/
public static function getParentClass($className)
{
return get_parent_class(self::getRealClass($className));
}
/**
* Creates a new reflection class.
*
* @param string $className
* @psalm-param class-string $className
*
* @return ReflectionClass
*/
public static function newReflectionClass($className)
{
return new ReflectionClass(self::getRealClass($className));
}
/**
* Creates a new reflection object.
*
* @param object $object
*
* @return ReflectionClass
*/
public static function newReflectionObject($object)
{
return self::newReflectionClass(self::getClass($object));
}
/**
* Given a class name and a proxy namespace returns the proxy name.
*
* @param string $className
* @param string $proxyNamespace
* @psalm-param class-string $className
*
* @return string
* @psalm-return class-string
*/
public static function generateProxyClassName($className, $proxyNamespace)
{
return rtrim($proxyNamespace, '\\') . '\\' . Proxy::MARKER . '\\' . ltrim($className, '\\');
}
}

View File

@@ -1,185 +0,0 @@
<?php
namespace Doctrine\Common\Util;
use ArrayIterator;
use ArrayObject;
use DateTimeInterface;
use Doctrine\Common\Collections\Collection;
use Doctrine\Persistence\Proxy;
use stdClass;
use function array_keys;
use function count;
use function end;
use function explode;
use function extension_loaded;
use function get_class;
use function html_entity_decode;
use function ini_get;
use function ini_set;
use function is_array;
use function is_object;
use function method_exists;
use function ob_end_clean;
use function ob_get_contents;
use function ob_start;
use function spl_object_hash;
use function strip_tags;
use function var_dump;
/**
* Static class containing most used debug methods.
*
* @deprecated The Debug class is deprecated, please use symfony/var-dumper instead.
*
* @link www.doctrine-project.org
*/
final class Debug
{
/**
* Private constructor (prevents instantiation).
*/
private function __construct()
{
}
/**
* Prints a dump of the public, protected and private properties of $var.
*
* @link https://xdebug.org/
*
* @param mixed $var The variable to dump.
* @param int $maxDepth The maximum nesting level for object properties.
* @param bool $stripTags Whether output should strip HTML tags.
* @param bool $echo Send the dumped value to the output buffer
*
* @return string
*/
public static function dump($var, $maxDepth = 2, $stripTags = true, $echo = true)
{
$html = ini_get('html_errors');
if ($html !== true) {
ini_set('html_errors', 'on');
}
if (extension_loaded('xdebug')) {
ini_set('xdebug.var_display_max_depth', $maxDepth);
}
$var = self::export($var, $maxDepth);
ob_start();
var_dump($var);
$dump = ob_get_contents();
ob_end_clean();
$dumpText = ($stripTags ? strip_tags(html_entity_decode($dump)) : $dump);
ini_set('html_errors', $html);
if ($echo) {
echo $dumpText;
}
return $dumpText;
}
/**
* @param mixed $var
* @param int $maxDepth
*
* @return mixed
*/
public static function export($var, $maxDepth)
{
$return = null;
$isObj = is_object($var);
if ($var instanceof Collection) {
$var = $var->toArray();
}
if (! $maxDepth) {
return is_object($var) ? get_class($var)
: (is_array($var) ? 'Array(' . count($var) . ')' : $var);
}
if (is_array($var)) {
$return = [];
foreach ($var as $k => $v) {
$return[$k] = self::export($v, $maxDepth - 1);
}
return $return;
}
if (! $isObj) {
return $var;
}
$return = new stdClass();
if ($var instanceof DateTimeInterface) {
$return->__CLASS__ = get_class($var);
$return->date = $var->format('c');
$return->timezone = $var->getTimezone()->getName();
return $return;
}
$return->__CLASS__ = ClassUtils::getClass($var);
if ($var instanceof Proxy) {
$return->__IS_PROXY__ = true;
$return->__PROXY_INITIALIZED__ = $var->__isInitialized();
}
if ($var instanceof ArrayObject || $var instanceof ArrayIterator) {
$return->__STORAGE__ = self::export($var->getArrayCopy(), $maxDepth - 1);
}
return self::fillReturnWithClassAttributes($var, $return, $maxDepth);
}
/**
* Fill the $return variable with class attributes
* Based on obj2array function from {@see https://secure.php.net/manual/en/function.get-object-vars.php#47075}
*
* @param object $var
* @param int $maxDepth
*
* @return mixed
*/
private static function fillReturnWithClassAttributes($var, stdClass $return, $maxDepth)
{
$clone = (array) $var;
foreach (array_keys($clone) as $key) {
$aux = explode("\0", $key);
$name = end($aux);
if ($aux[0] === '') {
$name .= ':' . ($aux[1] === '*' ? 'protected' : $aux[1] . ':private');
}
$return->$name = self::export($clone[$key], $maxDepth - 1);
}
return $return;
}
/**
* Returns a string representation of an object.
*
* @param object $obj
*
* @return string
*/
public static function toString($obj)
{
return method_exists($obj, '__toString') ? (string) $obj : get_class($obj) . '@' . spl_object_hash($obj);
}
}

View File

@@ -1,11 +0,0 @@
# Circular dependency
This package has a development dependency on `doctrine/common`, which has a
regular dependency on this package (`^2.0` at the time of writing).
To be able to use Composer, one has to let it understand that this is version 2
(even when developing on 3.0.x), as follows:
```shell
COMPOSER_ROOT_VERSION=2.0 composer update -v
```

View File

@@ -1,19 +0,0 @@
Copyright (c) 2006-2015 Doctrine Project
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@@ -1,12 +0,0 @@
# Doctrine Persistence
[![Build Status](https://travis-ci.org/doctrine/persistence.svg)](https://travis-ci.org/doctrine/persistence)
[![Code Coverage](https://codecov.io/gh/doctrine/persistence/branch/2.1.x/graph/badge.svg)](https://codecov.io/gh/doctrine/persistence/branch/2.1.x)
The Doctrine Persistence project is a library that provides common abstractions for object mapper persistence.
## More resources:
* [Website](https://www.doctrine-project.org/)
* [Documentation](https://www.doctrine-project.org/projects/doctrine-persistence/en/latest/index.html)
* [Downloads](https://github.com/doctrine/persistence/releases)

View File

@@ -1,152 +0,0 @@
Note about upgrading: Doctrine uses static and runtime mechanisms to raise
awareness about deprecated code.
- Use of `@deprecated` docblock that is detected by IDEs (like PHPStorm) or
Static Analysis tools (like Psalm, phpstan)
- Use of our low-overhead runtime deprecation API, details:
https://github.com/doctrine/deprecations/
# Upgrade to 3.1
## Added method `Proxy::__setInitialized()`
Classes implementing `Doctrine\Persistence\Proxy` should implement the new
method. This method will be added to the interface in 4.0.
## Deprecated `RuntimePublicReflectionProperty`
Use `RuntimeReflectionProperty` instead.
# Upgrade to 3.0
## Removed `OnClearEventArgs::clearsAllEntities()` and `OnClearEventArgs::getEntityClass()`
These methods only make sense when partially clearing the object manager, which
is no longer possible.
The second argument of the constructor of `OnClearEventArgs` is removed as well.
## BC Break: removed `ObjectManagerAware`
Implement active record style functionality directly in your application, by
using a `postLoad` event.
## BC Break: removed `AnnotationDriver`
Use `ColocatedMappingDriver` instead.
## BC Break: Removed `MappingException::pathRequired()`
Use `MappingException::pathRequiredForDriver()` instead.
## BC Break: removed `LifecycleEventArgs::getEntity()`
Use `LifecycleEventArgs::getObject()` instead.
## BC Break: removed support for short namespace aliases
- `AbstractClassMetadataFactory::getFqcnFromAlias()` is removed.
- `ClassMetadataFactory` methods now require their `$className` argument to be an
actual FQCN.
## BC Break: removed `ObjectManager::merge()`
`ObjectManagerDecorator::merge()` is removed without replacement.
## BC Break: removed support for `doctrine/cache`
Removed support for using doctrine/cache for metadata caching. The
`setCacheDriver` and `getCacheDriver` methods have been removed from
`Doctrine\Persistence\Mapping\AbstractMetadata`. Please use `getCache` and
`setCache` with a PSR-6 implementation instead.
## BC Break: changed signatures
`$objectName` has been dropped from the signature of `ObjectManager::clear()`.
```diff
- public function clear($objectName = null)
+ public function clear(): void
```
Also, native parameter type declarations have been added on all public APIs.
Native return type declarations have not been added so that it is possible to
implement types compatible with both 2.x and 3.x.
## BC Break: Removed `PersistentObject`
Please implement this functionality directly in your application if you want
ActiveRecord style functionality.
# Upgrade to 2.5
## Deprecated `OnClearEventArgs::clearsAllEntities()` and `OnClearEventArgs::getEntityClass()`
These methods only make sense when partially clearing the object manager, which
is deprecated.
Passing a second argument to the constructor of `OnClearEventArgs` is
deprecated as well.
## Deprecated `ObjectManagerAware`
Along with deprecating `PersistentObject`, deprecating `ObjectManagerAware`
means deprecating support for active record, which already came with a word of
warning. Please implement this directly in your application with a `postLoad`
event if you need active record style functionality.
## Deprecated `MappingException::pathRequired()`
`MappingException::pathRequiredForDriver()` should be used instead.
# Upgrade to 2.4
## Deprecated `AnnotationDriver`
Since attributes were introduced in PHP 8.0, annotations are deprecated.
`AnnotationDriver` is an abstract class that is used when implementing concrete
annotation drivers in dependent packages. It is deprecated in favor of using
`ColocatedMappingDriver` to implement both annotation and attribute based
drivers. This will involve implementing `isTransient()` as well as
`__construct()` and `getReader()` to retain backward compatibility.
# Upgrade to 2.3
## Deprecated using short namespace alias syntax in favor of `::class` syntax.
Before:
```php
$objectManager->find('MyPackage:MyClass', $id);
$objectManager->createQuery('SELECT u FROM MyPackage:MyClass');
```
After:
```php
$objectManager->find(MyClass::class, $id);
$objectManager->createQuery('SELECT u FROM '. MyClass::class);
```
# Upgrade to 2.2
## Deprecated `doctrine/cache` usage for metadata caching
The `setCacheDriver` and `getCacheDriver` methods in
`Doctrine\Persistence\Mapping\AbstractMetadata` have been deprecated. Please
use `getCache` and `setCache` with a PSR-6 implementation instead. Note that
even after switching to PSR-6, `getCacheDriver` will return a cache instance
that wraps the PSR-6 cache. Note that if you use a custom implementation of
doctrine/cache, the library may not be able to provide a forward compatibility
layer. The cache implementation MUST extend the
`Doctrine\Common\Cache\CacheProvider` class.
# Upgrade to 1.2
## Deprecated `ObjectManager::merge()` and `ObjectManager::detach()`
Please handle merge operations in your application, and use
`ObjectManager::clear()` instead.
## Deprecated `PersistentObject`
Please implement this functionality directly in your application if you want
ActiveRecord style functionality.

View File

@@ -1,59 +0,0 @@
{
"name": "doctrine/persistence",
"type": "library",
"description": "The Doctrine Persistence project is a set of shared interfaces and functionality that the different Doctrine object mappers share.",
"keywords": [
"persistence",
"object",
"mapper",
"orm",
"odm"
],
"homepage": "https://www.doctrine-project.org/projects/persistence.html",
"license": "MIT",
"authors": [
{"name": "Guilherme Blanco", "email": "guilhermeblanco@gmail.com"},
{"name": "Roman Borschel", "email": "roman@code-factory.org"},
{"name": "Benjamin Eberlei", "email": "kontakt@beberlei.de"},
{"name": "Jonathan Wage", "email": "jonwage@gmail.com"},
{"name": "Johannes Schmitt", "email": "schmittjoh@gmail.com"},
{"name": "Marco Pivetta", "email": "ocramius@gmail.com"}
],
"require": {
"php": "^7.2 || ^8.0",
"doctrine/event-manager": "^1 || ^2",
"psr/cache": "^1.0 || ^2.0 || ^3.0"
},
"require-dev": {
"composer/package-versions-deprecated": "^1.11",
"phpstan/phpstan": "1.9.4",
"phpstan/phpstan-phpunit": "^1",
"phpstan/phpstan-strict-rules": "^1.1",
"doctrine/coding-standard": "^11",
"doctrine/common": "^3.0",
"phpunit/phpunit": "^8.5 || ^9.5",
"symfony/cache": "^4.4 || ^5.4 || ^6.0",
"vimeo/psalm": "4.30.0 || 5.3.0"
},
"conflict": {
"doctrine/common": "<2.10"
},
"autoload": {
"psr-4": {
"Doctrine\\Persistence\\": "src/Persistence"
}
},
"autoload-dev": {
"psr-4": {
"Doctrine\\Tests\\": "tests",
"Doctrine\\Tests_PHP74\\": "tests_php74",
"Doctrine\\Tests_PHP81\\": "tests_php81"
}
},
"config": {
"allow-plugins": {
"dealerdirect/phpcodesniffer-composer-installer": true,
"composer/package-versions-deprecated": true
}
}
}

View File

@@ -1,11 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<files psalm-version="5.3.0@b6faa3e96b8eb50ec71384c53799b8a107236bb6">
<file src="src/Persistence/AbstractManagerRegistry.php">
<PossiblyNullReference occurrences="1">
<code>getName</code>
</PossiblyNullReference>
<TypeDoesNotContainType occurrences="1">
<code>$parentClass === false</code>
</TypeDoesNotContainType>
</file>
</files>

View File

@@ -1,12 +0,0 @@
<?php
/**
* Workaround for psalm to return a class-string when used with a class string
* Can be removed when https://github.com/vimeo/psalm/pull/8219 is released
*
* @psalm-pure
*
* @return ($string is class-string ? ($characters is '\\' ? class-string : string) : string)
*
* @psalm-flow ($string) -> return
*/
function ltrim(string $string, string $characters = " \t\n\r\0\x0B") : string {}

View File

@@ -1,263 +0,0 @@
<?php
declare(strict_types=1);
namespace Doctrine\Persistence;
use InvalidArgumentException;
use ReflectionClass;
use function sprintf;
/**
* Abstract implementation of the ManagerRegistry contract.
*/
abstract class AbstractManagerRegistry implements ManagerRegistry
{
/** @var string */
private $name;
/** @var array<string, string> */
private $connections;
/** @var array<string, string> */
private $managers;
/** @var string */
private $defaultConnection;
/** @var string */
private $defaultManager;
/**
* @var string
* @psalm-var class-string
*/
private $proxyInterfaceName;
/**
* @param array<string, string> $connections
* @param array<string, string> $managers
* @psalm-param class-string $proxyInterfaceName
*/
public function __construct(
string $name,
array $connections,
array $managers,
string $defaultConnection,
string $defaultManager,
string $proxyInterfaceName
) {
$this->name = $name;
$this->connections = $connections;
$this->managers = $managers;
$this->defaultConnection = $defaultConnection;
$this->defaultManager = $defaultManager;
$this->proxyInterfaceName = $proxyInterfaceName;
}
/**
* Fetches/creates the given services.
*
* A service in this context is connection or a manager instance.
*
* @param string $name The name of the service.
*
* @return ObjectManager The instance of the given service.
*/
abstract protected function getService(string $name);
/**
* Resets the given services.
*
* A service in this context is connection or a manager instance.
*
* @param string $name The name of the service.
*
* @return void
*/
abstract protected function resetService(string $name);
/**
* Gets the name of the registry.
*
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* {@inheritdoc}
*/
public function getConnection(?string $name = null)
{
if ($name === null) {
$name = $this->defaultConnection;
}
if (! isset($this->connections[$name])) {
throw new InvalidArgumentException(
sprintf('Doctrine %s Connection named "%s" does not exist.', $this->name, $name)
);
}
return $this->getService($this->connections[$name]);
}
/**
* {@inheritdoc}
*/
public function getConnectionNames()
{
return $this->connections;
}
/**
* {@inheritdoc}
*/
public function getConnections()
{
$connections = [];
foreach ($this->connections as $name => $id) {
$connections[$name] = $this->getService($id);
}
return $connections;
}
/**
* {@inheritdoc}
*/
public function getDefaultConnectionName()
{
return $this->defaultConnection;
}
/**
* {@inheritdoc}
*/
public function getDefaultManagerName()
{
return $this->defaultManager;
}
/**
* {@inheritdoc}
*
* @throws InvalidArgumentException
*/
public function getManager(?string $name = null)
{
if ($name === null) {
$name = $this->defaultManager;
}
if (! isset($this->managers[$name])) {
throw new InvalidArgumentException(
sprintf('Doctrine %s Manager named "%s" does not exist.', $this->name, $name)
);
}
return $this->getService($this->managers[$name]);
}
/**
* {@inheritDoc}
*/
public function getManagerForClass(string $class)
{
$proxyClass = new ReflectionClass($class);
if ($proxyClass->isAnonymous()) {
return null;
}
if ($proxyClass->implementsInterface($this->proxyInterfaceName)) {
$parentClass = $proxyClass->getParentClass();
if ($parentClass === false) {
return null;
}
$class = $parentClass->getName();
}
foreach ($this->managers as $id) {
$manager = $this->getService($id);
if (! $manager->getMetadataFactory()->isTransient($class)) {
return $manager;
}
}
return null;
}
/**
* {@inheritdoc}
*/
public function getManagerNames()
{
return $this->managers;
}
/**
* {@inheritdoc}
*/
public function getManagers()
{
$managers = [];
foreach ($this->managers as $name => $id) {
$manager = $this->getService($id);
$managers[$name] = $manager;
}
return $managers;
}
/**
* {@inheritdoc}
*/
public function getRepository(
string $persistentObject,
?string $persistentManagerName = null
) {
return $this
->selectManager($persistentObject, $persistentManagerName)
->getRepository($persistentObject);
}
/**
* {@inheritdoc}
*/
public function resetManager(?string $name = null)
{
if ($name === null) {
$name = $this->defaultManager;
}
if (! isset($this->managers[$name])) {
throw new InvalidArgumentException(sprintf('Doctrine %s Manager named "%s" does not exist.', $this->name, $name));
}
// force the creation of a new document manager
// if the current one is closed
$this->resetService($this->managers[$name]);
return $this->getManager($name);
}
/** @psalm-param class-string $persistentObject */
private function selectManager(
string $persistentObject,
?string $persistentManagerName = null
): ObjectManager {
if ($persistentManagerName !== null) {
return $this->getManager($persistentManagerName);
}
return $this->getManagerForClass($persistentObject) ?? $this->getManager();
}
}

View File

@@ -1,41 +0,0 @@
<?php
declare(strict_types=1);
namespace Doctrine\Persistence;
/**
* Contract covering connection for a Doctrine persistence layer ManagerRegistry class to implement.
*/
interface ConnectionRegistry
{
/**
* Gets the default connection name.
*
* @return string The default connection name.
*/
public function getDefaultConnectionName();
/**
* Gets the named connection.
*
* @param string|null $name The connection name (null for the default one).
*
* @return object
*/
public function getConnection(?string $name = null);
/**
* Gets an array of all registered connections.
*
* @return array<string, object> An array of Connection instances.
*/
public function getConnections();
/**
* Gets all connection names.
*
* @return array<string, string> An array of connection names.
*/
public function getConnectionNames();
}

View File

@@ -1,54 +0,0 @@
<?php
declare(strict_types=1);
namespace Doctrine\Persistence\Event;
use Doctrine\Common\EventArgs;
use Doctrine\Persistence\ObjectManager;
/**
* Lifecycle Events are triggered by the UnitOfWork during lifecycle transitions
* of entities.
*
* @template-covariant TObjectManager of ObjectManager
*/
class LifecycleEventArgs extends EventArgs
{
/**
* @var ObjectManager
* @psalm-var TObjectManager
*/
private $objectManager;
/** @var object */
private $object;
/** @psalm-param TObjectManager $objectManager */
public function __construct(object $object, ObjectManager $objectManager)
{
$this->object = $object;
$this->objectManager = $objectManager;
}
/**
* Retrieves the associated object.
*
* @return object
*/
public function getObject()
{
return $this->object;
}
/**
* Retrieves the associated ObjectManager.
*
* @return ObjectManager
* @psalm-return TObjectManager
*/
public function getObjectManager()
{
return $this->objectManager;
}
}

View File

@@ -1,61 +0,0 @@
<?php
declare(strict_types=1);
namespace Doctrine\Persistence\Event;
use Doctrine\Common\EventArgs;
use Doctrine\Persistence\Mapping\ClassMetadata;
use Doctrine\Persistence\ObjectManager;
/**
* Class that holds event arguments for a loadMetadata event.
*
* @template-covariant TClassMetadata of ClassMetadata<object>
* @template-covariant TObjectManager of ObjectManager
*/
class LoadClassMetadataEventArgs extends EventArgs
{
/**
* @var ClassMetadata
* @psalm-var TClassMetadata
*/
private $classMetadata;
/**
* @var ObjectManager
* @psalm-var TObjectManager
*/
private $objectManager;
/**
* @psalm-param TClassMetadata $classMetadata
* @psalm-param TObjectManager $objectManager
*/
public function __construct(ClassMetadata $classMetadata, ObjectManager $objectManager)
{
$this->classMetadata = $classMetadata;
$this->objectManager = $objectManager;
}
/**
* Retrieves the associated ClassMetadata.
*
* @return ClassMetadata
* @psalm-return TClassMetadata
*/
public function getClassMetadata()
{
return $this->classMetadata;
}
/**
* Retrieves the associated ObjectManager.
*
* @return TObjectManager
*/
public function getObjectManager()
{
return $this->objectManager;
}
}

View File

@@ -1,39 +0,0 @@
<?php
declare(strict_types=1);
namespace Doctrine\Persistence\Event;
use Doctrine\Common\EventArgs;
use Doctrine\Persistence\ObjectManager;
/**
* Provides event arguments for the preFlush event.
*
* @template-covariant TObjectManager of ObjectManager
*/
class ManagerEventArgs extends EventArgs
{
/**
* @var ObjectManager
* @psalm-var TObjectManager
*/
private $objectManager;
/** @psalm-param TObjectManager $objectManager */
public function __construct(ObjectManager $objectManager)
{
$this->objectManager = $objectManager;
}
/**
* Retrieves the associated ObjectManager.
*
* @return ObjectManager
* @psalm-return TObjectManager
*/
public function getObjectManager()
{
return $this->objectManager;
}
}

View File

@@ -1,42 +0,0 @@
<?php
declare(strict_types=1);
namespace Doctrine\Persistence\Event;
use Doctrine\Common\EventArgs;
use Doctrine\Persistence\ObjectManager;
/**
* Provides event arguments for the onClear event.
*
* @template-covariant TObjectManager of ObjectManager
*/
class OnClearEventArgs extends EventArgs
{
/**
* @var ObjectManager
* @psalm-var TObjectManager
*/
private $objectManager;
/**
* @param ObjectManager $objectManager The object manager.
* @psalm-param TObjectManager $objectManager
*/
public function __construct(ObjectManager $objectManager)
{
$this->objectManager = $objectManager;
}
/**
* Retrieves the associated ObjectManager.
*
* @return ObjectManager
* @psalm-return TObjectManager
*/
public function getObjectManager()
{
return $this->objectManager;
}
}

View File

@@ -1,110 +0,0 @@
<?php
declare(strict_types=1);
namespace Doctrine\Persistence\Event;
use Doctrine\Persistence\ObjectManager;
use InvalidArgumentException;
use function get_class;
use function sprintf;
/**
* Class that holds event arguments for a preUpdate event.
*
* @template-covariant TObjectManager of ObjectManager
* @extends LifecycleEventArgs<TObjectManager>
*/
class PreUpdateEventArgs extends LifecycleEventArgs
{
/** @var array<string, array<int, mixed>> */
private $entityChangeSet;
/**
* @param array<string, array<int, mixed>> $changeSet
* @psalm-param TObjectManager $objectManager
*/
public function __construct(object $entity, ObjectManager $objectManager, array &$changeSet)
{
parent::__construct($entity, $objectManager);
$this->entityChangeSet = &$changeSet;
}
/**
* Retrieves the entity changeset.
*
* @return array<string, array<int, mixed>>
*/
public function getEntityChangeSet()
{
return $this->entityChangeSet;
}
/**
* Checks if field has a changeset.
*
* @return bool
*/
public function hasChangedField(string $field)
{
return isset($this->entityChangeSet[$field]);
}
/**
* Gets the old value of the changeset of the changed field.
*
* @return mixed
*/
public function getOldValue(string $field)
{
$this->assertValidField($field);
return $this->entityChangeSet[$field][0];
}
/**
* Gets the new value of the changeset of the changed field.
*
* @return mixed
*/
public function getNewValue(string $field)
{
$this->assertValidField($field);
return $this->entityChangeSet[$field][1];
}
/**
* Sets the new value of this field.
*
* @param mixed $value
*
* @return void
*/
public function setNewValue(string $field, $value)
{
$this->assertValidField($field);
$this->entityChangeSet[$field][1] = $value;
}
/**
* Asserts the field exists in changeset.
*
* @return void
*
* @throws InvalidArgumentException
*/
private function assertValidField(string $field)
{
if (! isset($this->entityChangeSet[$field])) {
throw new InvalidArgumentException(sprintf(
'Field "%s" is not a valid field of the entity "%s" in PreUpdateEventArgs.',
$field,
get_class($this->getObject())
));
}
}
}

View File

@@ -1,89 +0,0 @@
<?php
declare(strict_types=1);
namespace Doctrine\Persistence;
/**
* Contract covering object managers for a Doctrine persistence layer ManagerRegistry class to implement.
*/
interface ManagerRegistry extends ConnectionRegistry
{
/**
* Gets the default object manager name.
*
* @return string The default object manager name.
*/
public function getDefaultManagerName();
/**
* Gets a named object manager.
*
* @param string|null $name The object manager name (null for the default one).
*
* @return ObjectManager
*/
public function getManager(?string $name = null);
/**
* Gets an array of all registered object managers.
*
* @return array<string, ObjectManager> An array of ObjectManager instances
*/
public function getManagers();
/**
* Resets a named object manager.
*
* This method is useful when an object manager has been closed
* because of a rollbacked transaction AND when you think that
* it makes sense to get a new one to replace the closed one.
*
* Be warned that you will get a brand new object manager as
* the existing one is not useable anymore. This means that any
* other object with a dependency on this object manager will
* hold an obsolete reference. You can inject the registry instead
* to avoid this problem.
*
* @param string|null $name The object manager name (null for the default one).
*
* @return ObjectManager
*/
public function resetManager(?string $name = null);
/**
* Gets all object manager names and associated service IDs. A service ID
* is a string that allows to obtain an object manager, typically from a
* PSR-11 container.
*
* @return array<string,string> An array with object manager names as keys,
* and service IDs as values.
*/
public function getManagerNames();
/**
* Gets the ObjectRepository for a persistent object.
*
* @param string $persistentObject The name of the persistent object.
* @param string|null $persistentManagerName The object manager name (null for the default one).
* @psalm-param class-string<T> $persistentObject
*
* @return ObjectRepository
* @psalm-return ObjectRepository<T>
*
* @template T of object
*/
public function getRepository(
string $persistentObject,
?string $persistentManagerName = null
);
/**
* Gets the object manager associated with a given class.
*
* @param class-string $class A persistent object class name.
*
* @return ObjectManager|null
*/
public function getManagerForClass(string $class);
}

View File

@@ -1,499 +0,0 @@
<?php
declare(strict_types=1);
namespace Doctrine\Persistence\Mapping;
use Doctrine\Persistence\Mapping\Driver\MappingDriver;
use Doctrine\Persistence\Proxy;
use Psr\Cache\CacheItemPoolInterface;
use ReflectionClass;
use ReflectionException;
use function array_combine;
use function array_keys;
use function array_map;
use function array_reverse;
use function array_unshift;
use function assert;
use function class_exists;
use function ltrim;
use function str_replace;
use function strpos;
use function strrpos;
use function substr;
/**
* The ClassMetadataFactory is used to create ClassMetadata objects that contain all the
* metadata mapping informations of a class which describes how a class should be mapped
* to a relational database.
*
* This class was abstracted from the ORM ClassMetadataFactory.
*
* @template CMTemplate of ClassMetadata
* @template-implements ClassMetadataFactory<CMTemplate>
*/
abstract class AbstractClassMetadataFactory implements ClassMetadataFactory
{
/**
* Salt used by specific Object Manager implementation.
*
* @var string
*/
protected $cacheSalt = '__CLASSMETADATA__';
/** @var CacheItemPoolInterface|null */
private $cache;
/**
* @var array<string, ClassMetadata>
* @psalm-var CMTemplate[]
*/
private $loadedMetadata = [];
/** @var bool */
protected $initialized = false;
/** @var ReflectionService|null */
private $reflectionService = null;
/** @var ProxyClassNameResolver|null */
private $proxyClassNameResolver = null;
public function setCache(CacheItemPoolInterface $cache): void
{
$this->cache = $cache;
}
final protected function getCache(): ?CacheItemPoolInterface
{
return $this->cache;
}
/**
* Returns an array of all the loaded metadata currently in memory.
*
* @return ClassMetadata[]
* @psalm-return CMTemplate[]
*/
public function getLoadedMetadata()
{
return $this->loadedMetadata;
}
/**
* {@inheritDoc}
*/
public function getAllMetadata()
{
if (! $this->initialized) {
$this->initialize();
}
$driver = $this->getDriver();
$metadata = [];
foreach ($driver->getAllClassNames() as $className) {
$metadata[] = $this->getMetadataFor($className);
}
return $metadata;
}
public function setProxyClassNameResolver(ProxyClassNameResolver $resolver): void
{
$this->proxyClassNameResolver = $resolver;
}
/**
* Lazy initialization of this stuff, especially the metadata driver,
* since these are not needed at all when a metadata cache is active.
*
* @return void
*/
abstract protected function initialize();
/**
* Returns the mapping driver implementation.
*
* @return MappingDriver
*/
abstract protected function getDriver();
/**
* Wakes up reflection after ClassMetadata gets unserialized from cache.
*
* @psalm-param CMTemplate $class
*
* @return void
*/
abstract protected function wakeupReflection(
ClassMetadata $class,
ReflectionService $reflService
);
/**
* Initializes Reflection after ClassMetadata was constructed.
*
* @psalm-param CMTemplate $class
*
* @return void
*/
abstract protected function initializeReflection(
ClassMetadata $class,
ReflectionService $reflService
);
/**
* Checks whether the class metadata is an entity.
*
* This method should return false for mapped superclasses or embedded classes.
*
* @psalm-param CMTemplate $class
*
* @return bool
*/
abstract protected function isEntity(ClassMetadata $class);
/**
* Removes the prepended backslash of a class string to conform with how php outputs class names
*
* @psalm-param class-string $className
*
* @psalm-return class-string
*/
private function normalizeClassName(string $className): string
{
return ltrim($className, '\\');
}
/**
* {@inheritDoc}
*
* @throws ReflectionException
* @throws MappingException
*/
public function getMetadataFor(string $className)
{
$className = $this->normalizeClassName($className);
if (isset($this->loadedMetadata[$className])) {
return $this->loadedMetadata[$className];
}
if (class_exists($className, false) && (new ReflectionClass($className))->isAnonymous()) {
throw MappingException::classIsAnonymous($className);
}
if (! class_exists($className, false) && strpos($className, ':') !== false) {
throw MappingException::nonExistingClass($className);
}
$realClassName = $this->getRealClass($className);
if (isset($this->loadedMetadata[$realClassName])) {
// We do not have the alias name in the map, include it
return $this->loadedMetadata[$className] = $this->loadedMetadata[$realClassName];
}
try {
if ($this->cache !== null) {
$cached = $this->cache->getItem($this->getCacheKey($realClassName))->get();
if ($cached instanceof ClassMetadata) {
/** @psalm-var CMTemplate $cached */
$this->loadedMetadata[$realClassName] = $cached;
$this->wakeupReflection($cached, $this->getReflectionService());
} else {
$loadedMetadata = $this->loadMetadata($realClassName);
$classNames = array_combine(
array_map([$this, 'getCacheKey'], $loadedMetadata),
$loadedMetadata
);
foreach ($this->cache->getItems(array_keys($classNames)) as $item) {
if (! isset($classNames[$item->getKey()])) {
continue;
}
$item->set($this->loadedMetadata[$classNames[$item->getKey()]]);
$this->cache->saveDeferred($item);
}
$this->cache->commit();
}
} else {
$this->loadMetadata($realClassName);
}
} catch (MappingException $loadingException) {
$fallbackMetadataResponse = $this->onNotFoundMetadata($realClassName);
if ($fallbackMetadataResponse === null) {
throw $loadingException;
}
$this->loadedMetadata[$realClassName] = $fallbackMetadataResponse;
}
if ($className !== $realClassName) {
// We do not have the alias name in the map, include it
$this->loadedMetadata[$className] = $this->loadedMetadata[$realClassName];
}
return $this->loadedMetadata[$className];
}
/**
* {@inheritDoc}
*/
public function hasMetadataFor(string $className)
{
$className = $this->normalizeClassName($className);
return isset($this->loadedMetadata[$className]);
}
/**
* Sets the metadata descriptor for a specific class.
*
* NOTE: This is only useful in very special cases, like when generating proxy classes.
*
* @psalm-param class-string $className
* @psalm-param CMTemplate $class
*
* @return void
*/
public function setMetadataFor(string $className, ClassMetadata $class)
{
$this->loadedMetadata[$this->normalizeClassName($className)] = $class;
}
/**
* Gets an array of parent classes for the given entity class.
*
* @psalm-param class-string $name
*
* @return string[]
* @psalm-return list<class-string>
*/
protected function getParentClasses(string $name)
{
// Collect parent classes, ignoring transient (not-mapped) classes.
$parentClasses = [];
foreach (array_reverse($this->getReflectionService()->getParentClasses($name)) as $parentClass) {
if ($this->getDriver()->isTransient($parentClass)) {
continue;
}
$parentClasses[] = $parentClass;
}
return $parentClasses;
}
/**
* Loads the metadata of the class in question and all it's ancestors whose metadata
* is still not loaded.
*
* Important: The class $name does not necessarily exist at this point here.
* Scenarios in a code-generation setup might have access to XML/YAML
* Mapping files without the actual PHP code existing here. That is why the
* {@see \Doctrine\Persistence\Mapping\ReflectionService} interface
* should be used for reflection.
*
* @param string $name The name of the class for which the metadata should get loaded.
* @psalm-param class-string $name
*
* @return array<int, string>
* @psalm-return list<string>
*/
protected function loadMetadata(string $name)
{
if (! $this->initialized) {
$this->initialize();
}
$loaded = [];
$parentClasses = $this->getParentClasses($name);
$parentClasses[] = $name;
// Move down the hierarchy of parent classes, starting from the topmost class
$parent = null;
$rootEntityFound = false;
$visited = [];
$reflService = $this->getReflectionService();
foreach ($parentClasses as $className) {
if (isset($this->loadedMetadata[$className])) {
$parent = $this->loadedMetadata[$className];
if ($this->isEntity($parent)) {
$rootEntityFound = true;
array_unshift($visited, $className);
}
continue;
}
$class = $this->newClassMetadataInstance($className);
$this->initializeReflection($class, $reflService);
$this->doLoadMetadata($class, $parent, $rootEntityFound, $visited);
$this->loadedMetadata[$className] = $class;
$parent = $class;
if ($this->isEntity($class)) {
$rootEntityFound = true;
array_unshift($visited, $className);
}
$this->wakeupReflection($class, $reflService);
$loaded[] = $className;
}
return $loaded;
}
/**
* Provides a fallback hook for loading metadata when loading failed due to reflection/mapping exceptions
*
* Override this method to implement a fallback strategy for failed metadata loading
*
* @return ClassMetadata|null
* @psalm-return CMTemplate|null
*/
protected function onNotFoundMetadata(string $className)
{
return null;
}
/**
* Actually loads the metadata from the underlying metadata.
*
* @param bool $rootEntityFound True when there is another entity (non-mapped superclass) class above the current class in the PHP class hierarchy.
* @param list<class-string> $nonSuperclassParents All parent class names that are not marked as mapped superclasses, with the direct parent class being the first and the root entity class the last element.
* @psalm-param CMTemplate $class
* @psalm-param CMTemplate|null $parent
*
* @return void
*/
abstract protected function doLoadMetadata(
ClassMetadata $class,
?ClassMetadata $parent,
bool $rootEntityFound,
array $nonSuperclassParents
);
/**
* Creates a new ClassMetadata instance for the given class name.
*
* @psalm-param class-string<T> $className
*
* @return ClassMetadata<T>
* @psalm-return CMTemplate
*
* @template T of object
*/
abstract protected function newClassMetadataInstance(string $className);
/**
* {@inheritDoc}
*/
public function isTransient(string $className)
{
if (! $this->initialized) {
$this->initialize();
}
if (class_exists($className, false) && (new ReflectionClass($className))->isAnonymous()) {
return false;
}
if (! class_exists($className, false) && strpos($className, ':') !== false) {
throw MappingException::nonExistingClass($className);
}
/** @psalm-var class-string $className */
return $this->getDriver()->isTransient($className);
}
/**
* Sets the reflectionService.
*
* @return void
*/
public function setReflectionService(ReflectionService $reflectionService)
{
$this->reflectionService = $reflectionService;
}
/**
* Gets the reflection service associated with this metadata factory.
*
* @return ReflectionService
*/
public function getReflectionService()
{
if ($this->reflectionService === null) {
$this->reflectionService = new RuntimeReflectionService();
}
return $this->reflectionService;
}
protected function getCacheKey(string $realClassName): string
{
return str_replace('\\', '__', $realClassName) . $this->cacheSalt;
}
/**
* Gets the real class name of a class name that could be a proxy.
*
* @psalm-param class-string<Proxy<T>>|class-string<T> $class
*
* @psalm-return class-string<T>
*
* @template T of object
*/
private function getRealClass(string $class): string
{
if ($this->proxyClassNameResolver === null) {
$this->createDefaultProxyClassNameResolver();
}
assert($this->proxyClassNameResolver !== null);
return $this->proxyClassNameResolver->resolveClassName($class);
}
private function createDefaultProxyClassNameResolver(): void
{
$this->proxyClassNameResolver = new class implements ProxyClassNameResolver {
/**
* @psalm-param class-string<Proxy<T>>|class-string<T> $className
*
* @psalm-return class-string<T>
*
* @template T of object
*/
public function resolveClassName(string $className): string
{
$pos = strrpos($className, '\\' . Proxy::MARKER . '\\');
if ($pos === false) {
/** @psalm-var class-string<T> */
return $className;
}
/** @psalm-var class-string<T> */
return substr($className, $pos + Proxy::MARKER_LENGTH + 2);
}
};
}
}

View File

@@ -1,141 +0,0 @@
<?php
declare(strict_types=1);
namespace Doctrine\Persistence\Mapping;
use ReflectionClass;
/**
* Contract for a Doctrine persistence layer ClassMetadata class to implement.
*
* @template-covariant T of object
*/
interface ClassMetadata
{
/**
* Gets the fully-qualified class name of this persistent class.
*
* @return string
* @psalm-return class-string<T>
*/
public function getName();
/**
* Gets the mapped identifier field name.
*
* The returned structure is an array of the identifier field names.
*
* @return array<int, string>
* @psalm-return list<string>
*/
public function getIdentifier();
/**
* Gets the ReflectionClass instance for this mapped class.
*
* @return ReflectionClass<T>
*/
public function getReflectionClass();
/**
* Checks if the given field name is a mapped identifier for this class.
*
* @return bool
*/
public function isIdentifier(string $fieldName);
/**
* Checks if the given field is a mapped property for this class.
*
* @return bool
*/
public function hasField(string $fieldName);
/**
* Checks if the given field is a mapped association for this class.
*
* @return bool
*/
public function hasAssociation(string $fieldName);
/**
* Checks if the given field is a mapped single valued association for this class.
*
* @return bool
*/
public function isSingleValuedAssociation(string $fieldName);
/**
* Checks if the given field is a mapped collection valued association for this class.
*
* @return bool
*/
public function isCollectionValuedAssociation(string $fieldName);
/**
* A numerically indexed list of field names of this persistent class.
*
* This array includes identifier fields if present on this class.
*
* @return array<int, string>
*/
public function getFieldNames();
/**
* Returns an array of identifier field names numerically indexed.
*
* @return array<int, string>
*/
public function getIdentifierFieldNames();
/**
* Returns a numerically indexed list of association names of this persistent class.
*
* This array includes identifier associations if present on this class.
*
* @return array<int, string>
*/
public function getAssociationNames();
/**
* Returns a type name of this field.
*
* This type names can be implementation specific but should at least include the php types:
* integer, string, boolean, float/double, datetime.
*
* @return string|null
*/
public function getTypeOfField(string $fieldName);
/**
* Returns the target class name of the given association.
*
* @return string|null
* @psalm-return class-string|null
*/
public function getAssociationTargetClass(string $assocName);
/**
* Checks if the association is the inverse side of a bidirectional association.
*
* @return bool
*/
public function isAssociationInverseSide(string $assocName);
/**
* Returns the target field of the owning side of the association.
*
* @return string
*/
public function getAssociationMappedByTargetField(string $assocName);
/**
* Returns the identifier of this object as an array with field name as key.
*
* Has to return an empty array if no identifier isset.
*
* @return array<string, mixed>
*/
public function getIdentifierValues(object $object);
}

View File

@@ -1,61 +0,0 @@
<?php
declare(strict_types=1);
namespace Doctrine\Persistence\Mapping;
/**
* Contract for a Doctrine persistence layer ClassMetadata class to implement.
*
* @template T of ClassMetadata
*/
interface ClassMetadataFactory
{
/**
* Forces the factory to load the metadata of all classes known to the underlying
* mapping driver.
*
* @return ClassMetadata[] The ClassMetadata instances of all mapped classes.
* @psalm-return list<T>
*/
public function getAllMetadata();
/**
* Gets the class metadata descriptor for a class.
*
* @param class-string $className The name of the class.
*
* @return ClassMetadata
* @psalm-return T
*/
public function getMetadataFor(string $className);
/**
* Checks whether the factory has the metadata for a class loaded already.
*
* @param class-string $className
*
* @return bool TRUE if the metadata of the class in question is already loaded, FALSE otherwise.
*/
public function hasMetadataFor(string $className);
/**
* Sets the metadata descriptor for a specific class.
*
* @param class-string $className
* @psalm-param T $class
*
* @return void
*/
public function setMetadataFor(string $className, ClassMetadata $class);
/**
* Returns whether the class with the specified name should have its metadata loaded.
* This is only the case if it is either mapped directly or as a MappedSuperclass.
*
* @psalm-param class-string $className
*
* @return bool
*/
public function isTransient(string $className);
}

View File

@@ -1,212 +0,0 @@
<?php
declare(strict_types=1);
namespace Doctrine\Persistence\Mapping\Driver;
use Doctrine\Persistence\Mapping\MappingException;
use FilesystemIterator;
use RecursiveDirectoryIterator;
use RecursiveIteratorIterator;
use RecursiveRegexIterator;
use ReflectionClass;
use RegexIterator;
use function array_merge;
use function array_unique;
use function assert;
use function get_declared_classes;
use function in_array;
use function is_dir;
use function preg_match;
use function preg_quote;
use function realpath;
use function str_replace;
use function strpos;
/**
* The ColocatedMappingDriver reads the mapping metadata located near the code.
*/
trait ColocatedMappingDriver
{
/**
* The paths where to look for mapping files.
*
* @var array<int, string>
*/
protected $paths = [];
/**
* The paths excluded from path where to look for mapping files.
*
* @var array<int, string>
*/
protected $excludePaths = [];
/**
* The file extension of mapping documents.
*
* @var string
*/
protected $fileExtension = '.php';
/**
* Cache for getAllClassNames().
*
* @var array<int, string>|null
* @psalm-var list<class-string>|null
*/
protected $classNames;
/**
* Appends lookup paths to metadata driver.
*
* @param array<int, string> $paths
*
* @return void
*/
public function addPaths(array $paths)
{
$this->paths = array_unique(array_merge($this->paths, $paths));
}
/**
* Retrieves the defined metadata lookup paths.
*
* @return array<int, string>
*/
public function getPaths()
{
return $this->paths;
}
/**
* Append exclude lookup paths to metadata driver.
*
* @param string[] $paths
*
* @return void
*/
public function addExcludePaths(array $paths)
{
$this->excludePaths = array_unique(array_merge($this->excludePaths, $paths));
}
/**
* Retrieve the defined metadata lookup exclude paths.
*
* @return array<int, string>
*/
public function getExcludePaths()
{
return $this->excludePaths;
}
/**
* Gets the file extension used to look for mapping files under.
*
* @return string
*/
public function getFileExtension()
{
return $this->fileExtension;
}
/**
* Sets the file extension used to look for mapping files under.
*
* @return void
*/
public function setFileExtension(string $fileExtension)
{
$this->fileExtension = $fileExtension;
}
/**
* {@inheritDoc}
*
* Returns whether the class with the specified name is transient. Only non-transient
* classes, that is entities and mapped superclasses, should have their metadata loaded.
*
* @psalm-param class-string $className
*
* @return bool
*/
abstract public function isTransient(string $className);
/**
* Gets the names of all mapped classes known to this driver.
*
* @return string[] The names of all mapped classes known to this driver.
* @psalm-return list<class-string>
*/
public function getAllClassNames()
{
if ($this->classNames !== null) {
return $this->classNames;
}
if ($this->paths === []) {
throw MappingException::pathRequiredForDriver(static::class);
}
$classes = [];
$includedFiles = [];
foreach ($this->paths as $path) {
if (! is_dir($path)) {
throw MappingException::fileMappingDriversRequireConfiguredDirectoryPath($path);
}
$iterator = new RegexIterator(
new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($path, FilesystemIterator::SKIP_DOTS),
RecursiveIteratorIterator::LEAVES_ONLY
),
'/^.+' . preg_quote($this->fileExtension) . '$/i',
RecursiveRegexIterator::GET_MATCH
);
foreach ($iterator as $file) {
$sourceFile = $file[0];
if (preg_match('(^phar:)i', $sourceFile) === 0) {
$sourceFile = realpath($sourceFile);
}
foreach ($this->excludePaths as $excludePath) {
$realExcludePath = realpath($excludePath);
assert($realExcludePath !== false);
$exclude = str_replace('\\', '/', $realExcludePath);
$current = str_replace('\\', '/', $sourceFile);
if (strpos($current, $exclude) !== false) {
continue 2;
}
}
require_once $sourceFile;
$includedFiles[] = $sourceFile;
}
}
$declared = get_declared_classes();
foreach ($declared as $className) {
$rc = new ReflectionClass($className);
$sourceFile = $rc->getFileName();
if (! in_array($sourceFile, $includedFiles, true) || $this->isTransient($className)) {
continue;
}
$classes[] = $className;
}
$this->classNames = $classes;
return $classes;
}
}

View File

@@ -1,175 +0,0 @@
<?php
declare(strict_types=1);
namespace Doctrine\Persistence\Mapping\Driver;
use Doctrine\Persistence\Mapping\MappingException;
use RecursiveDirectoryIterator;
use RecursiveIteratorIterator;
use function array_merge;
use function array_unique;
use function assert;
use function is_dir;
use function is_file;
use function is_string;
use function str_replace;
use const DIRECTORY_SEPARATOR;
/**
* Locates the file that contains the metadata information for a given class name.
*
* This behavior is independent of the actual content of the file. It just detects
* the file which is responsible for the given class name.
*/
class DefaultFileLocator implements FileLocator
{
/**
* The paths where to look for mapping files.
*
* @var array<int, string>
*/
protected $paths = [];
/**
* The file extension of mapping documents.
*
* @var string|null
*/
protected $fileExtension;
/**
* Initializes a new FileDriver that looks in the given path(s) for mapping
* documents and operates in the specified operating mode.
*
* @param string|array<int, string> $paths One or multiple paths where mapping documents
* can be found.
* @param string|null $fileExtension The file extension of mapping documents,
* usually prefixed with a dot.
*/
public function __construct($paths, ?string $fileExtension = null)
{
$this->addPaths((array) $paths);
$this->fileExtension = $fileExtension;
}
/**
* Appends lookup paths to metadata driver.
*
* @param array<int, string> $paths
*
* @return void
*/
public function addPaths(array $paths)
{
$this->paths = array_unique(array_merge($this->paths, $paths));
}
/**
* Retrieves the defined metadata lookup paths.
*
* @return array<int, string>
*/
public function getPaths()
{
return $this->paths;
}
/**
* Gets the file extension used to look for mapping files under.
*
* @return string|null
*/
public function getFileExtension()
{
return $this->fileExtension;
}
/**
* Sets the file extension used to look for mapping files under.
*
* @param string|null $fileExtension The file extension to set.
*
* @return void
*/
public function setFileExtension(?string $fileExtension)
{
$this->fileExtension = $fileExtension;
}
/**
* {@inheritDoc}
*/
public function findMappingFile(string $className)
{
$fileName = str_replace('\\', '.', $className) . $this->fileExtension;
// Check whether file exists
foreach ($this->paths as $path) {
if (is_file($path . DIRECTORY_SEPARATOR . $fileName)) {
return $path . DIRECTORY_SEPARATOR . $fileName;
}
}
throw MappingException::mappingFileNotFound($className, $fileName);
}
/**
* {@inheritDoc}
*/
public function getAllClassNames(string $globalBasename)
{
if ($this->paths === []) {
return [];
}
$classes = [];
foreach ($this->paths as $path) {
if (! is_dir($path)) {
throw MappingException::fileMappingDriversRequireConfiguredDirectoryPath($path);
}
$iterator = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($path),
RecursiveIteratorIterator::LEAVES_ONLY
);
foreach ($iterator as $file) {
$fileName = $file->getBasename($this->fileExtension);
if ($fileName === $file->getBasename() || $fileName === $globalBasename) {
continue;
}
// NOTE: All files found here means classes are not transient!
assert(is_string($fileName));
/** @psalm-var class-string */
$class = str_replace('.', '\\', $fileName);
$classes[] = $class;
}
}
return $classes;
}
/**
* {@inheritDoc}
*/
public function fileExists(string $className)
{
$fileName = str_replace('\\', '.', $className) . $this->fileExtension;
// Check whether file exists
foreach ($this->paths as $path) {
if (is_file($path . DIRECTORY_SEPARATOR . $fileName)) {
return true;
}
}
return false;
}
}

View File

@@ -1,212 +0,0 @@
<?php
declare(strict_types=1);
namespace Doctrine\Persistence\Mapping\Driver;
use Doctrine\Persistence\Mapping\ClassMetadata;
use Doctrine\Persistence\Mapping\MappingException;
use function array_keys;
use function array_merge;
use function array_unique;
use function array_values;
use function is_file;
use function str_replace;
/**
* Base driver for file-based metadata drivers.
*
* A file driver operates in a mode where it loads the mapping files of individual
* classes on demand. This requires the user to adhere to the convention of 1 mapping
* file per class and the file names of the mapping files must correspond to the full
* class name, including namespace, with the namespace delimiters '\', replaced by dots '.'.
*/
abstract class FileDriver implements MappingDriver
{
/** @var FileLocator */
protected $locator;
/**
* @var ClassMetadata[]|null
* @psalm-var array<class-string, ClassMetadata<object>>|null
*/
protected $classCache;
/** @var string */
protected $globalBasename = '';
/**
* Initializes a new FileDriver that looks in the given path(s) for mapping
* documents and operates in the specified operating mode.
*
* @param string|array<int, string>|FileLocator $locator A FileLocator or one/multiple paths
* where mapping documents can be found.
*/
public function __construct($locator, ?string $fileExtension = null)
{
if ($locator instanceof FileLocator) {
$this->locator = $locator;
} else {
$this->locator = new DefaultFileLocator((array) $locator, $fileExtension);
}
}
/**
* Sets the global basename.
*
* @return void
*/
public function setGlobalBasename(string $file)
{
$this->globalBasename = $file;
}
/**
* Retrieves the global basename.
*
* @return string|null
*/
public function getGlobalBasename()
{
return $this->globalBasename;
}
/**
* Gets the element of schema meta data for the class from the mapping file.
* This will lazily load the mapping file if it is not loaded yet.
*
* @psalm-param class-string $className
*
* @return ClassMetadata The element of schema meta data.
* @psalm-return ClassMetadata<object>
*
* @throws MappingException
*/
public function getElement(string $className)
{
if ($this->classCache === null) {
$this->initialize();
}
if (isset($this->classCache[$className])) {
return $this->classCache[$className];
}
$result = $this->loadMappingFile($this->locator->findMappingFile($className));
if (! isset($result[$className])) {
throw MappingException::invalidMappingFile(
$className,
str_replace('\\', '.', $className) . $this->locator->getFileExtension()
);
}
$this->classCache[$className] = $result[$className];
return $result[$className];
}
/**
* {@inheritDoc}
*/
public function isTransient(string $className)
{
if ($this->classCache === null) {
$this->initialize();
}
if (isset($this->classCache[$className])) {
return false;
}
return ! $this->locator->fileExists($className);
}
/**
* {@inheritDoc}
*/
public function getAllClassNames()
{
if ($this->classCache === null) {
$this->initialize();
}
if ($this->classCache === []) {
return $this->locator->getAllClassNames($this->globalBasename);
}
/** @psalm-var array<class-string, ClassMetadata<object>> $classCache */
$classCache = $this->classCache;
/** @var list<class-string> $keys */
$keys = array_keys($classCache);
return array_values(array_unique(array_merge(
$keys,
$this->locator->getAllClassNames($this->globalBasename)
)));
}
/**
* Loads a mapping file with the given name and returns a map
* from class/entity names to their corresponding file driver elements.
*
* @param string $file The mapping file to load.
*
* @return ClassMetadata[]
* @psalm-return array<class-string, ClassMetadata<object>>
*/
abstract protected function loadMappingFile(string $file);
/**
* Initializes the class cache from all the global files.
*
* Using this feature adds a substantial performance hit to file drivers as
* more metadata has to be loaded into memory than might actually be
* necessary. This may not be relevant to scenarios where caching of
* metadata is in place, however hits very hard in scenarios where no
* caching is used.
*
* @return void
*/
protected function initialize()
{
$this->classCache = [];
if ($this->globalBasename === null) {
return;
}
foreach ($this->locator->getPaths() as $path) {
$file = $path . '/' . $this->globalBasename . $this->locator->getFileExtension();
if (! is_file($file)) {
continue;
}
$this->classCache = array_merge(
$this->classCache,
$this->loadMappingFile($file)
);
}
}
/**
* Retrieves the locator used to discover mapping files by className.
*
* @return FileLocator
*/
public function getLocator()
{
return $this->locator;
}
/**
* Sets the locator used to discover mapping files by className.
*
* @return void
*/
public function setLocator(FileLocator $locator)
{
$this->locator = $locator;
}
}

View File

@@ -1,52 +0,0 @@
<?php
declare(strict_types=1);
namespace Doctrine\Persistence\Mapping\Driver;
/**
* Locates the file that contains the metadata information for a given class name.
*
* This behavior is independent of the actual content of the file. It just detects
* the file which is responsible for the given class name.
*/
interface FileLocator
{
/**
* Locates mapping file for the given class name.
*
* @return string
*/
public function findMappingFile(string $className);
/**
* Gets all class names that are found with this file locator.
*
* @param string $globalBasename Passed to allow excluding the basename.
*
* @return array<int, string>
* @psalm-return list<class-string>
*/
public function getAllClassNames(string $globalBasename);
/**
* Checks if a file can be found for this class name.
*
* @return bool
*/
public function fileExists(string $className);
/**
* Gets all the paths that this file locator looks for mapping files.
*
* @return array<int, string>
*/
public function getPaths();
/**
* Gets the file extension that mapping files are suffixed with.
*
* @return string|null
*/
public function getFileExtension();
}

View File

@@ -1,43 +0,0 @@
<?php
declare(strict_types=1);
namespace Doctrine\Persistence\Mapping\Driver;
use Doctrine\Persistence\Mapping\ClassMetadata;
/**
* Contract for metadata drivers.
*/
interface MappingDriver
{
/**
* Loads the metadata for the specified class into the provided container.
*
* @psalm-param class-string<T> $className
* @psalm-param ClassMetadata<T> $metadata
*
* @return void
*
* @template T of object
*/
public function loadMetadataForClass(string $className, ClassMetadata $metadata);
/**
* Gets the names of all mapped classes known to this driver.
*
* @return array<int, string> The names of all mapped classes known to this driver.
* @psalm-return list<class-string>
*/
public function getAllClassNames();
/**
* Returns whether the class with the specified name should have its metadata loaded.
* This is only the case if it is either mapped as an Entity or a MappedSuperclass.
*
* @psalm-param class-string $className
*
* @return bool
*/
public function isTransient(string $className);
}

View File

@@ -1,142 +0,0 @@
<?php
declare(strict_types=1);
namespace Doctrine\Persistence\Mapping\Driver;
use Doctrine\Persistence\Mapping\ClassMetadata;
use Doctrine\Persistence\Mapping\MappingException;
use function array_keys;
use function spl_object_hash;
use function strpos;
/**
* The DriverChain allows you to add multiple other mapping drivers for
* certain namespaces.
*/
class MappingDriverChain implements MappingDriver
{
/**
* The default driver.
*
* @var MappingDriver|null
*/
private $defaultDriver;
/** @var array<string, MappingDriver> */
private $drivers = [];
/**
* Gets the default driver.
*
* @return MappingDriver|null
*/
public function getDefaultDriver()
{
return $this->defaultDriver;
}
/**
* Set the default driver.
*
* @return void
*/
public function setDefaultDriver(MappingDriver $driver)
{
$this->defaultDriver = $driver;
}
/**
* Adds a nested driver.
*
* @return void
*/
public function addDriver(MappingDriver $nestedDriver, string $namespace)
{
$this->drivers[$namespace] = $nestedDriver;
}
/**
* Gets the array of nested drivers.
*
* @return array<string, MappingDriver> $drivers
*/
public function getDrivers()
{
return $this->drivers;
}
/**
* {@inheritDoc}
*/
public function loadMetadataForClass(string $className, ClassMetadata $metadata)
{
foreach ($this->drivers as $namespace => $driver) {
if (strpos($className, $namespace) === 0) {
$driver->loadMetadataForClass($className, $metadata);
return;
}
}
if ($this->defaultDriver !== null) {
$this->defaultDriver->loadMetadataForClass($className, $metadata);
return;
}
throw MappingException::classNotFoundInNamespaces($className, array_keys($this->drivers));
}
/**
* {@inheritDoc}
*/
public function getAllClassNames()
{
$classNames = [];
$driverClasses = [];
foreach ($this->drivers as $namespace => $driver) {
$oid = spl_object_hash($driver);
if (! isset($driverClasses[$oid])) {
$driverClasses[$oid] = $driver->getAllClassNames();
}
foreach ($driverClasses[$oid] as $className) {
if (strpos($className, $namespace) !== 0) {
continue;
}
$classNames[$className] = true;
}
}
if ($this->defaultDriver !== null) {
foreach ($this->defaultDriver->getAllClassNames() as $className) {
$classNames[$className] = true;
}
}
return array_keys($classNames);
}
/**
* {@inheritDoc}
*/
public function isTransient(string $className)
{
foreach ($this->drivers as $namespace => $driver) {
if (strpos($className, $namespace) === 0) {
return $driver->isTransient($className);
}
}
if ($this->defaultDriver !== null) {
return $this->defaultDriver->isTransient($className);
}
return true;
}
}

View File

@@ -1,47 +0,0 @@
<?php
declare(strict_types=1);
namespace Doctrine\Persistence\Mapping\Driver;
use Doctrine\Persistence\Mapping\ClassMetadata;
/**
* The PHPDriver includes php files which just populate ClassMetadataInfo
* instances with plain PHP code.
*/
class PHPDriver extends FileDriver
{
/**
* @var ClassMetadata
* @psalm-var ClassMetadata<object>
*/
protected $metadata;
/** @param string|array<int, string>|FileLocator $locator */
public function __construct($locator)
{
parent::__construct($locator, '.php');
}
/**
* {@inheritDoc}
*/
public function loadMetadataForClass(string $className, ClassMetadata $metadata)
{
$this->metadata = $metadata;
$this->loadMappingFile($this->locator->findMappingFile($className));
}
/**
* {@inheritDoc}
*/
protected function loadMappingFile(string $file)
{
$metadata = $this->metadata;
include $file;
return [$metadata->getName() => $metadata];
}
}

View File

@@ -1,132 +0,0 @@
<?php
declare(strict_types=1);
namespace Doctrine\Persistence\Mapping\Driver;
use Doctrine\Persistence\Mapping\ClassMetadata;
use Doctrine\Persistence\Mapping\MappingException;
use RecursiveDirectoryIterator;
use RecursiveIteratorIterator;
use ReflectionClass;
use function array_merge;
use function array_unique;
use function get_declared_classes;
use function in_array;
use function is_dir;
use function method_exists;
use function realpath;
/**
* The StaticPHPDriver calls a static loadMetadata() method on your entity
* classes where you can manually populate the ClassMetadata instance.
*/
class StaticPHPDriver implements MappingDriver
{
/**
* Paths of entity directories.
*
* @var array<int, string>
*/
private $paths = [];
/**
* Map of all class names.
*
* @var array<int, string>
* @psalm-var list<class-string>
*/
private $classNames;
/** @param array<int, string>|string $paths */
public function __construct($paths)
{
$this->addPaths((array) $paths);
}
/**
* @param array<int, string> $paths
*
* @return void
*/
public function addPaths(array $paths)
{
$this->paths = array_unique(array_merge($this->paths, $paths));
}
/**
* {@inheritdoc}
*/
public function loadMetadataForClass(string $className, ClassMetadata $metadata)
{
$className::loadMetadata($metadata);
}
/**
* {@inheritDoc}
*
* @todo Same code exists in ColocatedMappingDriver, should we re-use it
* somehow or not worry about it?
*/
public function getAllClassNames()
{
if ($this->classNames !== null) {
return $this->classNames;
}
if ($this->paths === []) {
throw MappingException::pathRequiredForDriver(static::class);
}
$classes = [];
$includedFiles = [];
foreach ($this->paths as $path) {
if (! is_dir($path)) {
throw MappingException::fileMappingDriversRequireConfiguredDirectoryPath($path);
}
$iterator = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($path),
RecursiveIteratorIterator::LEAVES_ONLY
);
foreach ($iterator as $file) {
if ($file->getBasename('.php') === $file->getBasename()) {
continue;
}
$sourceFile = realpath($file->getPathName());
require_once $sourceFile;
$includedFiles[] = $sourceFile;
}
}
$declared = get_declared_classes();
foreach ($declared as $className) {
$rc = new ReflectionClass($className);
$sourceFile = $rc->getFileName();
if (! in_array($sourceFile, $includedFiles, true) || $this->isTransient($className)) {
continue;
}
$classes[] = $className;
}
$this->classNames = $classes;
return $classes;
}
/**
* {@inheritdoc}
*/
public function isTransient(string $className)
{
return ! method_exists($className, 'loadMetadata');
}
}

View File

@@ -1,265 +0,0 @@
<?php
declare(strict_types=1);
namespace Doctrine\Persistence\Mapping\Driver;
use Doctrine\Persistence\Mapping\MappingException;
use InvalidArgumentException;
use RecursiveDirectoryIterator;
use RecursiveIteratorIterator;
use RuntimeException;
use function array_keys;
use function array_merge;
use function assert;
use function is_dir;
use function is_file;
use function is_int;
use function realpath;
use function sprintf;
use function str_replace;
use function strlen;
use function strpos;
use function strrpos;
use function strtr;
use function substr;
use const DIRECTORY_SEPARATOR;
/**
* The Symfony File Locator makes a simplifying assumptions compared
* to the DefaultFileLocator. By assuming paths only contain entities of a certain
* namespace the mapping files consists of the short classname only.
*/
class SymfonyFileLocator implements FileLocator
{
/**
* The paths where to look for mapping files.
*
* @var array<int, string>
*/
protected $paths = [];
/**
* A map of mapping directory path to namespace prefix used to expand class shortnames.
*
* @var array<string, string>
*/
protected $prefixes = [];
/**
* File extension that is searched for.
*
* @var string|null
*/
protected $fileExtension;
/**
* Represents PHP namespace delimiters when looking for files
*
* @var string
*/
private $nsSeparator;
/**
* @param array<string, string> $prefixes
* @param string $nsSeparator String which would be used when converting FQCN
* to filename and vice versa. Should not be empty
*/
public function __construct(
array $prefixes,
string $fileExtension = '',
string $nsSeparator = '.'
) {
$this->addNamespacePrefixes($prefixes);
$this->fileExtension = $fileExtension;
if ($nsSeparator === '') {
throw new InvalidArgumentException('Namespace separator should not be empty');
}
$this->nsSeparator = $nsSeparator;
}
/**
* Adds Namespace Prefixes.
*
* @param array<string, string> $prefixes
*
* @return void
*/
public function addNamespacePrefixes(array $prefixes)
{
$this->prefixes = array_merge($this->prefixes, $prefixes);
$this->paths = array_merge($this->paths, array_keys($prefixes));
}
/**
* Gets Namespace Prefixes.
*
* @return string[]
*/
public function getNamespacePrefixes()
{
return $this->prefixes;
}
/**
* {@inheritDoc}
*/
public function getPaths()
{
return $this->paths;
}
/**
* {@inheritDoc}
*/
public function getFileExtension()
{
return $this->fileExtension;
}
/**
* Sets the file extension used to look for mapping files under.
*
* @param string $fileExtension The file extension to set.
*
* @return void
*/
public function setFileExtension(string $fileExtension)
{
$this->fileExtension = $fileExtension;
}
/**
* {@inheritDoc}
*/
public function fileExists(string $className)
{
$defaultFileName = str_replace('\\', $this->nsSeparator, $className) . $this->fileExtension;
foreach ($this->paths as $path) {
if (! isset($this->prefixes[$path])) {
// global namespace class
if (is_file($path . DIRECTORY_SEPARATOR . $defaultFileName)) {
return true;
}
continue;
}
$prefix = $this->prefixes[$path];
if (strpos($className, $prefix . '\\') !== 0) {
continue;
}
$filename = $path . '/' . strtr(substr($className, strlen($prefix) + 1), '\\', $this->nsSeparator) . $this->fileExtension;
if (is_file($filename)) {
return true;
}
}
return false;
}
/**
* {@inheritDoc}
*/
public function getAllClassNames(?string $globalBasename = null)
{
if ($this->paths === []) {
return [];
}
$classes = [];
foreach ($this->paths as $path) {
if (! is_dir($path)) {
throw MappingException::fileMappingDriversRequireConfiguredDirectoryPath($path);
}
$iterator = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($path),
RecursiveIteratorIterator::LEAVES_ONLY
);
foreach ($iterator as $file) {
$fileName = $file->getBasename($this->fileExtension);
if ($fileName === $file->getBasename() || $fileName === $globalBasename) {
continue;
}
// NOTE: All files found here means classes are not transient!
if (isset($this->prefixes[$path])) {
// Calculate namespace suffix for given prefix as a relative path from basepath to file path
$nsSuffix = strtr(
substr($this->realpath($file->getPath()), strlen($this->realpath($path))),
$this->nsSeparator,
'\\'
);
/** @psalm-var class-string */
$class = $this->prefixes[$path] . str_replace(DIRECTORY_SEPARATOR, '\\', $nsSuffix) . '\\' . str_replace($this->nsSeparator, '\\', $fileName);
} else {
/** @psalm-var class-string */
$class = str_replace($this->nsSeparator, '\\', $fileName);
}
$classes[] = $class;
}
}
return $classes;
}
/**
* {@inheritDoc}
*/
public function findMappingFile(string $className)
{
$defaultFileName = str_replace('\\', $this->nsSeparator, $className) . $this->fileExtension;
foreach ($this->paths as $path) {
if (! isset($this->prefixes[$path])) {
if (is_file($path . DIRECTORY_SEPARATOR . $defaultFileName)) {
return $path . DIRECTORY_SEPARATOR . $defaultFileName;
}
continue;
}
$prefix = $this->prefixes[$path];
if (strpos($className, $prefix . '\\') !== 0) {
continue;
}
$filename = $path . '/' . strtr(substr($className, strlen($prefix) + 1), '\\', $this->nsSeparator) . $this->fileExtension;
if (is_file($filename)) {
return $filename;
}
}
$pos = strrpos($className, '\\');
assert(is_int($pos));
throw MappingException::mappingFileNotFound(
$className,
substr($className, $pos + 1) . $this->fileExtension
);
}
private function realpath(string $path): string
{
$realpath = realpath($path);
if ($realpath === false) {
throw new RuntimeException(sprintf('Could not get realpath for %s', $path));
}
return $realpath;
}
}

View File

@@ -1,88 +0,0 @@
<?php
declare(strict_types=1);
namespace Doctrine\Persistence\Mapping;
use Exception;
use function implode;
use function sprintf;
/**
* A MappingException indicates that something is wrong with the mapping setup.
*/
class MappingException extends Exception
{
/**
* @param array<int, string> $namespaces
*
* @return self
*/
public static function classNotFoundInNamespaces(
string $className,
array $namespaces
) {
return new self(sprintf(
"The class '%s' was not found in the chain configured namespaces %s",
$className,
implode(', ', $namespaces)
));
}
/** @param class-string $driverClassName */
public static function pathRequiredForDriver(string $driverClassName): self
{
return new self(sprintf(
'Specifying the paths to your entities is required when using %s to retrieve all class names.',
$driverClassName
));
}
/** @return self */
public static function fileMappingDriversRequireConfiguredDirectoryPath(
?string $path = null
) {
if ($path !== null) {
$path = '[' . $path . ']';
}
return new self(sprintf(
'File mapping drivers must have a valid directory path, ' .
'however the given path %s seems to be incorrect!',
(string) $path
));
}
/** @return self */
public static function mappingFileNotFound(string $entityName, string $fileName)
{
return new self(sprintf(
"No mapping file found named '%s' for class '%s'.",
$fileName,
$entityName
));
}
/** @return self */
public static function invalidMappingFile(string $entityName, string $fileName)
{
return new self(sprintf(
"Invalid mapping file '%s' for class '%s'.",
$fileName,
$entityName
));
}
/** @return self */
public static function nonExistingClass(string $className)
{
return new self(sprintf("Class '%s' does not exist", $className));
}
/** @param class-string $className */
public static function classIsAnonymous(string $className): self
{
return new self(sprintf('Class "%s" is anonymous', $className));
}
}

View File

@@ -1,19 +0,0 @@
<?php
declare(strict_types=1);
namespace Doctrine\Persistence\Mapping;
use Doctrine\Persistence\Proxy;
interface ProxyClassNameResolver
{
/**
* @psalm-param class-string<Proxy<T>>|class-string<T> $className
*
* @psalm-return class-string<T>
*
* @template T of object
*/
public function resolveClassName(string $className): string;
}

View File

@@ -1,75 +0,0 @@
<?php
declare(strict_types=1);
namespace Doctrine\Persistence\Mapping;
use ReflectionClass;
use ReflectionProperty;
/**
* Very simple reflection service abstraction.
*
* This is required inside metadata layers that may require either
* static or runtime reflection.
*/
interface ReflectionService
{
/**
* Returns an array of the parent classes (not interfaces) for the given class.
*
* @psalm-param class-string $class
*
* @return string[]
* @psalm-return class-string[]
*
* @throws MappingException
*/
public function getParentClasses(string $class);
/**
* Returns the shortname of a class.
*
* @psalm-param class-string $class
*
* @return string
*/
public function getClassShortName(string $class);
/**
* @psalm-param class-string $class
*
* @return string
*/
public function getClassNamespace(string $class);
/**
* Returns a reflection class instance or null.
*
* @psalm-param class-string<T> $class
*
* @return ReflectionClass|null
* @psalm-return ReflectionClass<T>|null
*
* @template T of object
*/
public function getClass(string $class);
/**
* Returns an accessible property (setAccessible(true)) or null.
*
* @psalm-param class-string $class
*
* @return ReflectionProperty|null
*/
public function getAccessibleProperty(string $class, string $property);
/**
* Checks if the class have a public method with the given name.
*
* @psalm-param class-string $class
*
* @return bool
*/
public function hasPublicMethod(string $class, string $method);
}

View File

@@ -1,111 +0,0 @@
<?php
declare(strict_types=1);
namespace Doctrine\Persistence\Mapping;
use Doctrine\Persistence\Reflection\RuntimeReflectionProperty;
use Doctrine\Persistence\Reflection\TypedNoDefaultReflectionProperty;
use ReflectionClass;
use ReflectionException;
use ReflectionMethod;
use function array_key_exists;
use function assert;
use function class_exists;
use function class_parents;
use function phpversion;
use function version_compare;
/**
* PHP Runtime Reflection Service.
*/
class RuntimeReflectionService implements ReflectionService
{
/** @var bool */
private $supportsTypedPropertiesWorkaround;
public function __construct()
{
$this->supportsTypedPropertiesWorkaround = version_compare(phpversion(), '7.4.0') >= 0;
}
/**
* {@inheritDoc}
*/
public function getParentClasses(string $class)
{
if (! class_exists($class)) {
throw MappingException::nonExistingClass($class);
}
$parents = class_parents($class);
assert($parents !== false);
return $parents;
}
/**
* {@inheritDoc}
*/
public function getClassShortName(string $class)
{
$reflectionClass = new ReflectionClass($class);
return $reflectionClass->getShortName();
}
/**
* {@inheritDoc}
*/
public function getClassNamespace(string $class)
{
$reflectionClass = new ReflectionClass($class);
return $reflectionClass->getNamespaceName();
}
/**
* @psalm-param class-string<T> $class
*
* @return ReflectionClass
* @psalm-return ReflectionClass<T>
*
* @template T of object
*/
public function getClass(string $class)
{
return new ReflectionClass($class);
}
/**
* {@inheritDoc}
*/
public function getAccessibleProperty(string $class, string $property)
{
$reflectionProperty = new RuntimeReflectionProperty($class, $property);
if ($this->supportsTypedPropertiesWorkaround && ! array_key_exists($property, $this->getClass($class)->getDefaultProperties())) {
$reflectionProperty = new TypedNoDefaultReflectionProperty($class, $property);
}
$reflectionProperty->setAccessible(true);
return $reflectionProperty;
}
/**
* {@inheritDoc}
*/
public function hasPublicMethod(string $class, string $method)
{
try {
$reflectionMethod = new ReflectionMethod($class, $method);
} catch (ReflectionException $e) {
return false;
}
return $reflectionMethod->isPublic();
}
}

View File

@@ -1,78 +0,0 @@
<?php
declare(strict_types=1);
namespace Doctrine\Persistence\Mapping;
use function strpos;
use function strrev;
use function strrpos;
use function substr;
/**
* PHP Runtime Reflection Service.
*/
class StaticReflectionService implements ReflectionService
{
/**
* {@inheritDoc}
*/
public function getParentClasses(string $class)
{
return [];
}
/**
* {@inheritDoc}
*/
public function getClassShortName(string $class)
{
$nsSeparatorLastPosition = strrpos($class, '\\');
if ($nsSeparatorLastPosition !== false) {
$class = substr($class, $nsSeparatorLastPosition + 1);
}
return $class;
}
/**
* {@inheritDoc}
*/
public function getClassNamespace(string $class)
{
$namespace = '';
if (strpos($class, '\\') !== false) {
$namespace = strrev(substr(strrev($class), (int) strpos(strrev($class), '\\') + 1));
}
return $namespace;
}
/**
* {@inheritDoc}
*
* @return null
*/
public function getClass(string $class)
{
return null;
}
/**
* {@inheritDoc}
*/
public function getAccessibleProperty(string $class, string $property)
{
return null;
}
/**
* {@inheritDoc}
*/
public function hasPublicMethod(string $class, string $method)
{
return true;
}
}

View File

@@ -1,22 +0,0 @@
<?php
declare(strict_types=1);
namespace Doctrine\Persistence;
/**
* Interface for classes that notify event listeners of changes to their managed properties.
*
* This interface is implemented by objects that manually want to notify their object manager or
* other listeners when properties change, instead of relying on the object manager to compute
* property changes itself when changes are to be persisted.
*/
interface NotifyPropertyChanged
{
/**
* Adds a listener that wants to be notified about property changes.
*
* @return void
*/
public function addPropertyChangedListener(PropertyChangedListener $listener);
}

View File

@@ -1,143 +0,0 @@
<?php
declare(strict_types=1);
namespace Doctrine\Persistence;
use Doctrine\Persistence\Mapping\ClassMetadata;
use Doctrine\Persistence\Mapping\ClassMetadataFactory;
/**
* Contract for a Doctrine persistence layer ObjectManager class to implement.
*/
interface ObjectManager
{
/**
* Finds an object by its identifier.
*
* This is just a convenient shortcut for getRepository($className)->find($id).
*
* @param string $className The class name of the object to find.
* @param mixed $id The identity of the object to find.
* @psalm-param class-string<T> $className
*
* @return object|null The found object.
* @psalm-return T|null
*
* @template T of object
*/
public function find(string $className, $id);
/**
* Tells the ObjectManager to make an instance managed and persistent.
*
* The object will be entered into the database as a result of the flush operation.
*
* NOTE: The persist operation always considers objects that are not yet known to
* this ObjectManager as NEW. Do not pass detached objects to the persist operation.
*
* @param object $object The instance to make managed and persistent.
*
* @return void
*/
public function persist(object $object);
/**
* Removes an object instance.
*
* A removed object will be removed from the database as a result of the flush operation.
*
* @param object $object The object instance to remove.
*
* @return void
*/
public function remove(object $object);
/**
* Clears the ObjectManager. All objects that are currently managed
* by this ObjectManager become detached.
*
* @return void
*/
public function clear();
/**
* Detaches an object from the ObjectManager, causing a managed object to
* become detached. Unflushed changes made to the object if any
* (including removal of the object), will not be synchronized to the database.
* Objects which previously referenced the detached object will continue to
* reference it.
*
* @param object $object The object to detach.
*
* @return void
*/
public function detach(object $object);
/**
* Refreshes the persistent state of an object from the database,
* overriding any local changes that have not yet been persisted.
*
* @param object $object The object to refresh.
*
* @return void
*/
public function refresh(object $object);
/**
* Flushes all changes to objects that have been queued up to now to the database.
* This effectively synchronizes the in-memory state of managed objects with the
* database.
*
* @return void
*/
public function flush();
/**
* Gets the repository for a class.
*
* @psalm-param class-string<T> $className
*
* @psalm-return ObjectRepository<T>
*
* @template T of object
*/
public function getRepository(string $className);
/**
* Returns the ClassMetadata descriptor for a class.
*
* The class name must be the fully-qualified class name without a leading backslash
* (as it is returned by get_class($obj)).
*
* @psalm-param class-string<T> $className
*
* @psalm-return ClassMetadata<T>
*
* @template T of object
*/
public function getClassMetadata(string $className);
/**
* Gets the metadata factory used to gather the metadata of classes.
*
* @psalm-return ClassMetadataFactory<ClassMetadata<object>>
*/
public function getMetadataFactory();
/**
* Helper method to initialize a lazy loading proxy or persistent collection.
*
* This method is a no-op for other objects.
*
* @return void
*/
public function initializeObject(object $obj);
/**
* Checks if the object is part of the current UnitOfWork and therefore managed.
*
* @return bool
*/
public function contains(object $object);
}

View File

@@ -1,92 +0,0 @@
<?php
declare(strict_types=1);
namespace Doctrine\Persistence;
use Doctrine\Persistence\Mapping\ClassMetadata;
use Doctrine\Persistence\Mapping\ClassMetadataFactory;
/**
* Base class to simplify ObjectManager decorators
*
* @template-covariant TObjectManager of ObjectManager
*/
abstract class ObjectManagerDecorator implements ObjectManager
{
/** @var TObjectManager */
protected $wrapped;
/**
* {@inheritdoc}
*/
public function find(string $className, $id)
{
return $this->wrapped->find($className, $id);
}
public function persist(object $object)
{
$this->wrapped->persist($object);
}
public function remove(object $object)
{
$this->wrapped->remove($object);
}
public function clear(): void
{
$this->wrapped->clear();
}
public function detach(object $object)
{
$this->wrapped->detach($object);
}
public function refresh(object $object)
{
$this->wrapped->refresh($object);
}
public function flush()
{
$this->wrapped->flush();
}
/**
* {@inheritdoc}
*/
public function getRepository(string $className)
{
return $this->wrapped->getRepository($className);
}
/**
* {@inheritdoc}
*/
public function getClassMetadata(string $className)
{
return $this->wrapped->getClassMetadata($className);
}
/** @psalm-return ClassMetadataFactory<ClassMetadata<object>> */
public function getMetadataFactory()
{
return $this->wrapped->getMetadataFactory();
}
public function initializeObject(object $obj)
{
$this->wrapped->initializeObject($obj);
}
/**
* {@inheritdoc}
*/
public function contains(object $object)
{
return $this->wrapped->contains($object);
}
}

View File

@@ -1,73 +0,0 @@
<?php
declare(strict_types=1);
namespace Doctrine\Persistence;
use UnexpectedValueException;
/**
* Contract for a Doctrine persistence layer ObjectRepository class to implement.
*
* @template-covariant T of object
*/
interface ObjectRepository
{
/**
* Finds an object by its primary key / identifier.
*
* @param mixed $id The identifier.
*
* @return object|null The object.
* @psalm-return T|null
*/
public function find($id);
/**
* Finds all objects in the repository.
*
* @return array<int, object> The objects.
* @psalm-return T[]
*/
public function findAll();
/**
* Finds objects by a set of criteria.
*
* Optionally sorting and limiting details can be passed. An implementation may throw
* an UnexpectedValueException if certain values of the sorting or limiting details are
* not supported.
*
* @param array<string, mixed> $criteria
* @param array<string, string>|null $orderBy
* @psalm-param array<string, 'asc'|'desc'|'ASC'|'DESC'>|null $orderBy
*
* @return array<int, object> The objects.
* @psalm-return T[]
*
* @throws UnexpectedValueException
*/
public function findBy(
array $criteria,
?array $orderBy = null,
?int $limit = null,
?int $offset = null
);
/**
* Finds a single object by a set of criteria.
*
* @param array<string, mixed> $criteria The criteria.
*
* @return object|null The object.
* @psalm-return T|null
*/
public function findOneBy(array $criteria);
/**
* Returns the class name of the object managed by the repository.
*
* @psalm-return class-string<T>
*/
public function getClassName();
}

View File

@@ -1,24 +0,0 @@
<?php
declare(strict_types=1);
namespace Doctrine\Persistence;
/**
* Contract for classes that are potential listeners of a {@see NotifyPropertyChanged}
* implementor.
*/
interface PropertyChangedListener
{
/**
* Collect information about a property change.
*
* @param object $sender The object on which the property changed.
* @param string $propertyName The name of the property that changed.
* @param mixed $oldValue The old value of the property that changed.
* @param mixed $newValue The new value of the property that changed.
*
* @return void
*/
public function propertyChanged(object $sender, string $propertyName, $oldValue, $newValue);
}

View File

@@ -1,40 +0,0 @@
<?php
declare(strict_types=1);
namespace Doctrine\Persistence;
/**
* Interface for proxy classes.
*
* @template T of object
* @method void __setInitialized(bool $initialized) Implementing this method will be mandatory in version 4.
*/
interface Proxy
{
/**
* Marker for Proxy class names.
*/
public const MARKER = '__CG__';
/**
* Length of the proxy marker.
*/
public const MARKER_LENGTH = 6;
/**
* Initializes this proxy if its not yet initialized.
*
* Acts as a no-op if already initialized.
*
* @return void
*/
public function __load();
/**
* Returns whether this proxy is initialized or not.
*
* @return bool
*/
public function __isInitialized();
}

View File

@@ -1,68 +0,0 @@
<?php
declare(strict_types=1);
namespace Doctrine\Persistence\Reflection;
use BackedEnum;
use ReflectionProperty;
use ReturnTypeWillChange;
/**
* PHP Enum Reflection Property - special override for backed enums.
*/
class EnumReflectionProperty extends ReflectionProperty
{
/** @var ReflectionProperty */
private $originalReflectionProperty;
/** @var class-string<BackedEnum> */
private $enumType;
/** @param class-string<BackedEnum> $enumType */
public function __construct(ReflectionProperty $originalReflectionProperty, string $enumType)
{
$this->originalReflectionProperty = $originalReflectionProperty;
$this->enumType = $enumType;
}
/**
* {@inheritDoc}
*
* Converts enum instance to its value.
*
* @param object|null $object
*
* @return int|string|null
*/
#[ReturnTypeWillChange]
public function getValue($object = null)
{
if ($object === null) {
return null;
}
$enum = $this->originalReflectionProperty->getValue($object);
if ($enum === null) {
return null;
}
return $enum->value;
}
/**
* Converts enum value to enum instance.
*
* @param object $object
* @param mixed $value
*/
public function setValue($object, $value = null): void
{
if ($value !== null) {
$value = $this->enumType::from($value);
}
$this->originalReflectionProperty->setValue($object, $value);
}
}

View File

@@ -1,61 +0,0 @@
<?php
declare(strict_types=1);
namespace Doctrine\Persistence\Reflection;
use Doctrine\Common\Proxy\Proxy;
use ReflectionProperty;
use ReturnTypeWillChange;
/**
* PHP Runtime Reflection Public Property - special overrides for public properties.
*
* @deprecated since version 3.1, use RuntimeReflectionProperty instead.
*/
class RuntimePublicReflectionProperty extends ReflectionProperty
{
/**
* {@inheritDoc}
*
* Returns the value of a public property without calling
* `__get` on the provided $object if it exists.
*
* @return mixed
*/
#[ReturnTypeWillChange]
public function getValue($object = null)
{
return $object !== null ? ((array) $object)[$this->getName()] ?? null : parent::getValue();
}
/**
* {@inheritDoc}
*
* Avoids triggering lazy loading via `__set` if the provided object
* is a {@see \Doctrine\Common\Proxy\Proxy}.
*
* @link https://bugs.php.net/bug.php?id=63463
*
* @param object|null $object
* @param mixed $value
*
* @return void
*/
#[ReturnTypeWillChange]
public function setValue($object, $value = null)
{
if (! ($object instanceof Proxy && ! $object->__isInitialized())) {
parent::setValue($object, $value);
return;
}
$originalInitializer = $object->__getInitializer();
$object->__setInitializer(null);
parent::setValue($object, $value);
$object->__setInitializer($originalInitializer);
}
}

View File

@@ -1,86 +0,0 @@
<?php
declare(strict_types=1);
namespace Doctrine\Persistence\Reflection;
use Doctrine\Common\Proxy\Proxy as CommonProxy;
use Doctrine\Persistence\Proxy;
use ReflectionProperty;
use ReturnTypeWillChange;
use function ltrim;
use function method_exists;
/**
* PHP Runtime Reflection Property.
*
* Avoids triggering lazy loading if the provided object
* is a {@see \Doctrine\Persistence\Proxy}.
*/
class RuntimeReflectionProperty extends ReflectionProperty
{
/** @var string */
private $key;
public function __construct(string $class, string $name)
{
parent::__construct($class, $name);
$this->key = $this->isPrivate() ? "\0" . ltrim($class, '\\') . "\0" . $name : ($this->isProtected() ? "\0*\0" . $name : $name);
}
/**
* {@inheritDoc}
*
* @return mixed
*/
#[ReturnTypeWillChange]
public function getValue($object = null)
{
if ($object === null) {
return parent::getValue($object);
}
return ((array) $object)[$this->key] ?? null;
}
/**
* {@inheritDoc}
*
* @param object|null $object
* @param mixed $value
*
* @return void
*/
#[ReturnTypeWillChange]
public function setValue($object, $value = null)
{
if (! ($object instanceof Proxy && ! $object->__isInitialized())) {
parent::setValue($object, $value);
return;
}
if ($object instanceof CommonProxy) {
$originalInitializer = $object->__getInitializer();
$object->__setInitializer(null);
parent::setValue($object, $value);
$object->__setInitializer($originalInitializer);
return;
}
if (! method_exists($object, '__setInitialized')) {
return;
}
$object->__setInitialized(true);
parent::setValue($object, $value);
$object->__setInitialized(false);
}
}

View File

@@ -1,13 +0,0 @@
<?php
declare(strict_types=1);
namespace Doctrine\Persistence\Reflection;
/**
* PHP Typed No Default Reflection Property - special override for typed properties without a default value.
*/
class TypedNoDefaultReflectionProperty extends RuntimeReflectionProperty
{
use TypedNoDefaultReflectionPropertyBase;
}

View File

@@ -1,68 +0,0 @@
<?php
declare(strict_types=1);
namespace Doctrine\Persistence\Reflection;
use Closure;
use ReturnTypeWillChange;
use function assert;
/**
* PHP Typed No Default Reflection Property Base - special override for typed properties without a default value.
*
* @internal since version 3.1
*/
trait TypedNoDefaultReflectionPropertyBase
{
/**
* {@inheritDoc}
*
* Checks that a typed property is initialized before accessing its value.
* This is necessary to avoid PHP error "Error: Typed property must not be accessed before initialization".
* Should be used only for reflecting typed properties without a default value.
*
* @param object|null $object
*
* @return mixed
*/
#[ReturnTypeWillChange]
public function getValue($object = null)
{
return $object !== null && $this->isInitialized($object) ? parent::getValue($object) : null;
}
/**
* {@inheritDoc}
*
* Works around the problem with setting typed no default properties to
* NULL which is not supported, instead unset() to uninitialize.
*
* @link https://github.com/doctrine/orm/issues/7999
*
* @param object|null $object
*
* @return void
*/
#[ReturnTypeWillChange]
public function setValue($object, $value = null)
{
if ($value === null && $this->hasType() && ! $this->getType()->allowsNull()) {
$propertyName = $this->getName();
$unsetter = function () use ($propertyName): void {
unset($this->$propertyName);
};
$unsetter = $unsetter->bindTo($object, $this->getDeclaringClass()->getName());
assert($unsetter instanceof Closure);
$unsetter();
return;
}
parent::setValue($object, $value);
}
}

View File

@@ -1,15 +0,0 @@
<?php
declare(strict_types=1);
namespace Doctrine\Persistence\Reflection;
/**
* PHP Typed No Default Runtime Public Reflection Property - special override for public typed properties without a default value.
*
* @deprecated since version 3.1, use TypedNoDefaultReflectionProperty instead.
*/
class TypedNoDefaultRuntimePublicReflectionProperty extends RuntimePublicReflectionProperty
{
use TypedNoDefaultReflectionPropertyBase;
}