CopyMethod   A
last analyzed

Complexity

Total Complexity 9

Size/Duplication

Total Lines 53
Duplicated Lines 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 20
c 2
b 0
f 0
dl 0
loc 53
rs 10
wmc 9

3 Methods

Rating   Name   Duplication   Size   Complexity  
A exposeDirectory() 0 8 2
A __construct() 0 3 2
A copy() 0 19 5
1
<?php
2
3
namespace SilverStripe\VendorPlugin\Methods;
4
5
use Composer\Util\Filesystem;
6
use RecursiveDirectoryIterator;
7
use RecursiveIteratorIterator;
8
use RuntimeException;
9
10
/**
11
 * Expose the vendor module resources via a file copy
12
 */
13
class CopyMethod implements ExposeMethod
14
{
15
    const NAME = 'copy';
16
17
    /**
18
     * @var Filesystem
19
     */
20
    protected $filesystem = null;
21
22
    public function __construct(Filesystem $filesystem = null)
23
    {
24
        $this->filesystem = $filesystem ?: new Filesystem();
25
    }
26
27
    public function exposeDirectory($source, $target)
28
    {
29
        // Remove destination directory to ensure it is clean
30
        $this->filesystem->removeDirectory($target);
31
32
        // Copy to destination
33
        if (!$this->copy($source, $target)) {
34
            throw new RuntimeException("Could not write to directory $target");
35
        }
36
    }
37
38
    /**
39
     * Copies a file or directory from $source to $target.
40
     *
41
     * @todo Replace with `$this->filesystem->copy() once composer 1.6.0 is released
42
     *
43
     * @param string $source
44
     * @param string $target
45
     * @return bool
46
     */
47
    public function copy($source, $target)
48
    {
49
        if (!is_dir($source)) {
50
            return copy($source, $target);
51
        }
52
        $it = new RecursiveDirectoryIterator($source, RecursiveDirectoryIterator::SKIP_DOTS);
53
        /** @var RecursiveDirectoryIterator $ri */
54
        $ri = new RecursiveIteratorIterator($it, RecursiveIteratorIterator::SELF_FIRST);
55
        $this->filesystem->ensureDirectoryExists($target);
56
        $result = true;
57
        foreach ($ri as $file) {
58
            $targetPath = $target . DIRECTORY_SEPARATOR . $ri->getSubPathName();
59
            if ($file->isDir()) {
60
                $this->filesystem->ensureDirectoryExists($targetPath);
61
            } else {
62
                $result = $result && copy($file->getPathname(), $targetPath);
63
            }
64
        }
65
        return $result;
66
    }
67
}
68