1<?php declare(strict_types=1);
2/*
3 * This file is part of phpunit/php-file-iterator.
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 */
10namespace SebastianBergmann\FileIterator;
11
12use const DIRECTORY_SEPARATOR;
13use function array_unique;
14use function count;
15use function dirname;
16use function explode;
17use function is_file;
18use function is_string;
19use function realpath;
20use function sort;
21
22class Facade
23{
24    /**
25     * @param array|string $paths
26     * @param array|string $suffixes
27     * @param array|string $prefixes
28     */
29    public function getFilesAsArray($paths, $suffixes = '', $prefixes = '', array $exclude = [], bool $commonPath = false): array
30    {
31        if (is_string($paths)) {
32            $paths = [$paths];
33        }
34
35        $iterator = (new Factory)->getFileIterator($paths, $suffixes, $prefixes, $exclude);
36
37        $files = [];
38
39        foreach ($iterator as $file) {
40            $file = $file->getRealPath();
41
42            if ($file) {
43                $files[] = $file;
44            }
45        }
46
47        foreach ($paths as $path) {
48            if (is_file($path)) {
49                $files[] = realpath($path);
50            }
51        }
52
53        $files = array_unique($files);
54        sort($files);
55
56        if ($commonPath) {
57            return [
58                'commonPath' => $this->getCommonPath($files),
59                'files'      => $files,
60            ];
61        }
62
63        return $files;
64    }
65
66    protected function getCommonPath(array $files): string
67    {
68        $count = count($files);
69
70        if ($count === 0) {
71            return '';
72        }
73
74        if ($count === 1) {
75            return dirname($files[0]) . DIRECTORY_SEPARATOR;
76        }
77
78        $_files = [];
79
80        foreach ($files as $file) {
81            $_files[] = $_fileParts = explode(DIRECTORY_SEPARATOR, $file);
82
83            if (empty($_fileParts[0])) {
84                $_fileParts[0] = DIRECTORY_SEPARATOR;
85            }
86        }
87
88        $common = '';
89        $done   = false;
90        $j      = 0;
91        $count--;
92
93        while (!$done) {
94            for ($i = 0; $i < $count; $i++) {
95                if ($_files[$i][$j] != $_files[$i + 1][$j]) {
96                    $done = true;
97
98                    break;
99                }
100            }
101
102            if (!$done) {
103                $common .= $_files[0][$j];
104
105                if ($j > 0) {
106                    $common .= DIRECTORY_SEPARATOR;
107                }
108            }
109
110            $j++;
111        }
112
113        return DIRECTORY_SEPARATOR . $common;
114    }
115}
116