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