Skip to content

Commit dbbd702

Browse files
committed
Adding base capturing
1 parent b92041e commit dbbd702

File tree

2 files changed

+113
-0
lines changed

2 files changed

+113
-0
lines changed
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
<?php
2+
3+
namespace PHPMatcher\Matcher;
4+
5+
class CaptureMatcher implements PropertyMatcher, \ArrayAccess
6+
{
7+
const MATCH_PATTERN = "/^:.*:$/";
8+
9+
private $captures = array();
10+
11+
/**
12+
* {@inheritDoc}
13+
*/
14+
public function match($value, $pattern)
15+
{
16+
$this->captures[$this->extractPattern($pattern)] = $value;
17+
18+
return true;
19+
}
20+
21+
/**
22+
* {@inheritDoc}
23+
*/
24+
public function canMatch($pattern)
25+
{
26+
return is_string($pattern) && 0 !== preg_match(self::MATCH_PATTERN, $pattern);
27+
}
28+
29+
private function extractPattern($pattern)
30+
{
31+
return str_replace(":", "", $pattern);
32+
}
33+
34+
public function offsetSet($offset, $value)
35+
{
36+
if (is_null($offset)) {
37+
$this->captures[] = $value;
38+
} else {
39+
$this->captures[$offset] = $value;
40+
}
41+
}
42+
public function offsetExists($offset)
43+
{
44+
return isset($this->captures[$offset]);
45+
}
46+
47+
public function offsetUnset($offset)
48+
{
49+
unset($this->captures[$offset]);
50+
}
51+
52+
public function offsetGet($offset)
53+
{
54+
return isset($this->captures[$offset]) ? $this->captures[$offset] : null;
55+
}
56+
}
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
<?php
2+
namespace PHPMatcher\Tests\Matcher;
3+
4+
use PHPMatcher\Matcher\CaptureMatcher;
5+
6+
class CaptureMatcherTest extends \PHPUnit_Framework_TestCase
7+
{
8+
/**
9+
* @dataProvider positiveCanMatchData
10+
*/
11+
public function test_positive_can_matches($pattern)
12+
{
13+
$matcher = new CaptureMatcher();
14+
$this->assertTrue($matcher->canMatch($pattern));
15+
}
16+
17+
/**
18+
* @dataProvider negativeCanMatchData
19+
*/
20+
public function test_negative_can_matches($pattern)
21+
{
22+
$matcher = new CaptureMatcher();
23+
$this->assertFalse($matcher->canMatch($pattern));
24+
}
25+
26+
public function test_capturing()
27+
{
28+
$matcher = new CaptureMatcher();
29+
30+
$matcher->match(50, ':userId:');
31+
$matcher->match('1111-qqqq-eeee-xxxx', ':token:');
32+
$this->assertEquals($matcher['userId'], 50);
33+
$this->assertEquals($matcher['token'], '1111-qqqq-eeee-xxxx');
34+
}
35+
36+
public static function positiveCanMatchData()
37+
{
38+
return array(
39+
array(":id:"),
40+
array(":user_id:"),
41+
array(":foobar:")
42+
);
43+
}
44+
45+
public static function negativeCanMatchData()
46+
{
47+
return array(
48+
array(":user_id"),
49+
array("foobar"),
50+
array(1),
51+
array("user_id:"),
52+
array(new \stdClass),
53+
array(array("foobar"))
54+
);
55+
}
56+
57+
}

0 commit comments

Comments
 (0)