Merge "User: Avoid deprecated Linker::link()"
[lhc/web/wiklou.git] / includes / libs / ObjectFactory.php
1 <?php
2 /**
3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
17 *
18 * @file
19 */
20
21 /**
22 * Construct objects from configuration instructions.
23 *
24 * @copyright © 2014 Wikimedia Foundation and contributors
25 */
26 class ObjectFactory {
27
28 /**
29 * Instantiate an object based on a specification array.
30 *
31 * The specification array must contain a 'class' key with string value
32 * that specifies the class name to instantiate or a 'factory' key with
33 * a callable (is_callable() === true). It can optionally contain
34 * an 'args' key that provides arguments to pass to the
35 * constructor/callable.
36 *
37 * Values in the arguments collection which are Closure instances will be
38 * expanded by invoking them with no arguments before passing the
39 * resulting value on to the constructor/callable. This can be used to
40 * pass IDatabase instances or other live objects to the
41 * constructor/callable. This behavior can be suppressed by adding
42 * closure_expansion => false to the specification.
43 *
44 * The specification may also contain a 'calls' key that describes method
45 * calls to make on the newly created object before returning it. This
46 * pattern is often known as "setter injection". The value of this key is
47 * expected to be an associative array with method names as keys and
48 * argument lists as values. The argument list will be expanded (or not)
49 * in the same way as the 'args' key for the main object.
50 *
51 * @param array $spec Object specification
52 * @return object
53 * @throws InvalidArgumentException when object specification does not
54 * contain 'class' or 'factory' keys
55 * @throws ReflectionException when 'args' are supplied and 'class'
56 * constructor is non-public or non-existent
57 */
58 public static function getObjectFromSpec( $spec ) {
59 $args = isset( $spec['args'] ) ? $spec['args'] : [];
60 $expandArgs = !isset( $spec['closure_expansion'] ) ||
61 $spec['closure_expansion'] === true;
62
63 if ( $expandArgs ) {
64 $args = static::expandClosures( $args );
65 }
66
67 if ( isset( $spec['class'] ) ) {
68 $clazz = $spec['class'];
69 if ( !$args ) {
70 $obj = new $clazz();
71 } else {
72 $obj = static::constructClassInstance( $clazz, $args );
73 }
74 } elseif ( isset( $spec['factory'] ) ) {
75 $obj = call_user_func_array( $spec['factory'], $args );
76 } else {
77 throw new InvalidArgumentException(
78 'Provided specification lacks both factory and class parameters.'
79 );
80 }
81
82 if ( isset( $spec['calls'] ) && is_array( $spec['calls'] ) ) {
83 // Call additional methods on the newly created object
84 foreach ( $spec['calls'] as $method => $margs ) {
85 if ( $expandArgs ) {
86 $margs = static::expandClosures( $margs );
87 }
88 call_user_func_array( [ $obj, $method ], $margs );
89 }
90 }
91
92 return $obj;
93 }
94
95 /**
96 * Iterate a list and call any closures it contains.
97 *
98 * @param array $list List of things
99 * @return array List with any Closures replaced with their output
100 */
101 protected static function expandClosures( $list ) {
102 return array_map( function ( $value ) {
103 if ( is_object( $value ) && $value instanceof Closure ) {
104 // If $value is a Closure, call it.
105 return $value();
106 } else {
107 return $value;
108 }
109 }, $list );
110 }
111
112 /**
113 * Construct an instance of the given class using the given arguments.
114 *
115 * PHP's `call_user_func_array()` doesn't work with object construction so
116 * we have to use other measures. Starting with PHP 5.6.0 we could use the
117 * "splat" operator (`...`) to unpack the array into an argument list.
118 * Sadly there is no way to conditionally include a syntax construct like
119 * a new operator in a way that allows older versions of PHP to still
120 * parse the file. Instead, we will try a loop unrolling technique that
121 * works for 0-10 arguments. If we are passed 11 or more arguments we will
122 * take the performance penalty of using
123 * `ReflectionClass::newInstanceArgs()` to construct the desired object.
124 *
125 * @param string $clazz Class name
126 * @param array $args Constructor arguments
127 * @return mixed Constructed instance
128 */
129 public static function constructClassInstance( $clazz, $args ) {
130 // $args should be a non-associative array; show nice error if that's not the case
131 if ( $args && array_keys( $args ) !== range( 0, count( $args ) - 1 ) ) {
132 throw new InvalidArgumentException( __METHOD__ . ': $args cannot be an associative array' );
133 }
134
135 // TODO: when PHP min version supported is >=5.6.0 replace this
136 // with `return new $clazz( ... $args );`.
137 $obj = null;
138 switch ( count( $args ) ) {
139 case 0:
140 $obj = new $clazz();
141 break;
142 case 1:
143 $obj = new $clazz( $args[0] );
144 break;
145 case 2:
146 $obj = new $clazz( $args[0], $args[1] );
147 break;
148 case 3:
149 $obj = new $clazz( $args[0], $args[1], $args[2] );
150 break;
151 case 4:
152 $obj = new $clazz( $args[0], $args[1], $args[2], $args[3] );
153 break;
154 case 5:
155 $obj = new $clazz(
156 $args[0], $args[1], $args[2], $args[3], $args[4]
157 );
158 break;
159 case 6:
160 $obj = new $clazz(
161 $args[0], $args[1], $args[2], $args[3], $args[4],
162 $args[5]
163 );
164 break;
165 case 7:
166 $obj = new $clazz(
167 $args[0], $args[1], $args[2], $args[3], $args[4],
168 $args[5], $args[6]
169 );
170 break;
171 case 8:
172 $obj = new $clazz(
173 $args[0], $args[1], $args[2], $args[3], $args[4],
174 $args[5], $args[6], $args[7]
175 );
176 break;
177 case 9:
178 $obj = new $clazz(
179 $args[0], $args[1], $args[2], $args[3], $args[4],
180 $args[5], $args[6], $args[7], $args[8]
181 );
182 break;
183 case 10:
184 $obj = new $clazz(
185 $args[0], $args[1], $args[2], $args[3], $args[4],
186 $args[5], $args[6], $args[7], $args[8], $args[9]
187 );
188 break;
189 default:
190 // Fall back to using ReflectionClass and curse the developer
191 // who decided that 11+ args was a reasonable method
192 // signature.
193 $ref = new ReflectionClass( $clazz );
194 $obj = $ref->newInstanceArgs( $args );
195 }
196 return $obj;
197 }
198 }