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: 86: 87: 88: 89: 90:
<?php
namespace Coast\App;
use Coast\Request,
Coast\App\Exception,
Coast\App\Executable,
Coast\Response;
class Subpath implements Executable
{
use Executable\Implementation;
protected $_executable;
protected $_path;
protected $_regex;
public function __construct(Executable $executable, $path)
{
$this->executable($executable);
$this->path($path);
}
public function executable(Executable $executable = null)
{
if (func_num_args() > 0) {
if (!$executable instanceof Closure && !$executable instanceof Executable) {
throw new App\Exception("Object is not a closure or instance of Coast\App\Executable");
}
$this->_executable = $executable;
return $this;
}
return $this->_executable;
}
public function path($path = null)
{
if (func_num_args() > 0) {
$this->_path = $path;
$this->_regex = '/^(' . preg_quote((string) $this->_path, '/') . ')(?:\/(.*))?$/';
return $this;
}
return $this->_path;
}
public function execute(Request $req, Response $res)
{
if (!preg_match($this->_regex, $req->path(), $path)) {
return;
}
$base = $req->base();
$req->base("{$base}{$path[1]}/")
->path(isset($path[2]) ? $path[2] : '');
$result = call_user_func($this->_executable instanceof Executable
? [$this->_executable, 'execute']
: $this->_executable, $req, $res);
$req->base($base)
->path($path[0]);
return $result;
}
public function preExecute(Request $req, Response $res)
{
if (!preg_match($this->_regex, $req->path(), $path)) {
return;
}
if ($this->_executable instanceof Executable) {
$this->_executable->preExecute($req, $res);
}
}
public function postExecute(Request $req, Response $res)
{
if (!preg_match($this->_regex, $req->path(), $path)) {
return;
}
if ($this->_executable instanceof Executable) {
$this->_executable->postExecute($req, $res);
}
}
}