Completed
Push — master ( 35dbd5...1712eb )
by Vladimir
02:34
created

FileExplorer::strpos_array()   C

Complexity

Conditions 7
Paths 8

Size

Total Lines 22
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 8.1426

Importance

Changes 0
Metric Value
cc 7
eloc 9
nc 8
nop 3
dl 0
loc 22
rs 6.9811
c 0
b 0
f 0
ccs 10
cts 14
cp 0.7143
crap 8.1426
1
<?php
2
3
/**
4
 * @copyright 2016 Vladimir Jimenez
5
 * @license   https://github.com/allejo/stakx/blob/master/LICENSE.md MIT
6
 */
7
8
namespace allejo\stakx\System;
9
10
use Symfony\Component\Finder\SplFileInfo;
11
12
class FileExplorer extends \RecursiveFilterIterator
13
{
14
    /**
15
     * A bitwise flag to have FileExplorer ignore all files unless its been explicitly included; all other files will be
16
     * ignored.
17
     */
18
    const INCLUDE_ONLY_FILES = 0x1;
19
20
    /**
21
     * A bitwise flag to have FileExplorer search files starting with a period as well
22
     */
23
    const ALLOW_DOT_FILES    = 0x2;
24
25
    /**
26
     * A list of common version control folders to ignore.
27
     *
28
     * The following folders should be ignored explicitly by the end user. Their usage isn't as popular so adding more
29
     * conditions to loop through will only slow down FileExplorer.
30
     *
31
     *   - 'CVS'
32
     *   - '_darcs'
33
     *   - '.arch-params'
34
     *   - '.monotone'
35
     *   - '.bzr'
36
     *
37
     * @var string[]
38
     */
39
    public static $vcsPatterns =  array('.git', '.hg', '.svn', '_svn');
40
41
    /**
42
     * A list of phrases to exclude from the search
43
     *
44
     * @var string[]
45
     */
46
    private $excludes;
47
48
    /**
49
     * A list of phrases to explicitly include in the search
50
     *
51
     * @var string[]
52
     */
53
    private $includes;
54
55
    /**
56
     * The bitwise sum of the flags applied to this FileExplorer instance
57
     *
58
     * @var int|null
59
     */
60
    private $flags;
61
62
    /**
63
     * FileExplorer constructor.
64
     *
65
     * @param \RecursiveIterator $iterator
66
     * @param array              $excludes
67
     * @param array              $includes
68
     * @param int|null           $flags
69
     */
70 4
    public function __construct(\RecursiveIterator $iterator, array $excludes = array(), array $includes = array(), $flags = null)
71
    {
72 4
        parent::__construct($iterator);
73
74 4
        $this->excludes = array_merge(self::$vcsPatterns, $excludes);
0 ignored issues
show
Documentation Bug introduced by
It seems like array_merge(self::$vcsPatterns, $excludes) of type array is incompatible with the declared type array<integer,string> of property $excludes.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
75 4
        $this->includes = $includes;
76 4
        $this->flags = $flags;
77 4
    }
78
79
    /**
80
     * @return string
81
     */
82
    public function __toString()
83
    {
84
        return $this->current()->getFilename();
85
    }
86
87
    /**
88
     * {@inheritdoc}
89
     */
90 4
    public function accept ()
91
    {
92 4
        $filePath = str_replace(getcwd() . '/', '', $this->current()->getPathname());
93
94 4
        if ($this->strpos_array($filePath, $this->includes)) { return true; }
95 4
        if (($this->flags & self::INCLUDE_ONLY_FILES) && !$this->current()->isDir()) { return false; }
96
97 4
        if (!($this->flags & self::ALLOW_DOT_FILES) &&
98 4
            preg_match('#(^|\/)\..+(\/|$)#', $filePath) === 1) { return false; }
99
100 4
        return ($this->strpos_array($filePath, $this->excludes) === false);
101
    }
102
103
    /**
104
     * Get the current SplFileInfo object
105
     *
106
     * @return SplFileInfo
107
     */
108 4
    public function current()
109
    {
110
        /** @var \SplFileInfo $current */
111 4
        $current = parent::current();
112
113 4
        return (new SplFileInfo(
114 4
            $current->getPathname(),
115 4
            $this->getRelativePath($current->getPath()),
116 4
            $this->getRelativePath($current->getPathname())
117 4
        ));
118
    }
119
120
    /**
121
     * {@inheritdoc}
122
     */
123
    public function getChildren()
124
    {
125
        return (new self(
126
            $this->getInnerIterator()->getChildren(),
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Iterator as the method getChildren() does only exist in the following implementations of said interface: DoctrineTest\InstantiatorTestAsset\PharAsset, PHPUnit_Runner_Filter_GroupFilterIterator, PHPUnit_Runner_Filter_Group_Exclude, PHPUnit_Runner_Filter_Group_Include, PHPUnit_Runner_Filter_Test, PHPUnit_Util_TestSuiteIterator, PHP_CodeCoverage_Report_Node_Iterator, ParentIterator, Phar, PharData, RecursiveArrayIterator, RecursiveCachingIterator, RecursiveCallbackFilterIterator, RecursiveDirectoryIterator, RecursiveFilterIterator, RecursiveRegexIterator, SimpleXMLIterator, SplFileObject, SplTempFileObject, Symfony\Component\Finder...DirectoryFilterIterator, Symfony\Component\Finder...ursiveDirectoryIterator, allejo\stakx\System\FileExplorer.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
127
            $this->excludes,
128
            $this->includes,
129
            $this->flags
130
        ));
131
    }
132
133
    /**
134
     * Get an Iterator with all of the files that have met the search requirements
135
     *
136
     * @return \RecursiveIteratorIterator
137
     */
138 4
    public function getExplorer ()
139
    {
140 4
        return (new \RecursiveIteratorIterator($this));
141
    }
142
143
    /**
144
     * Create an instance of FileExplorer from a directory path as a string
145
     *
146
     * @param  string   $folder   The path to the folder we're scanning
147
     * @param  string[] $excludes
148
     * @param  string[] $includes
149
     * @param  int|null $flags
150
     *
151
     * @return FileExplorer
152
     */
153 4
    public static function create ($folder, $excludes = array(), $includes = array(), $flags = null)
154
    {
155 4
        $iterator = new \RecursiveDirectoryIterator($folder, \RecursiveDirectoryIterator::SKIP_DOTS);
156
157 4
        return (new self($iterator, $excludes, $includes, $flags));
158
    }
159
160
    /**
161
     * Search a given string for an array of possible elements
162
     *
163
     * @param  string   $haystack
164
     * @param  string[] $needle
165
     * @param  int      $offset
166
     *
167
     * @return bool True if an element from the given array was found in the string
168
     */
169 4
    private function strpos_array ($haystack, $needle, $offset = 0)
0 ignored issues
show
Coding Style introduced by
This method is not in camel caps format.

This check looks for method names that are not written in camelCase.

In camelCase names are written without any punctuation, the start of each new word being marked by a capital letter. Thus the name database connection seeker becomes databaseConnectionSeeker.

Loading history...
170
    {
171 4
        if (!is_array($needle))
172 4
        {
173
            $needle = array($needle);
174
        }
175
176 4
        foreach ($needle as $query)
177
        {
178 4
            if (substr($query, 0, 1) == '/' && substr($query, -1, 1) == '/' && preg_match($query, $haystack) === 1)
179 4
            {
180
                return true;
181
            }
182
183 4
            if (strpos($haystack, $query, $offset) !== false) // stop on first true result
184 4
            {
185
                return true;
186
            }
187 4
        }
188
189 4
        return false;
190
    }
191
192
    /**
193
     * Strip the current working directory from an absolute path
194
     *
195
     * @param  string $path An absolute path
196
     *
197
     * @return string
198
     */
199 4
    private function getRelativePath ($path)
200
    {
201 4
        return str_replace(getcwd() . DIRECTORY_SEPARATOR, '', $path);
202
    }
203
}
204