owowagency /
laravel-media
| 1 | <?php |
||
| 2 | |||
| 3 | namespace Owowagency\LaravelMedia\Rules; |
||
| 4 | |||
| 5 | use Illuminate\Support\Arr; |
||
| 6 | use Illuminate\Contracts\Validation\Rule; |
||
| 7 | use Owowagency\LaravelMedia\Rules\Concerns\ValidatesBase64; |
||
| 8 | |||
| 9 | class IsBase64 implements Rule |
||
| 10 | { |
||
| 11 | use ValidatesBase64; |
||
| 12 | |||
| 13 | /** |
||
| 14 | * Determine if the validation rule passes. |
||
| 15 | * |
||
| 16 | * @param string $attribute |
||
| 17 | * @param mixed $value |
||
| 18 | * @return bool |
||
| 19 | */ |
||
| 20 | public function passes($attribute, $value) |
||
| 21 | { |
||
| 22 | $values = Arr::wrap($value); |
||
| 23 | |||
| 24 | foreach ($values as $value) { |
||
|
0 ignored issues
–
show
introduced
by
Loading history...
|
|||
| 25 | if (! $this->isBase64($value)) { |
||
| 26 | return false; |
||
| 27 | } |
||
| 28 | } |
||
| 29 | |||
| 30 | // All base64 strings are valid. Now we only need to verify if there |
||
| 31 | // where any base64 strings at all. |
||
| 32 | return count($values) > 0; |
||
| 33 | } |
||
| 34 | |||
| 35 | /** |
||
| 36 | * Determine if the given value is base64 encoded. |
||
| 37 | * |
||
| 38 | * @param mixed $value |
||
| 39 | * @return bool |
||
| 40 | */ |
||
| 41 | protected function isBase64($value): bool |
||
| 42 | { |
||
| 43 | if (! is_string($value)) { |
||
| 44 | return false; |
||
| 45 | } |
||
| 46 | |||
| 47 | // Remove data uri scheme |
||
| 48 | $value = $this->removeScheme($value); |
||
| 49 | |||
| 50 | // Check if can be decoded and encoded again. |
||
| 51 | if (base64_decode($value, true) === false |
||
| 52 | || base64_encode(base64_decode($value)) !== $value |
||
| 53 | ) { |
||
| 54 | return false; |
||
| 55 | } |
||
| 56 | |||
| 57 | return true; |
||
| 58 | } |
||
| 59 | |||
| 60 | /** |
||
| 61 | * Get the validation error message. |
||
| 62 | * |
||
| 63 | * @return string |
||
| 64 | */ |
||
| 65 | public function message(): string |
||
| 66 | { |
||
| 67 | return trans('validation.custom.is_base_64'); |
||
|
0 ignored issues
–
show
|
|||
| 68 | } |
||
| 69 | } |
||
| 70 |