1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/* |
4
|
|
|
* This file is part of the Runalyze BSON. |
5
|
|
|
* (c) RUNALYZE <[email protected]> |
6
|
|
|
* This source file is subject to the MIT license that is bundled |
7
|
|
|
* with this source code in the file LICENSE. |
8
|
|
|
*/ |
9
|
|
|
|
10
|
|
|
namespace Runalyze\BSON\BsonSerializable; |
11
|
|
|
|
12
|
|
|
use MongoDB\BSON\ObjectID; |
13
|
|
|
|
14
|
|
|
abstract class AbstractBsonSerializableObject implements BsonSerializableInterface |
15
|
|
|
{ |
16
|
|
|
/** @var ObjectID */ |
17
|
|
|
protected $BSONObjectId; |
18
|
|
|
|
19
|
|
|
/** @var string|null */ |
20
|
|
|
protected $Hash; |
21
|
|
|
|
22
|
|
|
/** @var bool */ |
23
|
|
|
protected $IsDirty = false; |
24
|
|
|
|
25
|
3 |
|
public function __construct() |
26
|
|
|
{ |
27
|
3 |
|
$this->BSONObjectId = new ObjectID(); |
28
|
3 |
|
} |
29
|
|
|
|
30
|
1 |
|
public function setHash($hash) |
31
|
|
|
{ |
32
|
1 |
|
$this->Hash = $hash; |
33
|
1 |
|
} |
34
|
|
|
|
35
|
1 |
|
public function getHash() |
36
|
|
|
{ |
37
|
1 |
|
return $this->Hash; |
38
|
|
|
} |
39
|
|
|
|
40
|
1 |
|
public function isDirty() |
41
|
|
|
{ |
42
|
1 |
|
return $this->IsDirty; |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
protected function setDirty() |
46
|
|
|
{ |
47
|
|
|
$this->IsDirty = true; |
48
|
|
|
} |
49
|
|
|
|
50
|
2 |
|
public function bsonSerialize() |
51
|
|
|
{ |
52
|
2 |
|
$data = ['_id' => $this->BSONObjectId]; |
53
|
|
|
|
54
|
2 |
|
foreach ($this->getSerializableProperties() as $property) { |
55
|
2 |
|
$data[$property] = $this->{$property}; |
56
|
|
|
} |
57
|
|
|
|
58
|
2 |
|
return $data; |
59
|
|
|
} |
60
|
|
|
|
61
|
2 |
|
public function bsonUnserialize(array $data) |
62
|
|
|
{ |
63
|
2 |
|
$this->IsDirty = false; |
64
|
2 |
|
$this->BSONObjectId = isset($data['_id']) ? $data['_id'] : new ObjectID(); |
65
|
|
|
|
66
|
2 |
|
foreach ($this->getSerializableProperties() as $property) { |
67
|
2 |
|
if (isset($data[$property])) { |
68
|
2 |
|
$this->{$property} = $data[$property]; |
69
|
|
|
} |
70
|
|
|
} |
71
|
2 |
|
} |
72
|
|
|
|
73
|
2 |
|
public function toBinary() |
74
|
|
|
{ |
75
|
2 |
|
return \MongoDB\BSON\fromPHP($this->bsonSerialize()); |
76
|
|
|
} |
77
|
|
|
|
78
|
1 |
|
public function fromBinary($string) |
79
|
|
|
{ |
80
|
1 |
|
return \MongoDB\BSON\toPHP($string, [ |
81
|
1 |
|
'root' => get_class($this), |
82
|
|
|
]); |
83
|
|
|
} |
84
|
|
|
|
85
|
|
|
/** |
86
|
|
|
* @return array |
87
|
|
|
*/ |
88
|
|
|
abstract protected function getSerializableProperties(); |
89
|
|
|
} |
90
|
|
|
|