RouteCompiler.php 1.74 KB
Newer Older
Crell's avatar
Crell committed
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
<?php

namespace Drupal\Core\Routing;

use Symfony\Component\Routing\RouteCompilerInterface;
use Symfony\Component\Routing\Route;

/**
 * Description of RouteCompiler
 */
class RouteCompiler implements RouteCompilerInterface {

  /**
   * The maximum number of path elements for a route pattern;
   */
  const MAX_PARTS = 9;

  /**
    * Compiles the current route instance.
    *
    * @param Route $route
    *   A Route instance
    *
    * @return CompiledRoute
    *   A CompiledRoute instance
    */
  public function compile(Route $route) {


    $fit = $this->getFit($route->getPattern());

32
33
34
    $pattern_outline = $this->getPatternOutline($route->getPattern());

    return new CompiledRoute($route, $fit, $pattern_outline);
Crell's avatar
Crell committed
35
36
37

  }

38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
  /**
   * Returns the pattern outline.
   *
   * The pattern outline is the path pattern but normalized so that all
   * placeholders are equal strings.
   *
   * @param string $path
   *   The path pattern to normalize to an outline.
   *
   * @return string
   *   The path pattern outline.
   */
  public function getPatternOutline($path) {
    return preg_replace('#\{\w+\}#', '%', $path);
  }
Crell's avatar
Crell committed
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

  /**
   * Determines the fitness of the provided path.
   *
   * @param string $path
   *   The path whose fitness we want.
   *
   * @return int
   *   The fitness of the path, as an integer.
   */
  public function getFit($path) {

    $parts = explode('/', trim($path, '/'), static::MAX_PARTS);
    $number_parts = count($parts);
    // We store the highest index of parts here to save some work in the fit
    // calculation loop.
    $slashes = $number_parts - 1;

    $fit = 0;
    foreach ($parts as $k => $part) {
      if (strpos($part, '{') === FALSE) {
        $fit |=  1 << ($slashes - $k);
      }
    }

    return $fit;
  }
}