/** * Sets a route. * * @param string $method The route method, * @param string $uri The URI to route. * @param string $options The route options. * @return bool */ public static function add(string $method, string $uri, array $options) : bool { if (static::validateOptions($options)) { // Set module. if (!isset($options['module'])) { $options['module'] = static::$module; } // Set route. Repository::store($method, static::prefixed($uri), $options); return true; } return false; }
/** * @covers Repository */ public function testRepository() { Repository::store('get', 'about', ['controller' => 'pages', 'action' => 'about']); $stored = Repository::retrieve('get', 'about'); $removed = Repository::remove('get', 'about'); $this->assertInternalType('array', $stored); $this->assertArrayHasKey('controller', $stored); $this->assertArrayHasKey('action', $stored); $this->assertTrue($removed); Repository::store('post', 'login', ['controller' => 'account', 'action' => 'login']); $stored = Repository::retrieve('post', 'login'); $removed = Repository::remove('post', 'login'); $this->assertInternalType('array', $stored); $this->assertArrayHasKey('controller', $stored); $this->assertArrayHasKey('action', $stored); $this->assertTrue($removed); $stored = Repository::retrieve('get', 'notexist'); $removed = Repository::remove('get', 'notexist'); $this->assertInternalType('array', $stored); $this->assertEmpty($stored); $this->assertFalse($removed); }
/** * Rewrites the application routes. * * @return void */ private static function rewrite() { foreach (Repository::stored() as $method => $routes) { foreach ($routes as $uri => $options) { $segments = explode('/', $uri); $rewrite = false; foreach ($segments as $key => $segment) { $matches = []; // Get route URI segments we need to rewrite. preg_match('/\\(([0-9a-z]+)\\:([a-z]+)\\)/i', $segment, $matches); // Do we have matches? if (!empty($matches)) { // Get the real value for this segment and validate it // against the rule. $value = Uri::segment($key + 1); $rule = $matches[2]; $valid = false; // Validate the rule. if ($rule === 'numeric' && is_numeric($value)) { $valid = true; } else { if ($rule === 'any') { $valid = true; } } // If the segment is valid, assign the value. if ($valid === true) { $segments[$key] = $value; } // Add the parameters. if (!isset($options['parameters'])) { $options['parameters'] = [$value]; } else { array_push($options['parameters'], $value); } // We will need to rewrite this URL. $rewrite = true; } } // Do we need to rewrite the URI value. if ($rewrite) { // Remove the old URI. Repository::remove($method, $uri); // Add the new one. Repository::store($method, implode('/', $segments), $options); } } } }