$this->name = isset($config['name']) ? $config['name'] : null;
$this->parameters = isset($config['parameters']) ? $config['parameters'] : array();
$this->filters = isset($config['filters']) ? $config['filters'] : array();
- $action = explode('::', $this->config['_controller']);
+ $action = isset ($this->config['_controller']) ? explode('::', $this->config['_controller']) : array();
$this->class = isset($action[0]) ? $action[0] : null;
$this->action = isset($action[1]) ? $action[1] : null;
}
return array_merge($arguments, $parameters);
}
+ private function canBeEchoed($var)
+ {
+ return method_exists($var, '__toString') || (is_scalar($var) && !is_null($var));
+ }
+
public function dispatch($instance = null)
{
is_null($instance) and $instance = new $this->class();
if (empty($this->action) || trim($this->action) === '') {
// __invoke on a class
- call_user_func_array($instance, $param);
+ $result = call_user_func_array($instance, $param);
} else {
- call_user_func_array(array($instance, $this->action), $param);
+ $result = call_user_func_array(array($instance, $this->action), $param);
+ }
+
+ if ($this->canBeEchoed($result)) {
+ echo $result;
}
- $result = ob_get_clean();
+ $buffer = ob_get_clean();
- return $result;
+ return $buffer;
}
public function getAction()
--- /dev/null
+<?php
+
+namespace PHPRouter\Test\Fixtures;
+
+final class PrintableDate
+{
+ public function __construct()
+ {
+ }
+
+ public function __toString()
+ {
+ return "to string";
+ }
+}
use PHPRouter\Route;
use PHPRouter\Test\Fixtures\InvokableController;
+use PHPRouter\Test\Fixtures\PrintableDate;
use PHPUnit_Framework_TestCase;
class RouteTest extends PHPUnit_Framework_TestCase
{
$buffer = $this->routeWithParameters->dispatch();
- var_dump($buffer);
+ $this->assertEquals("", $buffer);
}
public function testParameterSorting()
$route->setParameters($params);
$this->assertEquals($expected, $route->dispatch());
}
+
+ public function testCanBeEchoed()
+ {
+ $route = new Route("", array());
+
+ $rexl = new \ReflectionMethod($route, "canBeEchoed");
+
+ $rexl->setAccessible(true);
+
+ $provider = array(
+ array(true, 1, "1"),
+ array(true, 0, "0"),
+ array(true, 1.23, "1.23"),
+ array(true, 0.45, "0.45"),
+ array(true, "", ""),
+ array(true, new PrintableDate(), "to string"),
+ array(false, null),
+ array(false, array()),
+ );
+
+ foreach ($provider as $case) {
+ $expected = $case[0];
+ $item = $case[1];
+
+ $result = $rexl->invoke($route, $item);
+
+ $this->assertEquals($expected, $result);
+
+ if ($expected) {
+ ob_start();
+ echo $item;
+
+ $strval = ob_get_clean();
+
+ $this->assertEquals($strval, $case[2]);
+ }
+ }
+ }
}