Passed
Push — master ( 88bdea...e6d71f )
by Hrvoje
10:43
created

GeoJsonRule::message()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 9
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 6
c 0
b 0
f 0
nc 3
nop 0
dl 0
loc 9
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yuca\LaravelGeoJsonRule;
6
7
use GeoJson\GeoJson;
8
use GeoJson\Geometry\Polygon;
9
use Illuminate\Contracts\Validation\Rule;
10
use Throwable;
11
12
/**
13
 * RFC 7946 GeoJSON Format specification.
14
 */
15
class GeoJsonRule implements Rule
16
{
17
    /** @var string */
18
    private $geometryClass;
19
    /** @var Throwable */
20
    private $exception;
21
22
    /**
23
     * Constructor.
24
     * @param string|null $geometryClass Expected geometry.
25
     */
26
    public function __construct(?string $geometryClass = null)
27
    {
28
        $this->geometryClass = $geometryClass;
29
    }
30
31
    /**
32
     * Determine if the validation rule passes.
33
     *
34
     * @param string $attribute
35
     * @param mixed $value
36
     * @return bool
37
     */
38
    public function passes($attribute, $value)
39
    {
40
        try {
41
            $value = json_decode($value);
42
            // An exception will be thrown if parsing fails
43
            $geometry = GeoJson::jsonUnserialize($value);
44
        } catch (Throwable $t) {
45
            $this->exception = $t;
46
            return false;
47
        }
48
        // Check geometry type if specified
49
        if (!empty($this->geometryClass)) {
50
            return get_class($geometry) === $this->geometryClass;
51
        }
52
        return true;
53
    }
54
55
    /**
56
     * Get the validation error message.
57
     *
58
     * @return string|array
59
     */
60
    public function message()
61
    {
62
        $message = 'The :attribute does not satisfy the RFC 7946 GeoJSON Format specification';
63
        if (!empty($this->exception)) {
64
            $message .= ' because ' . $this->exception->getMessage();
65
        } elseif (!empty($this->geometryClass)) {
66
            $message .= ' for ' . basename(str_replace('\\', '/', $this->geometryClass));
67
        }
68
        return $message;
69
    }
70
}
71