Skip to content

Commit 1a6ab37

Browse files
author
Halleck45
committed
tokenCollection is immutable, way to remove token from collection
1 parent c7b4711 commit 1a6ab37

File tree

2 files changed

+78
-3
lines changed

2 files changed

+78
-3
lines changed

src/Hal/Component/Token/TokenCollection.php

Lines changed: 33 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -134,13 +134,43 @@ public function asArray() {
134134

135135
/**
136136
* Replace token with another
137-
*
137+
*
138138
* @param $index
139139
* @param Token $token
140140
* @return $this
141141
*/
142142
public function replace($index, Token $token) {
143-
$this->tokens[$index] = $token;
144-
return $this;
143+
$tokens = $this->tokens;
144+
$tokens[$index] = $token;
145+
return new TokenCollection($tokens);
146+
}
147+
148+
/**
149+
* Remove part of tokens
150+
*
151+
* @param $index
152+
* @param null $end
153+
* @return TokenCollection
154+
*/
155+
public function remove($index, $end = null)
156+
{
157+
$tokens = $this->tokens;
158+
if (null === $end) {
159+
$end = $index;
160+
}
161+
for ($i = $index; $i <= $end; $i++) {
162+
unset($tokens[$i]);
163+
}
164+
return new TokenCollection(array_values($tokens));
165+
}
166+
167+
/**
168+
* Get token by its index
169+
*
170+
* @param $index
171+
* @return null|Token
172+
*/
173+
public function get($index) {
174+
return isset($this->tokens[$index]) ? $this->tokens[$index] : null;
145175
}
146176
}
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
<?php
2+
namespace Test\Hal\Component\Token;
3+
4+
use Hal\Component\Token\Token;
5+
use Hal\Component\Token\TokenCollection;
6+
7+
/**
8+
* @group token
9+
*/
10+
class TokenCollectionTest extends \PHPUnit_Framework_TestCase {
11+
12+
13+
private $tokens;
14+
15+
public function __construct() {
16+
$this->tokens = new TokenCollection(array(
17+
array(T_STRING, 'a')
18+
, array(T_STRING, 'b')
19+
, array(T_STRING, 'c')
20+
));
21+
}
22+
23+
public function testICanCountTokens() {
24+
$this->assertEquals(3, sizeof($this->tokens, COUNT_NORMAL));
25+
}
26+
27+
public function testTokenCollectionIsImmutable() {
28+
$instance = $this->tokens->remove(0);
29+
$this->assertFalse($instance === $this->tokens);
30+
31+
$instance = $this->tokens->replace(0, new Token(array(T_STRING, 'abc')));
32+
$this->assertFalse($instance === $this->tokens);
33+
}
34+
35+
public function testICanGetTokenByIndex() {
36+
$this->assertInstanceOf('\Hal\Component\Token\Token', $this->tokens->get(0));
37+
}
38+
39+
public function testICanExtractPartOfCollection() {
40+
$instance = $this->tokens->extract(0, 2);
41+
$this->assertEquals(2, $instance->count());
42+
$this->assertFalse($instance === $this->tokens);
43+
44+
}
45+
}

0 commit comments

Comments
 (0)