FileFinder.php 15.8 KB
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 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658
<?php

/**
 * Hoa
 *
 *
 * @license
 *
 * New BSD License
 *
 * Copyright © 2007-2017, Hoa community. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of the Hoa nor the names of its contributors may be
 *       used to endorse or promote products derived from this software without
 *       specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

namespace Psy\Readline\Hoa;

/**
 * Class \Hoa\File\Finder.
 *
 * This class allows to find files easily by using filters and flags.
 */
class FileFinder implements \IteratorAggregate
{
    /**
     * SplFileInfo classname.
     */
    protected $_splFileInfo = \SplFileInfo::class;

    /**
     * Paths where to look for.
     */
    protected $_paths = [];

    /**
     * Max depth in recursion.
     */
    protected $_maxDepth = -1;

    /**
     * Filters.
     */
    protected $_filters = [];

    /**
     * Flags.
     */
    protected $_flags = -1;

    /**
     * Types of files to handle.
     */
    protected $_types = [];

    /**
     * What comes first: parent or child?
     */
    protected $_first = -1;

    /**
     * Sorts.
     */
    protected $_sorts = [];

    /**
     * Initialize.
     */
    public function __construct()
    {
        $this->_flags = IteratorFileSystem::KEY_AS_PATHNAME
                        | IteratorFileSystem::CURRENT_AS_FILEINFO
                        | IteratorFileSystem::SKIP_DOTS;
        $this->_first = \RecursiveIteratorIterator::SELF_FIRST;

        return;
    }

    /**
     * Select a directory to scan.
     */
    public function in($paths): self
    {
        if (!\is_array($paths)) {
            $paths = [$paths];
        }

        foreach ($paths as $path) {
            if (1 === \preg_match('/[\*\?\[\]]/', $path)) {
                $iterator = new \CallbackFilterIterator(
                    new \GlobIterator(\rtrim($path, \DIRECTORY_SEPARATOR)),
                    function ($current) {
                        return $current->isDir();
                    }
                );

                foreach ($iterator as $fileInfo) {
                    $this->_paths[] = $fileInfo->getPathname();
                }
            } else {
                $this->_paths[] = $path;
            }
        }

        return $this;
    }

    /**
     * Set max depth for recursion.
     */
    public function maxDepth(int $depth): self
    {
        $this->_maxDepth = $depth;

        return $this;
    }

    /**
     * Include files in the result.
     */
    public function files(): self
    {
        $this->_types[] = 'file';

        return $this;
    }

    /**
     * Include directories in the result.
     */
    public function directories(): self
    {
        $this->_types[] = 'dir';

        return $this;
    }

    /**
     * Include links in the result.
     */
    public function links(): self
    {
        $this->_types[] = 'link';

        return $this;
    }

    /**
     * Follow symbolink links.
     */
    public function followSymlinks(bool $flag = true): self
    {
        if (true === $flag) {
            $this->_flags ^= IteratorFileSystem::FOLLOW_SYMLINKS;
        } else {
            $this->_flags |= IteratorFileSystem::FOLLOW_SYMLINKS;
        }

        return $this;
    }

    /**
     * Include files that match a regex.
     * Example:
     *     $this->name('#\.php$#');.
     */
    public function name(string $regex): self
    {
        $this->_filters[] = function (\SplFileInfo $current) use ($regex) {
            return 0 !== \preg_match($regex, $current->getBasename());
        };

        return $this;
    }

    /**
     * Exclude directories that match a regex.
     * Example:
     *      $this->notIn('#^\.(git|hg)$#');.
     */
    public function notIn(string $regex): self
    {
        $this->_filters[] = function (\SplFileInfo $current) use ($regex) {
            foreach (\explode(\DIRECTORY_SEPARATOR, $current->getPathname()) as $part) {
                if (0 !== \preg_match($regex, $part)) {
                    return false;
                }
            }

            return true;
        };

        return $this;
    }

    /**
     * Include files that respect a certain size.
     * The size is a string of the form:
     *     operator number unit
     * where
     *     • operator could be: <, <=, >, >= or =;
     *     • number is a positive integer;
     *     • unit could be: b (default), Kb, Mb, Gb, Tb, Pb, Eb, Zb, Yb.
     * Example:
     *     $this->size('>= 12Kb');.
     */
    public function size(string $size): self
    {
        if (0 === \preg_match('#^(<|<=|>|>=|=)\s*(\d+)\s*((?:[KMGTPEZY])b)?$#', $size, $matches)) {
            return $this;
        }

        $number = (float) ($matches[2]);
        $unit = $matches[3] ?? 'b';
        $operator = $matches[1];

        switch ($unit) {
            case 'b':
                break;

            // kilo
            case 'Kb':
                $number <<= 10;

                break;

            // mega.
            case 'Mb':
                $number <<= 20;

                break;

            // giga.
            case 'Gb':
                $number <<= 30;

                break;

            // tera.
            case 'Tb':
                $number *= 1099511627776;

                break;

            // peta.
            case 'Pb':
                $number *= 1024 ** 5;

                break;

            // exa.
            case 'Eb':
                $number *= 1024 ** 6;

                break;

            // zetta.
            case 'Zb':
                $number *= 1024 ** 7;

                break;

            // yota.
            case 'Yb':
                $number *= 1024 ** 8;

                break;
        }

        $filter = null;

        switch ($operator) {
            case '<':
                $filter = function (\SplFileInfo $current) use ($number) {
                    return $current->getSize() < $number;
                };

                break;

            case '<=':
                $filter = function (\SplFileInfo $current) use ($number) {
                    return $current->getSize() <= $number;
                };

                break;

            case '>':
                $filter = function (\SplFileInfo $current) use ($number) {
                    return $current->getSize() > $number;
                };

                break;

            case '>=':
                $filter = function (\SplFileInfo $current) use ($number) {
                    return $current->getSize() >= $number;
                };

                break;

            case '=':
                $filter = function (\SplFileInfo $current) use ($number) {
                    return $current->getSize() === $number;
                };

                break;
        }

        $this->_filters[] = $filter;

        return $this;
    }

    /**
     * Whether we should include dots or not (respectively . and ..).
     */
    public function dots(bool $flag = true): self
    {
        if (true === $flag) {
            $this->_flags ^= IteratorFileSystem::SKIP_DOTS;
        } else {
            $this->_flags |= IteratorFileSystem::SKIP_DOTS;
        }

        return $this;
    }

    /**
     * Include files that are owned by a certain owner.
     */
    public function owner(int $owner): self
    {
        $this->_filters[] = function (\SplFileInfo $current) use ($owner) {
            return $current->getOwner() === $owner;
        };

        return $this;
    }

    /**
     * Format date.
     * Date can have the following syntax:
     *     date
     *     since date
     *     until date
     * If the date does not have the “ago” keyword, it will be added.
     * Example: “42 hours” is equivalent to “since 42 hours” which is equivalent
     * to “since 42 hours ago”.
     */
    protected function formatDate(string $date, &$operator): int
    {
        $operator = -1;

        if (0 === \preg_match('#\bago\b#', $date)) {
            $date .= ' ago';
        }

        if (0 !== \preg_match('#^(since|until)\b(.+)$#', $date, $matches)) {
            $time = \strtotime($matches[2]);

            if ('until' === $matches[1]) {
                $operator = 1;
            }
        } else {
            $time = \strtotime($date);
        }

        return $time;
    }

    /**
     * Include files that have been changed from a certain date.
     * Example:
     *     $this->changed('since 13 days');.
     */
    public function changed(string $date): self
    {
        $time = $this->formatDate($date, $operator);

        if (-1 === $operator) {
            $this->_filters[] = function (\SplFileInfo $current) use ($time) {
                return $current->getCTime() >= $time;
            };
        } else {
            $this->_filters[] = function (\SplFileInfo $current) use ($time) {
                return $current->getCTime() < $time;
            };
        }

        return $this;
    }

    /**
     * Include files that have been modified from a certain date.
     * Example:
     *     $this->modified('since 13 days');.
     */
    public function modified(string $date): self
    {
        $time = $this->formatDate($date, $operator);

        if (-1 === $operator) {
            $this->_filters[] = function (\SplFileInfo $current) use ($time) {
                return $current->getMTime() >= $time;
            };
        } else {
            $this->_filters[] = function (\SplFileInfo $current) use ($time) {
                return $current->getMTime() < $time;
            };
        }

        return $this;
    }

    /**
     * Add your own filter.
     * The callback will receive 3 arguments: $current, $key and $iterator. It
     * must return a boolean: true to include the file, false to exclude it.
     * Example:
     *     // Include files that are readable
     *     $this->filter(function ($current) {
     *         return $current->isReadable();
     *     });.
     */
    public function filter($callback): self
    {
        $this->_filters[] = $callback;

        return $this;
    }

    /**
     * Sort result by name.
     * If \Collator exists (from ext/intl), the $locale argument will be used
     * for its constructor. Else, strcmp() will be used.
     * Example:
     *     $this->sortByName('fr_FR');.
     */
    public function sortByName(string $locale = 'root'): self
    {
        if (true === \class_exists('Collator', false)) {
            $collator = new \Collator($locale);

            $this->_sorts[] = function (\SplFileInfo $a, \SplFileInfo $b) use ($collator) {
                return $collator->compare($a->getPathname(), $b->getPathname());
            };
        } else {
            $this->_sorts[] = function (\SplFileInfo $a, \SplFileInfo $b) {
                return \strcmp($a->getPathname(), $b->getPathname());
            };
        }

        return $this;
    }

    /**
     * Sort result by size.
     * Example:
     *     $this->sortBySize();.
     */
    public function sortBySize(): self
    {
        $this->_sorts[] = function (\SplFileInfo $a, \SplFileInfo $b) {
            return $a->getSize() < $b->getSize();
        };

        return $this;
    }

    /**
     * Add your own sort.
     * The callback will receive 2 arguments: $a and $b. Please see the uasort()
     * function.
     * Example:
     *     // Sort files by their modified time.
     *     $this->sort(function ($a, $b) {
     *         return $a->getMTime() < $b->getMTime();
     *     });.
     */
    public function sort($callable): self
    {
        $this->_sorts[] = $callable;

        return $this;
    }

    /**
     * Child comes first when iterating.
     */
    public function childFirst(): self
    {
        $this->_first = \RecursiveIteratorIterator::CHILD_FIRST;

        return $this;
    }

    /**
     * Get the iterator.
     */
    public function getIterator()
    {
        $_iterator = new \AppendIterator();
        $types = $this->getTypes();

        if (!empty($types)) {
            $this->_filters[] = function (\SplFileInfo $current) use ($types) {
                return \in_array($current->getType(), $types);
            };
        }

        $maxDepth = $this->getMaxDepth();
        $splFileInfo = $this->getSplFileInfo();

        foreach ($this->getPaths() as $path) {
            if (1 === $maxDepth) {
                $iterator = new \IteratorIterator(
                    new IteratorRecursiveDirectory(
                        $path,
                        $this->getFlags(),
                        $splFileInfo
                    ),
                    $this->getFirst()
                );
            } else {
                $iterator = new \RecursiveIteratorIterator(
                    new IteratorRecursiveDirectory(
                        $path,
                        $this->getFlags(),
                        $splFileInfo
                    ),
                    $this->getFirst()
                );

                if (1 < $maxDepth) {
                    $iterator->setMaxDepth($maxDepth - 1);
                }
            }

            $_iterator->append($iterator);
        }

        foreach ($this->getFilters() as $filter) {
            $_iterator = new \CallbackFilterIterator(
                $_iterator,
                $filter
            );
        }

        $sorts = $this->getSorts();

        if (empty($sorts)) {
            return $_iterator;
        }

        $array = \iterator_to_array($_iterator);

        foreach ($sorts as $sort) {
            \uasort($array, $sort);
        }

        return new \ArrayIterator($array);
    }

    /**
     * Set SplFileInfo classname.
     */
    public function setSplFileInfo(string $splFileInfo): string
    {
        $old = $this->_splFileInfo;
        $this->_splFileInfo = $splFileInfo;

        return $old;
    }

    /**
     * Get SplFileInfo classname.
     */
    public function getSplFileInfo(): string
    {
        return $this->_splFileInfo;
    }

    /**
     * Get all paths.
     */
    protected function getPaths(): array
    {
        return $this->_paths;
    }

    /**
     * Get max depth.
     */
    public function getMaxDepth(): int
    {
        return $this->_maxDepth;
    }

    /**
     * Get types.
     */
    public function getTypes(): array
    {
        return $this->_types;
    }

    /**
     * Get filters.
     */
    protected function getFilters(): array
    {
        return $this->_filters;
    }

    /**
     * Get sorts.
     */
    protected function getSorts(): array
    {
        return $this->_sorts;
    }

    /**
     * Get flags.
     */
    public function getFlags(): int
    {
        return $this->_flags;
    }

    /**
     * Get first.
     */
    public function getFirst(): int
    {
        return $this->_first;
    }
}