1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/** |
4
|
|
|
* This file is part of laravel-quota |
5
|
|
|
* |
6
|
|
|
* (c) David Faith <[email protected]> |
7
|
|
|
* |
8
|
|
|
* Full copyright and license information is available |
9
|
|
|
* in the LICENSE file distributed with this source code. |
10
|
|
|
*/ |
11
|
|
|
|
12
|
|
|
namespace Projectmentor\Quota\Factories; |
13
|
|
|
|
14
|
|
|
use bandwidthThrottle\tokenBucket\Rate; |
15
|
|
|
use Projectmentor\Quota\Contracts\FactoryInterface; |
16
|
|
|
use Projectmentor\Quota\Contracts\PayloadInterface; |
17
|
|
|
|
18
|
|
|
/** |
19
|
|
|
* This is the token-bucket Rate factory class. |
20
|
|
|
* |
21
|
|
|
* @author David Faith <[email protected]> |
22
|
|
|
*/ |
23
|
|
|
class RateFactory implements FactoryInterface |
24
|
|
|
{ |
25
|
|
|
/** |
26
|
|
|
* Make a new rate instance. |
27
|
|
|
* |
28
|
|
|
* TODO: abstract the return value via contract |
29
|
|
|
* |
30
|
|
|
* @param \Projectmentor\Quota\Contracts\PayloadInterface $data |
31
|
|
|
* @return \bandwidthThrottle\tokenBucket\Rate |
32
|
|
|
*/ |
33
|
1 |
|
public function make(PayloadInterface $data) |
34
|
|
|
{ |
35
|
1 |
|
return new Rate($data->getlimit(), $data->getPeriod()); |
|
|
|
|
36
|
|
|
} |
37
|
|
|
|
38
|
|
|
/** |
39
|
|
|
* Retrieve value for constant defined in Rate::class. |
40
|
|
|
* Convienience method. |
41
|
|
|
* |
42
|
|
|
* @param string $key constant name |
43
|
|
|
* @return string constant value |
|
|
|
|
44
|
|
|
* @throws InvalidArgumentException |
45
|
|
|
*/ |
46
|
1 |
|
public function getConstant($key) |
47
|
|
|
{ |
48
|
1 |
|
$constants = $this->getConstants(); |
49
|
1 |
|
if (array_key_exists($key, $constants)) { |
50
|
1 |
|
return $constants[$key]; |
51
|
|
|
} else { |
52
|
1 |
|
throw new \InvalidArgumentException( |
53
|
1 |
|
__CLASS__.'::'.__FUNCTION__. |
54
|
1 |
|
' Invalid constant. Got: ' . $key . |
55
|
1 |
|
' Expected: ' . print_r($constants, 1) |
56
|
1 |
|
); |
57
|
|
|
} |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
/** |
61
|
|
|
* Retrieve an array of constants defined in Rate::class. |
62
|
|
|
* Convienience method. |
63
|
|
|
* |
64
|
|
|
* @return array |
|
|
|
|
65
|
|
|
*/ |
66
|
2 |
|
public function getConstants() |
67
|
|
|
{ |
68
|
2 |
|
$reflect = new \ReflectionClass(Rate::class); |
69
|
2 |
|
return $reflect->getConstants(); |
70
|
|
|
} |
71
|
|
|
} |
|
|
|
|
72
|
|
|
|
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: