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

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