Skip to content

Commit

Permalink
Adding base capturing
Browse files Browse the repository at this point in the history
  • Loading branch information
defrag committed Apr 20, 2014
1 parent b92041e commit dbbd702
Show file tree
Hide file tree
Showing 2 changed files with 113 additions and 0 deletions.
56 changes: 56 additions & 0 deletions src/PHPMatcher/Matcher/CaptureMatcher.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
<?php

namespace PHPMatcher\Matcher;

class CaptureMatcher implements PropertyMatcher, \ArrayAccess
{
const MATCH_PATTERN = "/^:.*:$/";

private $captures = array();

/**
* {@inheritDoc}
*/
public function match($value, $pattern)
{
$this->captures[$this->extractPattern($pattern)] = $value;

return true;
}

/**
* {@inheritDoc}
*/
public function canMatch($pattern)
{
return is_string($pattern) && 0 !== preg_match(self::MATCH_PATTERN, $pattern);
}

private function extractPattern($pattern)
{
return str_replace(":", "", $pattern);
}

public function offsetSet($offset, $value)
{
if (is_null($offset)) {
$this->captures[] = $value;
} else {
$this->captures[$offset] = $value;
}
}
public function offsetExists($offset)
{
return isset($this->captures[$offset]);
}

public function offsetUnset($offset)
{
unset($this->captures[$offset]);
}

public function offsetGet($offset)
{
return isset($this->captures[$offset]) ? $this->captures[$offset] : null;
}
}
57 changes: 57 additions & 0 deletions tests/PHPMatcher/Matcher/CaptureMatcherTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
<?php
namespace PHPMatcher\Tests\Matcher;

use PHPMatcher\Matcher\CaptureMatcher;

class CaptureMatcherTest extends \PHPUnit_Framework_TestCase
{
/**
* @dataProvider positiveCanMatchData
*/
public function test_positive_can_matches($pattern)
{
$matcher = new CaptureMatcher();
$this->assertTrue($matcher->canMatch($pattern));
}

/**
* @dataProvider negativeCanMatchData
*/
public function test_negative_can_matches($pattern)
{
$matcher = new CaptureMatcher();
$this->assertFalse($matcher->canMatch($pattern));
}

public function test_capturing()
{
$matcher = new CaptureMatcher();

$matcher->match(50, ':userId:');
$matcher->match('1111-qqqq-eeee-xxxx', ':token:');
$this->assertEquals($matcher['userId'], 50);
$this->assertEquals($matcher['token'], '1111-qqqq-eeee-xxxx');
}

public static function positiveCanMatchData()
{
return array(
array(":id:"),
array(":user_id:"),
array(":foobar:")
);
}

public static function negativeCanMatchData()
{
return array(
array(":user_id"),
array("foobar"),
array(1),
array("user_id:"),
array(new \stdClass),
array(array("foobar"))
);
}

}

0 comments on commit dbbd702

Please sign in to comment.