Completed
Push — master ( 31b0f1...a1a0e3 )
by Ronnie
11s
created

Regex::getRoutesData()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 11
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 3.576

Importance

Changes 1
Bugs 0 Features 0
Metric Value
dl 0
loc 11
ccs 3
cts 5
cp 0.6
rs 9.4285
c 1
b 0
f 0
cc 3
eloc 7
nc 3
nop 1
crap 3.576
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 9
  public function digest($file)
23
  {
24 2
    $routesData = $this->getRoutesData($file);
25 9
    $routeRegexes = [];
26
    for($i = 0; $i < count($routesData) -1; ++$i) {
27
      $this->setRouteRegexData($routeRegexes, $routesData, $i);
28 3
      $routeRegexes[$routesData[$i][self::VERB]] .= $routesData[$i][self::URI] . self::REGEX_SEPARATOR;
29 1
    }
30
    $this->setRouteRegexData($routeRegexes, $routesData, $i);
31 9
    $routeRegexes[$routesData[$i][self::VERB]] .= $routesData[$i][self::URI];
32
    foreach($routeRegexes as $verb => $regex) {
33 4
      $routeRegexes[$verb] .= self::REGEX_AFFIX;   
34
    }
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 10
  private function getRoutesData($file) {
46
    if(file_exists($file) === false) {
47
      throw new \Exception('Route file not found.');
48
    }
49
    $routesData = require $file;
50 10
    if(empty($routesData)) {
51
      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 4
  private function setRouteRegexData(&$routeRegexes, &$routesData, $index) {
65 1
     if(isset($routeRegexes[$routesData[$index][self::VERB]]) === false) {
66 4
        $routeRegexes[$routesData[$index][self::VERB]] = self::REGEX_PREFIX;
67
      }
68
  }
69
}