Skip to content

Instantly share code, notes, and snippets.

@devosc
Last active August 20, 2017 16:28
Show Gist options
  • Save devosc/f3f2f4d52b3ae7ea6452b47279a31f49 to your computer and use it in GitHub Desktop.
Save devosc/f3f2f4d52b3ae7ea6452b47279a31f49 to your computer and use it in GitHub Desktop.
Middleware Args
<?php
/**
*
*/
namespace Mvc5\Service;
use Mvc5\Arg;
use Mvc5\Signal;
trait Middleware
{
/**
* @var Service
*/
protected $service;
/**
* @var array|\Iterator
*/
protected $config;
/**
* @param Service $service
* @param array|\Iterator $config
*/
function __construct(Service $service, $config = [])
{
$this->service = $service;
$this->config = $config;
}
/**
* @param array $argv
* @return array
*/
protected function args(array $argv)
{
return is_string(key($argv)) ? [Arg::NEXT => $this->delegate()] + $argv : array_merge($argv, [$this->delegate()]);
}
/**
* @param $middleware
* @param array $args
* @return mixed
*/
protected function call($middleware, $args)
{
return $middleware ? $this->service->call($middleware, $this->args(Signal::args($args))) : $this->end(Signal::args($args));
}
/**
* @return mixed
*/
protected function delegate()
{
return function(...$argv) {
return $this->call($this->next(), $argv);
};
}
/**
* @param array $args
* @return mixed|null
*/
protected function end(array $args)
{
return $args ? end($args) : null;
}
/**
* @return mixed
*/
protected function next()
{
if ($this->config instanceof \Iterator) {
$this->config->next();
return $this->config->current();
}
return next($this->config);
}
/**
* @return mixed
*/
protected function rewind()
{
if ($this->config instanceof \Iterator) {
$this->config->rewind();
return $this->config->current();
}
return reset($this->config);
}
/**
* @param array ...$argv
* @return mixed
*/
function __invoke(...$argv)
{
return $this->call($this->rewind(), $argv);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment