Completed
Push — master ( d7f072...e80481 )
by Shcherbak
05:37
created

GitFileFinder::getFiles()   B

Complexity

Conditions 6
Paths 10

Size

Total Lines 43
Code Lines 27

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 42

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 43
ccs 0
cts 33
cp 0
rs 8.439
cc 6
eloc 27
nc 10
nop 0
crap 42
1
<?php
2
3
  namespace Funivan\Cs\FileFinder;
4
5
  use Symfony\Component\Process\Process;
6
7
  /**
8
9
   * @author Ivan Shcherbak <[email protected]> 2016
10
   */
11
  class GitFileFinder implements FileFinderInterface {
12
13
    /**
14
     * @var string
15
     */
16
    private $directory;
17
18
    /**
19
     * @var null|string
20
     */
21
    private $commit = null;
22
23
24
    /**
25
     * By default we will check all uncommitted files
26
     *
27
     * @param string $directory
28
     * @param string|null $commit
29
     */
30
    public function __construct($directory, $commit = null) {
31
      $this->directory = rtrim($directory, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;
32
      $this->commit = $commit;
33
    }
34
35
36
    /**
37
     * @return FileInfoCollection
38
     */
39
    public function getFileCollection() {
40
41
      if (!empty($this->commit)) {
42
        $process = new Process('git diff-tree --no-commit-id --name-status  -r ' . $this->commit);
43
      } else {
44
        $process = new Process('git diff --name-status ; git diff --cached --name-status');
45
      }
46
47
      $filesCollection = new FileInfoCollection();
48
      $process->run();
49
      if (!$process->isSuccessful()) {
50
        return $filesCollection;
51
      }
52
53
      $baseDir = $this->directory;
54
55
      $filesList = array_filter(explode("\n", $process->getOutput()));
56
57
      $statusMap = [
58
        'A' => File::STATUS_ADDED,
59
        'C' => File::STATUS_COPIED,
60
        'M' => File::STATUS_MODIFIED,
61
        'R' => File::STATUS_RENAMED,
62
        'D' => File::STATUS_DELETED,
63
      ];
64
65
      foreach ($filesList as $fileInfo) {
66
67
        preg_match('!^([^\s]+)\s+(.+)$!', $fileInfo, $matchedFileInfo);
68
        if (empty($matchedFileInfo[2])) {
69
          continue;
70
        }
71
        $gitStatus = trim($matchedFileInfo[1]);
72
73
        $status = !empty($statusMap[$gitStatus]) ? $statusMap[$gitStatus] : File::STATUS_UNKNOWN;
74
75
        $fullPath = $baseDir . ltrim($matchedFileInfo[2], DIRECTORY_SEPARATOR);
76
        $file = new File($fullPath, $status);
77
        $filesCollection[] = $file;
78
      }
79
80
      return $filesCollection;
81
    }
82
83
  }