GitCheckoutRevisionToTemporaryPath::remove()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

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