| 1 |
<?php |
| 2 |
/** |
| 3 |
* @package WPEmerge |
| 4 |
* @author Atanas Angelov <hi@atanas.dev> |
| 5 |
* @copyright 2017-2019 Atanas Angelov |
| 6 |
* @license https://www.gnu.org/licenses/gpl-2.0.html GPL-2.0 |
| 7 |
* @link https://wpemerge.com/ |
| 8 |
*/ |
| 9 |
|
| 10 |
namespace WPEmerge\Application; |
| 11 |
|
| 12 |
use Closure; |
| 13 |
|
| 14 |
/** |
| 15 |
* Factory that makes closures which resolve values from the container. |
| 16 |
*/ |
| 17 |
class ClosureFactory { |
| 18 |
/** |
| 19 |
* Factory. |
| 20 |
* |
| 21 |
* @var GenericFactory |
| 22 |
*/ |
| 23 |
protected $factory = null; |
| 24 |
|
| 25 |
/** |
| 26 |
* Constructor. |
| 27 |
* |
| 28 |
* @codeCoverageIgnore |
| 29 |
* @param GenericFactory $factory |
| 30 |
*/ |
| 31 |
public function __construct( GenericFactory $factory ) { |
| 32 |
$this->factory = $factory; |
| 33 |
} |
| 34 |
|
| 35 |
/** |
| 36 |
* Make a closure that resolves a value from the container. |
| 37 |
* |
| 38 |
* @param string $key |
| 39 |
* @return Closure |
| 40 |
*/ |
| 41 |
public function value( $key ) { |
| 42 |
return function () use ( $key ) { |
| 43 |
return $this->factory->make( $key ); |
| 44 |
}; |
| 45 |
} |
| 46 |
|
| 47 |
/** |
| 48 |
* Make a closure that resolves a class instance from the container and |
| 49 |
* calls one of its methods. |
| 50 |
* Useful if you need to pass a callable to an API without container |
| 51 |
* support such as the REST API. |
| 52 |
* |
| 53 |
* @param string $key |
| 54 |
* @param string $method |
| 55 |
* @return Closure |
| 56 |
*/ |
| 57 |
public function method( $key, $method ) { |
| 58 |
return function () use ( $key, $method ) { |
| 59 |
return call_user_func_array( |
| 60 |
[$this->factory->make( $key ), $method], |
| 61 |
func_get_args() |
| 62 |
); |
| 63 |
}; |
| 64 |
} |
| 65 |
} |
| 66 |
|