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 string it is evaluated for contains
13 * a given string.
14 *
15 * Uses mb_strpos() to find the position of the string in the input, if not
16 * found the evaluation fails.
17 *
18 * The sub-string is passed in the constructor.
19 */
20class PHPUnit_Framework_Constraint_StringContains extends PHPUnit_Framework_Constraint
21{
22    /**
23     * @var string
24     */
25    protected $string;
26
27    /**
28     * @var bool
29     */
30    protected $ignoreCase;
31
32    /**
33     * @param string $string
34     * @param bool   $ignoreCase
35     */
36    public function __construct($string, $ignoreCase = false)
37    {
38        parent::__construct();
39
40        $this->string     = $string;
41        $this->ignoreCase = $ignoreCase;
42    }
43
44    /**
45     * Evaluates the constraint for parameter $other. Returns true if the
46     * constraint is met, false otherwise.
47     *
48     * @param mixed $other Value or object to evaluate.
49     *
50     * @return bool
51     */
52    protected function matches($other)
53    {
54        if ($this->ignoreCase) {
55            return mb_stripos($other, $this->string) !== false;
56        } else {
57            return mb_strpos($other, $this->string) !== false;
58        }
59    }
60
61    /**
62     * Returns a string representation of the constraint.
63     *
64     * @return string
65     */
66    public function toString()
67    {
68        if ($this->ignoreCase) {
69            $string = mb_strtolower($this->string);
70        } else {
71            $string = $this->string;
72        }
73
74        return sprintf(
75            'contains "%s"',
76            $string
77        );
78    }
79}
80