1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Mattbit\Flat; |
4
|
|
|
|
5
|
|
|
use Mattbit\Flat\Query\Expression\Factory; |
6
|
|
|
use Mattbit\Flat\Query\Parser; |
7
|
|
|
use Mattbit\Flat\Storage\DocumentStore; |
8
|
|
|
use Mattbit\Flat\Storage\Engine; |
9
|
|
|
|
10
|
|
|
class Database |
11
|
|
|
{ |
12
|
|
|
/** |
13
|
|
|
* The storage engine. |
14
|
|
|
* |
15
|
|
|
* @var Engine |
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(Engine $engine) |
32
|
|
|
{ |
33
|
1 |
|
$this->engine = $engine; |
34
|
|
|
|
35
|
1 |
|
$this->initializeParser(); |
36
|
1 |
|
} |
37
|
|
|
|
38
|
|
|
/** |
39
|
|
|
* Select an existing collection or create a new one. |
40
|
|
|
* |
41
|
|
|
* @param string $name |
42
|
|
|
* |
43
|
|
|
* @return Collection |
44
|
|
|
*/ |
45
|
1 |
|
public function collection($name) |
46
|
|
|
{ |
47
|
1 |
|
return $this->getOrCreateCollection($name); |
48
|
|
|
} |
49
|
|
|
|
50
|
1 |
|
public function getOrCreateCollection($name) |
51
|
|
|
{ |
52
|
1 |
|
if (isset($this->collections[$name])) { |
53
|
1 |
|
return $this->collections[$name]; |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
return $this->createCollection($name); |
57
|
|
|
} |
58
|
|
|
|
59
|
1 |
|
public function createCollection($name) |
60
|
|
|
{ |
61
|
1 |
|
$store = $this->engine->createCollection($name); |
62
|
|
|
|
63
|
1 |
|
return $this->collections[$name] = $this->newCollection($store, $name); |
64
|
|
|
} |
65
|
|
|
|
66
|
|
|
public function dropCollection($name) |
67
|
|
|
{ |
68
|
|
|
$this->engine->dropCollection($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
|
|
|
|