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

FileSystemWriter   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 48
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
wmc 7
lcom 1
cbo 3
dl 0
loc 48
ccs 0
cts 15
cp 0
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A isWritable() 0 4 1
A write() 0 5 1
A validate() 0 10 4
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