| 1 |
<?php |
| 2 |
/** |
| 3 |
* Container class |
| 4 |
* |
| 5 |
* @since 4.7.0 |
| 6 |
* @package elasticpress |
| 7 |
* @see https://github.com/php-fig/container |
| 8 |
*/ |
| 9 |
|
| 10 |
namespace ElasticPress; |
| 11 |
|
| 12 |
use ElasticPress\Vendor_Prefixed\Psr\Container\ContainerInterface; |
| 13 |
|
| 14 |
use ElasticPress\Exception\NotFoundException; |
| 15 |
|
| 16 |
/** |
| 17 |
* PSR11 compliant container class |
| 18 |
*/ |
| 19 |
final class Container implements ContainerInterface { |
| 20 |
/** |
| 21 |
* Hold all instances |
| 22 |
* |
| 23 |
* @var array<object> |
| 24 |
*/ |
| 25 |
private $instances = []; |
| 26 |
|
| 27 |
/** |
| 28 |
* Finds an entry of the container by its identifier and returns it. |
| 29 |
* |
| 30 |
* @param string $id Identifier of the entry to look for. |
| 31 |
* |
| 32 |
* @throws NotFoundException No entry was found for **this** identifier. |
| 33 |
* |
| 34 |
* @return mixed Entry. |
| 35 |
*/ |
| 36 |
public function get( $id ) { |
| 37 |
if ( ! isset( $this->instances[ $id ] ) ) { |
| 38 |
throw new NotFoundException( 'Class not found' ); |
| 39 |
} |
| 40 |
|
| 41 |
return $this->instances[ $id ]; |
| 42 |
} |
| 43 |
|
| 44 |
/** |
| 45 |
* Returns true if the container can return an entry for the given identifier. |
| 46 |
* Returns false otherwise. |
| 47 |
* |
| 48 |
* @param string $id Identifier of the entry to look for. |
| 49 |
* |
| 50 |
* @return bool |
| 51 |
*/ |
| 52 |
public function has( $id ): bool { |
| 53 |
return isset( $this->instances[ $id ] ); |
| 54 |
} |
| 55 |
|
| 56 |
/** |
| 57 |
* Register an instance. |
| 58 |
* |
| 59 |
* @param string $id Identifier of the entry. |
| 60 |
* @param object $instance The new instance. |
| 61 |
* @param boolean $setup Whether the setup() method should be called or not. |
| 62 |
* @return object The instance. |
| 63 |
*/ |
| 64 |
public function set( string $id, $instance, bool $setup = false ) { |
| 65 |
/** |
| 66 |
* Filter an instance before it is added to the container |
| 67 |
* |
| 68 |
* @since 4.7.0 |
| 69 |
* @hook ep_container_set |
| 70 |
* @param {object} $instance Object instance |
| 71 |
* @param {string} $id Id |
| 72 |
* @return {object} New object |
| 73 |
*/ |
| 74 |
$instance = apply_filters( 'ep_container_set', $instance, $id ); |
| 75 |
|
| 76 |
$this->instances[ $id ] = $instance; |
| 77 |
|
| 78 |
if ( $setup && method_exists( $instance, 'setup' ) ) { |
| 79 |
$instance->setup(); |
| 80 |
} |
| 81 |
|
| 82 |
return $instance; |
| 83 |
} |
| 84 |
} |
| 85 |
|