1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/** |
4
|
|
|
* This software package is licensed under AGPL or Commercial license. |
5
|
|
|
* |
6
|
|
|
* @package maslosoft/mangan |
7
|
|
|
* @licence AGPL or Commercial |
8
|
|
|
* @copyright Copyright (c) Piotr Masełkowski <[email protected]> |
9
|
|
|
* @copyright Copyright (c) Maslosoft |
10
|
|
|
* @copyright Copyright (c) Others as mentioned in code |
11
|
|
|
* @link https://maslosoft.com/mangan/ |
12
|
|
|
*/ |
13
|
|
|
|
14
|
|
|
namespace Maslosoft\Mangan\Sanitizers; |
15
|
|
|
|
16
|
|
|
use Maslosoft\Mangan\Interfaces\Sanitizers\Property\SanitizerInterface; |
17
|
|
|
use MongoId; |
18
|
|
|
|
19
|
|
|
/** |
20
|
|
|
* MongoObjectId |
21
|
|
|
* This sanitizer forces MongoId type for both client and mongo |
22
|
|
|
* @author Piotr Maselkowski <pmaselkowski at gmail.com> |
23
|
|
|
*/ |
24
|
|
|
class MongoObjectId implements SanitizerInterface |
25
|
|
|
{ |
26
|
|
|
const IdPattern = '~^[a-f0-9]{24}$~'; |
27
|
|
|
|
28
|
|
|
/** |
29
|
|
|
* Whenever allow nulls |
30
|
|
|
* @var bool |
31
|
|
|
*/ |
32
|
|
|
public $nullable = false; |
33
|
|
|
|
34
|
145 |
|
public function read($model, $dbValue) |
35
|
|
|
{ |
36
|
145 |
|
return $this->_cast($dbValue); |
37
|
|
|
} |
38
|
|
|
|
39
|
125 |
|
public function write($model, $phpValue) |
40
|
|
|
{ |
41
|
125 |
|
return $this->_cast($phpValue); |
42
|
|
|
} |
43
|
|
|
|
44
|
147 |
|
protected function _cast($value, $string = false) |
45
|
|
|
{ |
46
|
147 |
|
if($string && is_string($value) && preg_match(self::IdPattern, $value)) |
47
|
|
|
{ |
48
|
6 |
|
return $value; |
49
|
|
|
} |
50
|
147 |
|
if (!$value instanceof MongoId) |
51
|
|
|
{ |
52
|
77 |
|
if (is_array($value) && isset($value['$id'])) |
53
|
|
|
{ |
54
|
|
|
$value = $value['$id']; |
55
|
|
|
} |
56
|
77 |
|
if (is_object($value) && isset($value->{'$id'})) |
57
|
|
|
{ |
58
|
2 |
|
$value = $value->{'$id'}; |
59
|
|
|
} |
60
|
|
|
|
61
|
77 |
|
if (!preg_match(self::IdPattern, (string) $value)) |
62
|
|
|
{ |
63
|
62 |
|
$value = null; |
64
|
|
|
} |
65
|
77 |
|
if ($this->nullable && empty($value)) |
66
|
|
|
{ |
67
|
3 |
|
return null; |
68
|
|
|
} |
69
|
77 |
|
$value = new MongoId($value); |
70
|
|
|
} |
71
|
147 |
|
if ($string) |
72
|
|
|
{ |
73
|
19 |
|
return (string) $value; |
74
|
|
|
} |
75
|
146 |
|
return $value; |
76
|
|
|
} |
77
|
|
|
|
78
|
|
|
} |
79
|
|
|
|