1: 2: 3: 4: 5: 6: 7: 8: 9: 10: 11: 12: 13: 14: 15: 16: 17: 18: 19: 20: 21: 22: 23: 24: 25: 26: 27: 28: 29: 30: 31: 32: 33: 34: 35: 36: 37: 38: 39: 40: 41: 42: 43: 44: 45: 46: 47: 48: 49: 50: 51: 52: 53: 54: 55: 56: 57: 58: 59: 60: 61: 62: 63: 64: 65: 66: 67: 68: 69: 70: 71: 72: 73: 74: 75: 76: 77: 78: 79: 80: 81: 82: 83: 84: 85:
<?php
/**
* Spanish Guest Report Generator
*
* @package Spanish Guest Report Generator
* @author Javier Zapata <javierzapata82@gmail.com>
* @copyright 2021 Javier Zapata <javierzapata82@gmail.com>
* @license https://opensource.org/licenses/MIT The MIT License
* @link https://github.com/bahiazul/spanish-guest-report-generator
*/
namespace SpanishGuestReportGenerator;
use SpanishGuestReportGenerator\Util\Helper;
/**
* Abstract Factory
*
* @package Spanish Guest Report Generator
* @author Javier Zapata <javierzapata82@gmail.com>
* @copyright 2021 Javier Zapata <javierzapata82@gmail.com>
* @license https://opensource.org/licenses/MIT The MIT License
* @link https://github.com/bahiazul/spanish-guest-report-generator
*/
abstract class AbstractFactory
{
/**
* Name of the class to be built
*
* @var string
*/
protected $className;
/**
* Sorted list of constructor arguments for the class to be built
*
* @var array
*/
protected $argsOrder;
/**
* Returns a collection of instances given an array with its data
*
* @param array $collection Data for the objects to be built
* @return array Collection of instances of the given class
*/
final public function buildMultiple(array $collection)
{
foreach ($collection as &$args) {
// Already built
if ($args instanceof $this->className) continue;
$args = $this->build($args);
}
return $collection;
}
/**
* Returns a new instance of a given class name and arguments
*
* @param array $args Arguments for the constructor
* @return object Instance of the given class
*/
final public function build(array $args = [])
{
if (!empty($args) && !Helper::is_assoc_array($args)) {
throw new FactoryException("`args` should be an associative array indexed by the property names of the class to be built.");
}
$newArgs = [];
foreach ($this->argsOrder as $name) {
$value = array_key_exists($name, $args)
? $args[$name]
: null;
array_push($newArgs, $value);
}
$class = new \ReflectionClass($this->className);
return $class->newInstanceArgs($newArgs);
}
}