Passed
Pull Request — master (#181)
by Mathieu
03:22
created

Factory::setCascadePersist()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 1
CRAP Score 1

Importance

Changes 0
Metric Value
eloc 2
c 0
b 0
f 0
dl 0
loc 5
ccs 1
cts 1
cp 1
rs 10
cc 1
nc 1
nop 1
crap 1
1
<?php
2
3
namespace Zenstruck\Foundry;
4
5
use Faker;
6
7
/**
8
 * @template TObject as object
9
 * @abstract
10
 *
11
 * @author Kevin Bond <[email protected]>
12
 */
13
class Factory
14
{
15
    /** @var Configuration|null */
16
    private static $configuration;
17
18
    /**
19
     * @var string
20
     * @psalm-var class-string<TObject>
21
     */
22
    private $class;
23
24
    /** @var callable|null */
25
    private $instantiator;
26
27
    /** @var bool */
28
    private $persist = true;
29
30
    /** @var bool */
31
    private $cascadePersist = false;
32
33
    /** @var array<array|callable> */
34
    private $attributeSet = [];
35
36
    /** @var callable[] */
37
    private $beforeInstantiate = [];
38
39
    /** @var callable[] */
40
    private $afterInstantiate = [];
41
42
    /** @var callable[] */
43
    private $afterPersist = [];
44
45
    /**
46 834
     * @param array|callable $defaultAttributes
47
     *
48 834
     * @psalm-param class-string<TObject> $class
49 834
     */
50 834
    public function __construct(string $class, $defaultAttributes = [])
51
    {
52
        if (self::class === static::class) {
0 ignored issues
show
introduced by
The condition self::class === static::class is always true.
Loading history...
53
            trigger_deprecation('zenstruck/foundry', '1.9', 'Instantiating "%s" directly is deprecated and this class will be abstract in 2.0, use "%s" instead.', self::class, AnonymousFactory::class);
54
        }
55
56
        $this->class = $class;
57
        $this->attributeSet[] = $defaultAttributes;
58
    }
59 813
60
    public function __call(string $name, array $arguments)
61
    {
62 813
        if ('createMany' !== $name) {
63
            throw new \BadMethodCallException(\sprintf('Call to undefined method "%s::%s".', static::class, $name));
64
        }
65 813
66
        trigger_deprecation('zenstruck/foundry', '1.7', 'Calling instance method "%1$s::createMany()" is deprecated and will be removed in 2.0, use the static "%1$s:createMany()" method instead.', static::class);
67 813
68 20
        return $this->many($arguments[0])->create($arguments[1] ?? []);
69
    }
70 20
71 10
    /**
72
     * @param array|callable $attributes
73
     *
74
     * @return Proxy|object
75
     *
76 803
     * @psalm-return Proxy<TObject>
77
     */
78 753
    final public function create($attributes = []): Proxy
79 803
    {
80 803
        // merge the factory attribute set with the passed attributes
81
        $attributeSet = \array_merge($this->attributeSet, [$attributes]);
82
83
        // normalize each attribute set and collapse
84 803
        $attributes = \array_merge(...\array_map([$this, 'normalizeAttributes'], $attributeSet));
85
86 803
        foreach ($this->beforeInstantiate as $callback) {
87 10
            $attributes = $callback($attributes);
88
89
            if (!\is_array($attributes)) {
90 803
                throw new \LogicException('Before Instantiate event callback must return an array.');
91
            }
92 803
        }
93 190
94
        // filter each attribute to convert proxies and factories to objects
95
        $attributes = \array_map(
96
            function($value) {
97 625
                return $this->normalizeAttribute($value);
98 30
            },
99
            $attributes
100 625
        );
101
102
        // instantiate the object with the users instantiator or if not set, the default instantiator
103
        $object = ($this->instantiator ?? self::configuration()->instantiator())($attributes, $this->class);
104
105
        foreach ($this->afterInstantiate as $callback) {
106
            $callback($object, $attributes);
107
        }
108 240
109
        $proxy = new Proxy($object);
110 240
111
        if (!$this->isPersisting() || true === $this->cascadePersist) {
112
            return $proxy;
113
        }
114
115
        return $proxy->save()->withoutAutoRefresh(function(Proxy $proxy) use ($attributes) {
116
            foreach ($this->afterPersist as $callback) {
117
                $proxy->executeCallback($callback, $attributes);
118
            }
119
        });
120 190
    }
121
122 190
    /**
123
     * @see FactoryCollection::__construct()
124
     *
125
     * @psalm-return FactoryCollection<TObject>
126
     */
127
    final public function many(int $min, ?int $max = null): FactoryCollection
128 60
    {
129
        return new FactoryCollection($this, $min, $max);
130 60
    }
131 60
132
    /**
133 60
     * @return static
134
     */
135
    public function withoutPersisting(): self
136
    {
137
        $cloned = clone $this;
138
        $cloned->persist = false;
139
140
        return $cloned;
141 634
    }
142
143 634
    /**
144 634
     * @param array|callable $attributes
145
     *
146 634
     * @return static
147
     */
148
    final public function withAttributes($attributes = []): self
149
    {
150
        $cloned = clone $this;
151
        $cloned->attributeSet[] = $attributes;
152
153
        return $cloned;
154 30
    }
155
156 30
    /**
157 30
     * @param callable $callback (array $attributes): array
158
     *
159 30
     * @return static
160
     */
161
    final public function beforeInstantiate(callable $callback): self
162
    {
163
        $cloned = clone $this;
164
        $cloned->beforeInstantiate[] = $callback;
165
166
        return $cloned;
167 20
    }
168
169 20
    /**
170 20
     * @param callable $callback (object $object, array $attributes): void
171
     *
172 20
     * @return static
173
     */
174
    final public function afterInstantiate(callable $callback): self
175
    {
176
        $cloned = clone $this;
177
        $cloned->afterInstantiate[] = $callback;
178
179
        return $cloned;
180 20
    }
181
182 20
    /**
183 20
     * @param callable $callback (object|Proxy $object, array $attributes): void
184
     *
185 20
     * @return static
186
     */
187
    final public function afterPersist(callable $callback): self
188
    {
189
        $cloned = clone $this;
190
        $cloned->afterPersist[] = $callback;
191
192
        return $cloned;
193 20
    }
194
195 20
    /**
196 20
     * @param callable $instantiator (array $attributes, string $class): object
197
     *
198 20
     * @return static
199
     */
200
    final public function instantiateWith(callable $instantiator): self
201
    {
202
        $cloned = clone $this;
203
        $cloned->instantiator = $instantiator;
204 968
205
        return $cloned;
206 968
    }
207 968
208
    final public function setCascadePersist(bool $cascadePersist): self
209
    {
210
        $this->cascadePersist = $cascadePersist;
211
212 964
        return $this;
213
    }
214 964
215 10
    /**
216
     * @internal
217
     */
218 964
    final public static function boot(Configuration $configuration): void
219 964
    {
220 964
        self::$configuration = $configuration;
221
    }
222
223
    /**
224
     * @internal
225
     */
226
    final public static function shutdown(): void
227 934
    {
228
        if (!self::isBooted()) {
229 934
            return;
230
        }
231
232
        self::$configuration->faker()->unique(true); // reset unique
0 ignored issues
show
Bug introduced by
The method faker() does not exist on null. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

232
        self::$configuration->/** @scrutinizer ignore-call */ 
233
                              faker()->unique(true); // reset unique

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
233 934
        self::$configuration = null;
234
    }
235
236
    /**
237
     * @internal
238
     * @psalm-suppress InvalidNullableReturnType
239 1016
     * @psalm-suppress NullableReturnStatement
240
     */
241 1016
    final public static function configuration(): Configuration
242
    {
243
        if (!self::isBooted()) {
244 643
            throw new \RuntimeException('Foundry is not yet booted. Using in a test: is your Test case using the Factories trait? Using in a fixture: is ZenstruckFoundryBundle enabled for this environment?');
245
        }
246 643
247
        return self::$configuration;
0 ignored issues
show
Bug Best Practice introduced by
The expression return self::configuration could return the type null which is incompatible with the type-hinted return Zenstruck\Foundry\Configuration. Consider adding an additional type-check to rule them out.
Loading history...
248
    }
249
250
    /**
251
     * @internal
252 813
     */
253
    final public static function isBooted(): bool
254 813
    {
255
        return null !== self::$configuration;
256
    }
257
258
    final public static function faker(): Faker\Generator
259
    {
260
        return self::configuration()->faker();
261
    }
262 753
263
    /**
264 753
     * @internal
265 80
     *
266
     * @psalm-return class-string<TObject>
267
     */
268 753
    final protected function class(): string
269 70
    {
270
        return $this->class;
271
    }
272 753
273
    /**
274 100
     * @param array|callable $attributes
275
     */
276 80
    private static function normalizeAttributes($attributes): array
277 100
    {
278 100
        return \is_callable($attributes) ? $attributes(self::faker()) : $attributes;
0 ignored issues
show
Bug Best Practice introduced by
The expression return is_callable($attr...:faker()) : $attributes could return the type callable which is incompatible with the type-hinted return array. Consider adding an additional type-check to rule them out.
Loading history...
279
    }
280
281
    /**
282 753
     * @param mixed $value
283 753
     *
284
     * @return mixed
285
     */
286 130
    private function normalizeAttribute($value)
287
    {
288 30
        if ($value instanceof Proxy) {
289
            return $value->isPersisted() ? $value->refresh()->object() : $value->object();
290
        }
291 130
292
        if ($value instanceof FactoryCollection) {
293
            $value = $this->normalizeCollection($value);
294 70
        }
295
296 70
        if (\is_array($value)) {
297
            // possible OneToMany/ManyToMany relationship
298 20
            return \array_map(
299 20
                function($value) {
300 20
                    return $this->normalizeAttribute($value);
301
                },
302
                $value
303 20
            );
304
        }
305
306 50
        if (!$value instanceof self) {
307
            return \is_object($value) ? self::normalizeObject($value) : $value;
308
        }
309 50
310
        if (!$this->isPersisting()) {
311 50
            // ensure attribute Factory's are also not persisted
312 50
            $value = $value->withoutPersisting();
313
        }
314 50
315
        // Check if the attribute is cascade persist
316 50
        $relationField = $this->relationshipField($value) ?? $this->inverseRelationshipField($value);
317 20
        $cascadePersist = $this->hasCascadePersist($value, $relationField);
318
        if (true === $cascadePersist) {
319
            $value->setCascadePersist(true);
320
        }
321 30
322
        return $value->create()->object();
323
    }
324 803
325
    private static function normalizeObject(object $object): object
326 803
    {
327
        try {
328
            return Proxy::createFromPersisted($object)->refresh()->object();
329
        } catch (\RuntimeException $e) {
330
            return $object;
331
        }
332
    }
333
334
    private function normalizeCollection(FactoryCollection $collection): array
335
    {
336
        $field = $this->inverseRelationshipField($collection->factory());
337
        $cascadePersist = $this->hasCascadePersist($collection->factory(), $field);
338
339
        if ($this->isPersisting() && $field && false === $cascadePersist) {
340
            $this->afterPersist[] = static function(Proxy $proxy) use ($collection, $field) {
341
                $collection->create([$field => $proxy]);
342
                $proxy->refresh();
343
            };
344
345
            // creation delegated to afterPersist event - return empty array here
346
            return [];
347
        }
348
349
        return $collection->all($cascadePersist);
350
    }
351
352
    private function relationshipField(self $factory): ?string
353
    {
354
        $relationClass = $factory->class;
355
        $factoryClass = $this->class;
356
        $classMetadataFactory = self::configuration()->objectManagerFor($factoryClass)->getMetadataFactory()->getMetadataFor($factoryClass);
357
358
        foreach ($classMetadataFactory->getAssociationNames() as $field) {
359
            // ensure 1-1, n-1 and associated class matches
360
            if (!$classMetadataFactory->isAssociationInverseSide($field) && $classMetadataFactory->getAssociationTargetClass($field) === $relationClass) {
361
                return $field;
362
            }
363
        }
364
365
        return null; // no relationship found
366
    }
367
368
    private function inverseRelationshipField(self $factory): ?string
369
    {
370
        $collectionClass = $factory->class;
371
        $collectionMetadata = self::configuration()->objectManagerFor($collectionClass)->getClassMetadata($collectionClass);
372
373
        foreach ($collectionMetadata->getAssociationNames() as $field) {
374
            // ensure 1-n and associated class matches
375
            if ($collectionMetadata->isSingleValuedAssociation($field) && $collectionMetadata->getAssociationTargetClass($field) === $this->class) {
376
                return $field;
377
            }
378
        }
379
380
        return null; // no relationship found
381
    }
382
383
    private function hasCascadePersist(self $factory, ?string $field): bool
384
    {
385
        if (null === $field) {
386
            return false;
387
        }
388
389
        $collectionClass = $factory->class;
390
        $factoryClass = $this->class;
391
        $collectionMetadata = self::configuration()->objectManagerFor($collectionClass)->getClassMetadata($collectionClass);
392
        $classMetadataFactory = self::configuration()->objectManagerFor($factoryClass)->getMetadataFactory()->getMetadataFor($factoryClass);
393
394
        // Find inversedBy key
395
        $inversedBy = $collectionMetadata->associationMappings[$field]['inversedBy'] ?? null;
0 ignored issues
show
Bug introduced by
Accessing associationMappings on the interface Doctrine\Persistence\Mapping\ClassMetadata suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
396
397
        // Find cascade metatadata
398
        if (null !== $inversedBy) {
399
            $cascadeMetadata = $classMetadataFactory->associationMappings[$inversedBy]['cascade'] ?? [];
400
        } else {
401
            $cascadeMetadata = $classMetadataFactory->associationMappings[$field]['cascade'] ?? [];
402
        }
403
404
        return in_array('persist', $cascadeMetadata, true);
405
    }
406
407
    private function isPersisting(): bool
408
    {
409
        return self::configuration()->hasManagerRegistry() ? $this->persist : false;
410
    }
411
}
412