1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/** |
4
|
|
|
* This file is part of sensorario/resources repository |
5
|
|
|
* |
6
|
|
|
* (c) Simone Gentili <[email protected]> |
7
|
|
|
* |
8
|
|
|
* For the full copyright and license information, please view the LICENSE |
9
|
|
|
* file that was distributed with this source code. |
10
|
|
|
*/ |
11
|
|
|
|
12
|
|
|
namespace Sensorario\Resources\Validators\Validators; |
13
|
|
|
|
14
|
|
|
use RuntimeException; |
15
|
|
|
use Sensorario\Resources\Resource; |
16
|
|
|
use Sensorario\Resources\Validators\Interfaces\Validator; |
17
|
|
|
|
18
|
|
|
final class MandatoryConditional implements Validator |
19
|
|
|
{ |
20
|
|
|
public static function check(Resource $resource) |
21
|
|
|
{ |
22
|
|
|
foreach ($resource->mandatory() as $key => $value) { |
23
|
|
|
if (isset($value['when']['has_value'])) { |
24
|
|
|
$name = $value['when']['property']; |
25
|
|
|
$value = $value['when']['has_value']; |
26
|
|
|
|
27
|
|
View Code Duplication |
if (is_array($value)) { |
|
|
|
|
28
|
|
|
foreach ($value as $value) { |
29
|
|
|
if ($resource->get($name) === $value && $resource->hasNotProperty($key)) { |
30
|
|
|
static::buildException($value, $key); |
|
|
|
|
31
|
|
|
} |
32
|
|
|
} |
33
|
|
|
} |
34
|
|
|
|
35
|
|
View Code Duplication |
if (!is_array($value)) { |
|
|
|
|
36
|
|
|
if ($resource->get($name) === $value && $resource->hasNotProperty($key)) { |
37
|
|
|
static::exceptionMessage($name, $value, $key); |
|
|
|
|
38
|
|
|
} |
39
|
|
|
} |
40
|
|
|
} |
41
|
|
|
} |
42
|
|
|
} |
43
|
|
|
|
44
|
|
|
private static function buildException($value, $key) |
45
|
|
|
{ |
46
|
|
|
static::exceptionMessage($key, $value, $key); |
|
|
|
|
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
private static function exceptionMessage($name, $value, $key) |
50
|
|
|
{ |
51
|
|
|
throw new RuntimeException( |
52
|
|
|
'When property `' . $name . '` ' |
53
|
|
|
. 'has value ' . '`' . $value . '` ' |
54
|
|
|
. 'also `' . $key . '` is mandatory' |
55
|
|
|
); |
56
|
|
|
} |
57
|
|
|
} |
58
|
|
|
|
Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.
You can also find more detailed suggestions in the “Code” section of your repository.