File: Set.php

package info (click to toggle)
php-hamcrest 2.1.1-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,168 kB
  • sloc: php: 6,353; makefile: 14; sh: 9
file content (95 lines) | stat: -rw-r--r-- 2,408 bytes parent folder | download | duplicates (5)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
<?php
namespace Hamcrest\Core;

/*
 Copyright (c) 2010 hamcrest.org
 */
use Hamcrest\BaseMatcher;
use Hamcrest\Description;

/**
 * Tests if a value (class, object, or array) has a named property.
 *
 * For example:
 * <pre>
 * assertThat(array('a', 'b'), set('b'));
 * assertThat($foo, set('bar'));
 * assertThat('Server', notSet('defaultPort'));
 * </pre>
 *
 * @todo Replace $property with a matcher and iterate all property names.
 */
class Set extends BaseMatcher
{

    private $_property;
    private $_not;

    public function __construct($property, $not = false)
    {
        $this->_property = $property;
        $this->_not = $not;
    }

    public function matches($item)
    {
        if ($item === null) {
            return false;
        }
        $property = $this->_property;
        if (is_array($item)) {
            $result = isset($item[$property]);
        } elseif (is_object($item)) {
            $result = isset($item->$property);
        } elseif (is_string($item)) {
            $result = isset($item::$$property);
        } else {
            throw new \InvalidArgumentException('Must pass an object, array, or class name');
        }

        return $this->_not ? !$result : $result;
    }

    public function describeTo(Description $description)
    {
        $description->appendText($this->_not ? 'unset property ' : 'set property ')->appendText($this->_property);
    }

    public function describeMismatch($item, Description $description)
    {
        $value = '';
        if (!$this->_not) {
            $description->appendText('was not set');
        } else {
            $property = $this->_property;
            if (is_array($item)) {
                $value = $item[$property];
            } elseif (is_object($item)) {
                $value = $item->$property;
            } elseif (is_string($item)) {
                $value = $item::$$property;
            }
            parent::describeMismatch($value, $description);
        }
    }

    /**
     * Matches if value (class, object, or array) has named $property.
     *
     * @factory
     */
    public static function set($property)
    {
        return new self($property);
    }

    /**
     * Matches if value (class, object, or array) does not have named $property.
     *
     * @factory
     */
    public static function notSet($property)
    {
        return new self($property, true);
    }
}