Completed
Push — master ( 862be6...6b5941 )
by Nikola
50:19 queued 47:05
created

FilterUtilHelper::matchesArrayCriteria()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 16
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 16
rs 9.4285
cc 3
eloc 8
nc 3
nop 3
1
<?php
2
/*
3
 * This file is part of the Exchange Rate package, an RunOpenCode project.
4
 *
5
 * (c) 2016 RunOpenCode
6
 *
7
 * For the full copyright and license information, please view the LICENSE
8
 * file that was distributed with this source code.
9
 */
10
namespace RunOpenCode\ExchangeRate\Utils;
11
12
/**
13
 * Class BaseFilterUtil
14
 *
15
 * Common shared functions for filter utilities.
16
 *
17
 * @package RunOpenCode\ExchangeRate\Utils
18
 */
19
trait FilterUtilHelper
20
{
21
    /**
22
     * Extract array criteria from criterias.
23
     *
24
     * @param string $key Criteria name.
25
     * @param array $criteria Filter criterias.
26
     * @return array Extracted array criterias.
27
     */
28
    private static function extractArrayCriteria($key, array $criteria)
29
    {
30
        if (!empty($criteria[$key])) {
31
            return array($criteria[$key]);
32
        } elseif (!empty($criteria[$key . 's'])) {
33
            return $criteria[$key . 's'];
34
        }
35
36
        return array();
37
    }
38
39
    /**
40
     * Extract date from filter criterias.
41
     *
42
     * @param string $key Criteria name.
43
     * @param array $criteria Filter criterias.
44
     * @return \DateTime|null Extracted date criteria.
45
     */
46
    private static function extractDateCriteria($key, array $criteria)
47
    {
48
        return (!empty($criteria[$key])) ? $criteria[$key] : null;
49
    }
50
51
    /**
52
     * Check if array|string criteria is matched.
53
     *
54
     * @param string $key Array|string criteria key.
55
     * @param mixed $object Object to check for match.
56
     * @param array $criteria Filter criterias.
57
     * @return bool TRUE if there is a match.
58
     */
59
    private static function matchesArrayCriteria($key, $object, array $criteria)
60
    {
61
        $criteria = self::extractArrayCriteria($key, $criteria);
62
63
        if (count($criteria) === 0) {
64
            return true;
65
        }
66
67
        $getter = sprintf('get%s', ucfirst($key));
68
69
        if (!method_exists($object, $getter)) {
70
            throw new \RuntimeException(sprintf('Object instance of "%s" does not have required getter "%s" to be used for filtering.', get_class($object), $getter));
71
        }
72
73
        return in_array($object->{$getter}(), $criteria, true);
74
    }
75
}
76
77