StubObject: Allow using a factory function to construct the object
authorKunal Mehta <legoktm@member.fsf.org>
Tue, 16 Aug 2016 20:44:28 +0000 (13:44 -0700)
committerTim Starling <tstarling@wikimedia.org>
Wed, 17 Aug 2016 03:00:11 +0000 (03:00 +0000)
If $class is a callable, then assume it is a factory function, and pass
that onto ObjectFactory.

Change-Id: I20c3650843c2803e0f9521d67bb037abfc28e1d9

includes/StubObject.php

index 0b4d048..0210ed9 100644 (file)
@@ -48,6 +48,9 @@ class StubObject {
        /** @var null|string */
        protected $class;
 
+       /** @var null|callable */
+       protected $factory;
+
        /** @var array */
        protected $params;
 
@@ -55,12 +58,17 @@ class StubObject {
         * Constructor.
         *
         * @param string $global Name of the global variable.
-        * @param string $class Name of the class of the real object.
+        * @param string|callable $class Name of the class of the real object
+        *                               or a factory function to call
         * @param array $params Parameters to pass to constructor of the real object.
         */
        public function __construct( $global = null, $class = null, $params = [] ) {
                $this->global = $global;
-               $this->class = $class;
+               if ( is_callable( $class ) ) {
+                       $this->factory = $class;
+               } else {
+                       $this->class = $class;
+               }
                $this->params = $params;
        }
 
@@ -110,8 +118,10 @@ class StubObject {
         * @return object
         */
        public function _newObject() {
-               return ObjectFactory::getObjectFromSpec( [
-                       'class' => $this->class,
+               $params = $this->factory
+                       ? [ 'factory' => $this->factory ]
+                       : [ 'class' => $this->class ];
+               return ObjectFactory::getObjectFromSpec( $params + [
                        'args' => $this->params,
                        'closure_expansion' => false,
                ] );