123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158 |
- <?php
- declare(strict_types=1);
- namespace Yansongda\Supports;
- use Closure;
- use Psr\Container\ContainerInterface;
- class Pipeline
- {
-
- protected ContainerInterface $container;
-
- protected $passable;
-
- protected array $pipes = [];
-
- protected string $method = 'handle';
- public function __construct(ContainerInterface $container)
- {
- $this->container = $container;
- }
-
- public function send($passable): self
- {
- $this->passable = $passable;
- return $this;
- }
-
- public function through($pipes): self
- {
- $this->pipes = is_array($pipes) ? $pipes : func_get_args();
- return $this;
- }
-
- public function via(string $method): self
- {
- $this->method = $method;
- return $this;
- }
-
- public function then(Closure $destination)
- {
- $pipeline = array_reduce(array_reverse($this->pipes), $this->carry(), $this->prepareDestination($destination));
- return $pipeline($this->passable);
- }
-
- protected function prepareDestination(Closure $destination): Closure
- {
- return static function ($passable) use ($destination) {
- return $destination($passable);
- };
- }
-
- protected function carry(): Closure
- {
- return function ($stack, $pipe) {
- return function ($passable) use ($stack, $pipe) {
- if (is_callable($pipe)) {
-
-
-
- return $pipe($passable, $stack);
- }
- if (!is_object($pipe)) {
- [$name, $parameters] = $this->parsePipeString($pipe);
-
-
-
- $pipe = $this->container->get($name);
- $parameters = array_merge([$passable, $stack], $parameters);
- } else {
-
-
-
- $parameters = [$passable, $stack];
- }
- $carry = method_exists($pipe, $this->method) ? $pipe->{$this->method}(...$parameters) : $pipe(...$parameters);
- return $this->handleCarry($carry);
- };
- };
- }
-
- protected function parsePipeString(string $pipe): array
- {
- [$name, $parameters] = array_pad(explode(':', $pipe, 2), 2, []);
- if (is_string($parameters)) {
- $parameters = explode(',', $parameters);
- }
- return [$name, $parameters];
- }
-
- protected function handleCarry($carry)
- {
- return $carry;
- }
- }
|