aboutsummaryrefslogtreecommitdiff
path: root/cli/Commands/AbstractCommand.php
blob: b3ce3cca185563fb74133b43c8163505693b80da (plain)
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
<?php
namespace Studip\Cli\Commands;

use FilesystemIterator;
use Iterator;
use RecursiveDirectoryIterator;
use RecursiveIteratorIterator;
use RecursiveRegexIterator;
use RegexIterator;
use Symfony\Component\Console\Command\Command;

abstract class AbstractCommand extends Command
{
    /**
     * Returns a folder iterator accessing all files inside that folder.
     *
     * @param string     $folder     Folder to return iterator for
     * @param bool       $recursive  Recurse into subfolders as well
     * @param array|null $extensions Optional list of extensions for files to be returned
     *
     * @return Iterator
     */
    protected function getFolderIterator(string $folder, bool $recursive = false, ?array $extensions = null): Iterator
    {
        if ($recursive) {
            $iterator = new RecursiveDirectoryIterator(
                $folder,
                FilesystemIterator::FOLLOW_SYMLINKS | FilesystemIterator::UNIX_PATHS
            );
            $iterator = new RecursiveIteratorIterator($iterator);
        } else {
            $iterator = new FilesystemIterator($folder);
        }

        if ($extensions) {
            $extensions = array_map(function ($extension) {
                return preg_quote($extension, '/');
            }, $extensions);
            $iterator = new RegexIterator(
                $iterator,
                '/\.(?:' . implode('|', $extensions) . ')$/',
                RecursiveRegexIterator::MATCH
            );
        }

        return $iterator;
    }

    protected function relativeFilePath(string $filepath, bool $plugin = false): string
    {
        $filepath = str_replace($GLOBALS['STUDIP_BASE_PATH'] . '/', '', $filepath);

        if ($plugin) {
            $filepath = str_replace('public/plugins_packages/', '', $filepath);
        }

        return $filepath;
    }

    protected function absoluteFilePath(string $filepath, bool $plugin = false): string
    {
        if ($plugin && mb_strpos($filepath, 'public/plugins_packages') === false) {
            $filepath = 'public/plugins_packages/' . ltrim($filepath, '/');
        }

        if (mb_strpos($filepath, $GLOBALS['STUDIP_BASE_PATH']) === false) {
            $filepath = $GLOBALS['STUDIP_BASE_PATH'] . '/' . ltrim($filepath, '/');
        }

        return $filepath;
    }
}