Passed
Push — master ( 0cfc7e...b88fc1 )
by Tom
03:33 queued 42s
created

ArtifactSource::getAllFiles()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 3
nc 2
nop 0
dl 0
loc 7
ccs 4
cts 4
cp 1
crap 2
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
/* this file is part of pipelines */
4
5
namespace Ktomk\Pipelines\Runner;
6
7
use Ktomk\Pipelines\Cli\Exec;
8
use Ktomk\Pipelines\File\BbplMatch;
9
10
class ArtifactSource
11
{
12
    /**
13
     * @var Exec
14
     */
15
    private $exec;
16
17
    /**
18
     * @var string container id
19
     */
20
    private $id;
21
22
    /**
23
     * @var string in-container build directory
24
     */
25
    private $dir;
26
27
    /**
28
     * @var array|null all in-container build directory file paths
29
     */
30
    private $allFiles;
31
32
    /**
33
     * ArtifactSource constructor.
34
     * @param Exec $exec
35
     * @param string $id container id
36
     * @param string $dir in-container build directory ($BITBUCKET_CLONE_DIR)
37
     */
38 4
    public function __construct(Exec $exec, $id, $dir)
39
    {
40 4
        $this->exec = $exec;
41 4
        $this->id = $id;
42 4
        $this->dir = $dir;
43 4
    }
44
45
    /**
46
     * @return array|string[]
47
     */
48 3
    public function getAllFiles()
49
    {
50 3
        if ($this->allFiles === null) {
51 3
            $this->allFiles = $this->getFindPaths();
52
        }
53
54 3
        return $this->allFiles;
55
    }
56
57
    public function findByPattern($pattern)
58
    {
59 1
        $matcher = function ($subject) use ($pattern) {
60 1
            return BbplMatch::match($pattern, $subject);
61 1
        };
62
63 1
        $paths = $this->getAllFiles();
64
65 1
        $found = array_filter($paths, $matcher);
66
67 1
        return array_values($found);
68
    }
69
70
    /**
71
     * get an array of paths obtained via docker exec & find
72
     *
73
     * @return array
74
     */
75 3
    private function getFindPaths()
76
    {
77 3
        $buffer = $this->getFindBuffer();
78
79 3
        $lines = explode("\n", trim($buffer, "\n"));
80 3
        $pattern = '~^\\./~';
81 3
        $existing = preg_grep($pattern, $lines);
82 3
        $paths = preg_replace($pattern, '', $existing);
83
84 3
        return array_values($paths);
85
    }
86
87 3
    private function getFindBuffer()
88
    {
89
        $command = array(
90 3
            'find', '(', '-name', '.git', '-o', '-name', '.idea', ')',
91
            '-prune', '-type', 'f', '-o', '-type', 'f',
92
        );
93
94 3
        $status = $this->exec->capture('docker', array(
95 3
            'exec', '-w', '/app', $this->id, $command
96 3
        ), $out);
97
98 3
        if (0 === $status) {
99 2
            return $out;
100
        }
101
102 1
        return '';
103
    }
104
}
105