Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
| Total | |
100.00% |
80 / 80 |
|
100.00% |
5 / 5 |
CRAP | |
100.00% |
1 / 1 |
| ObjectFactory | |
100.00% |
80 / 80 |
|
100.00% |
5 / 5 |
40 | |
100.00% |
1 / 1 |
| __construct | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
| createObject | |
100.00% |
2 / 2 |
|
100.00% |
1 / 1 |
1 | |||
| getObjectFromSpec | |
100.00% |
57 / 57 |
|
100.00% |
1 / 1 |
29 | |||
| validateSpec | |
100.00% |
15 / 15 |
|
100.00% |
1 / 1 |
7 | |||
| expandClosures | |
100.00% |
5 / 5 |
|
100.00% |
1 / 1 |
2 | |||
| 1 | <?php |
| 2 | declare( strict_types = 1 ); |
| 3 | |
| 4 | /** |
| 5 | * @license GPL-2.0-or-later |
| 6 | * @file |
| 7 | */ |
| 8 | |
| 9 | namespace Wikimedia\ObjectFactory; |
| 10 | |
| 11 | use Closure; |
| 12 | use InvalidArgumentException; |
| 13 | use Psr\Container\ContainerInterface; |
| 14 | use UnexpectedValueException; |
| 15 | |
| 16 | /** |
| 17 | * Construct objects based on a specification array. |
| 18 | * |
| 19 | * Contents of the specification array are as follows: |
| 20 | * |
| 21 | * 'factory' => callable, |
| 22 | * 'class' => string, |
| 23 | * |
| 24 | * The specification array must contain either a 'class' key with string value |
| 25 | * that specifies the class name to instantiate or a 'factory' key with a |
| 26 | * callable (is_callable() === true). If both are passed, 'factory' takes |
| 27 | * precedence but an InvalidArgumentException will be thrown if the resulting |
| 28 | * object is not an instance of the named class. |
| 29 | * |
| 30 | * 'args' => array, |
| 31 | * 'closure_expansion' => bool, // default true |
| 32 | * 'spec_is_arg' => bool, // default false |
| 33 | * 'services' => (string|null)[], // default empty |
| 34 | * 'optional_services' => (string|null)[], // default empty |
| 35 | * |
| 36 | * The 'args' key, if provided, specifies arguments to pass to the constructor/callable. |
| 37 | * Values in 'args' which are Closure instances will be expanded by invoking |
| 38 | * them with no arguments before passing the resulting value on to the |
| 39 | * constructor/callable. This can be used to pass live objects to the |
| 40 | * constructor/callable. This behavior can be suppressed by adding |
| 41 | * closure_expansion => false to the specification. |
| 42 | * |
| 43 | * If 'spec_is_arg' => true is in the specification, 'args' is ignored. The |
| 44 | * entire spec array is passed to the constructor/callable instead. |
| 45 | * |
| 46 | * If 'services' is supplied and non-empty (and a service container is available), |
| 47 | * the named services are requested from the PSR-11 service container and |
| 48 | * prepended before 'args'. `null` values in 'services' are passed to the constructor |
| 49 | * unchanged. |
| 50 | * |
| 51 | * Optional services declared via 'optional_services' are handled the same, |
| 52 | * except that if the service is not available from the service container |
| 53 | * `null` is passed as a parameter instead. Optional services are appended |
| 54 | * directly after the normal required services. |
| 55 | * |
| 56 | * If any extra arguments are passed in the options to getObjectFromSpec() or |
| 57 | * createObject(), these are prepended before the 'services' and 'args'. |
| 58 | * |
| 59 | * 'calls' => array |
| 60 | * |
| 61 | * The specification may also contain a 'calls' key that describes method |
| 62 | * calls to make on the newly created object before returning it. This |
| 63 | * pattern is often known as "setter injection". The value of this key is |
| 64 | * expected to be an associative array with method names as keys and |
| 65 | * argument lists as values. The argument list will be expanded (or not) |
| 66 | * in the same way as the 'args' key for the main object. |
| 67 | * |
| 68 | * Note these calls are not passed the extra arguments. |
| 69 | * |
| 70 | * @copyright © 2014 Wikimedia Foundation and contributors |
| 71 | */ |
| 72 | class ObjectFactory { |
| 73 | |
| 74 | /** @var ContainerInterface Service container */ |
| 75 | protected ContainerInterface $serviceContainer; |
| 76 | |
| 77 | /** |
| 78 | * @param ContainerInterface $serviceContainer Service container |
| 79 | */ |
| 80 | public function __construct( ContainerInterface $serviceContainer ) { |
| 81 | $this->serviceContainer = $serviceContainer; |
| 82 | } |
| 83 | |
| 84 | /** |
| 85 | * Instantiate an object based on a specification array. |
| 86 | * |
| 87 | * This calls getObjectFromSpec(), with the ContainerInterface that was |
| 88 | * passed to the constructor passed as `$options['serviceContainer']`. |
| 89 | * |
| 90 | * @template T of object |
| 91 | * |
| 92 | * @phpcs:ignore Generic.Files.LineLength |
| 93 | * @param class-string<T>|callable(mixed ...$args):T|array{class?:class-string<T>,factory?:callable(mixed ...$args):T,args?:list,services?:array<string|null>,optional_services?:array<string|null>,calls?:string[],closure_expansion?:bool,spec_is_arg?:bool} $spec |
| 94 | * Specification array, or (when the respective $options flag is set) a class name or callable. Allowed fields |
| 95 | * (see class documentation for more details): |
| 96 | * - 'class': (string) Class of the object to create. If 'factory' is also specified, |
| 97 | * it will be used to validate the object. |
| 98 | * - 'factory': (callable) Factory method for creating the object. |
| 99 | * - 'args': (array) Arguments to pass to the constructor or the factory method. |
| 100 | * - 'services': (array of string/null) List of services to pass as arguments. Each |
| 101 | * name will be looked up in the container given to ObjectFactory in its constructor, |
| 102 | * and the results prepended to the argument list. Null values are passed unchanged. |
| 103 | * - 'optional_services': (array of string/null) Handled the same as services, but if |
| 104 | * the service is unavailable from the service container the parameter is set to 'null' |
| 105 | * instead of causing an error. |
| 106 | * - 'calls': (array) A list of calls to perform on the created object, for setter |
| 107 | * injection. Keys of the array are method names and values are argument lists |
| 108 | * (as arrays). These arguments are not affected by any of the other specification |
| 109 | * fields that manipulate constructor arguments. |
| 110 | * - 'closure_expansion': (bool, default true) Whether to expand (execute) closures |
| 111 | * in 'args'. |
| 112 | * - 'spec_is_arg': (bool, default false) When true, 'args' is ignored and the entire |
| 113 | * specification array is passed as an argument. |
| 114 | * One of 'class' and 'factory' is required. |
| 115 | * @param array{allowClassName?:bool,allowCallable?:bool,extraArgs?:list,assertClass?:class-string<T>} $options |
| 116 | * Allowed keys are: |
| 117 | * - 'allowClassName': (bool) If set and truthy, $spec may be a string class name. |
| 118 | * In this case, it will be treated as if it were `[ 'class' => $spec ]`. |
| 119 | * - 'allowCallable': (bool) If set and truthy, $spec may be a callable. In this |
| 120 | * case, it will be treated as if it were `[ 'factory' => $spec ]`. |
| 121 | * - 'extraArgs': (array) Extra arguments to pass to the constructor/callable. These |
| 122 | * will come before services and normal args. |
| 123 | * - 'assertClass': (string) Throw an UnexpectedValueException if the spec |
| 124 | * does not create an object of this class. |
| 125 | * @return T |
| 126 | * @throws InvalidArgumentException when object specification is not valid. |
| 127 | * @throws UnexpectedValueException when the factory returns a non-object, or |
| 128 | * the object is not an instance of the specified class. |
| 129 | */ |
| 130 | public function createObject( $spec, array $options = [] ) { |
| 131 | $options['serviceContainer'] = $this->serviceContainer; |
| 132 | return static::getObjectFromSpec( $spec, $options ); |
| 133 | } |
| 134 | |
| 135 | /** |
| 136 | * Instantiate an object based on a specification array. |
| 137 | * |
| 138 | * @template T of object |
| 139 | * |
| 140 | * @phpcs:disable Generic.Files.LineLength |
| 141 | * @param class-string<T>|callable(mixed ...$args):T|array{class?:class-string<T>,factory?:callable(mixed ...$args):T,args?:list,services?:array<string|null>,optional_services?:array<string|null>,calls?:string[],closure_expansion?:bool,spec_is_arg?:bool} $spec |
| 142 | * As for createObject(). |
| 143 | * @param array{allowClassName?:bool,allowCallable?:bool,extraArgs?:list,assertClass?:class-string<T>,serviceContainer?:ContainerInterface} $options |
| 144 | * As for createObject(). Additionally: |
| 145 | * - 'serviceContainer': (ContainerInterface) PSR-11 service container to use |
| 146 | * to handle 'services'. |
| 147 | * @phpcs:enable |
| 148 | * @return T |
| 149 | * @throws InvalidArgumentException when object specification is not valid. |
| 150 | * @throws InvalidArgumentException when $spec['services'] or $spec['optional_services'] |
| 151 | * is used without $options['serviceContainer'] being set and implementing ContainerInterface. |
| 152 | * @throws UnexpectedValueException when the factory returns a non-object, or |
| 153 | * the object is not an instance of the specified class. |
| 154 | */ |
| 155 | public static function getObjectFromSpec( $spec, array $options = [] ) { |
| 156 | $spec = static::validateSpec( $spec, $options ); |
| 157 | |
| 158 | $expandArgs = !isset( $spec['closure_expansion'] ) || $spec['closure_expansion']; |
| 159 | |
| 160 | if ( !empty( $spec['spec_is_arg'] ) ) { |
| 161 | $args = [ $spec ]; |
| 162 | } else { |
| 163 | $args = $spec['args'] ?? []; |
| 164 | |
| 165 | // $args should be a non-associative array; show nice error if that's not the case |
| 166 | if ( !is_array( $args ) || !array_is_list( $args ) ) { |
| 167 | throw new InvalidArgumentException( '\'args\' must be a list' ); |
| 168 | } |
| 169 | |
| 170 | if ( $expandArgs ) { |
| 171 | $args = static::expandClosures( $args ); |
| 172 | } |
| 173 | } |
| 174 | |
| 175 | $services = []; |
| 176 | if ( !empty( $spec['services'] ) || !empty( $spec['optional_services'] ) ) { |
| 177 | $container = $options['serviceContainer'] ?? null; |
| 178 | if ( !$container instanceof ContainerInterface ) { |
| 179 | throw new InvalidArgumentException( |
| 180 | '\'services\' and \'optional_services\' cannot be used without a service container' |
| 181 | ); |
| 182 | } |
| 183 | |
| 184 | if ( !empty( $spec['services'] ) ) { |
| 185 | foreach ( $spec['services'] as $service ) { |
| 186 | $services[] = $service === null ? null : $container->get( $service ); |
| 187 | } |
| 188 | } |
| 189 | |
| 190 | if ( !empty( $spec['optional_services'] ) ) { |
| 191 | foreach ( $spec['optional_services'] as $service ) { |
| 192 | if ( $service !== null && $container->has( $service ) ) { |
| 193 | $services[] = $container->get( $service ); |
| 194 | } else { |
| 195 | // Either $service was null, or the service was not available |
| 196 | $services[] = null; |
| 197 | } |
| 198 | } |
| 199 | } |
| 200 | } |
| 201 | |
| 202 | $extraArgs = $options['extraArgs'] ?? []; |
| 203 | // $extraArgs should be a non-associative array; show nice error if that's not the case |
| 204 | if ( !is_array( $extraArgs ) || !array_is_list( $extraArgs ) ) { |
| 205 | throw new InvalidArgumentException( '\'extraArgs\' must be a list' ); |
| 206 | } |
| 207 | |
| 208 | $args = array_merge( |
| 209 | $extraArgs, |
| 210 | $services, |
| 211 | $args |
| 212 | ); |
| 213 | |
| 214 | if ( isset( $spec['factory'] ) ) { |
| 215 | $obj = $spec['factory']( ...$args ); |
| 216 | if ( !is_object( $obj ) ) { |
| 217 | throw new UnexpectedValueException( '\'factory\' did not return an object' ); |
| 218 | } |
| 219 | // @phan-suppress-next-line PhanRedundantCondition |
| 220 | if ( isset( $spec['class'] ) && !$obj instanceof $spec['class'] ) { |
| 221 | throw new UnexpectedValueException( |
| 222 | '\'factory\' was expected to return an instance of ' . $spec['class'] |
| 223 | . ', got ' . get_class( $obj ) |
| 224 | ); |
| 225 | } |
| 226 | } elseif ( isset( $spec['class'] ) ) { |
| 227 | $clazz = $spec['class']; |
| 228 | $obj = new $clazz( ...$args ); |
| 229 | } else { |
| 230 | throw new InvalidArgumentException( |
| 231 | 'Provided specification lacks both \'factory\' and \'class\' parameters.' |
| 232 | ); |
| 233 | } |
| 234 | |
| 235 | // @phan-suppress-next-line PhanRedundantCondition |
| 236 | if ( isset( $options['assertClass'] ) && !$obj instanceof $options['assertClass'] ) { |
| 237 | throw new UnexpectedValueException( |
| 238 | 'Expected instance of ' . $options['assertClass'] . ', got ' . get_class( $obj ) |
| 239 | ); |
| 240 | } |
| 241 | |
| 242 | if ( isset( $spec['calls'] ) && is_array( $spec['calls'] ) ) { |
| 243 | // Call additional methods on the newly created object |
| 244 | foreach ( $spec['calls'] as $method => $margs ) { |
| 245 | if ( $expandArgs ) { |
| 246 | $margs = static::expandClosures( $margs ); |
| 247 | } |
| 248 | $obj->$method( ...$margs ); |
| 249 | } |
| 250 | } |
| 251 | |
| 252 | return $obj; |
| 253 | } |
| 254 | |
| 255 | /** |
| 256 | * Convert a string or callable to a spec array |
| 257 | * |
| 258 | * @param array|string|callable $spec As for createObject() or getObjectFromSpec() |
| 259 | * @param array $options As for createObject() or getObjectFromSpec() |
| 260 | * @return array Specification array |
| 261 | * @throws InvalidArgumentException when object specification does not |
| 262 | * contain 'class' or 'factory' keys |
| 263 | */ |
| 264 | protected static function validateSpec( $spec, array $options ): array { |
| 265 | if ( is_callable( $spec ) ) { |
| 266 | if ( empty( $options['allowCallable'] ) ) { |
| 267 | throw new InvalidArgumentException( |
| 268 | 'Passing a raw callable is not allowed here. Use [ \'factory\' => $callable ] instead.' |
| 269 | ); |
| 270 | } |
| 271 | return [ 'factory' => $spec ]; |
| 272 | } |
| 273 | if ( is_string( $spec ) && class_exists( $spec ) ) { |
| 274 | if ( empty( $options['allowClassName'] ) ) { |
| 275 | throw new InvalidArgumentException( |
| 276 | 'Passing a raw class name is not allowed here. Use [ \'class\' => $classname ] instead.' |
| 277 | ); |
| 278 | } |
| 279 | return [ 'class' => $spec ]; |
| 280 | } |
| 281 | |
| 282 | if ( !is_array( $spec ) ) { |
| 283 | throw new InvalidArgumentException( 'Provided specification is not an array.' ); |
| 284 | } |
| 285 | |
| 286 | return $spec; |
| 287 | } |
| 288 | |
| 289 | /** |
| 290 | * Iterate a list and call any closures it contains. |
| 291 | * |
| 292 | * @param array $list List of things |
| 293 | * |
| 294 | * @return array List with any Closures replaced with their output |
| 295 | */ |
| 296 | protected static function expandClosures( array $list ): array { |
| 297 | return array_map( static function ( $value ) { |
| 298 | if ( $value instanceof Closure ) { |
| 299 | // If $value is a Closure, call it. |
| 300 | return $value(); |
| 301 | } |
| 302 | |
| 303 | return $value; |
| 304 | }, $list ); |
| 305 | } |
| 306 | |
| 307 | } |