Regex::setRouteRegexData()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 5
ccs 5
cts 5
cp 1
rs 9.4285
cc 2
eloc 3
nc 2
nop 3
crap 2
1
<?php
2
namespace Skansing\Escapology\RouteFileParser;
3
4
use \Skansing\Escapology\RouteFileParser;
5
6
class Regex implements RouteFileParser {
7
8
  const 
9
    VERB = 0,
10
    URI = 1,
11
    REGEX_PREFIX = '~^(?:',
12
    REGEX_SEPARATOR = '|',
13
    REGEX_AFFIX = ')$~';
14
15
  /**
16
   * Parses the passed route file and return a specialized array
17
   * 
18
   * @param  string $file Absolute path to the route file
19
   * @throws \Exception If $file is missing or empty
20
   * @return Array Lookup table for routes and a combined regex
21
   */
22 11
  public function digest($file)
23
  {
24 11
    $routesData = $this->getRoutesData($file);
25 9
    $routeRegexes = [];
26 9
    for($i = 0; $i < count($routesData) -1; ++$i) {
27 8
      $this->setRouteRegexData($routeRegexes, $routesData, $i);
28 8
      $routeRegexes[$routesData[$i][self::VERB]] .= $routesData[$i][self::URI] . self::REGEX_SEPARATOR;
29 8
    }
30 9
    $this->setRouteRegexData($routeRegexes, $routesData, $i);
31 9
    $routeRegexes[$routesData[$i][self::VERB]] .= $routesData[$i][self::URI];
32 9
    foreach($routeRegexes as $verb => $regex) {
33 9
      $routeRegexes[$verb] .= self::REGEX_AFFIX;   
34 9
    }
35
36 9
    return $routeRegexes;
37
  }
38
39
  /**
40
   * Gets the routes data and returns it
41
   *
42
   * @param $file
43
   * @throws \Exception If $file is missing or empty
44
   */
45 11
  private function getRoutesData($file) {
46 11
    if(file_exists($file) === false) {
47 1
      throw new \Exception('Route file not found.');
48
    }
49 10
    $routesData = require $file;
50 10
    if(empty($routesData)) {
51 1
      throw new \Exception('Route file is empty.');
52
    }
53
54 9
    return $routesData;
55
  }
56
57
  /**
58
   * Sets the group regex string with the constant REGEX_PREFIX between each route
59
   * 
60
   * @param array &$routeRegexes
61
   * @param array &$routesData
62
   * @param int $index
63
   */
64 9
  private function setRouteRegexData(&$routeRegexes, &$routesData, $index) {
65 9
     if(isset($routeRegexes[$routesData[$index][self::VERB]]) === false) {
66 9
        $routeRegexes[$routesData[$index][self::VERB]] = self::REGEX_PREFIX;
67 9
      }
68
  }
69
}