Support named arguments in ObjectFactory
authorGergő Tisza <tgr.huwiki@gmail.com>
Thu, 29 Oct 2015 02:06:37 +0000 (19:06 -0700)
committerBryanDavis <bdavis@wikimedia.org>
Mon, 23 Nov 2015 23:04:08 +0000 (23:04 +0000)
Arguments are sometimes given as array( 'foo' => 1, 'bar' => 2 )
which makes the configuration self-documenting.

Change-Id: I43aa085090f1014ba841641867ebf9559d16e76d

includes/libs/ObjectFactory.php
tests/phpunit/includes/libs/ObjectFactoryTest.php

index 6191612..bd0da57 100644 (file)
@@ -128,8 +128,11 @@ class ObjectFactory {
         * @return mixed Constructed instance
         */
        public static function constructClassInstance( $clazz, $args ) {
+               // args are sometimes specified in a 'name' => $value format for readability
+               $args = array_values( $args );
+
                // TODO: when PHP min version supported is >=5.6.0 replace this
-               // function body with `return new $clazz( ... $args );`.
+               // with `return new $clazz( ... $args );`.
                $obj = null;
                switch ( count( $args ) ) {
                        case 0:
index 622fce2..6337210 100644 (file)
@@ -108,6 +108,14 @@ class ObjectFactoryTest extends PHPUnit_Framework_TestCase {
                        '11 args' => array( array( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ) ),
                );
        }
+
+       public function testNamedArgs() {
+               $args = array( 'foo' => 1, 'bar' => 2, 'baz' => 3 );
+               $obj = ObjectFactory::constructClassInstance(
+                       'ObjectFactoryTestFixture', $args
+               );
+               $this->assertSame( array( 1, 2, 3 ), $obj->args );
+       }
 }
 
 class ObjectFactoryTestFixture {