Completed
Push — master ( 898d30...0483c4 )
by Peter
21:25
created

MongoObjectId   A

Complexity

Total Complexity 12

Size/Duplication

Total Lines 49
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Test Coverage

Coverage 81.48%

Importance

Changes 3
Bugs 0 Features 0
Metric Value
wmc 12
c 3
b 0
f 0
lcom 1
cbo 0
dl 0
loc 49
ccs 22
cts 27
cp 0.8148
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A read() 0 4 1
A write() 0 4 1
D _cast() 0 28 10
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 http://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
27
	/**
28
	 * Whenever allow nulls
29
	 * @var bool
30
	 */
31
	public $nullable = false;
32
33 11
	public function read($model, $dbValue)
34
	{
35 11
		return $this->_cast($dbValue);
36
	}
37
38 71
	public function write($model, $phpValue)
39
	{
40 71
		return $this->_cast($phpValue);
41
	}
42
43 75
	protected function _cast($value, $string = false)
44
	{
45 75
		if (!$value instanceof MongoId)
46 75
		{
47 73
			if (is_array($value) && isset($value['$id']))
48 73
			{
49
				$value = $value['$id'];
50
			}
51 73
			if (is_object($value) && isset($value->{'$id'}))
52 73
			{
53
				$value = $value->{'$id'};
54
			}
55 73
			if (!preg_match('~^[a-z0-9]{24}$~', $value))
56 62
			{
57 60
				$value = null;
58 60
			}
59 62
			if ($this->nullable && empty($value))
60 62
			{
61
				return null;
62
			}
63 62
			$value = new MongoId($value);
64 62
		}
65
		if ($string)
66 71
		{
67 1
			return (string) $value;
68
		}
69 71
		return $value;
70
	}
71
72
}
73