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 Traversable it is applied to contains
13 * only values of a given type.
14 */
15class PHPUnit_Framework_Constraint_TraversableContainsOnly extends PHPUnit_Framework_Constraint
16{
17    /**
18     * @var PHPUnit_Framework_Constraint
19     */
20    protected $constraint;
21
22    /**
23     * @var string
24     */
25    protected $type;
26
27    /**
28     * @param string $type
29     * @param bool   $isNativeType
30     */
31    public function __construct($type, $isNativeType = true)
32    {
33        parent::__construct();
34
35        if ($isNativeType) {
36            $this->constraint = new PHPUnit_Framework_Constraint_IsType($type);
37        } else {
38            $this->constraint = new PHPUnit_Framework_Constraint_IsInstanceOf(
39                $type
40            );
41        }
42
43        $this->type = $type;
44    }
45
46    /**
47     * Evaluates the constraint for parameter $other
48     *
49     * If $returnResult is set to false (the default), an exception is thrown
50     * in case of a failure. null is returned otherwise.
51     *
52     * If $returnResult is true, the result of the evaluation is returned as
53     * a boolean value instead: true in case of success, false in case of a
54     * failure.
55     *
56     * @param mixed  $other        Value or object to evaluate.
57     * @param string $description  Additional information about the test
58     * @param bool   $returnResult Whether to return a result or throw an exception
59     *
60     * @return mixed
61     *
62     * @throws PHPUnit_Framework_ExpectationFailedException
63     */
64    public function evaluate($other, $description = '', $returnResult = false)
65    {
66        $success = true;
67
68        foreach ($other as $item) {
69            if (!$this->constraint->evaluate($item, '', true)) {
70                $success = false;
71                break;
72            }
73        }
74
75        if ($returnResult) {
76            return $success;
77        }
78
79        if (!$success) {
80            $this->fail($other, $description);
81        }
82    }
83
84    /**
85     * Returns a string representation of the constraint.
86     *
87     * @return string
88     */
89    public function toString()
90    {
91        return 'contains only values of type "' . $this->type . '"';
92    }
93}
94