1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Mattbit\Flat; |
4
|
|
|
|
5
|
|
|
use Mattbit\Flat\Query\Parser; |
6
|
|
|
use Mattbit\Flat\Storage\DocumentStore; |
7
|
|
|
use Mattbit\Flat\Storage\EngineInterface; |
8
|
|
|
use Mattbit\Flat\Query\Expression\Factory; |
9
|
|
|
|
10
|
|
|
class Database |
11
|
|
|
{ |
12
|
|
|
/** |
13
|
|
|
* The storage engine. |
14
|
|
|
* |
15
|
|
|
* @var EngineInterface |
16
|
|
|
*/ |
17
|
|
|
protected $engine; |
18
|
|
|
|
19
|
|
|
/** |
20
|
|
|
* @var Parser |
21
|
|
|
*/ |
22
|
|
|
protected $parser; |
23
|
|
|
|
24
|
|
|
/** |
25
|
|
|
* An array of the registered collections. |
26
|
|
|
* |
27
|
|
|
* @var array |
28
|
|
|
*/ |
29
|
|
|
protected $collections; |
30
|
|
|
|
31
|
1 |
|
public function __construct(EngineInterface $engine) |
32
|
|
|
{ |
33
|
1 |
|
$this->engine = $engine; |
34
|
1 |
|
$this->initializeParser(); |
35
|
1 |
|
} |
36
|
|
|
|
37
|
|
|
/** |
38
|
|
|
* Select an existing collection or create a new one. |
39
|
|
|
* |
40
|
|
|
* @param string $name |
41
|
|
|
* |
42
|
|
|
* @return Collection |
43
|
|
|
*/ |
44
|
1 |
|
public function collection($name) |
45
|
|
|
{ |
46
|
1 |
|
return $this->getOrCreateCollection($name); |
47
|
|
|
} |
48
|
|
|
|
49
|
1 |
|
public function getOrCreateCollection($name) |
50
|
|
|
{ |
51
|
1 |
|
if (isset($this->collections[$name])) { |
52
|
1 |
|
return $this->collections[$name]; |
53
|
|
|
} |
54
|
|
|
|
55
|
|
|
return $this->createCollection($name); |
56
|
|
|
} |
57
|
|
|
|
58
|
1 |
|
public function createCollection($name) |
59
|
|
|
{ |
60
|
1 |
|
$this->engine->init($name); |
61
|
1 |
|
$store = new DocumentStore($this->engine, $name); |
62
|
|
|
|
63
|
1 |
|
return $this->collections[$name] = $this->newCollection($store, $name); |
64
|
|
|
} |
65
|
|
|
|
66
|
|
|
public function dropCollection($name) |
67
|
|
|
{ |
68
|
|
|
$this->engine->destroy($name); |
69
|
|
|
unset($this->collections[$name]); |
70
|
|
|
|
71
|
|
|
return true; |
72
|
|
|
} |
73
|
|
|
|
74
|
1 |
|
public function getParser() |
75
|
|
|
{ |
76
|
1 |
|
return $this->parser; |
77
|
|
|
} |
78
|
|
|
|
79
|
1 |
|
protected function initializeParser() |
80
|
|
|
{ |
81
|
1 |
|
$factory = new Factory(); |
82
|
1 |
|
$this->parser = new Parser($factory); |
83
|
1 |
|
} |
84
|
|
|
|
85
|
1 |
|
protected function newCollection(DocumentStore $store, $name) |
86
|
|
|
{ |
87
|
1 |
|
return new Collection($this, $store, $name); |
88
|
|
|
} |
89
|
|
|
} |
90
|
|
|
|