Skip to content

Instantly share code, notes, and snippets.

@nullthoughts
Created September 8, 2021 20:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nullthoughts/5ff366f9f0df1530a2dfaf2a69640e41 to your computer and use it in GitHub Desktop.
Save nullthoughts/5ff366f9f0df1530a2dfaf2a69640e41 to your computer and use it in GitHub Desktop.
Pipeline extended with second parameter (with data)
<?php
namespace App\Filters;
use Closure;
use Illuminate\Pipeline\Pipeline;
use Throwable;
class PipelineFilter extends Pipeline
{
protected $params = [];
/**
* Set the array of data to filter with
*
* @param array|mixed $with
* @return $this
*/
public function with($params)
{
$this->params = $params;
return $this;
}
/**
* Run the pipeline with a final destination callback.
*
* @param \Closure $destination
* @return mixed
*/
public function then(Closure $destination)
{
$pipeline = array_reduce(
array_reverse($this->pipes()), $this->carry(), $this->prepareDestination($destination)
);
return $pipeline($this->passable, $this->params);
}
/**
* Get a Closure that represents a slice of the application onion.
*
* @return \Closure
*/
protected function carry()
{
return function ($stack, $pipe) {
return function ($passable, $params) use ($stack, $pipe) {
try {
if (is_callable($pipe)) {
// If the pipe is a callable, then we will call it directly, but otherwise we
// will resolve the pipes out of the dependency container and call it with
// the appropriate method and arguments, returning the results back out.
return $pipe($passable, $params, $stack);
} elseif (! is_object($pipe)) {
[$name, $parameters] = $this->parsePipeString($pipe);
// If the pipe is a string we will parse the string and resolve the class out
// of the dependency injection container. We can then build a callable and
// execute the pipe function giving in the parameters that are required.
$pipe = $this->getContainer()->make($name);
$parameters = array_merge([$passable, $params, $stack], $parameters);
} else {
// If the pipe is already an object we'll just make a callable and pass it to
// the pipe as-is. There is no need to do any extra parsing and formatting
// since the object we're given was already a fully instantiated object.
$parameters = [$passable, $params, $stack];
}
$carry = method_exists($pipe, $this->method)
? $pipe->{$this->method}(...$parameters)
: $pipe(...$parameters);
return $this->handleCarry($carry);
} catch (Throwable $e) {
return $this->handleException($passable, $e);
}
};
};
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment