vendor/doctrine/mongodb-odm/lib/Doctrine/ODM/MongoDB/Mapping/ClassMetadata.php line 2164

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace Doctrine\ODM\MongoDB\Mapping;
  4. use BackedEnum;
  5. use BadMethodCallException;
  6. use DateTime;
  7. use DateTimeImmutable;
  8. use Doctrine\Common\Collections\Collection;
  9. use Doctrine\Instantiator\Instantiator;
  10. use Doctrine\Instantiator\InstantiatorInterface;
  11. use Doctrine\ODM\MongoDB\Id\IdGenerator;
  12. use Doctrine\ODM\MongoDB\LockException;
  13. use Doctrine\ODM\MongoDB\Types\Incrementable;
  14. use Doctrine\ODM\MongoDB\Types\Type;
  15. use Doctrine\ODM\MongoDB\Types\Versionable;
  16. use Doctrine\ODM\MongoDB\Utility\CollectionHelper;
  17. use Doctrine\Persistence\Mapping\ClassMetadata as BaseClassMetadata;
  18. use Doctrine\Persistence\Mapping\ReflectionService;
  19. use Doctrine\Persistence\Mapping\RuntimeReflectionService;
  20. use Doctrine\Persistence\Reflection\EnumReflectionProperty;
  21. use InvalidArgumentException;
  22. use LogicException;
  23. use ProxyManager\Proxy\GhostObjectInterface;
  24. use ReflectionClass;
  25. use ReflectionEnum;
  26. use ReflectionNamedType;
  27. use ReflectionProperty;
  28. use function array_filter;
  29. use function array_key_exists;
  30. use function array_keys;
  31. use function array_map;
  32. use function array_pop;
  33. use function assert;
  34. use function class_exists;
  35. use function constant;
  36. use function count;
  37. use function enum_exists;
  38. use function extension_loaded;
  39. use function get_class;
  40. use function in_array;
  41. use function interface_exists;
  42. use function is_array;
  43. use function is_string;
  44. use function is_subclass_of;
  45. use function ltrim;
  46. use function sprintf;
  47. use function strtolower;
  48. use function strtoupper;
  49. use function trigger_deprecation;
  50. use const PHP_VERSION_ID;
  51. /**
  52.  * A <tt>ClassMetadata</tt> instance holds all the object-document mapping metadata
  53.  * of a document and it's references.
  54.  *
  55.  * Once populated, ClassMetadata instances are usually cached in a serialized form.
  56.  *
  57.  * <b>IMPORTANT NOTE:</b>
  58.  *
  59.  * The fields of this class are only public for 2 reasons:
  60.  * 1) To allow fast READ access.
  61.  * 2) To drastically reduce the size of a serialized instance (private/protected members
  62.  *    get the whole class name, namespace inclusive, prepended to every property in
  63.  *    the serialized representation).
  64.  *
  65.  * @psalm-type FieldMappingConfig = array{
  66.  *      type?: string,
  67.  *      fieldName?: string,
  68.  *      name?: string,
  69.  *      strategy?: string,
  70.  *      association?: int,
  71.  *      id?: bool,
  72.  *      isOwningSide?: bool,
  73.  *      collectionClass?: class-string,
  74.  *      cascade?: list<string>|string,
  75.  *      embedded?: bool,
  76.  *      orphanRemoval?: bool,
  77.  *      options?: array<string, mixed>,
  78.  *      nullable?: bool,
  79.  *      reference?: bool,
  80.  *      storeAs?: string,
  81.  *      targetDocument?: class-string|null,
  82.  *      mappedBy?: string|null,
  83.  *      inversedBy?: string|null,
  84.  *      discriminatorField?: string,
  85.  *      defaultDiscriminatorValue?: string,
  86.  *      discriminatorMap?: array<string, class-string>,
  87.  *      repositoryMethod?: string|null,
  88.  *      sort?: array<string, string|int>,
  89.  *      limit?: int|null,
  90.  *      skip?: int|null,
  91.  *      version?: bool,
  92.  *      lock?: bool,
  93.  *      inherited?: string,
  94.  *      declared?: class-string,
  95.  *      prime?: list<string>,
  96.  *      sparse?: bool,
  97.  *      unique?: bool,
  98.  *      index?: bool,
  99.  *      index-name?: string,
  100.  *      criteria?: array<string, string>,
  101.  *      alsoLoadFields?: list<string>,
  102.  *      order?: int|string,
  103.  *      background?: bool,
  104.  *      enumType?: class-string<BackedEnum>,
  105.  * }
  106.  * @psalm-type FieldMapping = array{
  107.  *      type: string,
  108.  *      fieldName: string,
  109.  *      name: string,
  110.  *      isCascadeRemove: bool,
  111.  *      isCascadePersist: bool,
  112.  *      isCascadeRefresh: bool,
  113.  *      isCascadeMerge: bool,
  114.  *      isCascadeDetach: bool,
  115.  *      isOwningSide: bool,
  116.  *      isInverseSide: bool,
  117.  *      strategy?: string,
  118.  *      association?: int,
  119.  *      id?: bool,
  120.  *      collectionClass?: class-string,
  121.  *      cascade?: list<string>|string,
  122.  *      embedded?: bool,
  123.  *      orphanRemoval?: bool,
  124.  *      options?: array<string, mixed>,
  125.  *      nullable?: bool,
  126.  *      reference?: bool,
  127.  *      storeAs?: string,
  128.  *      targetDocument?: class-string|null,
  129.  *      mappedBy?: string|null,
  130.  *      inversedBy?: string|null,
  131.  *      discriminatorField?: string,
  132.  *      defaultDiscriminatorValue?: string,
  133.  *      discriminatorMap?: array<string, class-string>,
  134.  *      repositoryMethod?: string|null,
  135.  *      sort?: array<string, string|int>,
  136.  *      limit?: int|null,
  137.  *      skip?: int|null,
  138.  *      version?: bool,
  139.  *      lock?: bool,
  140.  *      notSaved?: bool,
  141.  *      inherited?: string,
  142.  *      declared?: class-string,
  143.  *      prime?: list<string>,
  144.  *      sparse?: bool,
  145.  *      unique?: bool,
  146.  *      index?: bool,
  147.  *      criteria?: array<string, string>,
  148.  *      alsoLoadFields?: list<string>,
  149.  *      enumType?: class-string<BackedEnum>,
  150.  * }
  151.  * @psalm-type AssociationFieldMapping = array{
  152.  *      type?: string,
  153.  *      fieldName: string,
  154.  *      name: string,
  155.  *      isCascadeRemove: bool,
  156.  *      isCascadePersist: bool,
  157.  *      isCascadeRefresh: bool,
  158.  *      isCascadeMerge: bool,
  159.  *      isCascadeDetach: bool,
  160.  *      isOwningSide: bool,
  161.  *      isInverseSide: bool,
  162.  *      targetDocument: class-string|null,
  163.  *      association: int,
  164.  *      strategy?: string,
  165.  *      id?: bool,
  166.  *      collectionClass?: class-string,
  167.  *      cascade?: list<string>|string,
  168.  *      embedded?: bool,
  169.  *      orphanRemoval?: bool,
  170.  *      options?: array<string, mixed>,
  171.  *      nullable?: bool,
  172.  *      reference?: bool,
  173.  *      storeAs?: string,
  174.  *      mappedBy?: string|null,
  175.  *      inversedBy?: string|null,
  176.  *      discriminatorField?: string,
  177.  *      defaultDiscriminatorValue?: string,
  178.  *      discriminatorMap?: array<string, class-string>,
  179.  *      repositoryMethod?: string|null,
  180.  *      sort?: array<string, string|int>,
  181.  *      limit?: int|null,
  182.  *      skip?: int|null,
  183.  *      version?: bool,
  184.  *      lock?: bool,
  185.  *      notSaved?: bool,
  186.  *      inherited?: string,
  187.  *      declared?: class-string,
  188.  *      prime?: list<string>,
  189.  *      sparse?: bool,
  190.  *      unique?: bool,
  191.  *      index?: bool,
  192.  *      criteria?: array<string, string>,
  193.  *      alsoLoadFields?: list<string>,
  194.  * }
  195.  * @psalm-type IndexKeys = array<string, mixed>
  196.  * @psalm-type IndexOptions = array{
  197.  *      background?: bool,
  198.  *      bits?: int,
  199.  *      default_language?: string,
  200.  *      expireAfterSeconds?: int,
  201.  *      language_override?: string,
  202.  *      min?: float,
  203.  *      max?: float,
  204.  *      name?: string,
  205.  *      partialFilterExpression?: mixed[],
  206.  *      sparse?: bool,
  207.  *      storageEngine?: mixed[],
  208.  *      textIndexVersion?: int,
  209.  *      unique?: bool,
  210.  *      weights?: array{string, int},
  211.  * }
  212.  * @psalm-type IndexMapping = array{
  213.  *      keys: IndexKeys,
  214.  *      options: IndexOptions
  215.  * }
  216.  * @psalm-type ShardKeys = array<string, mixed>
  217.  * @psalm-type ShardOptions = array<string, mixed>
  218.  * @psalm-type ShardKey = array{
  219.  *      keys?: ShardKeys,
  220.  *      options?: ShardOptions
  221.  * }
  222.  * @final
  223.  * @template-covariant T of object
  224.  * @template-implements BaseClassMetadata<T>
  225.  */
  226. /* final */ class ClassMetadata implements BaseClassMetadata
  227. {
  228.     /* The Id generator types. */
  229.     /**
  230.      * AUTO means Doctrine will automatically create a new \MongoDB\BSON\ObjectId instance for us.
  231.      */
  232.     public const GENERATOR_TYPE_AUTO 1;
  233.     /**
  234.      * INCREMENT means a separate collection is used for maintaining and incrementing id generation.
  235.      * Offers full portability.
  236.      */
  237.     public const GENERATOR_TYPE_INCREMENT 2;
  238.     /**
  239.      * UUID means Doctrine will generate a uuid for us.
  240.      */
  241.     public const GENERATOR_TYPE_UUID 3;
  242.     /**
  243.      * ALNUM means Doctrine will generate Alpha-numeric string identifiers, using the INCREMENT
  244.      * generator to ensure identifier uniqueness
  245.      */
  246.     public const GENERATOR_TYPE_ALNUM 4;
  247.     /**
  248.      * CUSTOM means Doctrine expect a class parameter. It will then try to initiate that class
  249.      * and pass other options to the generator. It will throw an Exception if the class
  250.      * does not exist or if an option was passed for that there is not setter in the new
  251.      * generator class.
  252.      *
  253.      * The class will have to implement IdGenerator.
  254.      */
  255.     public const GENERATOR_TYPE_CUSTOM 5;
  256.     /**
  257.      * NONE means Doctrine will not generate any id for us and you are responsible for manually
  258.      * assigning an id.
  259.      */
  260.     public const GENERATOR_TYPE_NONE 6;
  261.     /**
  262.      * Default discriminator field name.
  263.      *
  264.      * This is used for associations value for associations where a that do not define a "targetDocument" or
  265.      * "discriminatorField" option in their mapping.
  266.      */
  267.     public const DEFAULT_DISCRIMINATOR_FIELD '_doctrine_class_name';
  268.     /**
  269.      * Association types
  270.      */
  271.     public const REFERENCE_ONE  1;
  272.     public const REFERENCE_MANY 2;
  273.     public const EMBED_ONE      3;
  274.     public const EMBED_MANY     4;
  275.     /**
  276.      * Mapping types
  277.      */
  278.     public const MANY 'many';
  279.     public const ONE  'one';
  280.     /**
  281.      * The types of storeAs references
  282.      */
  283.     public const REFERENCE_STORE_AS_ID             'id';
  284.     public const REFERENCE_STORE_AS_DB_REF         'dbRef';
  285.     public const REFERENCE_STORE_AS_DB_REF_WITH_DB 'dbRefWithDb';
  286.     public const REFERENCE_STORE_AS_REF            'ref';
  287.     /**
  288.      * The collection schema validationAction values
  289.      *
  290.      * @see https://docs.mongodb.com/manual/core/schema-validation/#accept-or-reject-invalid-documents
  291.      */
  292.     public const SCHEMA_VALIDATION_ACTION_ERROR 'error';
  293.     public const SCHEMA_VALIDATION_ACTION_WARN  'warn';
  294.     /**
  295.      * The collection schema validationLevel values
  296.      *
  297.      * @see https://docs.mongodb.com/manual/core/schema-validation/#existing-documents
  298.      */
  299.     public const SCHEMA_VALIDATION_LEVEL_OFF      'off';
  300.     public const SCHEMA_VALIDATION_LEVEL_STRICT   'strict';
  301.     public const SCHEMA_VALIDATION_LEVEL_MODERATE 'moderate';
  302.     /* The inheritance mapping types */
  303.     /**
  304.      * NONE means the class does not participate in an inheritance hierarchy
  305.      * and therefore does not need an inheritance mapping type.
  306.      */
  307.     public const INHERITANCE_TYPE_NONE 1;
  308.     /**
  309.      * SINGLE_COLLECTION means the class will be persisted according to the rules of
  310.      * <tt>Single Collection Inheritance</tt>.
  311.      */
  312.     public const INHERITANCE_TYPE_SINGLE_COLLECTION 2;
  313.     /**
  314.      * COLLECTION_PER_CLASS means the class will be persisted according to the rules
  315.      * of <tt>Concrete Collection Inheritance</tt>.
  316.      */
  317.     public const INHERITANCE_TYPE_COLLECTION_PER_CLASS 3;
  318.     /**
  319.      * DEFERRED_IMPLICIT means that changes of entities are calculated at commit-time
  320.      * by doing a property-by-property comparison with the original data. This will
  321.      * be done for all entities that are in MANAGED state at commit-time.
  322.      *
  323.      * This is the default change tracking policy.
  324.      */
  325.     public const CHANGETRACKING_DEFERRED_IMPLICIT 1;
  326.     /**
  327.      * DEFERRED_EXPLICIT means that changes of entities are calculated at commit-time
  328.      * by doing a property-by-property comparison with the original data. This will
  329.      * be done only for entities that were explicitly saved (through persist() or a cascade).
  330.      */
  331.     public const CHANGETRACKING_DEFERRED_EXPLICIT 2;
  332.     /**
  333.      * NOTIFY means that Doctrine relies on the entities sending out notifications
  334.      * when their properties change. Such entity classes must implement
  335.      * the <tt>NotifyPropertyChanged</tt> interface.
  336.      *
  337.      * @deprecated
  338.      */
  339.     public const CHANGETRACKING_NOTIFY 3;
  340.     /**
  341.      * SET means that fields will be written to the database using a $set operator
  342.      */
  343.     public const STORAGE_STRATEGY_SET 'set';
  344.     /**
  345.      * INCREMENT means that fields will be written to the database by calculating
  346.      * the difference and using the $inc operator
  347.      */
  348.     public const STORAGE_STRATEGY_INCREMENT 'increment';
  349.     public const STORAGE_STRATEGY_PUSH_ALL         'pushAll';
  350.     public const STORAGE_STRATEGY_ADD_TO_SET       'addToSet';
  351.     public const STORAGE_STRATEGY_ATOMIC_SET       'atomicSet';
  352.     public const STORAGE_STRATEGY_ATOMIC_SET_ARRAY 'atomicSetArray';
  353.     public const STORAGE_STRATEGY_SET_ARRAY        'setArray';
  354.     private const ALLOWED_GRIDFS_FIELDS = ['_id''chunkSize''filename''length''metadata''uploadDate'];
  355.     /**
  356.      * READ-ONLY: The name of the mongo database the document is mapped to.
  357.      *
  358.      * @var string|null
  359.      */
  360.     public $db;
  361.     /**
  362.      * READ-ONLY: The name of the mongo collection the document is mapped to.
  363.      *
  364.      * @var string
  365.      */
  366.     public $collection;
  367.     /**
  368.      * READ-ONLY: The name of the GridFS bucket the document is mapped to.
  369.      *
  370.      * @var string
  371.      */
  372.     public $bucketName 'fs';
  373.     /**
  374.      * READ-ONLY: If the collection should be a fixed size.
  375.      *
  376.      * @var bool
  377.      */
  378.     public $collectionCapped false;
  379.     /**
  380.      * READ-ONLY: If the collection is fixed size, its size in bytes.
  381.      *
  382.      * @var int|null
  383.      */
  384.     public $collectionSize;
  385.     /**
  386.      * READ-ONLY: If the collection is fixed size, the maximum number of elements to store in the collection.
  387.      *
  388.      * @var int|null
  389.      */
  390.     public $collectionMax;
  391.     /**
  392.      * READ-ONLY Describes how MongoDB clients route read operations to the members of a replica set.
  393.      *
  394.      * @var string|null
  395.      */
  396.     public $readPreference;
  397.     /**
  398.      * READ-ONLY Associated with readPreference Allows to specify criteria so that your application can target read
  399.      * operations to specific members, based on custom parameters.
  400.      *
  401.      * @var array<array<string, string>>
  402.      */
  403.     public $readPreferenceTags = [];
  404.     /**
  405.      * READ-ONLY: Describes the level of acknowledgement requested from MongoDB for write operations.
  406.      *
  407.      * @var string|int|null
  408.      */
  409.     public $writeConcern;
  410.     /**
  411.      * READ-ONLY: The field name of the document identifier.
  412.      *
  413.      * @var string|null
  414.      */
  415.     public $identifier;
  416.     /**
  417.      * READ-ONLY: The array of indexes for the document collection.
  418.      *
  419.      * @var array<array<string, mixed>>
  420.      * @psalm-var array<IndexMapping>
  421.      */
  422.     public $indexes = [];
  423.     /**
  424.      * READ-ONLY: Keys and options describing shard key. Only for sharded collections.
  425.      *
  426.      * @var array<string, array>
  427.      * @psalm-var ShardKey
  428.      */
  429.     public $shardKey = [];
  430.     /**
  431.      * Allows users to specify a validation schema for the collection.
  432.      *
  433.      * @var array|object|null
  434.      * @psalm-var array<string, mixed>|object|null
  435.      */
  436.     private $validator;
  437.     /**
  438.      * Determines whether to error on invalid documents or just warn about the violations but allow invalid documents to be inserted.
  439.      *
  440.      * @var string
  441.      */
  442.     private $validationAction self::SCHEMA_VALIDATION_ACTION_ERROR;
  443.     /**
  444.      * Determines how strictly MongoDB applies the validation rules to existing documents during an update.
  445.      */
  446.     private string $validationLevel self::SCHEMA_VALIDATION_LEVEL_STRICT;
  447.     /**
  448.      * READ-ONLY: The name of the document class.
  449.      *
  450.      * @var string
  451.      * @psalm-var class-string<T>
  452.      */
  453.     public $name;
  454.     /**
  455.      * READ-ONLY: The name of the document class that is at the root of the mapped document inheritance
  456.      * hierarchy. If the document is not part of a mapped inheritance hierarchy this is the same
  457.      * as {@link $documentName}.
  458.      *
  459.      * @var string
  460.      * @psalm-var class-string
  461.      */
  462.     public $rootDocumentName;
  463.     /**
  464.      * The name of the custom repository class used for the document class.
  465.      * (Optional).
  466.      *
  467.      * @var string|null
  468.      * @psalm-var class-string|null
  469.      */
  470.     public $customRepositoryClassName;
  471.     /**
  472.      * READ-ONLY: The names of the parent classes (ancestors).
  473.      *
  474.      * @var array
  475.      * @psalm-var list<class-string>
  476.      */
  477.     public $parentClasses = [];
  478.     /**
  479.      * READ-ONLY: The names of all subclasses (descendants).
  480.      *
  481.      * @var array
  482.      * @psalm-var list<class-string>
  483.      */
  484.     public $subClasses = [];
  485.     /**
  486.      * The ReflectionProperty instances of the mapped class.
  487.      *
  488.      * @var ReflectionProperty[]
  489.      */
  490.     public $reflFields = [];
  491.     /**
  492.      * READ-ONLY: The inheritance mapping type used by the class.
  493.      *
  494.      * @var int
  495.      */
  496.     public $inheritanceType self::INHERITANCE_TYPE_NONE;
  497.     /**
  498.      * READ-ONLY: The Id generator type used by the class.
  499.      *
  500.      * @var int
  501.      */
  502.     public $generatorType self::GENERATOR_TYPE_AUTO;
  503.     /**
  504.      * READ-ONLY: The Id generator options.
  505.      *
  506.      * @var array<string, mixed>
  507.      */
  508.     public $generatorOptions = [];
  509.     /**
  510.      * READ-ONLY: The ID generator used for generating IDs for this class.
  511.      *
  512.      * @var IdGenerator|null
  513.      */
  514.     public $idGenerator;
  515.     /**
  516.      * READ-ONLY: The field mappings of the class.
  517.      * Keys are field names and values are mapping definitions.
  518.      *
  519.      * The mapping definition array has the following values:
  520.      *
  521.      * - <b>fieldName</b> (string)
  522.      * The name of the field in the Document.
  523.      *
  524.      * - <b>id</b> (boolean, optional)
  525.      * Marks the field as the primary key of the document. Multiple fields of an
  526.      * document can have the id attribute, forming a composite key.
  527.      *
  528.      * @var array<string, mixed>
  529.      * @psalm-var array<string, FieldMapping>
  530.      */
  531.     public $fieldMappings = [];
  532.     /**
  533.      * READ-ONLY: The association mappings of the class.
  534.      * Keys are field names and values are mapping definitions.
  535.      *
  536.      * @var array<string, mixed>
  537.      * @psalm-var array<string, AssociationFieldMapping>
  538.      */
  539.     public $associationMappings = [];
  540.     /**
  541.      * READ-ONLY: Array of fields to also load with a given method.
  542.      *
  543.      * @var array<string, mixed[]>
  544.      */
  545.     public $alsoLoadMethods = [];
  546.     /**
  547.      * READ-ONLY: The registered lifecycle callbacks for documents of this class.
  548.      *
  549.      * @var array<string, list<string>>
  550.      */
  551.     public $lifecycleCallbacks = [];
  552.     /**
  553.      * READ-ONLY: The discriminator value of this class.
  554.      *
  555.      * <b>This does only apply to the JOINED and SINGLE_COLLECTION inheritance mapping strategies
  556.      * where a discriminator field is used.</b>
  557.      *
  558.      * @see discriminatorField
  559.      *
  560.      * @var string|null
  561.      * @psalm-var class-string|null
  562.      */
  563.     public $discriminatorValue;
  564.     /**
  565.      * READ-ONLY: The discriminator map of all mapped classes in the hierarchy.
  566.      *
  567.      * <b>This does only apply to the SINGLE_COLLECTION inheritance mapping strategy
  568.      * where a discriminator field is used.</b>
  569.      *
  570.      * @see discriminatorField
  571.      *
  572.      * @psalm-var array<string, class-string>
  573.      */
  574.     public $discriminatorMap = [];
  575.     /**
  576.      * READ-ONLY: The definition of the discriminator field used in SINGLE_COLLECTION
  577.      * inheritance mapping.
  578.      *
  579.      * @var string|null
  580.      */
  581.     public $discriminatorField;
  582.     /**
  583.      * READ-ONLY: The default value for discriminatorField in case it's not set in the document
  584.      *
  585.      * @see discriminatorField
  586.      *
  587.      * @var string|null
  588.      */
  589.     public $defaultDiscriminatorValue;
  590.     /**
  591.      * READ-ONLY: Whether this class describes the mapping of a mapped superclass.
  592.      *
  593.      * @var bool
  594.      */
  595.     public $isMappedSuperclass false;
  596.     /**
  597.      * READ-ONLY: Whether this class describes the mapping of a embedded document.
  598.      *
  599.      * @var bool
  600.      */
  601.     public $isEmbeddedDocument false;
  602.     /**
  603.      * READ-ONLY: Whether this class describes the mapping of an aggregation result document.
  604.      *
  605.      * @var bool
  606.      */
  607.     public $isQueryResultDocument false;
  608.     /**
  609.      * READ-ONLY: Whether this class describes the mapping of a database view.
  610.      */
  611.     private bool $isView false;
  612.     /**
  613.      * READ-ONLY: Whether this class describes the mapping of a gridFS file
  614.      *
  615.      * @var bool
  616.      */
  617.     public $isFile false;
  618.     /**
  619.      * READ-ONLY: The default chunk size in bytes for the file
  620.      *
  621.      * @var int|null
  622.      */
  623.     public $chunkSizeBytes;
  624.     /**
  625.      * READ-ONLY: The policy used for change-tracking on entities of this class.
  626.      *
  627.      * @var int
  628.      */
  629.     public $changeTrackingPolicy self::CHANGETRACKING_DEFERRED_IMPLICIT;
  630.     /**
  631.      * READ-ONLY: A flag for whether or not instances of this class are to be versioned
  632.      * with optimistic locking.
  633.      *
  634.      * @var bool $isVersioned
  635.      */
  636.     public $isVersioned false;
  637.     /**
  638.      * READ-ONLY: The name of the field which is used for versioning in optimistic locking (if any).
  639.      *
  640.      * @var string|null $versionField
  641.      */
  642.     public $versionField;
  643.     /**
  644.      * READ-ONLY: A flag for whether or not instances of this class are to allow pessimistic
  645.      * locking.
  646.      *
  647.      * @var bool $isLockable
  648.      */
  649.     public $isLockable false;
  650.     /**
  651.      * READ-ONLY: The name of the field which is used for locking a document.
  652.      *
  653.      * @var mixed $lockField
  654.      */
  655.     public $lockField;
  656.     /**
  657.      * The ReflectionClass instance of the mapped class.
  658.      *
  659.      * @var ReflectionClass
  660.      * @psalm-var ReflectionClass<T>
  661.      */
  662.     public $reflClass;
  663.     /**
  664.      * READ_ONLY: A flag for whether or not this document is read-only.
  665.      *
  666.      * @var bool
  667.      */
  668.     public $isReadOnly;
  669.     private InstantiatorInterface $instantiator;
  670.     private ReflectionService $reflectionService;
  671.     /**
  672.      * @var string|null
  673.      * @psalm-var class-string|null
  674.      */
  675.     private $rootClass;
  676.     /**
  677.      * Initializes a new ClassMetadata instance that will hold the object-document mapping
  678.      * metadata of the class with the given name.
  679.      *
  680.      * @psalm-param class-string<T> $documentName
  681.      */
  682.     public function __construct(string $documentName)
  683.     {
  684.         $this->name              $documentName;
  685.         $this->rootDocumentName  $documentName;
  686.         $this->reflectionService = new RuntimeReflectionService();
  687.         $this->reflClass         = new ReflectionClass($documentName);
  688.         $this->setCollection($this->reflClass->getShortName());
  689.         $this->instantiator = new Instantiator();
  690.     }
  691.     /**
  692.      * Helper method to get reference id of ref* type references
  693.      *
  694.      * @internal
  695.      *
  696.      * @param mixed $reference
  697.      *
  698.      * @return mixed
  699.      */
  700.     public static function getReferenceId($referencestring $storeAs)
  701.     {
  702.         return $storeAs === self::REFERENCE_STORE_AS_ID $reference $reference[self::getReferencePrefix($storeAs) . 'id'];
  703.     }
  704.     /**
  705.      * Returns the reference prefix used for a reference
  706.      */
  707.     private static function getReferencePrefix(string $storeAs): string
  708.     {
  709.         if (! in_array($storeAs, [self::REFERENCE_STORE_AS_REFself::REFERENCE_STORE_AS_DB_REFself::REFERENCE_STORE_AS_DB_REF_WITH_DB])) {
  710.             throw new LogicException('Can only get a reference prefix for DBRef and reference arrays');
  711.         }
  712.         return $storeAs === self::REFERENCE_STORE_AS_REF '' '$';
  713.     }
  714.     /**
  715.      * Returns a fully qualified field name for a given reference
  716.      *
  717.      * @internal
  718.      *
  719.      * @param string $pathPrefix The field path prefix
  720.      */
  721.     public static function getReferenceFieldName(string $storeAsstring $pathPrefix ''): string
  722.     {
  723.         if ($storeAs === self::REFERENCE_STORE_AS_ID) {
  724.             return $pathPrefix;
  725.         }
  726.         return ($pathPrefix $pathPrefix '.' '') . static::getReferencePrefix($storeAs) . 'id';
  727.     }
  728.     public function getReflectionClass(): ReflectionClass
  729.     {
  730.         return $this->reflClass;
  731.     }
  732.     /** @param string $fieldName */
  733.     public function isIdentifier($fieldName): bool
  734.     {
  735.         return $this->identifier === $fieldName;
  736.     }
  737.     /**
  738.      * Sets the mapped identifier field of this class.
  739.      *
  740.      * @internal
  741.      */
  742.     public function setIdentifier(?string $identifier): void
  743.     {
  744.         $this->identifier $identifier;
  745.     }
  746.     /**
  747.      * Since MongoDB only allows exactly one identifier field
  748.      * this will always return an array with only one value
  749.      *
  750.      * @return array<string|null>
  751.      */
  752.     public function getIdentifier(): array
  753.     {
  754.         return [$this->identifier];
  755.     }
  756.     /**
  757.      * Since MongoDB only allows exactly one identifier field
  758.      * this will always return an array with only one value
  759.      *
  760.      * @return array<string|null>
  761.      */
  762.     public function getIdentifierFieldNames(): array
  763.     {
  764.         return [$this->identifier];
  765.     }
  766.     /** @param string $fieldName */
  767.     public function hasField($fieldName): bool
  768.     {
  769.         return isset($this->fieldMappings[$fieldName]);
  770.     }
  771.     /**
  772.      * Sets the inheritance type used by the class and it's subclasses.
  773.      */
  774.     public function setInheritanceType(int $type): void
  775.     {
  776.         $this->inheritanceType $type;
  777.     }
  778.     /**
  779.      * Checks whether a mapped field is inherited from an entity superclass.
  780.      */
  781.     public function isInheritedField(string $fieldName): bool
  782.     {
  783.         return isset($this->fieldMappings[$fieldName]['inherited']);
  784.     }
  785.     /**
  786.      * Registers a custom repository class for the document class.
  787.      *
  788.      * @psalm-param class-string|null $repositoryClassName
  789.      */
  790.     public function setCustomRepositoryClass(?string $repositoryClassName): void
  791.     {
  792.         if ($this->isEmbeddedDocument || $this->isQueryResultDocument) {
  793.             return;
  794.         }
  795.         $this->customRepositoryClassName $repositoryClassName;
  796.     }
  797.     /**
  798.      * Dispatches the lifecycle event of the given document by invoking all
  799.      * registered callbacks.
  800.      *
  801.      * @param mixed[]|null $arguments
  802.      *
  803.      * @throws InvalidArgumentException If document class is not this class or
  804.      *                                   a Proxy of this class.
  805.      */
  806.     public function invokeLifecycleCallbacks(string $eventobject $document, ?array $arguments null): void
  807.     {
  808.         if ($this->isView()) {
  809.             return;
  810.         }
  811.         if (! $document instanceof $this->name) {
  812.             throw new InvalidArgumentException(sprintf('Expected document class "%s"; found: "%s"'$this->nameget_class($document)));
  813.         }
  814.         if (empty($this->lifecycleCallbacks[$event])) {
  815.             return;
  816.         }
  817.         foreach ($this->lifecycleCallbacks[$event] as $callback) {
  818.             if ($arguments !== null) {
  819.                 $document->$callback(...$arguments);
  820.             } else {
  821.                 $document->$callback();
  822.             }
  823.         }
  824.     }
  825.     /**
  826.      * Checks whether the class has callbacks registered for a lifecycle event.
  827.      */
  828.     public function hasLifecycleCallbacks(string $event): bool
  829.     {
  830.         return ! empty($this->lifecycleCallbacks[$event]);
  831.     }
  832.     /**
  833.      * Gets the registered lifecycle callbacks for an event.
  834.      *
  835.      * @return list<string>
  836.      */
  837.     public function getLifecycleCallbacks(string $event): array
  838.     {
  839.         return $this->lifecycleCallbacks[$event] ?? [];
  840.     }
  841.     /**
  842.      * Adds a lifecycle callback for documents of this class.
  843.      *
  844.      * If the callback is already registered, this is a NOOP.
  845.      */
  846.     public function addLifecycleCallback(string $callbackstring $event): void
  847.     {
  848.         if (isset($this->lifecycleCallbacks[$event]) && in_array($callback$this->lifecycleCallbacks[$event])) {
  849.             return;
  850.         }
  851.         $this->lifecycleCallbacks[$event][] = $callback;
  852.     }
  853.     /**
  854.      * Sets the lifecycle callbacks for documents of this class.
  855.      *
  856.      * Any previously registered callbacks are overwritten.
  857.      *
  858.      * @param array<string, list<string>> $callbacks
  859.      */
  860.     public function setLifecycleCallbacks(array $callbacks): void
  861.     {
  862.         $this->lifecycleCallbacks $callbacks;
  863.     }
  864.     /**
  865.      * Registers a method for loading document data before field hydration.
  866.      *
  867.      * Note: A method may be registered multiple times for different fields.
  868.      * it will be invoked only once for the first field found.
  869.      *
  870.      * @param array<string, mixed>|string $fields Database field name(s)
  871.      */
  872.     public function registerAlsoLoadMethod(string $method$fields): void
  873.     {
  874.         $this->alsoLoadMethods[$method] = is_array($fields) ? $fields : [$fields];
  875.     }
  876.     /**
  877.      * Sets the AlsoLoad methods for documents of this class.
  878.      *
  879.      * Any previously registered methods are overwritten.
  880.      *
  881.      * @param array<string, mixed[]> $methods
  882.      */
  883.     public function setAlsoLoadMethods(array $methods): void
  884.     {
  885.         $this->alsoLoadMethods $methods;
  886.     }
  887.     /**
  888.      * Sets the discriminator field.
  889.      *
  890.      * The field name is the the unmapped database field. Discriminator values
  891.      * are only used to discern the hydration class and are not mapped to class
  892.      * properties.
  893.      *
  894.      * @param array<string, mixed>|string|null $discriminatorField
  895.      * @psalm-param array{name?: string, fieldName?: string}|string|null $discriminatorField
  896.      *
  897.      * @throws MappingException If the discriminator field conflicts with the
  898.      *                          "name" attribute of a mapped field.
  899.      */
  900.     public function setDiscriminatorField($discriminatorField): void
  901.     {
  902.         if ($this->isFile) {
  903.             throw MappingException::discriminatorNotAllowedForGridFS($this->name);
  904.         }
  905.         if ($discriminatorField === null) {
  906.             $this->discriminatorField null;
  907.             return;
  908.         }
  909.         // @todo: deprecate, document and remove this:
  910.         // Handle array argument with name/fieldName keys for BC
  911.         if (is_array($discriminatorField)) {
  912.             if (isset($discriminatorField['name'])) {
  913.                 $discriminatorField $discriminatorField['name'];
  914.             } elseif (isset($discriminatorField['fieldName'])) {
  915.                 $discriminatorField $discriminatorField['fieldName'];
  916.             }
  917.         }
  918.         foreach ($this->fieldMappings as $fieldMapping) {
  919.             if ($discriminatorField === $fieldMapping['name']) {
  920.                 throw MappingException::discriminatorFieldConflict($this->name$discriminatorField);
  921.             }
  922.         }
  923.         $this->discriminatorField $discriminatorField;
  924.     }
  925.     /**
  926.      * Sets the discriminator values used by this class.
  927.      * Used for JOINED and SINGLE_TABLE inheritance mapping strategies.
  928.      *
  929.      * @param array<string, class-string> $map
  930.      *
  931.      * @throws MappingException
  932.      */
  933.     public function setDiscriminatorMap(array $map): void
  934.     {
  935.         if ($this->isFile) {
  936.             throw MappingException::discriminatorNotAllowedForGridFS($this->name);
  937.         }
  938.         $this->subClasses         = [];
  939.         $this->discriminatorMap   = [];
  940.         $this->discriminatorValue null;
  941.         foreach ($map as $value => $className) {
  942.             $this->discriminatorMap[$value] = $className;
  943.             if ($this->name === $className) {
  944.                 $this->discriminatorValue $value;
  945.             } else {
  946.                 if (! class_exists($className)) {
  947.                     throw MappingException::invalidClassInDiscriminatorMap($className$this->name);
  948.                 }
  949.                 if (is_subclass_of($className$this->name)) {
  950.                     $this->subClasses[] = $className;
  951.                 }
  952.             }
  953.         }
  954.     }
  955.     /**
  956.      * Sets the default discriminator value to be used for this class
  957.      * Used for SINGLE_TABLE inheritance mapping strategies if the document has no discriminator value
  958.      *
  959.      * @throws MappingException
  960.      */
  961.     public function setDefaultDiscriminatorValue(?string $defaultDiscriminatorValue): void
  962.     {
  963.         if ($this->isFile) {
  964.             throw MappingException::discriminatorNotAllowedForGridFS($this->name);
  965.         }
  966.         if ($defaultDiscriminatorValue === null) {
  967.             $this->defaultDiscriminatorValue null;
  968.             return;
  969.         }
  970.         if (! array_key_exists($defaultDiscriminatorValue$this->discriminatorMap)) {
  971.             throw MappingException::invalidDiscriminatorValue($defaultDiscriminatorValue$this->name);
  972.         }
  973.         $this->defaultDiscriminatorValue $defaultDiscriminatorValue;
  974.     }
  975.     /**
  976.      * Sets the discriminator value for this class.
  977.      * Used for JOINED/SINGLE_TABLE inheritance and multiple document types in a single
  978.      * collection.
  979.      *
  980.      * @throws MappingException
  981.      */
  982.     public function setDiscriminatorValue(string $value): void
  983.     {
  984.         if ($this->isFile) {
  985.             throw MappingException::discriminatorNotAllowedForGridFS($this->name);
  986.         }
  987.         $this->discriminatorMap[$value] = $this->name;
  988.         $this->discriminatorValue       $value;
  989.     }
  990.     /**
  991.      * Add a index for this Document.
  992.      *
  993.      * @param array<string, int|string> $keys
  994.      * @psalm-param IndexKeys $keys
  995.      * @psalm-param IndexOptions $options
  996.      */
  997.     public function addIndex(array $keys, array $options = []): void
  998.     {
  999.         $this->indexes[] = [
  1000.             'keys' => array_map(static function ($value) {
  1001.                 if ($value === || $value === -1) {
  1002.                     return $value;
  1003.                 }
  1004.                 if (is_string($value)) {
  1005.                     $lower strtolower($value);
  1006.                     if ($lower === 'asc') {
  1007.                         return 1;
  1008.                     }
  1009.                     if ($lower === 'desc') {
  1010.                         return -1;
  1011.                     }
  1012.                 }
  1013.                 return $value;
  1014.             }, $keys),
  1015.             'options' => $options,
  1016.         ];
  1017.     }
  1018.     /**
  1019.      * Returns the array of indexes for this Document.
  1020.      *
  1021.      * @psalm-return array<IndexMapping>
  1022.      */
  1023.     public function getIndexes(): array
  1024.     {
  1025.         return $this->indexes;
  1026.     }
  1027.     /**
  1028.      * Checks whether this document has indexes or not.
  1029.      */
  1030.     public function hasIndexes(): bool
  1031.     {
  1032.         return $this->indexes !== [];
  1033.     }
  1034.     /**
  1035.      * Set shard key for this Document.
  1036.      *
  1037.      * @param array<string, string|int> $keys
  1038.      * @param array<string, mixed>      $options
  1039.      * @psalm-param ShardKeys $keys
  1040.      * @psalm-param ShardOptions      $options
  1041.      *
  1042.      * @throws MappingException
  1043.      */
  1044.     public function setShardKey(array $keys, array $options = []): void
  1045.     {
  1046.         if ($this->inheritanceType === self::INHERITANCE_TYPE_SINGLE_COLLECTION && $this->shardKey !== []) {
  1047.             throw MappingException::shardKeyInSingleCollInheritanceSubclass($this->getName());
  1048.         }
  1049.         if ($this->isEmbeddedDocument) {
  1050.             throw MappingException::embeddedDocumentCantHaveShardKey($this->getName());
  1051.         }
  1052.         foreach (array_keys($keys) as $field) {
  1053.             if (! isset($this->fieldMappings[$field])) {
  1054.                 continue;
  1055.             }
  1056.             if (in_array($this->fieldMappings[$field]['type'], [self::MANYType::COLLECTION])) {
  1057.                 throw MappingException::noMultiKeyShardKeys($this->getName(), $field);
  1058.             }
  1059.             if ($this->fieldMappings[$field]['strategy'] !== self::STORAGE_STRATEGY_SET) {
  1060.                 throw MappingException::onlySetStrategyAllowedInShardKey($this->getName(), $field);
  1061.             }
  1062.         }
  1063.         $this->shardKey = [
  1064.             'keys' => array_map(static function ($value) {
  1065.                 if ($value === || $value === -1) {
  1066.                     return $value;
  1067.                 }
  1068.                 if (is_string($value)) {
  1069.                     $lower strtolower($value);
  1070.                     if ($lower === 'asc') {
  1071.                         return 1;
  1072.                     }
  1073.                     if ($lower === 'desc') {
  1074.                         return -1;
  1075.                     }
  1076.                 }
  1077.                 return $value;
  1078.             }, $keys),
  1079.             'options' => $options,
  1080.         ];
  1081.     }
  1082.     /** @psalm-return ShardKey */
  1083.     public function getShardKey(): array
  1084.     {
  1085.         return $this->shardKey;
  1086.     }
  1087.     /**
  1088.      * Checks whether this document has shard key or not.
  1089.      */
  1090.     public function isSharded(): bool
  1091.     {
  1092.         return $this->shardKey !== [];
  1093.     }
  1094.     /**
  1095.      * @return array|object|null
  1096.      * @psalm-return array<string, mixed>|object|null
  1097.      */
  1098.     public function getValidator()
  1099.     {
  1100.         return $this->validator;
  1101.     }
  1102.     /**
  1103.      * @param array|object|null $validator
  1104.      * @psalm-param array<string, mixed>|object|null $validator
  1105.      */
  1106.     public function setValidator($validator): void
  1107.     {
  1108.         $this->validator $validator;
  1109.     }
  1110.     public function getValidationAction(): string
  1111.     {
  1112.         return $this->validationAction;
  1113.     }
  1114.     public function setValidationAction(string $validationAction): void
  1115.     {
  1116.         $this->validationAction $validationAction;
  1117.     }
  1118.     public function getValidationLevel(): string
  1119.     {
  1120.         return $this->validationLevel;
  1121.     }
  1122.     public function setValidationLevel(string $validationLevel): void
  1123.     {
  1124.         $this->validationLevel $validationLevel;
  1125.     }
  1126.     /**
  1127.      * Sets the read preference used by this class.
  1128.      *
  1129.      * @param array<array<string, string>> $tags
  1130.      */
  1131.     public function setReadPreference(?string $readPreference, array $tags): void
  1132.     {
  1133.         $this->readPreference     $readPreference;
  1134.         $this->readPreferenceTags $tags;
  1135.     }
  1136.     /**
  1137.      * Sets the write concern used by this class.
  1138.      *
  1139.      * @param string|int|null $writeConcern
  1140.      */
  1141.     public function setWriteConcern($writeConcern): void
  1142.     {
  1143.         $this->writeConcern $writeConcern;
  1144.     }
  1145.     /** @return int|string|null */
  1146.     public function getWriteConcern()
  1147.     {
  1148.         return $this->writeConcern;
  1149.     }
  1150.     /**
  1151.      * Whether there is a write concern configured for this class.
  1152.      */
  1153.     public function hasWriteConcern(): bool
  1154.     {
  1155.         return $this->writeConcern !== null;
  1156.     }
  1157.     /**
  1158.      * Sets the change tracking policy used by this class.
  1159.      */
  1160.     public function setChangeTrackingPolicy(int $policy): void
  1161.     {
  1162.         $this->changeTrackingPolicy $policy;
  1163.     }
  1164.     /**
  1165.      * Whether the change tracking policy of this class is "deferred explicit".
  1166.      */
  1167.     public function isChangeTrackingDeferredExplicit(): bool
  1168.     {
  1169.         return $this->changeTrackingPolicy === self::CHANGETRACKING_DEFERRED_EXPLICIT;
  1170.     }
  1171.     /**
  1172.      * Whether the change tracking policy of this class is "deferred implicit".
  1173.      */
  1174.     public function isChangeTrackingDeferredImplicit(): bool
  1175.     {
  1176.         return $this->changeTrackingPolicy === self::CHANGETRACKING_DEFERRED_IMPLICIT;
  1177.     }
  1178.     /**
  1179.      * Whether the change tracking policy of this class is "notify".
  1180.      *
  1181.      * @deprecated This method was deprecated in doctrine/mongodb-odm 2.4. Please use DEFERRED_EXPLICIT tracking
  1182.      * policy and isChangeTrackingDeferredImplicit method to detect it.
  1183.      */
  1184.     public function isChangeTrackingNotify(): bool
  1185.     {
  1186.         return $this->changeTrackingPolicy === self::CHANGETRACKING_NOTIFY;
  1187.     }
  1188.     /**
  1189.      * Gets the ReflectionProperties of the mapped class.
  1190.      *
  1191.      * @return ReflectionProperty[]
  1192.      */
  1193.     public function getReflectionProperties(): array
  1194.     {
  1195.         return $this->reflFields;
  1196.     }
  1197.     /**
  1198.      * Gets a ReflectionProperty for a specific field of the mapped class.
  1199.      */
  1200.     public function getReflectionProperty(string $name): ReflectionProperty
  1201.     {
  1202.         return $this->reflFields[$name];
  1203.     }
  1204.     /** @psalm-return class-string<T> */
  1205.     public function getName(): string
  1206.     {
  1207.         return $this->name;
  1208.     }
  1209.     /**
  1210.      * Returns the database this Document is mapped to.
  1211.      */
  1212.     public function getDatabase(): ?string
  1213.     {
  1214.         return $this->db;
  1215.     }
  1216.     /**
  1217.      * Set the database this Document is mapped to.
  1218.      */
  1219.     public function setDatabase(?string $db): void
  1220.     {
  1221.         $this->db $db;
  1222.     }
  1223.     /**
  1224.      * Get the collection this Document is mapped to.
  1225.      */
  1226.     public function getCollection(): string
  1227.     {
  1228.         return $this->collection;
  1229.     }
  1230.     /**
  1231.      * Sets the collection this Document is mapped to.
  1232.      *
  1233.      * @param array|string $name
  1234.      * @psalm-param array{name: string, capped?: bool, size?: int, max?: int}|string $name
  1235.      *
  1236.      * @throws InvalidArgumentException
  1237.      */
  1238.     public function setCollection($name): void
  1239.     {
  1240.         if (is_array($name)) {
  1241.             if (! isset($name['name'])) {
  1242.                 throw new InvalidArgumentException('A name key is required when passing an array to setCollection()');
  1243.             }
  1244.             $this->collectionCapped $name['capped'] ?? false;
  1245.             $this->collectionSize   $name['size'] ?? 0;
  1246.             $this->collectionMax    $name['max'] ?? 0;
  1247.             $this->collection       $name['name'];
  1248.         } else {
  1249.             $this->collection $name;
  1250.         }
  1251.     }
  1252.     public function getBucketName(): ?string
  1253.     {
  1254.         return $this->bucketName;
  1255.     }
  1256.     public function setBucketName(string $bucketName): void
  1257.     {
  1258.         $this->bucketName $bucketName;
  1259.         $this->setCollection($bucketName '.files');
  1260.     }
  1261.     public function getChunkSizeBytes(): ?int
  1262.     {
  1263.         return $this->chunkSizeBytes;
  1264.     }
  1265.     public function setChunkSizeBytes(int $chunkSizeBytes): void
  1266.     {
  1267.         $this->chunkSizeBytes $chunkSizeBytes;
  1268.     }
  1269.     /**
  1270.      * Get whether or not the documents collection is capped.
  1271.      */
  1272.     public function getCollectionCapped(): bool
  1273.     {
  1274.         return $this->collectionCapped;
  1275.     }
  1276.     /**
  1277.      * Set whether or not the documents collection is capped.
  1278.      */
  1279.     public function setCollectionCapped(bool $bool): void
  1280.     {
  1281.         $this->collectionCapped $bool;
  1282.     }
  1283.     /**
  1284.      * Get the collection size
  1285.      */
  1286.     public function getCollectionSize(): ?int
  1287.     {
  1288.         return $this->collectionSize;
  1289.     }
  1290.     /**
  1291.      * Set the collection size.
  1292.      */
  1293.     public function setCollectionSize(int $size): void
  1294.     {
  1295.         $this->collectionSize $size;
  1296.     }
  1297.     /**
  1298.      * Get the collection max.
  1299.      */
  1300.     public function getCollectionMax(): ?int
  1301.     {
  1302.         return $this->collectionMax;
  1303.     }
  1304.     /**
  1305.      * Set the collection max.
  1306.      */
  1307.     public function setCollectionMax(int $max): void
  1308.     {
  1309.         $this->collectionMax $max;
  1310.     }
  1311.     /**
  1312.      * Returns TRUE if this Document is mapped to a collection FALSE otherwise.
  1313.      */
  1314.     public function isMappedToCollection(): bool
  1315.     {
  1316.         return $this->collection !== '' && $this->collection !== null;
  1317.     }
  1318.     /**
  1319.      * Validates the storage strategy of a mapping for consistency
  1320.      *
  1321.      * @psalm-param FieldMappingConfig $mapping
  1322.      *
  1323.      * @throws MappingException
  1324.      */
  1325.     private function applyStorageStrategy(array &$mapping): void
  1326.     {
  1327.         if (! isset($mapping['type']) || isset($mapping['id'])) {
  1328.             return;
  1329.         }
  1330.         switch (true) {
  1331.             case $mapping['type'] === self::MANY:
  1332.                 $defaultStrategy   CollectionHelper::DEFAULT_STRATEGY;
  1333.                 $allowedStrategies = [
  1334.                     self::STORAGE_STRATEGY_PUSH_ALL,
  1335.                     self::STORAGE_STRATEGY_ADD_TO_SET,
  1336.                     self::STORAGE_STRATEGY_SET,
  1337.                     self::STORAGE_STRATEGY_SET_ARRAY,
  1338.                     self::STORAGE_STRATEGY_ATOMIC_SET,
  1339.                     self::STORAGE_STRATEGY_ATOMIC_SET_ARRAY,
  1340.                 ];
  1341.                 break;
  1342.             case $mapping['type'] === self::ONE:
  1343.                 $defaultStrategy   self::STORAGE_STRATEGY_SET;
  1344.                 $allowedStrategies = [self::STORAGE_STRATEGY_SET];
  1345.                 break;
  1346.             default:
  1347.                 $defaultStrategy   self::STORAGE_STRATEGY_SET;
  1348.                 $allowedStrategies = [self::STORAGE_STRATEGY_SET];
  1349.                 $type              Type::getType($mapping['type']);
  1350.                 if ($type instanceof Incrementable) {
  1351.                     $allowedStrategies[] = self::STORAGE_STRATEGY_INCREMENT;
  1352.                 }
  1353.         }
  1354.         if (! isset($mapping['strategy'])) {
  1355.             $mapping['strategy'] = $defaultStrategy;
  1356.         }
  1357.         if (! in_array($mapping['strategy'], $allowedStrategies)) {
  1358.             throw MappingException::invalidStorageStrategy($this->name$mapping['fieldName'], $mapping['type'], $mapping['strategy']);
  1359.         }
  1360.         if (
  1361.             isset($mapping['reference']) && $mapping['type'] === self::MANY && $mapping['isOwningSide']
  1362.             && ! empty($mapping['sort']) && ! CollectionHelper::usesSet($mapping['strategy'])
  1363.         ) {
  1364.             throw MappingException::referenceManySortMustNotBeUsedWithNonSetCollectionStrategy($this->name$mapping['fieldName'], $mapping['strategy']);
  1365.         }
  1366.     }
  1367.     /**
  1368.      * Map a single embedded document.
  1369.      *
  1370.      * @psalm-param FieldMappingConfig $mapping
  1371.      */
  1372.     public function mapOneEmbedded(array $mapping): void
  1373.     {
  1374.         $mapping['embedded'] = true;
  1375.         $mapping['type']     = self::ONE;
  1376.         $this->mapField($mapping);
  1377.     }
  1378.     /**
  1379.      * Map a collection of embedded documents.
  1380.      *
  1381.      * @psalm-param FieldMappingConfig $mapping
  1382.      */
  1383.     public function mapManyEmbedded(array $mapping): void
  1384.     {
  1385.         $mapping['embedded'] = true;
  1386.         $mapping['type']     = self::MANY;
  1387.         $this->mapField($mapping);
  1388.     }
  1389.     /**
  1390.      * Map a single document reference.
  1391.      *
  1392.      * @psalm-param FieldMappingConfig $mapping
  1393.      */
  1394.     public function mapOneReference(array $mapping): void
  1395.     {
  1396.         $mapping['reference'] = true;
  1397.         $mapping['type']      = self::ONE;
  1398.         $this->mapField($mapping);
  1399.     }
  1400.     /**
  1401.      * Map a collection of document references.
  1402.      *
  1403.      * @psalm-param FieldMappingConfig $mapping
  1404.      */
  1405.     public function mapManyReference(array $mapping): void
  1406.     {
  1407.         $mapping['reference'] = true;
  1408.         $mapping['type']      = self::MANY;
  1409.         $this->mapField($mapping);
  1410.     }
  1411.     /**
  1412.      * Adds a field mapping without completing/validating it.
  1413.      * This is mainly used to add inherited field mappings to derived classes.
  1414.      *
  1415.      * @internal
  1416.      *
  1417.      * @psalm-param FieldMapping $fieldMapping
  1418.      */
  1419.     public function addInheritedFieldMapping(array $fieldMapping): void
  1420.     {
  1421.         $this->fieldMappings[$fieldMapping['fieldName']] = $fieldMapping;
  1422.         if (! isset($fieldMapping['association'])) {
  1423.             return;
  1424.         }
  1425.         $this->associationMappings[$fieldMapping['fieldName']] = $fieldMapping;
  1426.     }
  1427.     /**
  1428.      * Adds an association mapping without completing/validating it.
  1429.      * This is mainly used to add inherited association mappings to derived classes.
  1430.      *
  1431.      * @internal
  1432.      *
  1433.      * @psalm-param AssociationFieldMapping $mapping
  1434.      *
  1435.      * @throws MappingException
  1436.      */
  1437.     public function addInheritedAssociationMapping(array $mapping): void
  1438.     {
  1439.         $this->associationMappings[$mapping['fieldName']] = $mapping;
  1440.     }
  1441.     /**
  1442.      * Checks whether the class has a mapped association with the given field name.
  1443.      */
  1444.     public function hasReference(string $fieldName): bool
  1445.     {
  1446.         return isset($this->fieldMappings[$fieldName]['reference']);
  1447.     }
  1448.     /**
  1449.      * Checks whether the class has a mapped embed with the given field name.
  1450.      */
  1451.     public function hasEmbed(string $fieldName): bool
  1452.     {
  1453.         return isset($this->fieldMappings[$fieldName]['embedded']);
  1454.     }
  1455.     /**
  1456.      * Checks whether the class has a mapped association (embed or reference) with the given field name.
  1457.      *
  1458.      * @param string $fieldName
  1459.      */
  1460.     public function hasAssociation($fieldName): bool
  1461.     {
  1462.         return $this->hasReference($fieldName) || $this->hasEmbed($fieldName);
  1463.     }
  1464.     /**
  1465.      * Checks whether the class has a mapped reference or embed for the specified field and
  1466.      * is a single valued association.
  1467.      *
  1468.      * @param string $fieldName
  1469.      */
  1470.     public function isSingleValuedAssociation($fieldName): bool
  1471.     {
  1472.         return $this->isSingleValuedReference($fieldName) || $this->isSingleValuedEmbed($fieldName);
  1473.     }
  1474.     /**
  1475.      * Checks whether the class has a mapped reference or embed for the specified field and
  1476.      * is a collection valued association.
  1477.      *
  1478.      * @param string $fieldName
  1479.      */
  1480.     public function isCollectionValuedAssociation($fieldName): bool
  1481.     {
  1482.         return $this->isCollectionValuedReference($fieldName) || $this->isCollectionValuedEmbed($fieldName);
  1483.     }
  1484.     /**
  1485.      * Checks whether the class has a mapped association for the specified field
  1486.      * and if yes, checks whether it is a single-valued association (to-one).
  1487.      */
  1488.     public function isSingleValuedReference(string $fieldName): bool
  1489.     {
  1490.         return isset($this->fieldMappings[$fieldName]['association']) &&
  1491.             $this->fieldMappings[$fieldName]['association'] === self::REFERENCE_ONE;
  1492.     }
  1493.     /**
  1494.      * Checks whether the class has a mapped association for the specified field
  1495.      * and if yes, checks whether it is a collection-valued association (to-many).
  1496.      */
  1497.     public function isCollectionValuedReference(string $fieldName): bool
  1498.     {
  1499.         return isset($this->fieldMappings[$fieldName]['association']) &&
  1500.             $this->fieldMappings[$fieldName]['association'] === self::REFERENCE_MANY;
  1501.     }
  1502.     /**
  1503.      * Checks whether the class has a mapped embedded document for the specified field
  1504.      * and if yes, checks whether it is a single-valued association (to-one).
  1505.      */
  1506.     public function isSingleValuedEmbed(string $fieldName): bool
  1507.     {
  1508.         return isset($this->fieldMappings[$fieldName]['association']) &&
  1509.             $this->fieldMappings[$fieldName]['association'] === self::EMBED_ONE;
  1510.     }
  1511.     /**
  1512.      * Checks whether the class has a mapped embedded document for the specified field
  1513.      * and if yes, checks whether it is a collection-valued association (to-many).
  1514.      */
  1515.     public function isCollectionValuedEmbed(string $fieldName): bool
  1516.     {
  1517.         return isset($this->fieldMappings[$fieldName]['association']) &&
  1518.             $this->fieldMappings[$fieldName]['association'] === self::EMBED_MANY;
  1519.     }
  1520.     /**
  1521.      * Sets the ID generator used to generate IDs for instances of this class.
  1522.      */
  1523.     public function setIdGenerator(IdGenerator $generator): void
  1524.     {
  1525.         $this->idGenerator $generator;
  1526.     }
  1527.     /**
  1528.      * Casts the identifier to its portable PHP type.
  1529.      *
  1530.      * @param mixed $id
  1531.      *
  1532.      * @return mixed $id
  1533.      */
  1534.     public function getPHPIdentifierValue($id)
  1535.     {
  1536.         $idType $this->fieldMappings[$this->identifier]['type'];
  1537.         return Type::getType($idType)->convertToPHPValue($id);
  1538.     }
  1539.     /**
  1540.      * Casts the identifier to its database type.
  1541.      *
  1542.      * @param mixed $id
  1543.      *
  1544.      * @return mixed $id
  1545.      */
  1546.     public function getDatabaseIdentifierValue($id)
  1547.     {
  1548.         $idType $this->fieldMappings[$this->identifier]['type'];
  1549.         return Type::getType($idType)->convertToDatabaseValue($id);
  1550.     }
  1551.     /**
  1552.      * Sets the document identifier of a document.
  1553.      *
  1554.      * The value will be converted to a PHP type before being set.
  1555.      *
  1556.      * @param mixed $id
  1557.      */
  1558.     public function setIdentifierValue(object $document$id): void
  1559.     {
  1560.         $id $this->getPHPIdentifierValue($id);
  1561.         $this->reflFields[$this->identifier]->setValue($document$id);
  1562.     }
  1563.     /**
  1564.      * Gets the document identifier as a PHP type.
  1565.      *
  1566.      * @return mixed $id
  1567.      */
  1568.     public function getIdentifierValue(object $document)
  1569.     {
  1570.         return $this->reflFields[$this->identifier]->getValue($document);
  1571.     }
  1572.     /**
  1573.      * Since MongoDB only allows exactly one identifier field this is a proxy
  1574.      * to {@see getIdentifierValue()} and returns an array with the identifier
  1575.      * field as a key.
  1576.      *
  1577.      * @param object $object
  1578.      */
  1579.     public function getIdentifierValues($object): array
  1580.     {
  1581.         return [$this->identifier => $this->getIdentifierValue($object)];
  1582.     }
  1583.     /**
  1584.      * Get the document identifier object as a database type.
  1585.      *
  1586.      * @return mixed $id
  1587.      */
  1588.     public function getIdentifierObject(object $document)
  1589.     {
  1590.         return $this->getDatabaseIdentifierValue($this->getIdentifierValue($document));
  1591.     }
  1592.     /**
  1593.      * Sets the specified field to the specified value on the given document.
  1594.      *
  1595.      * @param mixed $value
  1596.      */
  1597.     public function setFieldValue(object $documentstring $field$value): void
  1598.     {
  1599.         if ($document instanceof GhostObjectInterface && ! $document->isProxyInitialized()) {
  1600.             //property changes to an uninitialized proxy will not be tracked or persisted,
  1601.             //so the proxy needs to be loaded first.
  1602.             $document->initializeProxy();
  1603.         }
  1604.         $this->reflFields[$field]->setValue($document$value);
  1605.     }
  1606.     /**
  1607.      * Gets the specified field's value off the given document.
  1608.      *
  1609.      * @return mixed
  1610.      */
  1611.     public function getFieldValue(object $documentstring $field)
  1612.     {
  1613.         if ($document instanceof GhostObjectInterface && $field !== $this->identifier && ! $document->isProxyInitialized()) {
  1614.             $document->initializeProxy();
  1615.         }
  1616.         return $this->reflFields[$field]->getValue($document);
  1617.     }
  1618.     /**
  1619.      * Gets the mapping of a field.
  1620.      *
  1621.      * @psalm-return FieldMapping
  1622.      *
  1623.      * @throws MappingException If the $fieldName is not found in the fieldMappings array.
  1624.      */
  1625.     public function getFieldMapping(string $fieldName): array
  1626.     {
  1627.         if (! isset($this->fieldMappings[$fieldName])) {
  1628.             throw MappingException::mappingNotFound($this->name$fieldName);
  1629.         }
  1630.         return $this->fieldMappings[$fieldName];
  1631.     }
  1632.     /**
  1633.      * Gets mappings of fields holding embedded document(s).
  1634.      *
  1635.      * @psalm-return array<string, FieldMapping>
  1636.      */
  1637.     public function getEmbeddedFieldsMappings(): array
  1638.     {
  1639.         return array_filter(
  1640.             $this->associationMappings,
  1641.             static fn ($assoc) => ! empty($assoc['embedded'])
  1642.         );
  1643.     }
  1644.     /**
  1645.      * Gets the field mapping by its DB name.
  1646.      * E.g. it returns identifier's mapping when called with _id.
  1647.      *
  1648.      * @psalm-return FieldMapping
  1649.      *
  1650.      * @throws MappingException
  1651.      */
  1652.     public function getFieldMappingByDbFieldName(string $dbFieldName): array
  1653.     {
  1654.         foreach ($this->fieldMappings as $mapping) {
  1655.             if ($mapping['name'] === $dbFieldName) {
  1656.                 return $mapping;
  1657.             }
  1658.         }
  1659.         throw MappingException::mappingNotFoundByDbName($this->name$dbFieldName);
  1660.     }
  1661.     /**
  1662.      * Check if the field is not null.
  1663.      */
  1664.     public function isNullable(string $fieldName): bool
  1665.     {
  1666.         $mapping $this->getFieldMapping($fieldName);
  1667.         return isset($mapping['nullable']) && $mapping['nullable'] === true;
  1668.     }
  1669.     /**
  1670.      * Checks whether the document has a discriminator field and value configured.
  1671.      */
  1672.     public function hasDiscriminator(): bool
  1673.     {
  1674.         return isset($this->discriminatorField$this->discriminatorValue);
  1675.     }
  1676.     /**
  1677.      * Sets the type of Id generator to use for the mapped class.
  1678.      */
  1679.     public function setIdGeneratorType(int $generatorType): void
  1680.     {
  1681.         $this->generatorType $generatorType;
  1682.     }
  1683.     /**
  1684.      * Sets the Id generator options.
  1685.      *
  1686.      * @param array<string, mixed> $generatorOptions
  1687.      */
  1688.     public function setIdGeneratorOptions(array $generatorOptions): void
  1689.     {
  1690.         $this->generatorOptions $generatorOptions;
  1691.     }
  1692.     public function isInheritanceTypeNone(): bool
  1693.     {
  1694.         return $this->inheritanceType === self::INHERITANCE_TYPE_NONE;
  1695.     }
  1696.     /**
  1697.      * Checks whether the mapped class uses the SINGLE_COLLECTION inheritance mapping strategy.
  1698.      */
  1699.     public function isInheritanceTypeSingleCollection(): bool
  1700.     {
  1701.         return $this->inheritanceType === self::INHERITANCE_TYPE_SINGLE_COLLECTION;
  1702.     }
  1703.     /**
  1704.      * Checks whether the mapped class uses the COLLECTION_PER_CLASS inheritance mapping strategy.
  1705.      */
  1706.     public function isInheritanceTypeCollectionPerClass(): bool
  1707.     {
  1708.         return $this->inheritanceType === self::INHERITANCE_TYPE_COLLECTION_PER_CLASS;
  1709.     }
  1710.     /**
  1711.      * Sets the mapped subclasses of this class.
  1712.      *
  1713.      * @param string[] $subclasses The names of all mapped subclasses.
  1714.      * @psalm-param class-string[] $subclasses
  1715.      */
  1716.     public function setSubclasses(array $subclasses): void
  1717.     {
  1718.         foreach ($subclasses as $subclass) {
  1719.             $this->subClasses[] = $subclass;
  1720.         }
  1721.     }
  1722.     /**
  1723.      * Sets the parent class names.
  1724.      * Assumes that the class names in the passed array are in the order:
  1725.      * directParent -> directParentParent -> directParentParentParent ... -> root.
  1726.      *
  1727.      * @param string[] $classNames
  1728.      * @psalm-param list<class-string> $classNames
  1729.      */
  1730.     public function setParentClasses(array $classNames): void
  1731.     {
  1732.         $this->parentClasses $classNames;
  1733.         if (count($classNames) <= 0) {
  1734.             return;
  1735.         }
  1736.         $this->rootDocumentName = (string) array_pop($classNames);
  1737.     }
  1738.     /**
  1739.      * Checks whether the class will generate a new \MongoDB\BSON\ObjectId instance for us.
  1740.      */
  1741.     public function isIdGeneratorAuto(): bool
  1742.     {
  1743.         return $this->generatorType === self::GENERATOR_TYPE_AUTO;
  1744.     }
  1745.     /**
  1746.      * Checks whether the class will use a collection to generate incremented identifiers.
  1747.      */
  1748.     public function isIdGeneratorIncrement(): bool
  1749.     {
  1750.         return $this->generatorType === self::GENERATOR_TYPE_INCREMENT;
  1751.     }
  1752.     /**
  1753.      * Checks whether the class will generate a uuid id.
  1754.      */
  1755.     public function isIdGeneratorUuid(): bool
  1756.     {
  1757.         return $this->generatorType === self::GENERATOR_TYPE_UUID;
  1758.     }
  1759.     /**
  1760.      * Checks whether the class uses no id generator.
  1761.      */
  1762.     public function isIdGeneratorNone(): bool
  1763.     {
  1764.         return $this->generatorType === self::GENERATOR_TYPE_NONE;
  1765.     }
  1766.     /**
  1767.      * Sets the version field mapping used for versioning. Sets the default
  1768.      * value to use depending on the column type.
  1769.      *
  1770.      * @psalm-param FieldMapping $mapping
  1771.      *
  1772.      * @throws LockException
  1773.      */
  1774.     public function setVersionMapping(array &$mapping): void
  1775.     {
  1776.         if (! Type::getType($mapping['type']) instanceof Versionable) {
  1777.             throw LockException::invalidVersionFieldType($mapping['type']);
  1778.         }
  1779.         $this->isVersioned  true;
  1780.         $this->versionField $mapping['fieldName'];
  1781.     }
  1782.     /**
  1783.      * Sets whether this class is to be versioned for optimistic locking.
  1784.      */
  1785.     public function setVersioned(bool $bool): void
  1786.     {
  1787.         $this->isVersioned $bool;
  1788.     }
  1789.     /**
  1790.      * Sets the name of the field that is to be used for versioning if this class is
  1791.      * versioned for optimistic locking.
  1792.      */
  1793.     public function setVersionField(?string $versionField): void
  1794.     {
  1795.         $this->versionField $versionField;
  1796.     }
  1797.     /**
  1798.      * Sets the version field mapping used for versioning. Sets the default
  1799.      * value to use depending on the column type.
  1800.      *
  1801.      * @psalm-param FieldMapping $mapping
  1802.      *
  1803.      * @throws LockException
  1804.      */
  1805.     public function setLockMapping(array &$mapping): void
  1806.     {
  1807.         if ($mapping['type'] !== 'int') {
  1808.             throw LockException::invalidLockFieldType($mapping['type']);
  1809.         }
  1810.         $this->isLockable true;
  1811.         $this->lockField  $mapping['fieldName'];
  1812.     }
  1813.     /**
  1814.      * Sets whether this class is to allow pessimistic locking.
  1815.      */
  1816.     public function setLockable(bool $bool): void
  1817.     {
  1818.         $this->isLockable $bool;
  1819.     }
  1820.     /**
  1821.      * Sets the name of the field that is to be used for storing whether a document
  1822.      * is currently locked or not.
  1823.      */
  1824.     public function setLockField(string $lockField): void
  1825.     {
  1826.         $this->lockField $lockField;
  1827.     }
  1828.     /**
  1829.      * Marks this class as read only, no change tracking is applied to it.
  1830.      */
  1831.     public function markReadOnly(): void
  1832.     {
  1833.         $this->isReadOnly true;
  1834.     }
  1835.     public function getRootClass(): ?string
  1836.     {
  1837.         return $this->rootClass;
  1838.     }
  1839.     public function isView(): bool
  1840.     {
  1841.         return $this->isView;
  1842.     }
  1843.     /** @psalm-param class-string $rootClass */
  1844.     public function markViewOf(string $rootClass): void
  1845.     {
  1846.         $this->isView    true;
  1847.         $this->rootClass $rootClass;
  1848.     }
  1849.     public function getFieldNames(): array
  1850.     {
  1851.         return array_keys($this->fieldMappings);
  1852.     }
  1853.     public function getAssociationNames(): array
  1854.     {
  1855.         return array_keys($this->associationMappings);
  1856.     }
  1857.     /** @param string $fieldName */
  1858.     public function getTypeOfField($fieldName): ?string
  1859.     {
  1860.         return isset($this->fieldMappings[$fieldName]) ?
  1861.             $this->fieldMappings[$fieldName]['type'] : null;
  1862.     }
  1863.     /**
  1864.      * @param string $assocName
  1865.      *
  1866.      * @psalm-return class-string|null
  1867.      */
  1868.     public function getAssociationTargetClass($assocName): ?string
  1869.     {
  1870.         if (! isset($this->associationMappings[$assocName])) {
  1871.             throw new InvalidArgumentException("Association name expected, '" $assocName "' is not an association.");
  1872.         }
  1873.         return $this->associationMappings[$assocName]['targetDocument'] ?? null;
  1874.     }
  1875.     /**
  1876.      * Retrieve the collectionClass associated with an association
  1877.      *
  1878.      * @psalm-return class-string
  1879.      */
  1880.     public function getAssociationCollectionClass(string $assocName): string
  1881.     {
  1882.         if (! isset($this->associationMappings[$assocName])) {
  1883.             throw new InvalidArgumentException("Association name expected, '" $assocName "' is not an association.");
  1884.         }
  1885.         if (! array_key_exists('collectionClass'$this->associationMappings[$assocName])) {
  1886.             throw new InvalidArgumentException("collectionClass can only be applied to 'embedMany' and 'referenceMany' associations.");
  1887.         }
  1888.         return $this->associationMappings[$assocName]['collectionClass'];
  1889.     }
  1890.     /** @param string $assocName */
  1891.     public function isAssociationInverseSide($assocName): bool
  1892.     {
  1893.         throw new BadMethodCallException(__METHOD__ '() is not implemented yet.');
  1894.     }
  1895.     /** @param string $assocName */
  1896.     public function getAssociationMappedByTargetField($assocName)
  1897.     {
  1898.         throw new BadMethodCallException(__METHOD__ '() is not implemented yet.');
  1899.     }
  1900.     /**
  1901.      * Map a field.
  1902.      *
  1903.      * @psalm-param FieldMappingConfig $mapping
  1904.      *
  1905.      * @psalm-return FieldMapping
  1906.      *
  1907.      * @throws MappingException
  1908.      */
  1909.     public function mapField(array $mapping): array
  1910.     {
  1911.         if (! isset($mapping['fieldName']) && isset($mapping['name'])) {
  1912.             $mapping['fieldName'] = $mapping['name'];
  1913.         }
  1914.         if ($this->isTypedProperty($mapping['fieldName'])) {
  1915.             $mapping $this->validateAndCompleteTypedFieldMapping($mapping);
  1916.             if (isset($mapping['type']) && $mapping['type'] === self::MANY) {
  1917.                 $mapping $this->validateAndCompleteTypedManyAssociationMapping($mapping);
  1918.             }
  1919.         }
  1920.         if (! isset($mapping['fieldName']) || ! is_string($mapping['fieldName'])) {
  1921.             throw MappingException::missingFieldName($this->name);
  1922.         }
  1923.         if (! isset($mapping['name'])) {
  1924.             $mapping['name'] = $mapping['fieldName'];
  1925.         }
  1926.         if ($this->identifier === $mapping['name'] && empty($mapping['id'])) {
  1927.             throw MappingException::mustNotChangeIdentifierFieldsType($this->name, (string) $mapping['name']);
  1928.         }
  1929.         if ($this->discriminatorField !== null && $this->discriminatorField === $mapping['name']) {
  1930.             throw MappingException::discriminatorFieldConflict($this->name$this->discriminatorField);
  1931.         }
  1932.         if (isset($mapping['collectionClass'])) {
  1933.             $mapping['collectionClass'] = ltrim($mapping['collectionClass'], '\\');
  1934.         }
  1935.         if (! empty($mapping['collectionClass'])) {
  1936.             $rColl = new ReflectionClass($mapping['collectionClass']);
  1937.             if (! $rColl->implementsInterface(Collection::class)) {
  1938.                 throw MappingException::collectionClassDoesNotImplementCommonInterface($this->name$mapping['fieldName'], $mapping['collectionClass']);
  1939.             }
  1940.         }
  1941.         if (isset($mapping['cascade']) && isset($mapping['embedded'])) {
  1942.             throw MappingException::cascadeOnEmbeddedNotAllowed($this->name$mapping['fieldName']);
  1943.         }
  1944.         $cascades = isset($mapping['cascade']) ? array_map('strtolower', (array) $mapping['cascade']) : [];
  1945.         if (in_array('all'$cascades) || isset($mapping['embedded'])) {
  1946.             $cascades = ['remove''persist''refresh''merge''detach'];
  1947.         }
  1948.         if (isset($mapping['embedded'])) {
  1949.             unset($mapping['cascade']);
  1950.         } elseif (isset($mapping['cascade'])) {
  1951.             $mapping['cascade'] = $cascades;
  1952.         }
  1953.         $mapping['isCascadeRemove']  = in_array('remove'$cascades);
  1954.         $mapping['isCascadePersist'] = in_array('persist'$cascades);
  1955.         $mapping['isCascadeRefresh'] = in_array('refresh'$cascades);
  1956.         $mapping['isCascadeMerge']   = in_array('merge'$cascades);
  1957.         $mapping['isCascadeDetach']  = in_array('detach'$cascades);
  1958.         if (isset($mapping['id']) && $mapping['id'] === true) {
  1959.             $mapping['name']  = '_id';
  1960.             $this->identifier $mapping['fieldName'];
  1961.             if (isset($mapping['strategy'])) {
  1962.                 $this->generatorType constant(self::class . '::GENERATOR_TYPE_' strtoupper($mapping['strategy']));
  1963.             }
  1964.             $this->generatorOptions $mapping['options'] ?? [];
  1965.             switch ($this->generatorType) {
  1966.                 case self::GENERATOR_TYPE_AUTO:
  1967.                     $mapping['type'] = 'id';
  1968.                     break;
  1969.                 default:
  1970.                     if (! empty($this->generatorOptions['type'])) {
  1971.                         $mapping['type'] = (string) $this->generatorOptions['type'];
  1972.                     } elseif (empty($mapping['type'])) {
  1973.                         $mapping['type'] = $this->generatorType === self::GENERATOR_TYPE_INCREMENT Type::INT Type::CUSTOMID;
  1974.                     }
  1975.             }
  1976.             unset($this->generatorOptions['type']);
  1977.         }
  1978.         if (! isset($mapping['type'])) {
  1979.             // Default to string
  1980.             $mapping['type'] = Type::STRING;
  1981.         }
  1982.         if (! isset($mapping['nullable'])) {
  1983.             $mapping['nullable'] = false;
  1984.         }
  1985.         if (
  1986.             isset($mapping['reference'])
  1987.             && isset($mapping['storeAs'])
  1988.             && $mapping['storeAs'] === self::REFERENCE_STORE_AS_ID
  1989.             && ! isset($mapping['targetDocument'])
  1990.         ) {
  1991.             throw MappingException::simpleReferenceRequiresTargetDocument($this->name$mapping['fieldName']);
  1992.         }
  1993.         if (
  1994.             isset($mapping['reference']) && empty($mapping['targetDocument']) && empty($mapping['discriminatorMap']) &&
  1995.                 (isset($mapping['mappedBy']) || isset($mapping['inversedBy']))
  1996.         ) {
  1997.             throw MappingException::owningAndInverseReferencesRequireTargetDocument($this->name$mapping['fieldName']);
  1998.         }
  1999.         if ($this->isEmbeddedDocument && $mapping['type'] === self::MANY && isset($mapping['strategy']) && CollectionHelper::isAtomic($mapping['strategy'])) {
  2000.             throw MappingException::atomicCollectionStrategyNotAllowed($mapping['strategy'], $this->name$mapping['fieldName']);
  2001.         }
  2002.         if (isset($mapping['repositoryMethod']) && ! (empty($mapping['skip']) && empty($mapping['limit']) && empty($mapping['sort']))) {
  2003.             throw MappingException::repositoryMethodCanNotBeCombinedWithSkipLimitAndSort($this->name$mapping['fieldName']);
  2004.         }
  2005.         if (isset($mapping['targetDocument']) && isset($mapping['discriminatorMap'])) {
  2006.             trigger_deprecation(
  2007.                 'doctrine/mongodb-odm',
  2008.                 '2.2',
  2009.                 'Mapping both "targetDocument" and "discriminatorMap" on field "%s" in class "%s" is deprecated. Only one of them can be used at a time',
  2010.                 $mapping['fieldName'],
  2011.                 $this->name,
  2012.             );
  2013.         }
  2014.         if (isset($mapping['reference']) && $mapping['type'] === self::ONE) {
  2015.             $mapping['association'] = self::REFERENCE_ONE;
  2016.         }
  2017.         if (isset($mapping['reference']) && $mapping['type'] === self::MANY) {
  2018.             $mapping['association'] = self::REFERENCE_MANY;
  2019.         }
  2020.         if (isset($mapping['embedded']) && $mapping['type'] === self::ONE) {
  2021.             $mapping['association'] = self::EMBED_ONE;
  2022.         }
  2023.         if (isset($mapping['embedded']) && $mapping['type'] === self::MANY) {
  2024.             $mapping['association'] = self::EMBED_MANY;
  2025.         }
  2026.         if (isset($mapping['association']) && ! isset($mapping['targetDocument']) && ! isset($mapping['discriminatorField'])) {
  2027.             $mapping['discriminatorField'] = self::DEFAULT_DISCRIMINATOR_FIELD;
  2028.         }
  2029.         if (isset($mapping['targetDocument']) && ! class_exists($mapping['targetDocument']) && ! interface_exists($mapping['targetDocument'])) {
  2030.             throw MappingException::invalidTargetDocument(
  2031.                 $mapping['targetDocument'],
  2032.                 $this->name,
  2033.                 $mapping['fieldName'],
  2034.             );
  2035.         }
  2036.         if (isset($mapping['discriminatorMap'])) {
  2037.             foreach ($mapping['discriminatorMap'] as $value => $class) {
  2038.                 if (! class_exists($class) && ! interface_exists($class)) {
  2039.                     throw MappingException::invalidClassInReferenceDiscriminatorMap($class$this->name$mapping['fieldName']);
  2040.                 }
  2041.             }
  2042.         }
  2043.         if (isset($mapping['version'])) {
  2044.             $mapping['notSaved'] = true;
  2045.             $this->setVersionMapping($mapping);
  2046.         }
  2047.         if (isset($mapping['lock'])) {
  2048.             $mapping['notSaved'] = true;
  2049.             $this->setLockMapping($mapping);
  2050.         }
  2051.         $mapping['isOwningSide']  = true;
  2052.         $mapping['isInverseSide'] = false;
  2053.         if (isset($mapping['reference'])) {
  2054.             if (isset($mapping['inversedBy']) && $mapping['inversedBy']) {
  2055.                 $mapping['isOwningSide']  = true;
  2056.                 $mapping['isInverseSide'] = false;
  2057.             }
  2058.             if (isset($mapping['mappedBy']) && $mapping['mappedBy']) {
  2059.                 $mapping['isInverseSide'] = true;
  2060.                 $mapping['isOwningSide']  = false;
  2061.             }
  2062.             if (isset($mapping['repositoryMethod'])) {
  2063.                 $mapping['isInverseSide'] = true;
  2064.                 $mapping['isOwningSide']  = false;
  2065.             }
  2066.             if (! isset($mapping['orphanRemoval'])) {
  2067.                 $mapping['orphanRemoval'] = false;
  2068.             }
  2069.         }
  2070.         if (! empty($mapping['prime']) && ($mapping['association'] !== self::REFERENCE_MANY || ! $mapping['isInverseSide'])) {
  2071.             throw MappingException::referencePrimersOnlySupportedForInverseReferenceMany($this->name$mapping['fieldName']);
  2072.         }
  2073.         if ($this->isFile && ! $this->isAllowedGridFSField($mapping['name'])) {
  2074.             throw MappingException::fieldNotAllowedForGridFS($this->name$mapping['fieldName']);
  2075.         }
  2076.         $this->applyStorageStrategy($mapping);
  2077.         $this->checkDuplicateMapping($mapping);
  2078.         $this->typeRequirementsAreMet($mapping);
  2079.         $deprecatedTypes = [
  2080.             Type::BOOLEAN => Type::BOOL,
  2081.             Type::INTEGER => Type::INT,
  2082.             Type::INTID => Type::INT,
  2083.         ];
  2084.         if (isset($deprecatedTypes[$mapping['type']])) {
  2085.             trigger_deprecation(
  2086.                 'doctrine/mongodb-odm',
  2087.                 '2.1',
  2088.                 'The "%s" mapping type is deprecated. Use "%s" instead.',
  2089.                 $mapping['type'],
  2090.                 $deprecatedTypes[$mapping['type']],
  2091.             );
  2092.         }
  2093.         $this->fieldMappings[$mapping['fieldName']] = $mapping;
  2094.         if (isset($mapping['association'])) {
  2095.             $this->associationMappings[$mapping['fieldName']] = $mapping;
  2096.         }
  2097.         $reflProp $this->reflectionService->getAccessibleProperty($this->name$mapping['fieldName']);
  2098.         assert($reflProp instanceof ReflectionProperty);
  2099.         if (isset($mapping['enumType'])) {
  2100.             if (PHP_VERSION_ID 80100) {
  2101.                 throw MappingException::enumsRequirePhp81($this->name$mapping['fieldName']);
  2102.             }
  2103.             if (! enum_exists($mapping['enumType'])) {
  2104.                 throw MappingException::nonEnumTypeMapped($this->name$mapping['fieldName'], $mapping['enumType']);
  2105.             }
  2106.             $reflectionEnum = new ReflectionEnum($mapping['enumType']);
  2107.             if (! $reflectionEnum->isBacked()) {
  2108.                 throw MappingException::nonBackedEnumMapped($this->name$mapping['fieldName'], $mapping['enumType']);
  2109.             }
  2110.             $reflProp = new EnumReflectionProperty($reflProp$mapping['enumType']);
  2111.         }
  2112.         $this->reflFields[$mapping['fieldName']] = $reflProp;
  2113.         return $mapping;
  2114.     }
  2115.     /**
  2116.      * Determines which fields get serialized.
  2117.      *
  2118.      * It is only serialized what is necessary for best unserialization performance.
  2119.      * That means any metadata properties that are not set or empty or simply have
  2120.      * their default value are NOT serialized.
  2121.      *
  2122.      * Parts that are also NOT serialized because they can not be properly unserialized:
  2123.      *      - reflClass (ReflectionClass)
  2124.      *      - reflFields (ReflectionProperty array)
  2125.      *
  2126.      * @return array The names of all the fields that should be serialized.
  2127.      */
  2128.     public function __sleep()
  2129.     {
  2130.         // This metadata is always serialized/cached.
  2131.         $serialized = [
  2132.             'fieldMappings',
  2133.             'associationMappings',
  2134.             'identifier',
  2135.             'name',
  2136.             'db',
  2137.             'collection',
  2138.             'readPreference',
  2139.             'readPreferenceTags',
  2140.             'writeConcern',
  2141.             'rootDocumentName',
  2142.             'generatorType',
  2143.             'generatorOptions',
  2144.             'idGenerator',
  2145.             'indexes',
  2146.             'shardKey',
  2147.         ];
  2148.         // The rest of the metadata is only serialized if necessary.
  2149.         if ($this->changeTrackingPolicy !== self::CHANGETRACKING_DEFERRED_IMPLICIT) {
  2150.             $serialized[] = 'changeTrackingPolicy';
  2151.         }
  2152.         if ($this->customRepositoryClassName) {
  2153.             $serialized[] = 'customRepositoryClassName';
  2154.         }
  2155.         if ($this->inheritanceType !== self::INHERITANCE_TYPE_NONE || $this->discriminatorField !== null) {
  2156.             $serialized[] = 'inheritanceType';
  2157.             $serialized[] = 'discriminatorField';
  2158.             $serialized[] = 'discriminatorValue';
  2159.             $serialized[] = 'discriminatorMap';
  2160.             $serialized[] = 'defaultDiscriminatorValue';
  2161.             $serialized[] = 'parentClasses';
  2162.             $serialized[] = 'subClasses';
  2163.         }
  2164.         if ($this->isMappedSuperclass) {
  2165.             $serialized[] = 'isMappedSuperclass';
  2166.         }
  2167.         if ($this->isEmbeddedDocument) {
  2168.             $serialized[] = 'isEmbeddedDocument';
  2169.         }
  2170.         if ($this->isQueryResultDocument) {
  2171.             $serialized[] = 'isQueryResultDocument';
  2172.         }
  2173.         if ($this->isView()) {
  2174.             $serialized[] = 'isView';
  2175.             $serialized[] = 'rootClass';
  2176.         }
  2177.         if ($this->isFile) {
  2178.             $serialized[] = 'isFile';
  2179.             $serialized[] = 'bucketName';
  2180.             $serialized[] = 'chunkSizeBytes';
  2181.         }
  2182.         if ($this->isVersioned) {
  2183.             $serialized[] = 'isVersioned';
  2184.             $serialized[] = 'versionField';
  2185.         }
  2186.         if ($this->isLockable) {
  2187.             $serialized[] = 'isLockable';
  2188.             $serialized[] = 'lockField';
  2189.         }
  2190.         if ($this->lifecycleCallbacks) {
  2191.             $serialized[] = 'lifecycleCallbacks';
  2192.         }
  2193.         if ($this->collectionCapped) {
  2194.             $serialized[] = 'collectionCapped';
  2195.             $serialized[] = 'collectionSize';
  2196.             $serialized[] = 'collectionMax';
  2197.         }
  2198.         if ($this->isReadOnly) {
  2199.             $serialized[] = 'isReadOnly';
  2200.         }
  2201.         if ($this->validator !== null) {
  2202.             $serialized[] = 'validator';
  2203.             $serialized[] = 'validationAction';
  2204.             $serialized[] = 'validationLevel';
  2205.         }
  2206.         return $serialized;
  2207.     }
  2208.     /**
  2209.      * Restores some state that can not be serialized/unserialized.
  2210.      */
  2211.     public function __wakeup()
  2212.     {
  2213.         // Restore ReflectionClass and properties
  2214.         $this->reflectionService = new RuntimeReflectionService();
  2215.         $this->reflClass         = new ReflectionClass($this->name);
  2216.         $this->instantiator      = new Instantiator();
  2217.         foreach ($this->fieldMappings as $field => $mapping) {
  2218.             $prop $this->reflectionService->getAccessibleProperty($mapping['declared'] ?? $this->name$field);
  2219.             assert($prop instanceof ReflectionProperty);
  2220.             if (isset($mapping['enumType'])) {
  2221.                 $prop = new EnumReflectionProperty($prop$mapping['enumType']);
  2222.             }
  2223.             $this->reflFields[$field] = $prop;
  2224.         }
  2225.     }
  2226.     /**
  2227.      * Creates a new instance of the mapped class, without invoking the constructor.
  2228.      *
  2229.      * @psalm-return T
  2230.      */
  2231.     public function newInstance(): object
  2232.     {
  2233.         /** @psalm-var T */
  2234.         return $this->instantiator->instantiate($this->name);
  2235.     }
  2236.     private function isAllowedGridFSField(string $name): bool
  2237.     {
  2238.         return in_array($nameself::ALLOWED_GRIDFS_FIELDStrue);
  2239.     }
  2240.     /** @psalm-param FieldMapping $mapping */
  2241.     private function typeRequirementsAreMet(array $mapping): void
  2242.     {
  2243.         if ($mapping['type'] === Type::DECIMAL128 && ! extension_loaded('bcmath')) {
  2244.             throw MappingException::typeRequirementsNotFulfilled($this->name$mapping['fieldName'], Type::DECIMAL128'ext-bcmath is missing');
  2245.         }
  2246.     }
  2247.     /** @psalm-param FieldMapping $mapping */
  2248.     private function checkDuplicateMapping(array $mapping): void
  2249.     {
  2250.         if ($mapping['notSaved'] ?? false) {
  2251.             return;
  2252.         }
  2253.         foreach ($this->fieldMappings as $fieldName => $otherMapping) {
  2254.             // Ignore fields with the same name - we can safely override their mapping
  2255.             if ($mapping['fieldName'] === $fieldName) {
  2256.                 continue;
  2257.             }
  2258.             // Ignore fields with a different name in the database
  2259.             if ($mapping['name'] !== $otherMapping['name']) {
  2260.                 continue;
  2261.             }
  2262.             // If the other field is not saved, ignore it as well
  2263.             if ($otherMapping['notSaved'] ?? false) {
  2264.                 continue;
  2265.             }
  2266.             throw MappingException::duplicateDatabaseFieldName($this->getName(), $mapping['fieldName'], $mapping['name'], $fieldName);
  2267.         }
  2268.     }
  2269.     private function isTypedProperty(string $name): bool
  2270.     {
  2271.         return $this->reflClass->hasProperty($name)
  2272.             && $this->reflClass->getProperty($name)->hasType();
  2273.     }
  2274.     /**
  2275.      * Validates & completes the given field mapping based on typed property.
  2276.      *
  2277.      * @psalm-param FieldMappingConfig $mapping
  2278.      *
  2279.      * @return FieldMappingConfig
  2280.      */
  2281.     private function validateAndCompleteTypedFieldMapping(array $mapping): array
  2282.     {
  2283.         $type $this->reflClass->getProperty($mapping['fieldName'])->getType();
  2284.         if (! $type instanceof ReflectionNamedType || isset($mapping['type'])) {
  2285.             return $mapping;
  2286.         }
  2287.         if (PHP_VERSION_ID >= 80100 && ! $type->isBuiltin() && enum_exists($type->getName())) {
  2288.             $mapping['enumType'] = $type->getName();
  2289.             $reflection = new ReflectionEnum($type->getName());
  2290.             $type       $reflection->getBackingType();
  2291.             if ($type === null) {
  2292.                 throw MappingException::nonBackedEnumMapped($this->name$mapping['fieldName'], $mapping['enumType']);
  2293.             }
  2294.             assert($type instanceof ReflectionNamedType);
  2295.         }
  2296.         switch ($type->getName()) {
  2297.             case DateTime::class:
  2298.                 $mapping['type'] = Type::DATE;
  2299.                 break;
  2300.             case DateTimeImmutable::class:
  2301.                 $mapping['type'] = Type::DATE_IMMUTABLE;
  2302.                 break;
  2303.             case 'array':
  2304.                 $mapping['type'] = Type::HASH;
  2305.                 break;
  2306.             case 'bool':
  2307.                 $mapping['type'] = Type::BOOL;
  2308.                 break;
  2309.             case 'float':
  2310.                 $mapping['type'] = Type::FLOAT;
  2311.                 break;
  2312.             case 'int':
  2313.                 $mapping['type'] = Type::INT;
  2314.                 break;
  2315.             case 'string':
  2316.                 $mapping['type'] = Type::STRING;
  2317.                 break;
  2318.         }
  2319.         return $mapping;
  2320.     }
  2321.     /**
  2322.      * Validates & completes the basic mapping information based on typed property.
  2323.      *
  2324.      * @psalm-param FieldMappingConfig $mapping
  2325.      *
  2326.      * @return FieldMappingConfig
  2327.      */
  2328.     private function validateAndCompleteTypedManyAssociationMapping(array $mapping): array
  2329.     {
  2330.         $type $this->reflClass->getProperty($mapping['fieldName'])->getType();
  2331.         if (! $type instanceof ReflectionNamedType) {
  2332.             return $mapping;
  2333.         }
  2334.         if (! isset($mapping['collectionClass']) && class_exists($type->getName())) {
  2335.             $mapping['collectionClass'] = $type->getName();
  2336.         }
  2337.         return $mapping;
  2338.     }
  2339. }