You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
flight-core/tests/DispatcherTest.php

99 lines
2.3 KiB

12 years ago
<?php
/**
* Flight: An extensible micro-framework.
*
* @copyright Copyright (c) 2012, Mike Cao <mike@mikecao.com>
* @license MIT, http://flightphp.com/license
12 years ago
*/
use flight\core\Dispatcher;
class DispatcherTest extends PHPUnit\Framework\TestCase
12 years ago
{
/**
* @var Dispatcher|null
12 years ago
*/
private Dispatcher $dispatcher;
12 years ago
protected function setUp(): void
{
$this->dispatcher = new Dispatcher();
12 years ago
}
// Map a closure
public function testClosureMapping()
{
$this->dispatcher->set('map1', function () {
12 years ago
return 'hello';
});
$result = $this->dispatcher->run('map1');
self::assertEquals('hello', $result);
12 years ago
}
// Map a function
public function testFunctionMapping()
{
$this->dispatcher->set('map2', function () {
12 years ago
return 'hello';
});
$result = $this->dispatcher->run('map2');
self::assertEquals('hello', $result);
12 years ago
}
// Map a class method
public function testClassMethodMapping()
{
12 years ago
$h = new Hello();
$this->dispatcher->set('map3', [$h, 'sayHi']);
12 years ago
$result = $this->dispatcher->run('map3');
self::assertEquals('hello', $result);
12 years ago
}
// Map a static class method
public function testStaticClassMethodMapping()
{
$this->dispatcher->set('map4', ['Hello', 'sayBye']);
12 years ago
$result = $this->dispatcher->run('map4');
self::assertEquals('goodbye', $result);
12 years ago
}
// Run before and after filters
public function testBeforeAndAfter()
{
$this->dispatcher->set('hello', function ($name) {
12 years ago
return "Hello, $name!";
});
$this->dispatcher->hook('hello', 'before', function (&$params, &$output) {
12 years ago
// Manipulate the parameter
$params[0] = 'Fred';
});
$this->dispatcher->hook('hello', 'after', function (&$params, &$output) {
12 years ago
// Manipulate the output
$output .= ' Have a nice day!';
12 years ago
});
$result = $this->dispatcher->run('hello', ['Bob']);
12 years ago
self::assertEquals('Hello, Fred! Have a nice day!', $result);
12 years ago
}
// Test an invalid callback
public function testInvalidCallback()
{
$this->expectException(Exception::class);
$this->dispatcher->execute(['NonExistentClass', 'nonExistentMethod']);
}
12 years ago
}