FilesystemEngine::init()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 10
rs 9.4285
c 0
b 0
f 0
ccs 5
cts 5
cp 1
cc 2
eloc 5
nc 2
nop 1
crap 2
1
<?php
2
3
namespace Mattbit\Flat\Storage;
4
5
use Mattbit\Flat\Storage\EncoderInterface;
6
use Mattbit\Flat\Storage\EngineInterface;
7
use Mattbit\Flat\Storage\DocumentStore;
8
9
class FilesystemEngine implements EngineInterface
10
{
11
    /**
12
     * @var EncoderInterface
13
     */
14
    protected $encoder;
15
16
    protected $namespace;
17
18 5
    public function __construct($path, EncoderInterface $encoder)
19
    {
20 5
        $this->namespace = $path;
21 5
        $this->encoder = $encoder;
22 5
    }
23
24
    /**
25
     * Get the EncoderInterface instance.
26
     *
27
     * @return EncoderInterface
28
     */
29 1
    public function getEncoder()
30
    {
31 1
        return $this->encoder;
32
    }
33
34 1
    public function put($document, $id, $collection)
35
    {
36 1
        $data = $this->encoder->encode($document);
37
38 1
        return file_put_contents($this->path($id, $collection), $data) !== false;
39
    }
40
41 1
    public function get($id, $collection)
42
    {
43 1
        $data = file_get_contents($this->path($id, $collection));
44
45 1
        return $this->encoder->decode($data);
46
    }
47
48 1
    public function delete($id, $collection)
49
    {
50 1
        return unlink($this->path($id, $collection));
51
    }
52
53
    public function all($collection)
54
    {
55
        return new FilesystemIterator($this->encoder, $this->path('*', $collection));
56
    }
57
58
    public function clear($collection)
59
    {
60
        return array_map('unlink', glob($this->path('*', $collection)));
61
    }
62
63 1
    public function init($collection)
64
    {
65 1
        $dir = $this->path('', $collection, '');
66
67 1
        if (!file_exists($dir)) {
68 1
            return mkdir($this->path('', $collection, ''));
69
        }
70
71 1
        return true;
72
    }
73
74 1
    public function has($id, $collection)
75
    {
76 1
        return file_exists($this->path($id, $collection));
77
    }
78
79
    public function destroy($collection)
80
    {
81
        array_map('unlink', glob($this->path('*', $collection, '')));
82
        return rmdir($this->path('', $collection, ''));
83
    }
84
85 4
    protected function path($id, $collection, $ext = '.data')
86
    {
87 4
        return $this->namespace.DIRECTORY_SEPARATOR.$collection.DIRECTORY_SEPARATOR.$id.$ext;
88
    }
89
}
90