/** * {@inheritdoc} */ protected function describeRoute(Route $route, array $options = array()) { $tableHeaders = array('Property', 'Value'); $tableRows = array(array('Route Name', $options['name']), array('Path', $route->getPath()), array('Path Regex', $route->compile()->getRegex()), array('Host', '' !== $route->getHost() ? $route->getHost() : 'ANY'), array('Host Regex', '' !== $route->getHost() ? $route->compile()->getHostRegex() : ''), array('Scheme', $route->getSchemes() ? implode('|', $route->getSchemes()) : 'ANY'), array('Method', $route->getMethods() ? implode('|', $route->getMethods()) : 'ANY'), array('Requirements', $route->getRequirements() ? $this->formatRouterConfig($route->getRequirements()) : 'NO CUSTOM'), array('Class', get_class($route)), array('Defaults', $this->formatRouterConfig($route->getDefaults())), array('Options', $this->formatRouterConfig($route->getOptions()))); $table = new Table($this->getOutput()); $table->setHeaders($tableHeaders)->setRows($tableRows); $table->render(); }
public function handle(ApiDoc $annotation, array $annotations, Route $route, \ReflectionMethod $method) { // description if (null === $annotation->getDescription()) { $comments = explode("\n", $annotation->getDocumentation()); // just set the first line $comment = trim($comments[0]); $comment = preg_replace("#\n+#", ' ', $comment); $comment = preg_replace('#\\s+#', ' ', $comment); $comment = preg_replace('#[_`*]+#', '', $comment); if ('@' !== substr($comment, 0, 1)) { $annotation->setDescription($comment); } } // requirements $requirements = $annotation->getRequirements(); foreach ($route->getRequirements() as $name => $value) { if (!isset($requirements[$name]) && '_method' !== $name && '_scheme' !== $name) { $requirements[$name] = array('requirement' => $value, 'dataType' => '', 'description' => ''); } if ('_scheme' === $name) { $https = 'https' == $value; $annotation->setHttps($https); } } if (method_exists($route, 'getSchemes')) { $annotation->setHttps(in_array('https', $route->getSchemes())); } $paramDocs = array(); foreach (explode("\n", $this->commentExtractor->getDocComment($method)) as $line) { if (preg_match('{^@param (.+)}', trim($line), $matches)) { $paramDocs[] = $matches[1]; } if (preg_match('{^@deprecated\\b(.*)}', trim($line), $matches)) { $annotation->setDeprecated(true); } if (preg_match('{^@link\\b(.*)}', trim($line), $matches)) { $annotation->setLink($matches[1]); } } $regexp = '{(\\w*) *\\$%s\\b *(.*)}i'; foreach ($route->compile()->getVariables() as $var) { $found = false; foreach ($paramDocs as $paramDoc) { if (preg_match(sprintf($regexp, preg_quote($var)), $paramDoc, $matches)) { $requirements[$var]['dataType'] = isset($matches[1]) ? $matches[1] : ''; $requirements[$var]['description'] = $matches[2]; if (!isset($requirements[$var]['requirement'])) { $requirements[$var]['requirement'] = ''; } $found = true; break; } } if (!isset($requirements[$var]) && false === $found) { $requirements[$var] = array('requirement' => '', 'dataType' => '', 'description' => ''); } } $annotation->setRequirements($requirements); }
/** * {@inheritdoc} */ protected function describeRoute(Route $route, array $options = array()) { $requirements = $route->getRequirements(); unset($requirements['_scheme'], $requirements['_method']); // fixme: values were originally written as raw $description = array( '<comment>Path</comment> '.$route->getPath(), '<comment>Host</comment> '.('' !== $route->getHost() ? $route->getHost() : 'ANY'), '<comment>Scheme</comment> '.($route->getSchemes() ? implode('|', $route->getSchemes()) : 'ANY'), '<comment>Method</comment> '.($route->getMethods() ? implode('|', $route->getMethods()) : 'ANY'), '<comment>Class</comment> '.get_class($route), '<comment>Defaults</comment> '.$this->formatRouterConfig($route->getDefaults()), '<comment>Requirements</comment> '.$this->formatRouterConfig($requirements) ?: 'NO CUSTOM', '<comment>Options</comment> '.$this->formatRouterConfig($route->getOptions()), '<comment>Path-Regex</comment> '.$route->compile()->getRegex(), ); if (isset($options['name'])) { array_unshift($description, '<comment>Name</comment> '.$options['name']); array_unshift($description, $this->formatSection('router', sprintf('Route "%s"', $options['name']))); } if (null !== $route->compile()->getHostRegex()) { $description[] = '<comment>Host-Regex</comment> '.$route->compile()->getHostRegex(); } $this->writeText(implode("\n", $description)."\n", $options); }
/** * {@inheritdoc} */ protected function describeRoute(Route $route, array $options = array()) { $requirements = $route->getRequirements(); unset($requirements['_scheme'], $requirements['_method']); $output = '- Path: ' . $route->getPath() . "\n" . '- Host: ' . ('' !== $route->getHost() ? $route->getHost() : 'ANY') . "\n" . '- Scheme: ' . ($route->getSchemes() ? implode('|', $route->getSchemes()) : 'ANY') . "\n" . '- Method: ' . ($route->getMethods() ? implode('|', $route->getMethods()) : 'ANY') . "\n" . '- Class: ' . get_class($route) . "\n" . '- Defaults: ' . $this->formatRouterConfig($route->getDefaults()) . "\n" . '- Requirements: ' . $this->formatRouterConfig($requirements) ?: 'NONE' . "\n" . '- Options: ' . $this->formatRouterConfig($route->getOptions()) . "\n" . '- Path-Regex: ' . $route->compile()->getRegex(); $this->write(isset($options['name']) ? $options['name'] . "\n" . str_repeat('-', strlen($options['name'])) . "\n\n" . $output : $output); $this->write("\n"); }
public function testRequirements() { $route = new Route('/{foo}'); $route->setRequirements(array('foo' => '\\d+')); $this->assertEquals(array('foo' => '\\d+'), $route->getRequirements(), '->setRequirements() sets the requirements'); $this->assertEquals('\\d+', $route->getRequirement('foo'), '->getRequirement() returns a requirement'); $this->assertNull($route->getRequirement('bar'), '->getRequirement() returns null if a requirement is not defined'); $route->setRequirements(array('foo' => '^\\d+$')); $this->assertEquals('\\d+', $route->getRequirement('foo'), '->getRequirement() removes ^ and $ from the pattern'); $this->assertEquals($route, $route->setRequirements(array()), '->setRequirements() implements a fluent interface'); }
/** * {@inheritdoc} */ public function access(Route $route, RouteMatchInterface $route_match, AccountInterface $account) { // Backup the original requirements. $original_requirements = $route->getRequirements(); // Replace it with our entity access value and run the parent access check. $route->setRequirement('_entity_access', $route->getRequirement('_page_access')); $access = parent::access($route, $route_match, $account); // Restore the original requirements. $route->setRequirements($original_requirements); return $access; }
public function testRequirements() { $route = new Route('/{foo}'); $route->setRequirements(array('foo' => '\\d+')); $this->assertEquals(array('foo' => '\\d+'), $route->getRequirements(), '->setRequirements() sets the requirements'); $this->assertEquals('\\d+', $route->getRequirement('foo'), '->getRequirement() returns a requirement'); $this->assertNull($route->getRequirement('bar'), '->getRequirement() returns null if a requirement is not defined'); $route->setRequirements(array('foo' => '^\\d+$')); $this->assertEquals('\\d+', $route->getRequirement('foo'), '->getRequirement() removes ^ and $ from the pattern'); $this->assertEquals($route, $route->setRequirements(array()), '->setRequirements() implements a fluent interface'); // test that an array requirement throws an exception $this->setExpectedException('InvalidArgumentException'); $route->setRequirements(array('foo' => array('bar', 'baz'))); }
/** * {@inheritdoc} */ public function generate($name, $parameters = array(), $referenceType = self::ABSOLUTE_PATH) { try { if ($name instanceof SeoAwareInterface) { $documentUrl = $name->getUrl(); } else { throw new RouteNotFoundException(); } $type = $this->collector->getDocumentType(get_class($name)); $route = new Route($documentUrl, ['_controller' => $this->routeMap[$type], 'document' => $name, 'type' => $type]); // the Route has a cache of its own and is not recompiled as long as it does not get modified $compiledRoute = $route->compile(); $hostTokens = $compiledRoute->getHostTokens(); return $this->doGenerate($compiledRoute->getVariables(), $route->getDefaults(), $route->getRequirements(), $compiledRoute->getTokens(), $parameters, 'ongr_route', $referenceType, $hostTokens); } catch (\Exception $e) { throw new RouteNotFoundException('Document is not correct or route cannot be generated.'); } }
/** * Implements AccessCheckInterface::applies(). */ public function applies(Route $route) { $requirements = $route->getRequirements(); if (array_key_exists('_access_rest_csrf', $requirements)) { if (isset($requirements['_method'])) { // There could be more than one method requirement separated with '|'. $methods = explode('|', $requirements['_method']); // CSRF protection only applies to write operations, so we can filter // out any routes that require reading methods only. $write_methods = array_diff($methods, array('GET', 'HEAD', 'OPTIONS', 'TRACE')); if (empty($write_methods)) { return FALSE; } } // No method requirement given, so we run this access check to be on the // safe side. return TRUE; } }
/** * {@inheritdoc} */ public function generate($name, $parameters = array(), $referenceType = self::ABSOLUTE_PATH) { try { $document = $parameters['document']; if (is_object($document)) { $documentUrl = $document->url; } else { $documentUrl = $document['url']; } $type = $this->collector->getDocumentType(get_class($document)); $route = new Route($documentUrl, ['_controller' => $this->routeMap[$type], 'document' => $document, 'type' => $type]); // the Route has a cache of its own and is not recompiled as long as it does not get modified $compiledRoute = $route->compile(); $hostTokens = $compiledRoute->getHostTokens(); $debug_message = $this->getRouteDebugMessage($name); return $this->doGenerate($compiledRoute->getVariables(), $route->getDefaults(), $route->getRequirements(), $compiledRoute->getTokens(), $parameters, $debug_message, $referenceType, $hostTokens); } catch (\Exception $e) { throw new RouteNotFoundException('Document is not correct or route cannot be generated.'); } }
/** * {@inheritdoc} */ public function version(Operation $operation, Result $result, Route $route) { if (!$operation->hasParameter($this->parameter)) { return $operation; } $version = $operation->getParameter($this->parameter); $operation->removeParameter($this->parameter); if (!($versions = $version->getType()->getEnum())) { $requirements = $route->getRequirements(); $versions = array($requirements[$this->parameter]); } $operations = array(); foreach ($versions as $version) { $op = clone $operation; $op->setVersion($version); $op->setPath(str_replace(sprintf('{%s}', $this->parameter), $version, $op->getPath())); $operations[] = $op; } return count($operations) === 1 ? current($operations) : $operations; }
private function isAccessedAnonymously($routeName, Route $route) { if (!in_array('GET', $route->getMethods()) && $route->getMethods()) { return false; // GET method must be allowed } if (strpos($routeName, '_') === 0) { return false; // internal|private routes } $compiled = $route->compile(); $params = []; foreach ($compiled->getPathVariables() as $key) { $params[$key] = 'any'; // we do not care about it } foreach ($route->getRequirements() as $key => $regex) { $params[$key] = 'any'; // we do not care about it } foreach ($route->getDefaults() as $key => $default) { $params[$key] = $default; } if (!array_key_exists('_controller', $params)) { return false; // route is dynamic, should not be index by robots } $uri = $this->get('router')->generate($routeName, $params); // mock the request $request = Request::create('http://mock.com' . $uri); $request->setSession(new Session(new MockFileSessionStorage())); // run the request through security firewall $event = new GetResponseEvent($this->getApplication()->getKernel(), $request, HttpKernelInterface::MASTER_REQUEST); try { $this->get('security.firewall')->onKernelRequest($event); } catch (AccessDeniedException $e) { return false; // access is denied } return !$event->getResponse() instanceof RedirectResponse; }
/** * {@inheritdoc} */ public function applies(Route $route) { $requirements = $route->getRequirements(); // Check for current requirement _csrf_request_header_token and deprecated // REST requirement. $applicable_requirements = ['_csrf_request_header_token', '_access_rest_csrf']; $requirement_keys = array_keys($requirements); if (array_intersect($applicable_requirements, $requirement_keys)) { if (isset($requirements['_method'])) { // There could be more than one method requirement separated with '|'. $methods = explode('|', $requirements['_method']); // CSRF protection only applies to write operations, so we can filter // out any routes that require reading methods only. $write_methods = array_diff($methods, array('GET', 'HEAD', 'OPTIONS', 'TRACE')); if (empty($write_methods)) { return FALSE; } } // No method requirement given, so we run this access check to be on the // safe side. return TRUE; } }
/** * Gets the path of a route. * * @param \Symfony\Component\Routing\Route $route * The route object. * @param array $parameters * An array of parameters as passed to * \Symfony\Component\Routing\Generator\UrlGeneratorInterface::generate(). * * @return string * The url path corresponding to the route, without the base path. */ protected function getInternalPathFromRoute(SymfonyRoute $route, $parameters = array()) { // The Route has a cache of its own and is not recompiled as long as it does // not get modified. $compiledRoute = $route->compile(); $hostTokens = $compiledRoute->getHostTokens(); $route_requirements = $route->getRequirements(); // We need to bypass the doGenerate() method's handling of absolute URLs as // we handle that ourselves after processing the path. if (isset($route_requirements['_scheme'])) { unset($route_requirements['_scheme']); } $path = $this->doGenerate($compiledRoute->getVariables(), $route->getDefaults(), $route_requirements, $compiledRoute->getTokens(), $parameters, $route->getPath(), FALSE, $hostTokens); // The URL returned from doGenerate() will include the base path if there is // one (i.e., if running in a subdirectory) so we need to strip that off // before processing the path. $base_url = $this->context->getBaseUrl(); if (!empty($base_url) && strpos($path, $base_url) === 0) { $path = substr($path, strlen($base_url)); } return $path; }
/** * Set the requirements * * @param array $requirements * @return Route */ public function setRequirements(array $requirements) { parent::setRequirements($requirements); $this->requirements = parent::getRequirements(); return $this; }
/** * Determine which registered access checks apply to a route. * * @param \Symfony\Component\Routing\Route $route * The route to get list of access checks for. * * @return array * An array of service ids for the access checks that apply to passed * route. */ protected function applies(Route $route) { $checks = array(); // Iterate through map requirements from appliesTo() on access checkers. // Only iterate through all checkIds if this is not used. foreach ($route->getRequirements() as $key => $value) { if (isset($this->staticRequirementMap[$key])) { foreach ($this->staticRequirementMap[$key] as $service_id) { $checks[] = $service_id; } } } // Finally, see if any dynamic access checkers apply. foreach ($this->dynamicRequirementMap as $service_id) { if ($this->checks[$service_id]->applies($route)) { $checks[] = $service_id; } } return $checks; }
/** * get collection and id from route * * @param Route $route route to look at * @param string $value value of reference as URI * * @return array */ private function getDataFromRoute(Route $route, $value) { $collection = null; $id = null; $reqs = $route->getRequirements(); $keys = array_filter(array_keys($reqs), function ($req) { return substr($req, 0, 1) !== '_'; }); $params = array(); foreach ($keys as $key) { $params[$key] = $reqs[$key]; } $matches = []; if (preg_match($route->compile()->getRegex(), $value, $matches)) { $id = $matches['id']; list($routeService) = explode(':', $route->getDefault('_controller')); list($core, $bundle, , $name) = explode('.', $routeService); $serviceName = implode('.', [$core, $bundle, 'rest', $name, 'get']); $collection = array_search($serviceName, $this->mapping); } return [$collection, $id]; }
public function handle(ApiDoc $annotation, array $annotations, Route $route, \ReflectionMethod $method) { // description if (null === $annotation->getDescription()) { $comments = explode("\n", $annotation->getDocumentation()); // just set the first line $comment = trim($comments[0]); $comment = preg_replace("#\n+#", ' ', $comment); $comment = preg_replace('#\\s+#', ' ', $comment); $comment = preg_replace('#[_`*]+#', '', $comment); if ('@' !== substr($comment, 0, 1)) { $annotation->setDescription($comment); } } // schema if ($annotation->getSchema() !== null) { $path = 'file://' . realpath($this->schemaPath . $annotation->getSchema()); $properties = (array) json_decode(file_get_contents($path))->properties; $tab = []; foreach ($properties as $objectName => $property) { if (isset($property->properties)) { $tab = array_merge($tab, $annotation->schemaFormat($property->properties, $property->required, $objectName)); } else { $required = json_decode(file_get_contents($path))->required; $tab = array_merge($tab, $annotation->schemaFormat($properties, $required)); } } $annotation->setParameters($tab); } // requirements $requirements = $annotation->getRequirements(); foreach ($route->getRequirements() as $name => $value) { if (!isset($requirements[$name]) && '_method' !== $name && '_scheme' !== $name) { $requirements[$name] = array('requirement' => $value, 'dataType' => '', 'description' => ''); } if ('_scheme' === $name) { $https = 'https' == $value; $annotation->setHttps($https); } } if (method_exists($route, 'getSchemes')) { $annotation->setHttps(in_array('https', $route->getSchemes())); } $paramDocs = array(); foreach (explode("\n", $this->commentExtractor->getDocComment($method)) as $line) { if (preg_match('{^@param (.+)}', trim($line), $matches)) { $paramDocs[] = $matches[1]; } if (preg_match('{^@deprecated}', trim($line))) { $annotation->setDeprecated(true); } if (preg_match('{^@link (.+)}', trim($line), $matches)) { $annotation->setLink($matches[1]); } } $regexp = '{(\\w*) *\\$%s\\b *(.*)}i'; foreach ($route->compile()->getVariables() as $var) { $found = false; foreach ($paramDocs as $paramDoc) { if (preg_match(sprintf($regexp, preg_quote($var)), $paramDoc, $matches)) { $annotationRequirements = $annotation->getrequirements(); if (!isset($annotationRequirements[$var]['dataType'])) { $requirements[$var]['dataType'] = isset($matches[1]) ? $matches[1] : ''; } if (!isset($annotationRequirements[$var]['description'])) { $requirements[$var]['description'] = $matches[2]; } if (!isset($requirements[$var]['requirement']) && !isset($annotationRequirements[$var]['requirement'])) { $requirements[$var]['requirement'] = ''; } $found = true; break; } } if (!isset($requirements[$var]) && false === $found) { $requirements[$var] = array('requirement' => '', 'dataType' => '', 'description' => ''); } } $annotation->setRequirements($requirements); }
/** * @param Route $route route * * @return array<Parameter> */ private function extractParametersFromRoute(Route $route) { $requirements = $route->getRequirements(); unset($requirements['_method']); $parameters = array(); $pathRequirements = preg_match_all('/{[_a-zA-Z]*}*/', $route->getPath(), $matches); $pathRequirements = array_filter(array_map(function ($v) { return trim(substr($v, 1, -1)); }, $matches[0])); foreach ($pathRequirements as $requirement) { if (!array_key_exists($requirement, $requirements)) { $requirements[$requirement] = null; } } foreach ($requirements as $name => $data) { $type = new DataType\StringType(); $type->setRequired(true); if (preg_match('/([a-zA-Z0-9_-]\\|)*/', $data)) { // check for enum $type->setEnum(explode('|', $data)); } $parameters[] = new Parameter($name, 'path', $type); } return $parameters; }
/** * Removes some deprecated requirements which cause depreciation notices. * * @param Route $route * * @todo Remove when Symfony 3.0 is used. */ private function fixRequirements(Route $route) { $requirements = $route->getRequirements(); if (isset($requirements['_method'])) { unset($requirements['_method']); } if (isset($requirements['_scheme'])) { unset($requirements['_scheme']); } $route->setRequirements($requirements); }
/** * Makes a clone of the given Route object. * * @param Route $route * * @return Route */ public function cloneRoute(Route $route) { return new Route($route->getPath(), $route->getDefaults(), $route->getRequirements(), $route->getOptions(), $route->getHost(), $route->getSchemes(), $route->getMethods()); }
/** * Implements \Drupal\Core\Access\AccessCheckInterface::applies(). */ public function applies(Route $route) { return array_key_exists('_access_fullcalendar_update', $route->getRequirements()); }
/** * @param Route $route * * @return array */ protected function getRouteData(Route $route) { $requirements = $route->getRequirements(); unset($requirements['_scheme'], $requirements['_method']); return array('path' => $route->getPath(), 'pathRegex' => $route->compile()->getRegex(), 'host' => '' !== $route->getHost() ? $route->getHost() : 'ANY', 'hostRegex' => '' !== $route->getHost() ? $route->compile()->getHostRegex() : '', 'scheme' => $route->getSchemes() ? implode('|', $route->getSchemes()) : 'ANY', 'method' => $route->getMethods() ? implode('|', $route->getMethods()) : 'ANY', 'class' => get_class($route), 'defaults' => $route->getDefaults(), 'requirements' => $requirements ?: 'NO CUSTOM', 'options' => $route->getOptions()); }
/** * Returns the requirements. * * @return array * The requirements. */ public function getRequirements() { return $this->route->getRequirements(); }
/** * Asserts that a route object has the expected properties. * * @param \Symfony\Component\Routing\Route $route * The route to test. * @param string $expected_path * The expected path for the route. * @param array $expected_defaults * The expected defaults for the route. * @param array $expected_requirements * The expected requirements for the route. * @param array $expected_options * The expected options for the route. */ protected function assertMatchingRoute(Route $route, $expected_path, $expected_defaults, $expected_requirements, $expected_options) { $this->assertSame($expected_path, $route->getPath()); $this->assertSame($expected_defaults, $route->getDefaults()); $this->assertSame($expected_requirements, $route->getRequirements()); $this->assertSame($expected_options, $route->getOptions()); }
/** * Returns the requirements. * * @return array The requirements */ public function getRequirements($startingWith = null) { if (null === $startingWith) { return parent::getRequirements(); } return 'HTTP-' == $startingWith ? $this->_headerRequirements : array(); }