-
Notifications
You must be signed in to change notification settings - Fork 0
/
Decorator.php
58 lines (45 loc) · 1.58 KB
/
Decorator.php
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
<?php
namespace Safronik\CodePatterns\Structural;
use Safronik\CodePatterns\Exceptions\DecoratorException;
/**
* Decorator
*
* Could be decorated anything via magic __call method
*
* @author Roman safronov
* @version 1.0.0
*/
trait Decorator
{
private object $decorated_object;
private array $callbacks = [];
public function __construct( object $decorated_object )
{
$this->decorated_object = $decorated_object;
}
public function setArgumentFilter( string $method, callable $callback ): void
{
$this->setCallback( $method, $callback, 'before' );
}
public function setResultFilter( string $method, callable $callback ): void
{
$this->setCallback( $method, $callback, 'after' );
}
public function setCallback( string $method, callable $callback, string $order = 'before' ): void
{
in_array( $order, ['before', 'after'], true )
|| throw new DecoratorException("Order $order is not allowed");
$this->callbacks[ $method ][ $order ] = $callback;
}
public function __call( string $name, array $arguments )
{
if( isset( $this->callbacks[ $name ][ 'before' ] ) ){
$this->callbacks[ $name ][ 'before' ]( $arguments );
}
$method_result = $this->decorated_object->$name( $arguments );
if( isset( $this->callbacks[ $name ][ 'after' ] ) ){
$method_result = $this->callbacks[ $name ][ 'after' ]( $method_result, $arguments );
}
return $method_result;
}
}