1
|
|
|
<?php |
2
|
|
|
namespace BretRZaun\StatusPage\Check; |
3
|
|
|
use MongoDB\Client; |
4
|
|
|
|
5
|
|
|
use BretRZaun\StatusPage\Result; |
6
|
|
|
|
7
|
|
|
class MongoDbCheck extends AbstractCheck |
8
|
|
|
{ |
9
|
|
|
private $client; |
10
|
|
|
private $databases = []; |
11
|
|
|
private $collections = []; |
12
|
|
|
|
13
|
|
|
public function __construct(string $label, Client $client) |
14
|
|
|
{ |
15
|
|
|
parent::__construct($label); |
16
|
|
|
$this->client = $client; |
17
|
|
|
} |
18
|
|
|
|
19
|
|
|
public function ensureDatabaseExists(string $database) |
20
|
|
|
{ |
21
|
|
|
$this->databases[] = $database; |
22
|
|
|
} |
23
|
|
|
|
24
|
|
|
public function ensureDatabaseHasCollecion(string $database, string $collection) |
25
|
|
|
{ |
26
|
|
|
$this->ensureDatabaseExists($database); |
27
|
|
|
if (!isset($this->collections[$database])) { |
28
|
|
|
$this->collections[$database] = []; |
29
|
|
|
} |
30
|
|
|
$this->collections[$database][] = $collection; |
31
|
|
|
} |
32
|
|
|
|
33
|
|
|
public function checkStatus(): Result |
34
|
|
|
{ |
35
|
|
|
$result = new Result($this->label); |
36
|
|
|
try { |
37
|
|
|
$dbs = $this->client->listDatabaseNames()->getArrayCopy(); |
|
|
|
|
38
|
|
|
|
39
|
|
|
if (count($this->databases) > 0) { |
40
|
|
|
$this->checkDatabases($dbs); |
41
|
|
|
} |
42
|
|
|
if (count($this->collections) > 0) { |
43
|
|
|
$this->checkCollections($dbs); |
44
|
|
|
} |
45
|
|
|
} catch(\Exception $e) { |
46
|
|
|
$result->setError($e->getMessage()); |
47
|
|
|
} |
48
|
|
|
return $result; |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
private function checkDatabases($databases) |
52
|
|
|
{ |
53
|
|
|
foreach($this->databases as $database) { |
54
|
|
|
if (!in_array($database, $databases)) { |
55
|
|
|
throw new \RuntimeException('Database '.$database.' does not exist'); |
56
|
|
|
} |
57
|
|
|
} |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
private function checkCollections(array $databases) |
|
|
|
|
61
|
|
|
{ |
62
|
|
|
foreach($this->collections as $databaseName => $collections) { |
63
|
|
|
$database = $this->client->selectDatabase($databaseName); |
64
|
|
|
$collectionNames = $database->listCollectionNames()->getArrayCopy(); |
65
|
|
|
foreach($collections as $collection) { |
66
|
|
|
if (!in_array($collection, $collectionNames)) { |
67
|
|
|
throw new \RuntimeException('Collection '.$collection.' does not exist in database '.$databaseName); |
68
|
|
|
} |
69
|
|
|
} |
70
|
|
|
} |
71
|
|
|
} |
72
|
|
|
|
73
|
|
|
} |
Let’s take a look at an example:
In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.
Available Fixes
Change the type-hint for the parameter:
Add an additional type-check:
Add the method to the interface: