1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace ProtoneMedia\LaravelMixins\Rules; |
4
|
|
|
|
5
|
|
|
use Illuminate\Contracts\Validation\Rule; |
6
|
|
|
use Illuminate\Support\Collection; |
7
|
|
|
use Illuminate\Validation\Concerns\ValidatesAttributes; |
8
|
|
|
use Illuminate\Validation\Rules\Dimensions as RulesDimensions; |
9
|
|
|
|
10
|
|
|
class DimensionsWithMargin extends RulesDimensions implements Rule |
11
|
|
|
{ |
12
|
|
|
use ValidatesAttributes { |
|
|
|
|
13
|
|
|
failsRatioCheck as failsRatioCheckTrait; |
14
|
|
|
} |
15
|
|
|
|
16
|
|
|
/** |
17
|
|
|
* Helper method to initialize the rule. |
18
|
|
|
* |
19
|
|
|
* @param array $constraints |
20
|
|
|
* @return self |
21
|
|
|
*/ |
22
|
|
|
public static function make(array $constraints = []): self |
23
|
|
|
{ |
24
|
|
|
return new static($constraints); |
25
|
|
|
} |
26
|
|
|
|
27
|
|
|
/** |
28
|
|
|
* Set the "margin" constraint. |
29
|
|
|
* |
30
|
|
|
* @param integer $margin |
31
|
|
|
* @return void |
32
|
|
|
*/ |
33
|
|
|
public function margin(int $margin) |
34
|
|
|
{ |
35
|
|
|
if ($margin > 0) { |
36
|
|
|
$this->constraints['margin'] = $margin; |
37
|
|
|
} |
38
|
|
|
|
39
|
|
|
return $this; |
40
|
|
|
} |
41
|
|
|
|
42
|
|
|
/** |
43
|
|
|
* Determine if the validation rule passes. |
44
|
|
|
* |
45
|
|
|
* @param string $attribute |
46
|
|
|
* @param mixed $value |
47
|
|
|
* @return bool |
48
|
|
|
*/ |
49
|
|
|
public function passes($attribute, $value) |
50
|
|
|
{ |
51
|
|
|
$parameters = Collection::make($this->constraints)->map(function ($value, $key) { |
52
|
|
|
return "{$key}={$value}"; |
53
|
|
|
})->all(); |
54
|
|
|
|
55
|
|
|
return $this->validateDimensions($attribute, $value, $parameters); |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
/** |
59
|
|
|
* It checks for every margin if the underlying rule doesn't fails. |
60
|
|
|
* |
61
|
|
|
* @param array $parameters |
62
|
|
|
* @param int $width |
63
|
|
|
* @param int $height |
64
|
|
|
* @return bool |
65
|
|
|
*/ |
66
|
|
|
protected function failsRatioCheck($parameters, $width, $height) |
67
|
|
|
{ |
68
|
|
|
if (!isset($parameters['ratio']) || !isset($parameters['margin'])) { |
69
|
|
|
return $this->failsRatioCheckTrait($parameters, $width, $height); |
70
|
|
|
} |
71
|
|
|
|
72
|
|
|
$range = range($parameters['margin'] * -1, $parameters['margin']); |
73
|
|
|
|
74
|
|
|
foreach ($range as $margin) { |
75
|
|
|
if (!$this->failsRatioCheckTrait($parameters, $width + $margin, $height)) { |
76
|
|
|
return false; |
77
|
|
|
} |
78
|
|
|
|
79
|
|
|
if (!$this->failsRatioCheckTrait($parameters, $width, $height + $margin)) { |
80
|
|
|
return false; |
81
|
|
|
} |
82
|
|
|
} |
83
|
|
|
|
84
|
|
|
return true; |
85
|
|
|
} |
86
|
|
|
|
87
|
|
|
/** |
88
|
|
|
* Get the validation error message. |
89
|
|
|
* |
90
|
|
|
* @return string |
91
|
|
|
*/ |
92
|
|
|
public function message() |
93
|
|
|
{ |
94
|
|
|
return __('validation.dimensions'); |
95
|
|
|
} |
96
|
|
|
} |
97
|
|
|
|