Passed
Branch master (4a352c)
by Allan
04:38 queued 02:31
created

FilterUtils::isInvertedFilter()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * Copyright © Vaimo Group. All rights reserved.
4
 * See LICENSE_VAIMO.txt for license details.
5
 */
6
namespace Vaimo\ComposerPatches\Utils;
7
8
class FilterUtils
9
{
10
    const AFFIRMATION = 0;
11
    const NEGATION = 1;
12
    
13
    const NEGATION_PREFIX = '!';
14
15
    public function composeRegex(array $filters, $delimiter)
16
    {
17
        $semanticGroups = array_fill_keys(array(0, 1), array());
18
19
        $escapeChar = chr('27');
20
        $that = $this;
21
22
        array_map(function ($filter) use (&$semanticGroups, $delimiter, $escapeChar, $that) {
23
            $escapedFilter = trim(
24
                str_replace(
25
                    $escapeChar,
26
                    '.*',
27
                    preg_quote(
28
                        str_replace('*', $escapeChar, ltrim($filter, FilterUtils::NEGATION_PREFIX)),
29
                        $delimiter
30
                    )
31
                )
32
            );
33
34
            if (!$escapedFilter) {
35
                return;
36
            }
37
38
            $semanticGroups[(int)$that->isInvertedFilter($filter)][] = $escapedFilter;
39
        }, $filters);
40
41
        $pattern = '%s';
42
43
        if ($semanticGroups[self::NEGATION]) {
44
            $pattern = sprintf(
45
                '^((?!.*(%s)).*%s)',
46
                implode('|', $semanticGroups[self::NEGATION]),
47
                $semanticGroups[self::AFFIRMATION] ? '(%s)' : ''
48
            );
49
        }
50
51
        return $delimiter .
52
            sprintf($pattern, implode('|', $semanticGroups[self::AFFIRMATION])) .
53
            $delimiter;
54
    }
55
56
    public function invertRules(array $filters)
57
    {
58
        $that = $this;
59
        
60
        return array_map(function ($filter) use ($that) {
61
            return (!$that->isInvertedFilter($filter) ? FilterUtils::NEGATION_PREFIX : '') .
62
                ltrim($filter, FilterUtils::NEGATION_PREFIX);
63
        }, $filters);
64
    }
65
    
66
    public function isInvertedFilter($filter)
67
    {
68
        return strpos($filter, FilterUtils::NEGATION_PREFIX) === 0;
69
    }
70
71
    public function trimRules(array $filters)
72
    {
73
        return array_map(function ($filter) {
74
            return ltrim($filter, FilterUtils::NEGATION_PREFIX);
75
        }, $filters);
76
    }
77
}
78