1
|
|
|
<?php |
2
|
|
|
declare(strict_types=1); |
3
|
|
|
/** |
4
|
|
|
* Caridea |
5
|
|
|
* |
6
|
|
|
* Licensed under the Apache License, Version 2.0 (the "License"); you may not |
7
|
|
|
* use this file except in compliance with the License. You may obtain a copy of |
8
|
|
|
* the License at |
9
|
|
|
* |
10
|
|
|
* http://www.apache.org/licenses/LICENSE-2.0 |
11
|
|
|
* |
12
|
|
|
* Unless required by applicable law or agreed to in writing, software |
13
|
|
|
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT |
14
|
|
|
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the |
15
|
|
|
* License for the specific language governing permissions and limitations under |
16
|
|
|
* the License. |
17
|
|
|
* |
18
|
|
|
* @copyright 2015-2016 LibreWorks contributors |
19
|
|
|
* @license http://opensource.org/licenses/Apache-2.0 Apache 2.0 License |
20
|
|
|
*/ |
21
|
|
|
namespace Caridea\Dao; |
22
|
|
|
|
23
|
|
|
use MongoDB\Driver\Manager; |
24
|
|
|
|
25
|
|
|
/** |
26
|
|
|
* An abstract Data Access Object for MongoDb. |
27
|
|
|
* |
28
|
|
|
* Requires the `mongodb` extension. |
29
|
|
|
* |
30
|
|
|
* @copyright 2015-2016 LibreWorks contributors |
31
|
|
|
* @license http://opensource.org/licenses/Apache-2.0 Apache 2.0 License |
32
|
|
|
*/ |
33
|
|
|
abstract class MongoDb extends Dao |
34
|
|
|
{ |
35
|
|
|
/** |
36
|
|
|
* @var \MongoDB\Driver\Manager The driver manager |
37
|
|
|
*/ |
38
|
|
|
protected $manager; |
39
|
|
|
/** |
40
|
|
|
* |
41
|
|
|
* @var string The collection name |
42
|
|
|
*/ |
43
|
|
|
protected $collection; |
44
|
|
|
|
45
|
|
|
/** |
46
|
|
|
* Creates a new MongoDB DAO. |
47
|
|
|
* |
48
|
|
|
* @param \MongoDB\Driver\Manager $manager The MongoDB driver manager |
49
|
|
|
* @param string $collection The collection name (e.g. `database.collection`) |
50
|
|
|
* @param \Psr\Log\LoggerInterface $logger A logger |
51
|
|
|
*/ |
52
|
|
|
public function __construct(Manager $manager, string $collection, \Psr\Log\LoggerInterface $logger = null) |
53
|
|
|
{ |
54
|
|
|
parent::__construct($logger); |
55
|
|
|
$this->manager = $manager; |
56
|
|
|
$this->collection = $collection; |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
/** |
60
|
|
|
* Executes something in the context of the collection. |
61
|
|
|
* |
62
|
|
|
* Exceptions are caught and translated. |
63
|
|
|
* |
64
|
|
|
* @param callable $cb The closure to execute, takes the entityManager and collection |
65
|
|
|
* @return mixed Whatever the function returns, this method also returns |
66
|
|
|
* @throws \Caridea\Dao\Exception If a database problem occurs |
67
|
|
|
* @see \Caridea\Dao\Exception\Translator\MongoDb |
68
|
|
|
*/ |
69
|
|
|
protected function doExecute(\Closure $cb) |
70
|
|
|
{ |
71
|
|
|
try { |
72
|
|
|
return $cb($this->manager, $this->collection); |
73
|
|
|
} catch (\Exception $e) { |
74
|
|
|
throw Exception\Translator\MongoDb::translate($e); |
75
|
|
|
} |
76
|
|
|
} |
77
|
|
|
} |
78
|
|
|
|