Advertisement
Guest User

Untitled

a guest
Jul 9th, 2021
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.15 KB | None | 0 0
  1.  
  2. class Car
  3. {
  4.     private const FACTORY_CLASSES = [
  5.         CarFactory::class,
  6.     ];
  7.  
  8.     /** @var iterable|AbstractCarFactory[] */
  9.     private iterable $factories;
  10.  
  11.     /**
  12.      * @param iterable|AbstractCarFactory[] $factories
  13.      */
  14.     public function __construct(iterable $factories)
  15.     {
  16.         $this->factories = $factories;
  17.     }
  18.  
  19.     public static function get(string $car): CarInterface
  20.     {
  21.         $factory = new self(self::getDefaultFactories());
  22.  
  23.         return $factory->create($car);
  24.     }
  25.  
  26.     public function create(string $car): CarInterface
  27.     {
  28.         foreach ($this->factories as $factory) {
  29.             if ($factory->supports($car)) {
  30.                 return $factory->create($car);
  31.             }
  32.         }
  33.  
  34.         throw new InvalidArgumentException(sprintf('No car supports the given name "%s".', $car));
  35.     }
  36.  
  37.     public static function getDefaultFactories(): Generator
  38.     {
  39.         foreach (self::FACTORY_CLASSES as $factoryClass) {
  40.             if (!class_exists($factoryClass)) {
  41.                 continue;
  42.             }
  43.  
  44.             yield new $factoryClass();
  45.         }
  46.     }
  47. }
  48.  
  49. Car::get('red');
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement