FilterUtils::composeRegex()   A
last analyzed

Complexity

Conditions 4
Paths 2

Size

Total Lines 39
Code Lines 23

Duplication

Lines 0
Ratio 0 %

Importance

Changes 4
Bugs 1 Features 0
Metric Value
cc 4
eloc 23
c 4
b 1
f 0
nc 2
nop 2
dl 0
loc 39
rs 9.552
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
        $query = sprintf($pattern, implode('|', $semanticGroups[self::AFFIRMATION]));
52
53
        return $delimiter . $query . $delimiter;
54
    }
55
56
    public function invertRules(array $filters)
57
    {
58
        $that = $this;
59
60
        return array_map(
61
            function ($filter) use ($that) {
62
                return (!$that->isInvertedFilter($filter) ? FilterUtils::NEGATION_PREFIX : '') .
63
                    ltrim($filter, FilterUtils::NEGATION_PREFIX);
64
            },
65
            $filters
66
        );
67
    }
68
69
    public function isInvertedFilter($filter)
70
    {
71
        return strpos($filter, FilterUtils::NEGATION_PREFIX) === 0;
72
    }
73
74
    public function trimRules(array $filters)
75
    {
76
        return array_map(
77
            function ($filter) {
78
                return ltrim($filter, FilterUtils::NEGATION_PREFIX);
79
            },
80
            $filters
81
        );
82
    }
83
}
84