MicroDb::normalize()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 4
nc 1
nop 1
dl 0
loc 6
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
namespace WebComplete\microDb;
4
5
class MicroDb
6
{
7
8
    const EXTENSION = 'fdb';
9
10
    /**
11
     * @var string
12
     */
13
    protected $storageDir;
14
    /**
15
     * @var string
16
     */
17
    protected $dbName;
18
    /**
19
     * @var string
20
     */
21
    protected $type;
22
    /**
23
     * @var Factory
24
     */
25
    protected $factory;
26
27
    /**
28
     * @param string $storageDir
29
     * @param string $dbName
30
     * @param string $type file or memory
31
     * @param Factory $factory
32
     */
33
    public function __construct(string $storageDir, string $dbName, string $type = 'file', Factory $factory = null)
34
    {
35
        $this->storageDir = \rtrim($storageDir, '/');
36
        $this->dbName = $this->normalize($dbName);
37
        $this->setType($type);
38
        $this->factory = $factory ?? new Factory();
39
    }
40
41
    /**
42
     * @param string $type file or memory
43
     */
44
    public function setType(string $type)
45
    {
46
        $this->type = $type;
47
    }
48
49
    /**
50
     * @param string $collectionName
51
     *
52
     * @return Collection
53
     */
54
    public function getCollection(string $collectionName): Collection
55
    {
56
        $collectionFile = $this->getCollectionFilePath($collectionName);
57
        $storage = $this->factory->storage($collectionFile, $this->type);
58
        return $this->factory->collection($storage);
59
    }
60
61
    /**
62
     * @param string $collectionName
63
     *
64
     * @return string
65
     */
66
    protected function getCollectionFilePath(string $collectionName): string
67
    {
68
        return $this->storageDir . '/' . $this->dbName . '_'
69
            . $this->normalize($collectionName) . '.' . self::EXTENSION;
70
    }
71
72
    /**
73
     * @param string $value
74
     *
75
     * @return string
76
     */
77
    private function normalize(string $value): string
78
    {
79
        return \preg_replace(
80
            '/[^a-z0-9\-]/',
81
            '',
82
            \strtolower(\str_replace('_', '-', $value))
83
        );
84
    }
85
}
86