Passed
Pull Request — master (#67)
by Aleksei
13:05
created

PhpFileSchemaProvider::write()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 3
c 1
b 0
f 0
dl 0
loc 5
rs 10
cc 1
nc 1
nop 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Yii\Cycle\Schema\Provider;
6
7
use Cycle\ORM\Schema;
8
use Yiisoft\Aliases\Aliases;
9
use Yiisoft\Yii\Cycle\Schema\Converter\SchemaToPHP;
10
use Yiisoft\Yii\Cycle\Schema\SchemaProviderInterface;
11
12
/**
13
 * Be careful, using this class may be insecure.
14
 */
15
final class PhpFileSchemaProvider implements SchemaProviderInterface
16
{
17
    private string $file = '';
18
19
    private Aliases $aliases;
20
21
    public function __construct(Aliases $aliases)
22
    {
23
        $this->aliases = $aliases;
24
    }
25
26
    public function withConfig(array $config): self
27
    {
28
        $new = clone $this;
29
        // required option
30
        if ($this->file === '' && !array_key_exists('file', $config)) {
31
            throw new \InvalidArgumentException('The "file" parameter is required.');
32
        }
33
        $new->file = $this->aliases->get($config['file']);
34
        return $new;
35
    }
36
37
    public function read(): ?array
38
    {
39
        if (!is_file($this->file)) {
40
            return null;
41
        }
42
        return include $this->file;
43
    }
44
45
    public function write(array $schema): bool
46
    {
47
        $content = (new SchemaToPHP(new Schema($schema)))->convert();
48
        file_put_contents($this->file, $content);
49
        return true;
50
    }
51
52
    private function removeFile(): void
53
    {
54
        if (!file_exists($this->file)) {
55
            return;
56
        }
57
        if (!is_file($this->file)) {
58
            throw new \RuntimeException("`$this->file` is not a file.");
59
        }
60
        if (!is_writable($this->file)) {
61
            throw new \RuntimeException("File `$this->file` is not writeable.");
62
        }
63
        unlink($this->file);
64
    }
65
66
    public function clear(): bool
67
    {
68
        try {
69
            $this->removeFile();
70
        } catch (\Throwable $e) {
71
            return false;
72
        }
73
        return true;
74
    }
75
76
    public function isWritable(): bool
77
    {
78
        return true;
79
    }
80
81
    public function isReadable(): bool
82
    {
83
        return true;
84
    }
85
}
86