1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Stratadox\Proxy; |
6
|
|
|
|
7
|
|
|
use Closure; |
8
|
|
|
use Stratadox\Collection\Alterable; |
9
|
|
|
|
10
|
|
|
/** |
11
|
|
|
* Updates a collection to include the newly loaded value. |
12
|
|
|
* |
13
|
|
|
* @package Stratadox\Hydrate |
14
|
|
|
* @author Stratadox |
15
|
|
|
*/ |
16
|
|
|
final class AlterableCollectionEntryUpdater implements UpdatesTheProxyOwner |
17
|
|
|
{ |
18
|
|
|
private $owner; |
19
|
|
|
private $propertyShouldReference; |
20
|
|
|
private $atPosition; |
21
|
|
|
private $setter; |
22
|
|
|
|
23
|
|
|
public function __construct( |
24
|
|
|
$theOwner, |
25
|
|
|
string $theProperty, |
26
|
|
|
$atPosition, |
27
|
|
|
Closure $setter = null |
28
|
|
|
) { |
29
|
|
|
$this->owner = $theOwner; |
30
|
|
|
$this->propertyShouldReference = $theProperty; |
31
|
|
|
$this->atPosition = $atPosition; |
32
|
|
|
$this->setter = $setter ?: function (string $property, $value, $position): void |
33
|
|
|
{ |
34
|
|
|
$original = $this->$property; |
35
|
|
|
if (!$original instanceof Alterable) { |
36
|
|
|
throw UnexpectedPropertyType::expectedThe(Alterable::class, |
37
|
|
|
$this, $original, $property |
38
|
|
|
); |
39
|
|
|
} |
40
|
|
|
$this->$property = $original->change($position, $value); |
41
|
|
|
}; |
42
|
|
|
} |
43
|
|
|
|
44
|
|
|
public static function forThe($owner, |
45
|
|
|
string $ofTheProperty, |
46
|
|
|
$atPosition, |
47
|
|
|
Closure $setter = null |
48
|
|
|
): UpdatesTheProxyOwner { |
49
|
|
|
return new static($owner, $ofTheProperty, $atPosition, $setter); |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
public function updateWith($theLoadedInstance): void |
53
|
|
|
{ |
54
|
|
|
$this->setter->call($this->owner, |
55
|
|
|
$this->propertyShouldReference, $theLoadedInstance, |
56
|
|
|
$this->atPosition |
57
|
|
|
); |
58
|
|
|
} |
59
|
|
|
} |
60
|
|
|
|