Passed
Pull Request — master (#38)
by Kevin
16:03
created

Factory::create()   A

Complexity

Conditions 6
Paths 9

Size

Total Lines 40
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 19
CRAP Score 6

Importance

Changes 0
Metric Value
cc 6
eloc 19
c 0
b 0
f 0
nc 9
nop 1
dl 0
loc 40
rs 9.0111
ccs 19
cts 19
cp 1
crap 6
1
<?php
2
3
namespace Zenstruck\Foundry;
4
5
use Faker;
6
7
/**
8
 * @author Kevin Bond <[email protected]>
9
 */
10
class Factory
11
{
12
    /** @var Configuration|null */
13
    private static $configuration;
14
15
    /** @var string */
16
    private $class;
17
18
    /** @var callable|null */
19
    private $instantiator;
20
21
    /** @var bool */
22
    private $persist = true;
23
24
    /** @var array<array|callable> */
25
    private $attributeSet = [];
26
27
    /** @var callable[] */
28
    private $beforeInstantiate = [];
29
30
    /** @var callable[] */
31
    private $afterInstantiate = [];
32
33
    /** @var callable[] */
34
    private $afterPersist = [];
35
36
    /**
37
     * @param array|callable $defaultAttributes
38
     */
39 270
    public function __construct(string $class, $defaultAttributes = [])
40
    {
41 270
        $this->class = $class;
42 270
        $this->attributeSet[] = $defaultAttributes;
43 270
    }
44
45
    /**
46
     * @param array|callable $attributes
47
     *
48
     * @return Proxy|object
49
     */
50 266
    final public function create($attributes = []): Proxy
51
    {
52
        // merge the factory attribute set with the passed attributes
53 266
        $attributeSet = \array_merge($this->attributeSet, [$attributes]);
54
55
        // normalize each attribute set and collapse
56 266
        $attributes = \array_merge(...\array_map([$this, 'normalizeAttributes'], $attributeSet));
57
58 266
        foreach ($this->beforeInstantiate as $callback) {
59 8
            $attributes = $callback($attributes);
60
61 8
            if (!\is_array($attributes)) {
62 4
                throw new \LogicException('Before Instantiate event callback must return an array.');
63
            }
64
        }
65
66
        // filter each attribute to convert proxies and factories to objects
67 262
        $attributes = \array_map(
68
            function($value) {
69 250
                return $this->normalizeAttribute($value);
70 262
            },
71 262
            $attributes
72
        );
73
74
        // instantiate the object with the users instantiator or if not set, the default instantiator
75 262
        $object = ($this->instantiator ?? self::configuration()->instantiator())($attributes, $this->class);
76
77 262
        foreach ($this->afterInstantiate as $callback) {
78 4
            $callback($object, $attributes);
79
        }
80
81 262
        $proxy = new Proxy($object);
82
83 262
        if (!$this->persist) {
84 56
            return $proxy;
85
        }
86
87
        return $proxy->save()->withoutAutoRefresh(function(Proxy $proxy) use ($attributes) {
88 206
            foreach ($this->afterPersist as $callback) {
89 4
                $proxy->executeCallback($callback, $attributes);
90
            }
91 206
        });
92
    }
93
94
    /**
95
     * @see FactoryCollection::__construct()
96
     */
97
    final public function many(int $min, ?int $max = null): FactoryCollection
98
    {
99 60
        return new FactoryCollection($this, $min, $max);
100
    }
101 60
102
    /**
103 60
     * @param array|callable $attributes
104 60
     *
105 60
     * @return Proxy[]|object[]
106
     */
107
    final public function createMany(int $number, $attributes = []): array
108
    {
109 64
        return $this->many($number)->create($attributes);
110
    }
111 64
112 64
    public function withoutPersisting(): self
113
    {
114 64
        $cloned = clone $this;
115
        $cloned->persist = false;
116
117
        return $cloned;
118
    }
119
120 214
    /**
121
     * @param array|callable $attributes
122 214
     */
123 214
    final public function withAttributes($attributes = []): self
124
    {
125 214
        $cloned = clone $this;
126
        $cloned->attributeSet[] = $attributes;
127
128
        return $cloned;
129
    }
130
131 12
    /**
132
     * @param callable $callback (array $attributes): array
133 12
     */
134 12
    final public function beforeInstantiate(callable $callback): self
135
    {
136 12
        $cloned = clone $this;
137
        $cloned->beforeInstantiate[] = $callback;
138
139
        return $cloned;
140
    }
141
142 8
    /**
143
     * @param callable $callback (object $object, array $attributes): void
144 8
     */
145 8
    final public function afterInstantiate(callable $callback): self
146
    {
147 8
        $cloned = clone $this;
148
        $cloned->afterInstantiate[] = $callback;
149
150
        return $cloned;
151
    }
152
153 8
    /**
154
     * @param callable $callback (object|Proxy $object, array $attributes): void
155 8
     */
156 8
    final public function afterPersist(callable $callback): self
157
    {
158 8
        $cloned = clone $this;
159
        $cloned->afterPersist[] = $callback;
160
161
        return $cloned;
162
    }
163
164 8
    /**
165
     * @param callable $instantiator (array $attributes, string $class): object
166 8
     */
167 8
    final public function instantiateWith(callable $instantiator): self
168
    {
169 8
        $cloned = clone $this;
170
        $cloned->instantiator = $instantiator;
171
172
        return $cloned;
173
    }
174
175 304
    /**
176
     * @internal
177 304
     */
178 304
    final public static function boot(Configuration $configuration): void
179
    {
180
        self::$configuration = $configuration;
181
    }
182
183 294
    /**
184
     * @internal
185 294
     */
186
    final public static function configuration(): Configuration
187
    {
188
        if (!self::isBooted()) {
189 294
            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?');
190
        }
191
192
        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...
193
    }
194
195 320
    /**
196
     * @internal
197 320
     */
198
    final public static function isBooted(): bool
199
    {
200 218
        return null !== self::$configuration;
201
    }
202 218
203
    final public static function faker(): Faker\Generator
204
    {
205
        return self::configuration()->faker();
206
    }
207
208 266
    /**
209
     * @param array|callable $attributes
210 266
     */
211
    private static function normalizeAttributes($attributes): array
212
    {
213
        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...
214
    }
215
216
    /**
217
     * @param mixed $value
218 250
     *
219
     * @return mixed
220 250
     */
221 24
    private function normalizeAttribute($value)
222
    {
223
        if ($value instanceof Proxy) {
224 250
            return $value->object();
225
        }
226 12
227
        if ($value instanceof FactoryCollection) {
228 12
            $value = $this->normalizeCollection($value);
229 12
        }
230 12
231
        if (\is_array($value)) {
232
            // possible OneToMany/ManyToMany relationship
233
            return \array_map(
234 250
                function($value) {
235 250
                    return $this->normalizeAttribute($value);
236
                },
237
                $value
238 28
            );
239
        }
240 4
241
        if (!$value instanceof self) {
242
            return $value;
243 28
        }
244
245
        if (!$this->persist) {
246
            // ensure attribute Factory's are also not persisted
247
            $value = $value->withoutPersisting();
248
        }
249
250
        return $value->create()->object();
251
    }
252
253
    private function normalizeCollection(FactoryCollection $collection): array
254
    {
255
        if ($this->persist && $field = $this->inverseRelationshipField($collection->factory())) {
256
            $this->afterPersist[] = static function(Proxy $proxy) use ($collection, $field) {
257
                $collection->create([$field => $proxy]);
258
                $proxy->refresh();
259
            };
260
261
            // creation delegated to afterPersist event - return empty array here
262
            return [];
263
        }
264
265
        return $collection->all();
266
    }
267
268
    private function inverseRelationshipField(self $factory): ?string
269
    {
270
        $collectionClass = $factory->class;
271
        $collectionMetadata = self::configuration()->objectManagerFor($collectionClass)->getClassMetadata($collectionClass);
272
273
        foreach ($collectionMetadata->getAssociationNames() as $field) {
274
            // ensure 1-n and associated class matches
275
            if ($collectionMetadata->isSingleValuedAssociation($field) && $collectionMetadata->getAssociationTargetClass($field) === $this->class) {
276
                return $field;
277
            }
278
        }
279
280
        return null; // no relationship found
281
    }
282
}
283