summaryrefslogtreecommitdiff
path: root/app/Rugby/Concerns/Matchable.php
blob: b0c512c072754daf42724c8405e76d4ad95d9890 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
<?php

namespace App\Rugby\Concerns;

trait Matchable
{
    public function matchableFilters()
    {

    }

    public function isMatch(string $search): bool
    {
        $filters = $this->matchableFilters();

        if (is_array($filters)) {
            $filters = collect($filters);
        }

        foreach ($filters as $filter) {
            $match = $this->matchArray($filter[1], explode(' ', $search), $filter[0]);

            if (!$match) {
                return false;
            }
        }

        return true;
    }

    public function matchString(string $needle, string $type, string $hay): bool
    {
        if ($type == 'date') {
            if (!$this->isDate($needle)) {
                dd('Matchable `' . $hay .  '` is not a date');
            };

            if (!$this->isDate($hay)) {
                return false;
            };

            return $this->getYear($hay) == $this->getYear($needle);
        }

        return $hay == $needle;
    }

    public function matchArray(string $needle, array $haystack, string $type): bool
    {
        foreach ($haystack as $hay) {
            $result = $this->matchString($needle, $type, $hay);

            if ($result) {
                return true;
            }
        }

        return false;
    }

    public function isDate(string $value): bool
    {
        $patterns = [
            "/\d{2}\-\d{2}\-\d{4}/",
            "/\d{2}\_\d{2}\_\d{4}/",
            "/\d{2}\/\d{2}\/\d{4}/",
            "/\d{4}/",
        ];

        foreach ($patterns as $pattern) {
            if (preg_match($pattern, $value, $matches)) {
                return true;
            }
        }

        return false;
    }

    public function getYear(string $value): string
    {
        $patterns = [
            "/\d{4}/"
        ];

        foreach ($patterns as $pattern) {
            if (preg_match($pattern, $value, $matches)) {
                return $matches[0];
            }
        }

        return false;
    }
}