Docblox /src/DocBlox/Parser/Files.php

Language PHP Lines 517
MD5 Hash 036d7018512763679e9db706cd0fe22d Estimated Cost $6,249 (why?)
Repository git://github.com/mvriel/Docblox.git View Raw File View Project SPDX
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
<?php
/**
 * DocBlox
 *
 * PHP Version 5
 *
 * @category  DocBlox
 * @package   Parser
 * @author    Mike van Riel <mike.vanriel@naenius.com>
 * @copyright 2010-2011 Mike van Riel / Naenius (http://www.naenius.com)
 * @license   http://www.opensource.org/licenses/mit-license.php MIT
 * @link      http://docblox-project.org
 */

/**
 * Files container handling directory scanning, project root detection and ignores.
 *
 * @category DocBlox
 * @package  Parser
 * @author   Mike van Riel <mike.vanriel@naenius.com>
 * @license  http://www.opensource.org/licenses/mit-license.php MIT
 * @link     http://docblox-project.org
 */
class DocBlox_Parser_Files extends DocBlox_Parser_Abstract
{
    /** @var bool Whether to follow symlinks*/
    protected $follow_symlinks = false;

    /** @var bool Whether to ignore hidden files and folders */
    protected $ignore_hidden = false;

    /**
     * the glob patterns which directories/files to ignore during parsing and
     * how many files were ignored.
     *
     * Structure of this array is:
     *
     *     array(
     *         0 => <GLOB>
     *         1 => <COUNT of USES>
     *     )
     *
     * @var array[]
     */
    protected $ignore_patterns = array();

    /**
     * @var string[] Array containing a list of allowed line endings;
     *               defaults to php, php3 and phtml.
     */
    protected $allowed_extensions = array('php', 'php3', 'phtml');

    /** @var string[] An array containing the file names which must be processed */
    protected $files = array();

    /** @var string Detected root folder for this project */
    protected $project_root = null;

    /**
     * Sets the patterns by which to detect which files to ignore.
     *
     * @param array $patterns Glob-like patterns to filter files.
     *
     * @return void
     */
    public function setIgnorePatterns(array $patterns)
    {
        $this->ignore_patterns = array();

        foreach ($patterns as $pattern) {
            $this->addIgnorePattern($pattern);
        }
    }

    /**
     * Returns the ignore patterns.
     *
     * @return array
     */
    public function getIgnorePatterns()
    {
        // extract first element; second is a count
        $result = array();
        foreach ($this->ignore_patterns as $pattern) {
            $result[] = $pattern[0];
        }
        return $result;
    }

    /**
     * Adds an ignore pattern to the collection.
     *
     * @param string $pattern Glob-like pattern to filter files with.
     *
     * @return void
     */
    public function addIgnorePattern($pattern)
    {
        $this->convertToPregCompliant($pattern);
        $this->ignore_patterns[] = array($pattern, 0);
    }

    /**
     * Sets a list of allowed extensions; if not used php, php3 and phtml
     * is assumed.
     *
     * @param array $extensions An array containing extensions to match for.
     *
     * @return void
     */
    public function setAllowedExtensions(array $extensions)
    {
        $this->allowed_extensions = array();

        foreach ($extensions as $extension) {
            $this->addAllowedExtension($extension);
        }
    }

    /**
     * Adds a file extension to the list of allowed extensions.
     *
     * No dot is necessary and will even prevent the extension from being
     * picked up.
     *
     * @param string $extension Allowed file Extension to add (i.e. php).
     *
     * @return void
     */
    public function addAllowedExtension($extension)
    {
        $this->allowed_extensions[] = $extension;
    }

    /**
     * Adds the content of a set of directories to the list of files to parse.
     *
     * @param array $paths The paths whose contents to add to the collection.
     *
     * @return void
     */
    public function addDirectories(array $paths)
    {
        foreach ($paths as $path) {
            $this->addDirectory($path);
        }
    }

    /**
     * Retrieve all files in the given directory and add them to the parsing list.
     *
     * @param string $path A path to a folder, may be relative, absolute or
     *  even phar.
     *
     * @throws InvalidArgumentException if the given path is not a folder.
     *
     * @return void
     */
    public function addDirectory($path)
    {
        $result = substr($path, 0, 7) !== 'phar://' ? glob($path) : array($path);
        if ($result === false) {
            throw new DocBlox_Parser_Exception(
                '"'.$path . '" does not match an existing directory pattern'
            );
        }

        // if the given path is the only one AND there are no registered files.
        // then use this as project root instead of the calculated version.
        // This will make sure than when a _single_ path is given, that the
        // root will not inadvertently skip to a higher location because no
        // file were found in the given location.
        // i.e. if only path `src` us given and no PHP files reside there, but
        // they do reside in `src/php` then with this code `src` will remain
        // root so that ignore statements work as expected. Without this the
        // root would be `src/php`, which is unexpected when only a single folder
        // is provided.
        if ((count($result) == 1) && (empty($this->files))) {
            $this->project_root = realpath(reset($result));
        } else {
            $this->project_root = null;
        }

        foreach ($result as $result_path) {
            // if the given is not a directory or is hidden and must be ignored,
            // skip it
            if (!is_dir($result_path)) {
                continue;
            }

            // add the CATCH_GET_CHILD option to make sure that an unreadable
            // directory does not halt process but skip that folder
            $recursive_iterator = new RecursiveIteratorIterator(
                new RecursiveDirectoryIterator($result_path,
                    $this->getFollowSymlinks()
                        ? RecursiveDirectoryIterator::FOLLOW_SYMLINKS : 0
                ),
                RecursiveIteratorIterator::LEAVES_ONLY,
                RecursiveIteratorIterator::CATCH_GET_CHILD
            );

            /** @var SplFileInfo $file */
            foreach ($recursive_iterator as $file) {
                $is_hidden = ((substr($file->getPath(), 0, 1) == '.')
                    || (strpos($file->getPath(), DIRECTORY_SEPARATOR.'.')
                        !== false));

                // skipping dots (should any be encountered) or skipping
                // files starting with a dot if IgnoreHidden is true
                if (($file->getFilename() == '.')
                    || ($file->getFilename() == '..')
                    || ($this->getIgnoreHidden() && $is_hidden)
                ) {
                    continue;
                }

                // Phar files return false on a call to getRealPath
                $this->addFile(
                    (substr($file->getPathname(), 0, 7) != 'phar://')
                    ? $file->getRealPath()
                    : $file->getPathname()
                );
            }
        }
    }

    /**
     * Adds a list of individual files to the collection.
     *
     * @param array $paths File locations, may be absolute, relative or even phar.
     *
     * @return void
     */
    public function addFiles(array $paths)
    {
        if (!empty($paths)) {
            // if separate files are provided then the root must always be
            // calculated.
            $this->project_root = null;
        }

        foreach ($paths as $path) {
            $this->addFile($path);
        }
    }

    /**
     * Adds a file to the collection.
     *
     * @param string $path File location, may be absolute, relative or even phar.
     *
     * @return void
     */
    public function addFile($path)
    {
        $is_hidden = ((substr($path, 0, 1) == '.')
            || (strpos($path, DIRECTORY_SEPARATOR . '.') !== false));

        // ignore hidden files if option is set
        if ($this->getIgnoreHidden() && $is_hidden) {
            return;
        }

        // if it is not a file contained in a phar; check it out with a glob
        if (substr($path, 0, 7) != 'phar://') {
            // search file(s) with the given expressions
            $result = glob($path);
            foreach ($result as $file) {
                // if the path is not a file OR it's extension does not match
                // the given, then do not process it.
                if (!is_file($file) || (!empty($this->allowed_extensions)
                    && !in_array(
                        strtolower(pathinfo($file, PATHINFO_EXTENSION)),
                        $this->allowed_extensions
                    ))
                ) {
                    continue;
                }

                $this->files[] = realpath($file);
            }
        } else {
            // only process if it is a file and it matches the allowed extensions
            if (is_file($path)
                && (empty($this->allowed_extensions)
                || in_array(
                    strtolower(pathinfo($path, PATHINFO_EXTENSION)),
                    $this->allowed_extensions
                ))
            ) {
                $this->files[] = $path;
            }
        }
    }

    /**
     * Returns a list of files that are ready to be parsed.
     *
     * Please note that the ignore pattern will be applied and all files are
     * converted to absolute paths.
     *
     * @return string[]
     */
    public function getFiles()
    {
        $result = array();

        foreach ($this->files as $filename) {
            // check whether this file is ignored; we do this in two steps:
            // 1. Determine whether this is a relative or absolute path, if the
            //    string does not start with *, ?, / or \ then we assume that it is
            //    a relative path
            // 2. check whether the given pattern matches with the filename (or
            //    relative filename in case of a relative comparison)
            foreach ($this->ignore_patterns as $key => $pattern) {
                $glob = $pattern[0];
                if ((($glob[0] !== '*')
                    && ($glob[0] !== '?')
                    && ($glob[0] !== '/')
                    && ($glob[0] !== '\\')
                    && (preg_match(
                        '/^' . $glob . '$/',
                        $this->getRelativeFilename($filename)
                    )))
                    || (preg_match('/^' . $glob . '$/', $filename))
                ) {

                    // increase ignore usage with 1
                    $this->ignore_patterns[$key][1]++;

                    $this->log(
                        'File "' . $filename . '" matches ignore pattern, '
                        . 'will be skipped', DocBlox_Core_Log::INFO
                    );
                    continue 2;
                }
            }
            $result[] = $filename;
        }

        // detect if ignore patterns have been unused
        foreach ($this->ignore_patterns as $pattern) {
            if ($pattern[1] < 1) {
                $this->log(
                    'Ignore pattern "' . $pattern[0] . '" has not been used '
                    . 'during processing'
                );
            }
        }

        return $result;
    }

    /**
     * Calculates the project root from the given files by determining their
     * highest common path.
     *
     * @return string
     */
    public function getProjectRoot()
    {
        if ($this->project_root === null) {
            $base = '';
            $file = reset($this->files);

            // realpath does not work on phar files
            $file = (substr($file, 0, 7) != 'phar://')
                ? realpath($file)
                : $file;

            $parts = explode(DIRECTORY_SEPARATOR, $file);

            foreach ($parts as $part) {
                $base_part = $base . $part . DIRECTORY_SEPARATOR;
                foreach ($this->files as $dir) {

                    // realpath does not work on phar files
                    $dir = (substr($dir, 0, 7) != 'phar://')
                            ? realpath($dir)
                            : $dir;

                    if (substr($dir, 0, strlen($base_part)) != $base_part) {
                        return $base;
                    }
                }

                $base = $base_part;
            }

            $this->project_root = $base;
        }

        return $this->project_root;
    }

    /**
     * Converts $string into a string that can be used with preg_match.
     *
     * @param string &$string Glob-like pattern with wildcards ? and *.
     *
     * @author Greg Beaver <cellog@php.net>
     * @author mike van Riel <mike.vanriel@naenius.com>
     *
     * @see PhpDocumentor/phpDocumentor/Io.php
     *
     * @return void
     */
    protected function convertToPregCompliant(&$string)
    {
        $y = (DIRECTORY_SEPARATOR == '\\') ? '\\\\' : '\/';
        $string = str_replace('/', DIRECTORY_SEPARATOR, $string);
        $x = strtr(
            $string,
            array(
                 '?' => '.',
                 '*' => '.*',
                 '.' => '\\.',
                 '\\' => '\\\\',
                 '/' => '\\/',
                 '[' => '\\[',
                 ']' => '\\]',
                 '-' => '\\-'
            )
        );

        if ((strpos($string, DIRECTORY_SEPARATOR) !== false)
            && (strrpos($string, DIRECTORY_SEPARATOR) === strlen($string) - 1)
        ) {
            $x = "(?:.*$y$x?.*|$x.*)";
        }

        $string = $x;
    }

    /**
     * Returns the filename, relative to the root of the project directory.
     *
     * @param string $filename The filename to make relative.
     *
     * @throws InvalidArgumentException if file is not in the project root.
     *
     * @return string
     */
    protected function getRelativeFilename($filename)
    {
        // strip path from filename
        $result = ltrim(
            substr($filename, strlen($this->getProjectRoot())),
            DIRECTORY_SEPARATOR
        );

        if ($result === '') {
            throw new InvalidArgumentException(
                'File is not present in the given project path: ' . $filename
            );
        }

        return $result;
    }

    /**
     * Sets whether to ignore hidden files and folders.
     *
     * @param boolean $ignore_hidden if true skips hidden files and folders.
     *
     * @return void
     */
    public function setIgnoreHidden($ignore_hidden)
    {
        $this->ignore_hidden = $ignore_hidden;
    }

    /**
     * Returns whether files and folders that are hidden are ignored.
     *
     * @return boolean
     */
    public function getIgnoreHidden()
    {
        return $this->ignore_hidden;
    }

    /**
     * Sets whether to follow symlinks.
     *
     * PHP version 5.2.11 is at least required since the
     * RecursiveDirectoryIterator does not support the FOLLOW_SYMLINKS
     * constant before that version.
     *
     * @param boolean $follow_symlinks
     *
     * @throws InvalidArgumentException
     *
     * @return void
     */
    public function setFollowSymlinks($follow_symlinks)
    {
        if ($follow_symlinks && version_compare(PHP_VERSION, '5.2.11', '<')) {
            throw new InvalidArgumentException(
                'To follow symlinks you need at least PHP version 5.2.11'
            );
        }

        $this->follow_symlinks = $follow_symlinks;
    }

    /**
     * Returns whether to follow symlinks.
     *
     * @return boolean
     */
    public function getFollowSymlinks()
    {
        return $this->follow_symlinks;
    }

}
Back to Top