Completed
Push — master ( 326b3e...061c53 )
by Freek
09:13
created

Manifest::addFiles()   A

Complexity

Conditions 4
Paths 6

Size

Total Lines 14
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 7
nc 6
nop 1
dl 0
loc 14
rs 9.2
c 0
b 0
f 0
1
<?php
2
3
namespace Spatie\Backup\Tasks\Backup;
4
5
use Countable;
6
use SplFileObject;
7
8
class Manifest implements Countable
9
{
10
    /** @var string */
11
    protected $manifestPath;
12
13
    /**
14
     * @param string $manifestPath
15
     *
16
     * @return \Spatie\Backup\Tasks\Backup\Manifest
17
     */
18
    public static function create(string $manifestPath): Manifest
19
    {
20
        return new static($manifestPath);
21
    }
22
23
    public function __construct(string $manifestPath)
24
    {
25
        $this->manifestPath = $manifestPath;
26
27
        touch($manifestPath);
28
    }
29
30
    public function path(): string
31
    {
32
        return $this->manifestPath;
33
    }
34
35
    /**
36
     * @param array $filePaths
37
     *
38
     * @return $this
39
     */
40
    public function addFiles($filePaths): Manifest
41
    {
42
        if (is_string($filePaths)) {
43
            $filePaths = [$filePaths];
44
        }
45
46
        foreach ($filePaths as $filePath) {
47
            if (! empty($filePath)) {
48
                file_put_contents($this->manifestPath, $filePath.PHP_EOL, FILE_APPEND);
49
            }
50
        }
51
52
        return $this;
53
    }
54
55
    /**
56
     * @return \Generator|string[]
57
     */
58
    public function files()
59
    {
60
        $file = new SplFileObject($this->path());
61
62
        while (! $file->eof()) {
63
            $filePath = $file->fgets();
64
65
            if (! empty($filePath)) {
66
                yield trim($filePath);
67
            }
68
        }
69
    }
70
71
    public function count(): int
72
    {
73
        $file = new SplFileObject($this->manifestPath, 'r');
74
75
        $file->seek(PHP_INT_MAX);
76
77
        return $file->key();
78
    }
79
}
80