MongoObjectId::_cast()   C
last analyzed

Complexity

Conditions 13
Paths 27

Size

Total Lines 33

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 15
CRAP Score 13.0412

Importance

Changes 0
Metric Value
dl 0
loc 33
ccs 15
cts 16
cp 0.9375
rs 6.6166
c 0
b 0
f 0
cc 13
nc 27
nop 2
crap 13.0412

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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