1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Twitter\Serializer; |
4
|
|
|
|
5
|
|
|
use Twitter\Object\TwitterVariantMedia; |
6
|
|
|
use Twitter\TwitterSerializable; |
7
|
|
|
use Twitter\TwitterSerializer; |
8
|
|
|
|
9
|
|
|
class TwitterVariantMediaSerializer implements TwitterSerializer |
10
|
|
|
{ |
11
|
|
|
/** |
12
|
|
|
* @param TwitterSerializable $object |
13
|
|
|
* @return \stdClass |
14
|
|
|
*/ |
15
|
6 |
|
public function serialize(TwitterSerializable $object) |
16
|
|
|
{ |
17
|
6 |
|
if (!$this->canSerialize($object)) { |
18
|
3 |
|
throw new \InvalidArgumentException('$object must be an instance of TwitterVariantMedia'); |
19
|
|
|
} |
20
|
|
|
|
21
|
3 |
|
$variantMedia = new \stdClass(); |
22
|
3 |
|
$variantMedia->content_type = $object->getContentType(); |
|
|
|
|
23
|
3 |
|
$variantMedia->url = $object->getUrl(); |
|
|
|
|
24
|
3 |
|
$variantMedia->bitrate = $object->getBitrate(); |
|
|
|
|
25
|
|
|
|
26
|
3 |
|
return $variantMedia; |
27
|
|
|
} |
28
|
|
|
|
29
|
|
|
/** |
30
|
|
|
* @param \stdClass $obj |
31
|
|
|
* @param array $context |
32
|
|
|
* @return TwitterVariantMedia |
33
|
|
|
*/ |
34
|
3 |
|
public function unserialize($obj, array $context = []) |
35
|
|
|
{ |
36
|
3 |
|
if (!$this->canUnserialize($obj)) { |
37
|
|
|
throw new \InvalidArgumentException('$object is not unserializable'); |
38
|
|
|
} |
39
|
|
|
|
40
|
|
|
return TwitterVariantMedia::create($obj->content_type, $obj->url, $obj->bitrate?:null); |
41
|
|
|
} |
42
|
24 |
|
|
43
|
|
|
/** |
44
|
24 |
|
* @param TwitterSerializable $object |
45
|
|
|
* @return boolean |
46
|
|
|
*/ |
47
|
|
|
public function canSerialize(TwitterSerializable $object) |
48
|
|
|
{ |
49
|
|
|
return $object instanceof TwitterVariantMedia; |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
/** |
53
|
|
|
* @param \stdClass $object |
54
|
|
|
* @return boolean |
55
|
|
|
*/ |
56
|
|
|
public function canUnserialize($object) |
57
|
|
|
{ |
58
|
|
|
return isset($object->content_type) && isset($object->url) && isset($object->bitrate); |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
/** |
62
|
|
|
* @return TwitterVariantMediaSerializer |
63
|
|
|
*/ |
64
|
|
|
public static function build() |
65
|
|
|
{ |
66
|
|
|
return new self(); |
67
|
|
|
} |
68
|
|
|
} |
69
|
|
|
|
Let’s take a look at an example:
In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.
Available Fixes
Change the type-hint for the parameter:
Add an additional type-check:
Add the method to the interface: