1<?php
2/*
3 * This file is part of the File_Iterator package.
4 *
5 * (c) Sebastian Bergmann <sebastian@phpunit.de>
6 *
7 * For the full copyright and license information, please view the LICENSE
8 * file that was distributed with this source code.
9 */
10
11/**
12 * Factory Method implementation that creates a File_Iterator that operates on
13 * an AppendIterator that contains an RecursiveDirectoryIterator for each given
14 * path.
15 *
16 * @since     Class available since Release 1.1.0
17 */
18class File_Iterator_Factory
19{
20    /**
21     * @param  array|string   $paths
22     * @param  array|string   $suffixes
23     * @param  array|string   $prefixes
24     * @param  array          $exclude
25     * @return AppendIterator
26     */
27    public function getFileIterator($paths, $suffixes = '', $prefixes = '', array $exclude = array())
28    {
29        if (is_string($paths)) {
30            $paths = array($paths);
31        }
32
33        $paths   = $this->getPathsAfterResolvingWildcards($paths);
34        $exclude = $this->getPathsAfterResolvingWildcards($exclude);
35
36        if (is_string($prefixes)) {
37            if ($prefixes != '') {
38                $prefixes = array($prefixes);
39            } else {
40                $prefixes = array();
41            }
42        }
43
44        if (is_string($suffixes)) {
45            if ($suffixes != '') {
46                $suffixes = array($suffixes);
47            } else {
48                $suffixes = array();
49            }
50        }
51
52        $iterator = new AppendIterator;
53
54        foreach ($paths as $path) {
55            if (is_dir($path)) {
56                $iterator->append(
57                  new File_Iterator(
58                    new RecursiveIteratorIterator(
59                      new RecursiveDirectoryIterator($path, RecursiveDirectoryIterator::FOLLOW_SYMLINKS)
60                    ),
61                    $suffixes,
62                    $prefixes,
63                    $exclude,
64                    $path
65                  )
66                );
67            }
68        }
69
70        return $iterator;
71    }
72
73    /**
74     * @param  array $paths
75     * @return array
76     */
77    protected function getPathsAfterResolvingWildcards(array $paths)
78    {
79        $_paths = array();
80
81        foreach ($paths as $path) {
82            if ($locals = glob($path, GLOB_ONLYDIR)) {
83                $_paths = array_merge($_paths, array_map('realpath', $locals));
84            } else {
85                $_paths[] = realpath($path);
86            }
87        }
88
89        return $_paths;
90    }
91}
92