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 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155
<?php
namespace ICanBoogie\Module;
use ICanBoogie\HTTP\Request;
use ICanBoogie\Module;
use ICanBoogie\Operation;
use ICanBoogie\Routing\Route;
use ICanBoogie\Routing\RouteCollection;
use function ICanBoogie\camelize;
class ModuleOperationDispatcher extends Operation\OperationRouteDispatcher
{
private $modules;
public function __construct(RouteCollection $routes, ModuleCollection $modules)
{
$this->modules = $modules;
parent::__construct($routes);
}
protected function resolve_route(Request $request, $normalized_path, array &$captured)
{
return parent::resolve_route($request, $normalized_path, $captured)
?: $this->resolve_module_route($request, $normalized_path, $captured);
}
protected function resolve_module_route(Request $request, $normalized_path, array &$captured)
{
$parsed_path = $this->parse_path($normalized_path);
if ($parsed_path === false)
{
return null;
}
list($module, $operation_name, $operation_key) = $parsed_path;
$operation_class = $this->resolve_operation_class($operation_name, $module);
if (!$operation_class)
{
return null;
}
$captured[Operation::KEY] = $operation_key;
$pattern = $operation_key
? sprintf('/api/:%s/:%s/:%s', Operation::DESTINATION, Operation::KEY, Operation::NAME)
: sprintf('/api/:%s/:%s', Operation::DESTINATION, Operation::NAME);
return Route::from([
ModuleRouteDefinition::PATTERN => $pattern,
ModuleRouteDefinition::CONTROLLER => $operation_class,
ModuleRouteDefinition::MODULE => $module->id,
ModuleRouteDefinition::VIA => $request->method
]);
}
protected function parse_path($path)
{
if (strpos($path, Operation::RESTFUL_BASE) !== 0)
{
return false;
}
$parts = explode('/', trim($path, '/'));
array_shift($parts);
$n = count($parts);
if ($n < 2 || $n > 4)
{
return false;
}
$operation_key = null;
if ($n === 2)
{
list($module_id, $operation_name) = $parts;
}
else
{
list($module_id, $operation_key, $operation_name) = $parts;
}
$modules = $this->modules;
if (!isset($modules[$module_id]))
{
return false;
}
return [ $modules[$module_id], $operation_name, $operation_key ];
}
protected function resolve_operation_class($operation_name, Module $module)
{
$unqualified_class_name = 'Operation\\' . camelize(strtr($operation_name, '-', '_')) . 'Operation';
return $this->modules->resolve_classname($unqualified_class_name, $module);
}
}