-
-
Notifications
You must be signed in to change notification settings - Fork 67
/
Proxy.php
478 lines (383 loc) · 14.7 KB
/
Proxy.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
<?php
/*
* This file is part of the zenstruck/foundry package.
*
* (c) Kevin Bond <kevinbond@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Zenstruck\Foundry;
use Doctrine\ODM\MongoDB\DocumentManager;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\Persistence\ObjectManager;
use Zenstruck\Assert;
use Zenstruck\Callback;
use Zenstruck\Callback\Parameter;
use Zenstruck\Foundry\Persistence\PersistentProxyObjectFactory;
use Zenstruck\Foundry\Persistence\Proxy as ProxyBase;
use Zenstruck\Foundry\Persistence\ProxyRepositoryDecorator;
/**
* @deprecated Typehint Zenstruck\Foundry\Persistence\Proxy instead
*
* @template TProxiedObject of object
* @implements ProxyBase<TProxiedObject>
*
* @mixin TProxiedObject
*
* @author Kevin Bond <kevinbond@gmail.com>
*/
final class Proxy implements \Stringable, ProxyBase
{
/**
* @phpstan-var class-string<TProxiedObject>
*/
private string $class;
private bool $autoRefresh;
private bool $persisted = false;
/**
* @internal
*
* @phpstan-param TProxiedObject $object
*/
public function __construct(
/** @param TProxiedObject $object */
private object $object,
) {
if ((new \ReflectionClass($object::class))->isFinal()) {
trigger_deprecation(
'zenstruck\foundry', '1.38.0',
'Using a proxy factory with a final class is deprecated and will throw an error in Foundry 2.0. Use "%s" instead (don\'t forget to remember all ->object() calls!), or unfinalize "%s" class.',
PersistentProxyObjectFactory::class,
$object::class,
);
}
if ((new \ReflectionClass($object::class))->isAnonymous()) {
trigger_deprecation(
'zenstruck\foundry', '1.38.0',
'Using a proxy factory with an anonymous class is deprecated and will throw an error in Foundry 2.0. Use "%s" instead.',
ObjectFactory::class,
$object::class,
);
}
$this->class = $object::class;
$this->autoRefresh = Factory::configuration()->defaultProxyAutoRefresh();
}
public function __call(string $method, array $arguments) // @phpstan-ignore-line
{
return $this->_real()->{$method}(...$arguments);
}
public function __get(string $name): mixed
{
return $this->_real()->{$name};
}
public function __set(string $name, mixed $value): void
{
$this->_real()->{$name} = $value;
}
public function __unset(string $name): void
{
unset($this->_real()->{$name});
}
public function __isset(string $name): bool
{
return isset($this->_real()->{$name});
}
public function __toString(): string
{
$object = $this->_real();
if (!\method_exists($object, '__toString')) {
throw new \RuntimeException(\sprintf('Proxied object "%s" cannot be converted to a string.', $this->class));
}
return $object->__toString();
}
/**
* @internal
*
* @template TObject of object
* @phpstan-param TObject $object
* @phpstan-return ProxyBase<TObject>
*/
public static function createFromPersisted(object $object): self
{
$proxy = new self($object);
$proxy->persisted = true;
return $proxy;
}
/**
* @deprecated without replacement
*/
public function isPersisted(bool $calledInternally = false): bool
{
if (!$calledInternally) {
trigger_deprecation('zenstruck\foundry', '1.38.0', 'Method "%s()" is deprecated and will be removed in 2.0 without replacement.', __METHOD__);
}
return $this->persisted;
}
/**
* @return TProxiedObject
*
* @deprecated Use method "_real()" instead
*/
public function object(): object
{
trigger_deprecation('zenstruck\foundry', '1.38.0', 'Method "%s()" is deprecated and will be removed in 2.0. Use "%s::_real()" instead.', __METHOD__, self::class);
return $this->_real();
}
public function _real(): object
{
if (!$this->autoRefresh || !$this->persisted || !Factory::configuration()->isFlushingEnabled() || !Factory::configuration()->isPersistEnabled()) {
return $this->object;
}
try {
$this->_autoRefresh();
} catch (\Throwable) {
}
return $this->object;
}
/**
* @deprecated Use method "_save()" instead
*/
public function save(): static
{
trigger_deprecation('zenstruck\foundry', '1.38.0', 'Method "%s()" is deprecated and will be removed in 2.0. Use "%s::_save()" instead.', __METHOD__, self::class);
return $this->_save();
}
public function _save(): static
{
$this->objectManager()->persist($this->object);
if (Factory::configuration()->isFlushingEnabled()) {
$this->objectManager()->flush();
}
$this->persisted = true;
return $this;
}
/**
* @deprecated Use method "_delete()" instead
*/
public function remove(): static
{
trigger_deprecation('zenstruck\foundry', '1.38.0', 'Method "%s()" is deprecated and will be removed in 2.0. Use "%s::_delete()" instead.', __METHOD__, self::class);
return $this->_delete();
}
public function _delete(): static
{
$this->objectManager()->remove($this->object);
$this->objectManager()->flush();
$this->autoRefresh = false;
$this->persisted = false;
return $this;
}
/**
* @deprecated Use method "_refresh()" instead
*/
public function refresh(): static
{
trigger_deprecation('zenstruck\foundry', '1.38.0', 'Method "%s()" is deprecated and will be removed in 2.0. Use "%s::_refresh()" instead.', __METHOD__, self::class);
return $this->_refresh();
}
public function _refresh(): static
{
if (!Factory::configuration()->isPersistEnabled()) {
return $this;
}
if (!$this->persisted) {
throw new \RuntimeException(\sprintf('Cannot refresh unpersisted object (%s).', $this->class));
}
$om = $this->objectManager();
// only check for changes if the object is managed in the current om
if (($om instanceof EntityManagerInterface || $om instanceof DocumentManager) && !$om->getUnitOfWork()->isScheduledForInsert($this->object) && $om->contains($this->object)) {
// cannot use UOW::recomputeSingleEntityChangeSet() here as it wrongly computes embedded objects as changed
$om->getUnitOfWork()->computeChangeSet($om->getClassMetadata($this->class), $this->object);
if (
($om instanceof EntityManagerInterface && !empty($om->getUnitOfWork()->getEntityChangeSet($this->object)))
|| ($om instanceof DocumentManager && !empty($om->getUnitOfWork()->getDocumentChangeSet($this->object)))) {
throw new \RuntimeException(\sprintf('Cannot auto refresh "%s" as there are unsaved changes. Be sure to call ->save() or disable auto refreshing (see https://symfony.com/bundles/ZenstruckFoundryBundle/current/index.html#auto-refresh for details).', $this->class));
}
}
if ($this->objectManager()->contains($this->object)) {
try {
$this->objectManager()->refresh($this->object);
} catch (\LogicException|\Error) {
// prevent entities/documents with readonly properties to create an error
// LogicException is for ORM / Error is for ODM
// @see https://github.com/doctrine/orm/issues/9505
}
return $this;
}
if (!$object = $this->fetchObject()) {
throw new \RuntimeException('The object no longer exists.');
}
$this->object = $object;
return $this;
}
/**
* @deprecated Use method "_set()" instead
*/
public function forceSet(string $property, mixed $value): static
{
trigger_deprecation('zenstruck\foundry', '1.38.0', 'Method "%s()" is deprecated and will be removed in 2.0. Use "%s::_set()" instead.', __METHOD__, self::class);
return $this->_set($property, $value);
}
public function _set(string $property, mixed $value): static
{
$this->_autoRefresh();
$object = $this->_real();
Instantiator::forceSet($object, $property, $value, calledInternally: true);
return $this;
}
/**
* @deprecated without replacement
*/
public function forceSetAll(array $properties): static
{
trigger_deprecation('zenstruck\foundry', '1.38.0', 'Method "%s()" is deprecated and will be removed in 2.0 without replacement.', __METHOD__);
$object = $this->_real();
foreach ($properties as $property => $value) {
Instantiator::forceSet($object, $property, $value, calledInternally: true);
}
return $this;
}
/**
* @deprecated Use method "_get()" instead
*/
public function forceGet(string $property): mixed
{
trigger_deprecation('zenstruck\foundry', '1.38.0', 'Method "%s()" is deprecated and will be removed in 2.0. Use "%s::_get()" instead.', __METHOD__, self::class);
return $this->_get($property);
}
public function _get(string $property): mixed
{
$this->_autoRefresh();
return Instantiator::forceGet($this->_real(), $property, calledInternally: true);
}
/**
* @deprecated Use method "_repository()" instead
*/
public function repository(): ProxyRepositoryDecorator
{
trigger_deprecation('zenstruck\foundry', '1.38.0', 'Method "%s()" is deprecated and will be removed in 2.0. Use "%s::_repository()" instead.', __METHOD__, self::class);
return $this->_repository();
}
public function _repository(): ProxyRepositoryDecorator
{
return Factory::configuration()->repositoryFor($this->class, proxy: true);
}
/**
* @deprecated Use method "_enableAutoRefresh()" instead
*/
public function enableAutoRefresh(): static
{
trigger_deprecation('zenstruck\foundry', '1.38.0', 'Method "%s()" is deprecated and will be removed in 2.0. Use "%s::_enableAutoRefresh()" instead.', __METHOD__, self::class);
return $this->_enableAutoRefresh();
}
public function _enableAutoRefresh(): static
{
if (!$this->persisted) {
throw new \RuntimeException(\sprintf('Cannot enable auto-refresh on unpersisted object (%s).', $this->class));
}
$this->autoRefresh = true;
return $this;
}
/**
* @deprecated Use method "_disableAutoRefresh()" instead
*/
public function disableAutoRefresh(): static
{
trigger_deprecation('zenstruck\foundry', '1.38.0', 'Method "%s()" is deprecated and will be removed in 2.0. Use "%s::_disableAutoRefresh()" instead.', __METHOD__, self::class);
return $this->_disableAutoRefresh();
}
public function _disableAutoRefresh(): static
{
$this->autoRefresh = false;
return $this;
}
/**
* @param callable $callback (object|Proxy $object): void
*
* @deprecated Use method "_withoutAutoRefresh()" instead
*/
public function withoutAutoRefresh(callable $callback): static
{
trigger_deprecation('zenstruck\foundry', '1.38.0', 'Method "%s()" is deprecated and will be removed in 2.0. Use "%s::_withoutAutoRefresh()" instead.', __METHOD__, self::class);
return $this->_withoutAutoRefresh($callback);
}
public function _withoutAutoRefresh(callable $callback): static
{
$original = $this->autoRefresh;
$this->autoRefresh = false;
$this->executeCallback($callback);
$this->autoRefresh = $original; // set to original value (even if it was false)
return $this;
}
/**
* @deprecated Use method "_assertPersisted" instead
*/
public function assertPersisted(string $message = '{entity} is not persisted.'): self
{
trigger_deprecation('zenstruck\foundry', '1.38.0', 'Method "%s()" is deprecated and will be removed in 2.0 without replacement.', __METHOD__);
return $this->_assertPersisted();
}
public function _assertPersisted(string $message = '{entity} is not persisted.'): self
{
Assert::that($this->fetchObject())->isNotEmpty($message, ['entity' => $this->class]);
return $this;
}
/**
* @deprecated Use method "_assertNotPersisted" instead
*/
public function assertNotPersisted(string $message = '{entity} is persisted but it should not be.'): self
{
trigger_deprecation('zenstruck\foundry', '1.38.0', 'Method "%s()" is deprecated and will be removed in 2.0 without replacement.', __METHOD__);
return $this->_assertNotPersisted();
}
public function _assertNotPersisted(string $message = '{entity} is persisted but it should not be.'): self
{
Assert::that($this->fetchObject())->isEmpty($message, ['entity' => $this->class]);
return $this;
}
/**
* @internal
*/
public function executeCallback(callable $callback, mixed ...$arguments): void
{
Callback::createFor($callback)->invoke(
Parameter::union(
Parameter::untyped($this),
Parameter::typed(ProxyBase::class, $this),
Parameter::typed($this->class, Parameter::factory(fn(): object => $this->_real())),
)->optional(),
...$arguments,
);
}
/**
* @phpstan-return TProxiedObject|null
*/
private function fetchObject(): ?object
{
$objectManager = $this->objectManager();
if ($objectManager instanceof DocumentManager) {
$classMetadata = $objectManager->getClassMetadata($this->class);
if (!$classMetadata->isEmbeddedDocument) {
$id = $classMetadata->getIdentifierValue($this->object);
}
} else {
$id = $objectManager->getClassMetadata($this->class)->getIdentifierValues($this->object);
}
return empty($id) ? null : $objectManager->find($this->class, $id);
}
private function objectManager(): ObjectManager
{
if (!Factory::configuration()->isPersistEnabled()) {
throw new \RuntimeException('Should not get doctrine\'s object manager when persist is disabled.');
}
return Factory::configuration()->objectManagerFor($this->class);
}
private function _autoRefresh(): void
{
if (!$this->autoRefresh) {
return;
}
$this->_refresh();
}
}