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 object it is evaluated for is an instance
13 * of a given class.
14 *
15 * The expected class name is passed in the constructor.
16 */
17class PHPUnit_Framework_Constraint_IsInstanceOf extends PHPUnit_Framework_Constraint
18{
19    /**
20     * @var string
21     */
22    protected $className;
23
24    /**
25     * @param string $className
26     */
27    public function __construct($className)
28    {
29        parent::__construct();
30        $this->className = $className;
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        return ($other instanceof $this->className);
44    }
45
46    /**
47     * Returns the description of the failure
48     *
49     * The beginning of failure messages is "Failed asserting that" in most
50     * cases. This method should return the second part of that sentence.
51     *
52     * @param mixed $other Evaluated value or object.
53     *
54     * @return string
55     */
56    protected function failureDescription($other)
57    {
58        return sprintf(
59            '%s is an instance of %s "%s"',
60            $this->exporter->shortenedExport($other),
61            $this->getType(),
62            $this->className
63        );
64    }
65
66    /**
67     * Returns a string representation of the constraint.
68     *
69     * @return string
70     */
71    public function toString()
72    {
73        return sprintf(
74            'is instance of %s "%s"',
75            $this->getType(),
76            $this->className
77        );
78    }
79
80    private function getType()
81    {
82        try {
83            $reflection = new ReflectionClass($this->className);
84            if ($reflection->isInterface()) {
85                return 'interface';
86            }
87        } catch (ReflectionException $e) {
88        }
89
90        return 'class';
91    }
92}
93