| 148 |
lars |
1 |
<?php
|
|
|
2 |
namespace Hamcrest\Core;
|
|
|
3 |
|
|
|
4 |
/*
|
|
|
5 |
Copyright (c) 2009 hamcrest.org
|
|
|
6 |
*/
|
|
|
7 |
use Hamcrest\BaseMatcher;
|
|
|
8 |
use Hamcrest\Description;
|
|
|
9 |
use Hamcrest\Matcher;
|
|
|
10 |
|
|
|
11 |
/**
|
|
|
12 |
* Provides a custom description to another matcher.
|
|
|
13 |
*/
|
|
|
14 |
class DescribedAs extends BaseMatcher
|
|
|
15 |
{
|
|
|
16 |
|
|
|
17 |
private $_descriptionTemplate;
|
|
|
18 |
private $_matcher;
|
|
|
19 |
private $_values;
|
|
|
20 |
|
|
|
21 |
const ARG_PATTERN = '/%([0-9]+)/';
|
|
|
22 |
|
|
|
23 |
public function __construct($descriptionTemplate, Matcher $matcher, array $values)
|
|
|
24 |
{
|
|
|
25 |
$this->_descriptionTemplate = $descriptionTemplate;
|
|
|
26 |
$this->_matcher = $matcher;
|
|
|
27 |
$this->_values = $values;
|
|
|
28 |
}
|
|
|
29 |
|
|
|
30 |
public function matches($item)
|
|
|
31 |
{
|
|
|
32 |
return $this->_matcher->matches($item);
|
|
|
33 |
}
|
|
|
34 |
|
|
|
35 |
public function describeTo(Description $description)
|
|
|
36 |
{
|
|
|
37 |
$textStart = 0;
|
|
|
38 |
while (preg_match(self::ARG_PATTERN, $this->_descriptionTemplate, $matches, PREG_OFFSET_CAPTURE, $textStart)) {
|
|
|
39 |
$text = $matches[0][0];
|
|
|
40 |
$index = $matches[1][0];
|
|
|
41 |
$offset = $matches[0][1];
|
|
|
42 |
|
|
|
43 |
$description->appendText(substr($this->_descriptionTemplate, $textStart, $offset - $textStart));
|
|
|
44 |
$description->appendValue($this->_values[$index]);
|
|
|
45 |
|
|
|
46 |
$textStart = $offset + strlen($text);
|
|
|
47 |
}
|
|
|
48 |
|
|
|
49 |
if ($textStart < strlen($this->_descriptionTemplate)) {
|
|
|
50 |
$description->appendText(substr($this->_descriptionTemplate, $textStart));
|
|
|
51 |
}
|
|
|
52 |
}
|
|
|
53 |
|
|
|
54 |
/**
|
|
|
55 |
* Wraps an existing matcher and overrides the description when it fails.
|
|
|
56 |
*
|
|
|
57 |
* @factory ...
|
|
|
58 |
*/
|
|
|
59 |
public static function describedAs(/* $description, Hamcrest\Matcher $matcher, $values... */)
|
|
|
60 |
{
|
|
|
61 |
$args = func_get_args();
|
|
|
62 |
$description = array_shift($args);
|
|
|
63 |
$matcher = array_shift($args);
|
|
|
64 |
$values = $args;
|
|
|
65 |
|
|
|
66 |
return new self($description, $matcher, $values);
|
|
|
67 |
}
|
|
|
68 |
}
|