1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Twitter\Serializer; |
4
|
|
|
|
5
|
|
|
use Twitter\Object\TwitterDisconnect; |
6
|
|
|
use Twitter\TwitterSerializable; |
7
|
|
|
use Twitter\TwitterSerializer; |
8
|
|
|
|
9
|
|
|
class TwitterDisconnectSerializer 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 TwitterDisconnect'); |
19
|
|
|
} |
20
|
|
|
|
21
|
3 |
|
$obj = new \stdClass(); |
22
|
3 |
|
$obj->code = $object->getCode(); |
|
|
|
|
23
|
3 |
|
$obj->stream_name = $object->getStreamName(); |
|
|
|
|
24
|
3 |
|
$obj->reason = $object->getReason(); |
|
|
|
|
25
|
|
|
|
26
|
3 |
|
$disconnect = new \stdClass(); |
27
|
3 |
|
$disconnect->disconnect = $obj; |
28
|
|
|
|
29
|
3 |
|
return $disconnect; |
30
|
|
|
} |
31
|
|
|
|
32
|
|
|
/** |
33
|
|
|
* @param \stdClass $obj |
34
|
|
|
* @param array $context |
35
|
|
|
* @return TwitterDisconnect |
36
|
|
|
*/ |
37
|
3 |
|
public function unserialize($obj, array $context = []) |
38
|
|
|
{ |
39
|
3 |
|
if (!$this->canUnserialize($obj)) { |
40
|
|
|
throw new \InvalidArgumentException('$object is not unserializable'); |
41
|
3 |
|
} |
42
|
3 |
|
|
43
|
3 |
|
$d = $obj->disconnect; |
44
|
3 |
|
|
45
|
2 |
|
return TwitterDisconnect::create( |
46
|
|
|
$d->code, |
47
|
|
|
$d->stream_name, |
48
|
|
|
$d->reason |
49
|
|
|
); |
50
|
|
|
} |
51
|
6 |
|
|
52
|
|
|
/** |
53
|
6 |
|
* @param TwitterSerializable $object |
54
|
|
|
* @return boolean |
55
|
|
|
*/ |
56
|
|
|
public function canSerialize(TwitterSerializable $object) |
57
|
|
|
{ |
58
|
|
|
return $object instanceof TwitterDisconnect; |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
/** |
62
|
|
|
* @param \stdClass $object |
63
|
|
|
* @return boolean |
64
|
|
|
*/ |
65
|
|
|
public function canUnserialize($object) |
66
|
|
|
{ |
67
|
|
|
return (isset($object->disconnect)); |
68
|
|
|
} |
69
|
|
|
|
70
|
|
|
/** |
71
|
|
|
* @return TwitterDisconnectSerializer |
72
|
|
|
*/ |
73
|
|
|
public static function build() |
74
|
|
|
{ |
75
|
|
|
return new self(); |
76
|
|
|
} |
77
|
|
|
} |
78
|
|
|
|
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: