| 1 | <?php |
||
| 10 | class Fibonacci extends Combinatorics implements \Iterator, \Countable |
||
| 11 | { |
||
| 12 | /** |
||
| 13 | * The maximum limit. |
||
| 14 | * |
||
| 15 | * @var int |
||
| 16 | */ |
||
| 17 | protected $max; |
||
| 18 | |||
| 19 | /** |
||
| 20 | * The previous element. |
||
| 21 | * |
||
| 22 | * @var int |
||
| 23 | */ |
||
| 24 | private $previous = 1; |
||
| 25 | |||
| 26 | /** |
||
| 27 | * The current element. |
||
| 28 | * |
||
| 29 | * @var int |
||
| 30 | */ |
||
| 31 | private $current = 0; |
||
| 32 | |||
| 33 | /** |
||
| 34 | * The current key. |
||
| 35 | * |
||
| 36 | * @var int |
||
| 37 | */ |
||
| 38 | private $key = 0; |
||
| 39 | |||
| 40 | /** |
||
| 41 | * Fibonacci constructor. |
||
| 42 | */ |
||
| 43 | 2 | public function __construct() |
|
| 44 | { |
||
| 45 | 2 | $this->setMaxLimit(PHP_INT_MAX); |
|
| 46 | 2 | } |
|
| 47 | |||
| 48 | /** |
||
| 49 | * {@inheritdoc} |
||
| 50 | */ |
||
| 51 | 2 | public function current() |
|
| 52 | { |
||
| 53 | 2 | return $this->current; |
|
| 54 | } |
||
| 55 | |||
| 56 | /** |
||
| 57 | * {@inheritdoc} |
||
| 58 | */ |
||
| 59 | public function key() |
||
| 60 | { |
||
| 61 | return $this->key; |
||
| 62 | } |
||
| 63 | |||
| 64 | /** |
||
| 65 | * {@inheritdoc} |
||
| 66 | */ |
||
| 67 | 2 | public function next() |
|
| 68 | { |
||
| 69 | 2 | list($this->current, $this->previous) = [$this->current + $this->previous, $this->current]; |
|
| 70 | 2 | ++$this->key; |
|
| 71 | 2 | } |
|
| 72 | |||
| 73 | /** |
||
| 74 | * {@inheritdoc} |
||
| 75 | */ |
||
| 76 | 2 | public function rewind() |
|
| 77 | { |
||
| 78 | 2 | $this->previous = 1; |
|
| 79 | 2 | $this->current = 0; |
|
| 80 | 2 | $this->key = 0; |
|
| 81 | 2 | } |
|
| 82 | |||
| 83 | /** |
||
| 84 | * {@inheritdoc} |
||
| 85 | */ |
||
| 86 | 2 | public function valid() |
|
| 87 | { |
||
| 88 | 2 | return $this->current < $this->getMaxLimit(); |
|
| 89 | } |
||
| 90 | |||
| 91 | /** |
||
| 92 | * {@inheritdoc} |
||
| 93 | */ |
||
| 94 | 2 | public function count() |
|
| 95 | { |
||
| 96 | 2 | return count($this->toArray()); |
|
| 97 | } |
||
| 98 | |||
| 99 | /** |
||
| 100 | * Convert the iterator into an array. |
||
| 101 | * |
||
| 102 | * @return array |
||
| 103 | * The elements |
||
| 104 | */ |
||
| 105 | 2 | public function toArray() |
|
| 115 | |||
| 116 | /** |
||
| 117 | * Set the maximum limit. |
||
| 118 | * |
||
| 119 | * @param int $max |
||
| 120 | * The limit |
||
| 121 | */ |
||
| 122 | 2 | public function setMaxLimit($max) |
|
| 126 | |||
| 127 | /** |
||
| 128 | * Get the maximum limit. |
||
| 129 | * |
||
| 130 | * @return int |
||
| 131 | * The limit |
||
| 132 | */ |
||
| 133 | 2 | public function getMaxLimit() |
|
| 137 | } |
||
| 138 |