|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace DCP\Mapper\Collections\Maps; |
|
4
|
|
|
|
|
5
|
|
|
use DCP\Mapper\Collection; |
|
6
|
|
|
use DCP\Mapper\Exception\InvalidArgumentException; |
|
7
|
|
|
use DCP\Mapper\Exception\OutOfBoundsException; |
|
8
|
|
|
|
|
9
|
|
|
abstract class CollectionMap extends Map implements CollectionMapInterface |
|
10
|
|
|
{ |
|
11
|
|
|
public function get($key, $default = true, $callback = null) |
|
12
|
|
|
{ |
|
13
|
|
|
if ($default) { |
|
14
|
|
|
return $this->getWithCallback($key, $callback); |
|
15
|
|
|
} |
|
16
|
|
|
|
|
17
|
|
|
return $this->getWithCallback($key, null); |
|
18
|
|
|
} |
|
19
|
|
|
|
|
20
|
|
|
public function add($key, $value, callable $defaultCollectionCallback = null) |
|
21
|
|
|
{ |
|
22
|
|
|
$collection = self::get($key, false); |
|
23
|
|
|
|
|
24
|
|
|
if (!$collection) { |
|
25
|
|
|
/** @var Collection $collection */ |
|
26
|
|
|
$collection = call_user_func($defaultCollectionCallback); |
|
27
|
|
|
$this->set($key, $collection); |
|
28
|
|
|
} |
|
29
|
|
|
|
|
30
|
|
|
$collection->add($value); |
|
31
|
|
|
|
|
32
|
|
|
return $this; |
|
33
|
|
|
} |
|
34
|
|
|
|
|
35
|
|
|
protected function getWithCallback($key, callable $defaultCallback = null) |
|
36
|
|
|
{ |
|
37
|
|
|
$collection = null; |
|
38
|
|
|
|
|
39
|
|
|
try { |
|
40
|
|
|
$collection = parent::get($key); |
|
|
|
|
|
|
41
|
|
|
} catch (OutOfBoundsException $exception) { |
|
42
|
|
|
if ($defaultCallback) { |
|
43
|
|
|
$collection = call_user_func($defaultCallback); |
|
44
|
|
|
} |
|
45
|
|
|
} |
|
46
|
|
|
|
|
47
|
|
|
return $collection; |
|
48
|
|
|
} |
|
49
|
|
|
|
|
50
|
|
|
protected function addWithTypeCheck($key, $value, $type, callable $callback = null) |
|
51
|
|
|
{ |
|
52
|
|
|
if (!(is_object($value) && is_subclass_of($value, $type))) { |
|
|
|
|
|
|
53
|
|
|
throw new InvalidArgumentException(sprintf('$value must be an instance of %s', $type)); |
|
54
|
|
|
} |
|
55
|
|
|
|
|
56
|
|
|
return self::add($key, $value, $callback); |
|
57
|
|
|
} |
|
58
|
|
|
} |
|
59
|
|
|
|
This check looks for a call to a parent method whose name is different than the method from which it is called.
Consider the following code:
The
getFirstName()method in theSoncalls the wrong method in the parent class.