-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathAnalyticsDriverFactory.php
More file actions
105 lines (89 loc) · 2.48 KB
/
AnalyticsDriverFactory.php
File metadata and controls
105 lines (89 loc) · 2.48 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
<?php declare(strict_types = 1);
namespace Dms\Package\Analytics;
use Dms\Core\Exception\InvalidArgumentException;
use Dms\Core\Ioc\IIocContainer;
use Dms\Core\Util\Debug;
use Dms\Package\Analytics\Google\GoogleAnalyticsDriver;
/**
* The analytics driver factory.
*
* @author Elliot Levin <elliotlevin@hotmail.com>
*/
class AnalyticsDriverFactory
{
private static $drivers = [
'google' => GoogleAnalyticsDriver::class,
];
/**
* @var IIocContainer
*/
private $iocContainer;
/**
* @var IAnalyticsDriver[]
*/
private $driversCache = [];
/**
* AnalyticsDriverFactory constructor.
*
* @param IIocContainer $iocContainer
*/
public function __construct(IIocContainer $iocContainer)
{
$this->iocContainer = $iocContainer;
}
/**
* @return IAnalyticsDriver[]
*/
public function getDrivers() : array
{
foreach (self::$drivers as $name => $driverClass) {
if (!isset($this->driversCache[$name])) {
$this->load($name);
}
}
return $this->driversCache;
}
/**
* @return string[]
*/
public function getDriverOptions() : array
{
$options = [];
foreach ($this->getDrivers() as $driver) {
$options[$driver->getName()] = $driver->getLabel();
}
return $options;
}
/**
* @param string $name
* @param string $class
*/
public function registerDriver(string $name, string $class)
{
InvalidArgumentException::verify(
is_a($class, IAnalyticsDriver::class, true),
'Class must implement %s, %s given',
IAnalyticsDriver::class, $class
);
self::$drivers[$name] = $class;
}
/**
* @param string $driverName
*
* @return IAnalyticsDriver
* @throws InvalidArgumentException
*/
public function load(string $driverName) : IAnalyticsDriver
{
if (!isset(self::$drivers[$driverName])) {
throw InvalidArgumentException::format(
'Invalid driver name supplied to %s: expecting one of (%s), \'%s\' given',
__METHOD__, Debug::formatValues(array_keys(self::$drivers)), $driverName
);
}
if (!isset($this->driversCache[$driverName])) {
$this->driversCache[$driverName] = $this->iocContainer->get(self::$drivers[$driverName]);
}
return $this->driversCache[$driverName];
}
}