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
11/**
12 * Constraint that asserts that the class it is evaluated for has a given
13 * attribute.
14 *
15 * The attribute name is passed in the constructor.
16 */
17class PHPUnit_Framework_Constraint_ClassHasAttribute extends PHPUnit_Framework_Constraint
18{
19    /**
20     * @var string
21     */
22    protected $attributeName;
23
24    /**
25     * @param string $attributeName
26     */
27    public function __construct($attributeName)
28    {
29        parent::__construct();
30        $this->attributeName = $attributeName;
31    }
32
33    /**
34     * Evaluates the constraint for parameter $other. Returns true if the
35     * constraint is met, false otherwise.
36     *
37     * @param mixed $other Value or object to evaluate.
38     *
39     * @return bool
40     */
41    protected function matches($other)
42    {
43        $class = new ReflectionClass($other);
44
45        return $class->hasProperty($this->attributeName);
46    }
47
48    /**
49     * Returns a string representation of the constraint.
50     *
51     * @return string
52     */
53    public function toString()
54    {
55        return sprintf(
56            'has attribute "%s"',
57            $this->attributeName
58        );
59    }
60
61    /**
62     * Returns the description of the failure
63     *
64     * The beginning of failure messages is "Failed asserting that" in most
65     * cases. This method should return the second part of that sentence.
66     *
67     * @param mixed $other Evaluated value or object.
68     *
69     * @return string
70     */
71    protected function failureDescription($other)
72    {
73        return sprintf(
74            '%sclass "%s" %s',
75            is_object($other) ? 'object of ' : '',
76            is_object($other) ? get_class($other) : $other,
77            $this->toString()
78        );
79    }
80}
81