1<?php
2/*
3 * This file is part of PHPUnit.
4 *
5 * (c) Sebastian Bergmann <sebastian@phpunit.de>
6 *
7 * For the full copyright and license information, please view the LICENSE
8 * file that was distributed with this source code.
9 */
10
11class PHPUnit_Framework_Constraint_ExceptionMessageRegExp extends PHPUnit_Framework_Constraint
12{
13    /**
14     * @var int
15     */
16    protected $expectedMessageRegExp;
17
18    /**
19     * @param string $expected
20     */
21    public function __construct($expected)
22    {
23        parent::__construct();
24        $this->expectedMessageRegExp = $expected;
25    }
26
27    /**
28     * Evaluates the constraint for parameter $other. Returns true if the
29     * constraint is met, false otherwise.
30     *
31     * @param Exception $other
32     *
33     * @return bool
34     */
35    protected function matches($other)
36    {
37        $match = PHPUnit_Util_Regex::pregMatchSafe($this->expectedMessageRegExp, $other->getMessage());
38
39        if (false === $match) {
40            throw new PHPUnit_Framework_Exception(
41                "Invalid expected exception message regex given: '{$this->expectedMessageRegExp}'"
42            );
43        }
44
45        return 1 === $match;
46    }
47
48    /**
49     * Returns the description of the failure
50     *
51     * The beginning of failure messages is "Failed asserting that" in most
52     * cases. This method should return the second part of that sentence.
53     *
54     * @param mixed $other Evaluated value or object.
55     *
56     * @return string
57     */
58    protected function failureDescription($other)
59    {
60        return sprintf(
61            "exception message '%s' matches '%s'",
62            $other->getMessage(),
63            $this->expectedMessageRegExp
64        );
65    }
66
67    /**
68     * @return string
69     */
70    public function toString()
71    {
72        return 'exception message matches ';
73    }
74}
75