Completed
Push — master ( a9602e...8f132d )
by Hong
02:45
created

GlobbingTrait::nameGlobbing()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 13
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 13
rs 9.2
cc 4
eloc 10
nc 3
nop 2
1
<?php
2
/**
3
 * Phossa Project
4
 *
5
 * PHP version 5.4
6
 *
7
 * @category  Library
8
 * @package   Phossa2\Shared
9
 * @copyright Copyright (c) 2016 phossa.com
10
 * @license   http://mit-license.org/ MIT License
11
 * @link      http://www.phossa.com/
12
 */
13
/*# declare(strict_types=1); */
14
15
namespace Phossa2\Shared\Globbing;
16
17
/**
18
 * GlobbingTrait
19
 *
20
 * Matches exact name like 'user.login' with 'user.*', 'u*.*' etc.
21
 *
22
 * @package Phossa2\Shared
23
 * @author  Hong Zhang <[email protected]>
24
 * @version 2.0.20
25
 * @since   2.0.20 added
26
 */
27
trait GlobbingTrait
28
{
29
    /**
30
     * Returns all names matches with $exactName
31
     *
32
     * e.g.
33
     * 'user.login' matches '*', 'u*.*', 'user.*', 'user.l*', 'user.login' etc.
34
     *
35
     * @param  string $exactName
36
     * @param  array $names
37
     * @return array
38
     * @access protected
39
     */
40
    protected function globbingNames(
41
        /*# string */ $exactName,
42
        array $names
43
    )/*# : array */ {
44
        $result = [];
45
        foreach ($names as $name) {
46
            if ($this->nameGlobbing($exactName, $name)) {
47
                $result[] = $name;
48
            }
49
        }
50
        return $result;
51
    }
52
53
    /**
54
     * Check to see if $name matches with $exactName
55
     *
56
     *  e.g.
57
     *  ```php
58
     *  // true
59
     *  $this->nameGlobbing('user.*', 'user.login');
60
     *
61
     *  // true
62
     *  $this->nameGlobbing('*', 'user.login');
63
     *
64
     *  // false
65
     *  $this->nameGLobbing('blog.*', 'user.login');
66
     *  ```
67
     *
68
     * @param  string $exactName
69
     * @param  string $name
70
     * @return bool
71
     * @access protected
72
     */
73
    protected function nameGlobbing(
74
        /*# string */ $exactName,
75
        /*# string */ $name
76
    )/*# : bool */ {
77
        if ('*' === $name || $name === $exactName) {
78
            return true;
79
        } elseif (false !== strpos($name, '*')) {
80
            $pat = str_replace(array('.', '*'), array('[.]', '[^.]*+'), $name);
81
            return (bool) preg_match('~^' . $pat . '$~', $exactName);
82
        } else {
83
            return false;
84
        }
85
    }
86
}
87