GitCheckoutRevisionToTemporaryPath   A
last analyzed

Complexity

Total Complexity 5

Size/Duplication

Total Lines 52
Duplicated Lines 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 15
c 2
b 0
f 0
dl 0
loc 52
rs 10
wmc 5

4 Methods

Rating   Name   Duplication   Size   Complexity  
A generateTemporaryPathFor() 0 14 2
A remove() 0 3 1
A __construct() 0 3 1
A checkout() 0 8 1
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