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

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