1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace CultuurNet\UDB3\Offer\Commands; |
4
|
|
|
|
5
|
|
|
use CultuurNet\Deserializer\DeserializerInterface; |
6
|
|
|
use CultuurNet\Deserializer\JSONDeserializer; |
7
|
|
|
use CultuurNet\Deserializer\MissingValueException; |
8
|
|
|
use CultuurNet\Deserializer\NotWellFormedException; |
9
|
|
|
use CultuurNet\UDB3\Label; |
10
|
|
|
use CultuurNet\UDB3\Offer\OfferIdentifierCollection; |
11
|
|
|
use ValueObjects\String\String; |
12
|
|
|
|
13
|
|
|
class AddLabelToMultipleJSONDeserializer extends JSONDeserializer |
14
|
|
|
{ |
15
|
|
|
/** |
16
|
|
|
* @var DeserializerInterface |
17
|
|
|
*/ |
18
|
|
|
private $offerIdentifierDeserializer; |
19
|
|
|
|
20
|
|
|
/** |
21
|
|
|
* @param DeserializerInterface $offerIdentifierDeserializer |
22
|
|
|
*/ |
23
|
|
|
public function __construct(DeserializerInterface $offerIdentifierDeserializer) |
24
|
|
|
{ |
25
|
|
|
$this->offerIdentifierDeserializer = $offerIdentifierDeserializer; |
26
|
|
|
} |
27
|
|
|
|
28
|
|
|
/** |
29
|
|
|
* @param \ValueObjects\String\String $data |
30
|
|
|
* |
31
|
|
|
* @return AddLabelToMultiple |
32
|
|
|
* |
33
|
|
|
* @throws NotWellFormedException |
34
|
|
|
*/ |
35
|
|
|
public function deserialize(String $data) |
36
|
|
|
{ |
37
|
|
|
$data = parent::deserialize($data); |
38
|
|
|
|
39
|
|
|
if (empty($data->label)) { |
40
|
|
|
throw new MissingValueException('Missing value "label".'); |
41
|
|
|
} |
42
|
|
|
if (empty($data->offers)) { |
43
|
|
|
throw new MissingValueException('Missing value "offers".'); |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
$label = new Label($data->label); |
47
|
|
|
$offers = new OfferIdentifierCollection(); |
48
|
|
|
|
49
|
|
|
foreach ($data->offers as $offer) { |
50
|
|
|
$offers = $offers->with( |
51
|
|
|
$this->offerIdentifierDeserializer->deserialize( |
52
|
|
|
new String( |
53
|
|
|
json_encode($offer) |
54
|
|
|
) |
55
|
|
|
) |
56
|
|
|
); |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
return new AddLabelToMultiple($offers, $label); |
|
|
|
|
60
|
|
|
} |
61
|
|
|
} |
62
|
|
|
|
If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.
Let’s take a look at an example:
Our function
my_function
expects aPost
object, and outputs the author of the post. The base classPost
returns a simple string and outputting a simple string will work just fine. However, the child classBlogPost
which is a sub-type ofPost
instead decided to return anobject
, and is therefore violating the SOLID principles. If aBlogPost
were passed tomy_function
, PHP would not complain, but ultimately fail when executing thestrtoupper
call in its body.