Move::process()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 15
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 15
ccs 9
cts 9
cp 1
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 10
nc 2
nop 2
crap 2
1
<?php
2
3
  declare(strict_types=1);
4
5
  namespace Funivan\PhpTokenizer\Strategy;
6
7
  use Funivan\PhpTokenizer\Exception\InvalidArgumentException;
8
9
  /**
10
   * Move forward or backward in collection with relative position
11
   *
12
   * Move forward 12 steps
13
   * ```
14
   * $result = (new Move(12))->process($collection, 1);
15
   * ```
16
   *
17
   * Move backward 10 steps
18
   * ```
19
   * $result = (new Move(-10))->process($collection, 1);
20
   * ```
21
   *
22
   *
23
   */
24
  class Move implements StrategyInterface {
25
26
27
    /**
28
     * @var int
29
     */
30
    protected $steps;
31
32
    /**
33
     * @var int
34
     */
35
    protected $direction;
36
37
38
    /**
39
     * @param int $steps
40
     * @return static
41
     */
42 21
    public static function create($steps) {
43 21
      return new static($steps);
44
    }
45
46
47
    /**
48
     * You can pass positive and negative numbers
49
     * Positive - move forward
50
     * Negative - move backward
51
     *
52
     * @param int $steps
53
     */
54 21
    public function __construct($steps) {
55
56 21
      if (!is_int($steps)) {
57 3
        throw new InvalidArgumentException('Invalid steps. Expect integer. Given: ' . gettype($steps));
58
      }
59
60 18
      $this->steps = $steps;
61
62 18
    }
63
64
65
    /**
66
     * @inheritdoc
67
     */
68 18
    public function process(\Funivan\PhpTokenizer\Collection $collection, $currentIndex) {
69 18
      $result = new StrategyResult();
70
71 18
      $endIndex = $currentIndex + $this->steps;
72
73 18
      $result->setNexTokenIndex($endIndex);
74 18
      if (isset($collection[$endIndex])) {
75 18
        $result->setValid(true);
76 18
        $result->setToken($collection[$endIndex]);
77
      } else {
78 9
        $result->setValid(false);
79
      }
80
81 18
      return $result;
82
    }
83
84
  }