Passed
Push — master ( f533bd...3986a9 )
by Ron
02:38
created

DBOptionalValue::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 3
c 1
b 0
f 0
dl 0
loc 4
rs 10
cc 1
nc 1
nop 3
1
<?php
2
3
namespace Kir\MySQL\Builder\Value;
4
5
use Kir\MySQL\Builder\Helpers\RecursiveStructureAccess;
6
7
class DBOptionalValue implements OptionalValue {
8
	/** @var object|array<string, mixed> */
9
	private $data;
10
	/** @var string|string[] */
11
	private $path;
12
	/** @var callable|null */
13
	private $validator;
14
15
	/**
16
	 * @param object|array<string, mixed> $data
17
	 * @param string|string[] $path
18
	 * @param null|callable(): bool $validator
19
	 */
20
	public function __construct($data, $path, $validator = null) {
21
		$this->data = $data;
22
		$this->path = $path;
23
		$this->validator = $validator;
24
	}
25
26
	/**
27
	 * @return bool
28
	 */
29
	public function isValid(): bool {
30
		if(!RecursiveStructureAccess::recursiveHas($this->data, $this->path)) {
31
			return false;
32
		}
33
		if($this->validator !== null) {
34
			$value = $this->getValue();
35
			return call_user_func($this->validator, $value);
36
		}
37
		return true;
38
	}
39
40
	/**
41
	 * @return mixed|null
42
	 */
43
	public function getValue() {
44
		return RecursiveStructureAccess::recursiveGet($this->data, $this->path, null);
45
	}
46
}
47