Passed
Pull Request — master (#58)
by James
04:45
created

GitCheckoutRevisionToTemporaryPath::__construct()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 4
nc 2
nop 1
dl 0
loc 8
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Roave\BackwardCompatibility\Git;
6
7
use RuntimeException;
8
use Symfony\Component\Process\Exception\RuntimeException as ProcessRuntimeException;
9
use Symfony\Component\Process\Process;
10
use function file_exists;
11
use function is_dir;
12
use function sprintf;
13
use function sys_get_temp_dir;
14
use function uniqid;
15
16
final class GitCheckoutRevisionToTemporaryPath implements PerformCheckoutOfRevision
17
{
18
    /** @var callable */
19
    private $uniquenessFunction;
20
21
    public function __construct(?callable $uniquenessFunction = null)
22
    {
23
        if ($uniquenessFunction === null) {
24
            $uniquenessFunction = function (string $nonUniqueThing) : string {
25
                return uniqid($nonUniqueThing, true);
26
            };
27
        }
28
        $this->uniquenessFunction = $uniquenessFunction;
29
    }
30
31
    /**
32
     * {@inheritDoc}
33
     * @throws ProcessRuntimeException
34
     */
35
    public function checkout(CheckedOutRepository $sourceRepository, Revision $revision) : CheckedOutRepository
36
    {
37
        $checkoutDirectory = $this->generateTemporaryPathFor($revision);
38
39
        (new Process(['git', 'clone', (string) $sourceRepository, $checkoutDirectory]))->mustRun();
40
        (new Process(['git', 'checkout', (string) $revision]))->setWorkingDirectory($checkoutDirectory)->mustRun();
41
42
        return CheckedOutRepository::fromPath($checkoutDirectory);
43
    }
44
45
    /**
46
     * {@inheritDoc}
47
     * @throws ProcessRuntimeException
48
     */
49
    public function remove(CheckedOutRepository $checkedOutRepository) : void
50
    {
51
        (new Process(['rm', '-rf', (string) $checkedOutRepository]))->mustRun();
52
    }
53
54
    /**
55
     * @throws RuntimeException
56
     */
57
    private function generateTemporaryPathFor(Revision $revision) : string
58
    {
59
        $uniquePathGenerator = $this->uniquenessFunction;
60
        $checkoutDirectory   = sys_get_temp_dir() . '/api-compare-' . $uniquePathGenerator((string) $revision . '_');
61
62
        if (file_exists($checkoutDirectory) || is_dir($checkoutDirectory)) {
63
            throw new RuntimeException(sprintf(
64
                'Tried to check out revision %s to directory %s which already exists',
65
                (string) $revision,
66
                $checkoutDirectory
67
            ));
68
        }
69
70
        return $checkoutDirectory;
71
    }
72
}
73