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