Completed
Pull Request — master (#13)
by Victor
01:57
created

FileSystemWriter::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 0
cts 3
cp 0
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 1
crap 2
1
<?php
2
3
namespace LazyEight\DiTesto\FileSystem;
4
5
use LazyEight\DiTesto\Exceptions\FileSystemException;
6
use LazyEight\DiTesto\Interfaces\FileSystem\FileSystemPathInterface;
7
use LazyEight\DiTesto\Interfaces\FileSystem\FileSystemWriterInterface;
8
use Test\DiTesto\FileSystem\Exceptions\InvalidPathException;
9
10
class FileSystemWriter implements FileSystemWriterInterface
11
{
12
    /**
13
     * @var FileSystemPathInterface
14
     */
15
    private $path;
16
17
    /**
18
     * FileSystemWriter constructor.
19
     * @param FileSystemPathInterface $path
20
     */
21
    public function __construct(FileSystemPathInterface $path)
22
    {
23
        $this->path = $path;
24
    }
25
26
    /**
27
     * @inheritDoc
28
     */
29
    public function isWritable(): bool
30
    {
31
        return is_writable($this->path->rawPath());
32
    }
33
34
    /**
35
     * @inheritDoc
36
     */
37
    public function write(string $content)
38
    {
39
        $this->validate();
40
        file_put_contents($this->path->rawPath(), $content);
41
    }
42
43
    /**
44
     * @throws FileSystemException
45
     * @throws InvalidPathException
46
     */
47
    public function validate()
48
    {
49
        if ($this->path->isDirectory()) {
50
            throw new InvalidPathException("Error, can't write file content to a directory.");
51
        }
52
53
        if (!is_writable($this->path->pathName()) && !$this->isWritable()) {
54
            throw new FileSystemException("Error, can't write to the file. The file must be writable.");
55
        }
56
    }
57
}
58