Subversion-Projekte lars-tiefland.laravel_shop

Revision

Details | Letzte Änderung | Log anzeigen | RSS feed

Revision Autor Zeilennr. Zeile
148 lars 1
<?php
2
namespace Hamcrest\Core;
3
 
4
/*
5
 Copyright (c) 2010 hamcrest.org
6
 */
7
use Hamcrest\BaseMatcher;
8
use Hamcrest\Description;
9
 
10
/**
11
 * Tests if a value (class, object, or array) has a named property.
12
 *
13
 * For example:
14
 * <pre>
15
 * assertThat(array('a', 'b'), set('b'));
16
 * assertThat($foo, set('bar'));
17
 * assertThat('Server', notSet('defaultPort'));
18
 * </pre>
19
 *
20
 * @todo Replace $property with a matcher and iterate all property names.
21
 */
22
class Set extends BaseMatcher
23
{
24
 
25
    private $_property;
26
    private $_not;
27
 
28
    public function __construct($property, $not = false)
29
    {
30
        $this->_property = $property;
31
        $this->_not = $not;
32
    }
33
 
34
    public function matches($item)
35
    {
36
        if ($item === null) {
37
            return false;
38
        }
39
        $property = $this->_property;
40
        if (is_array($item)) {
41
            $result = isset($item[$property]);
42
        } elseif (is_object($item)) {
43
            $result = isset($item->$property);
44
        } elseif (is_string($item)) {
45
            $result = isset($item::$$property);
46
        } else {
47
            throw new \InvalidArgumentException('Must pass an object, array, or class name');
48
        }
49
 
50
        return $this->_not ? !$result : $result;
51
    }
52
 
53
    public function describeTo(Description $description)
54
    {
55
        $description->appendText($this->_not ? 'unset property ' : 'set property ')->appendText($this->_property);
56
    }
57
 
58
    public function describeMismatch($item, Description $description)
59
    {
60
        $value = '';
61
        if (!$this->_not) {
62
            $description->appendText('was not set');
63
        } else {
64
            $property = $this->_property;
65
            if (is_array($item)) {
66
                $value = $item[$property];
67
            } elseif (is_object($item)) {
68
                $value = $item->$property;
69
            } elseif (is_string($item)) {
70
                $value = $item::$$property;
71
            }
72
            parent::describeMismatch($value, $description);
73
        }
74
    }
75
 
76
    /**
77
     * Matches if value (class, object, or array) has named $property.
78
     *
79
     * @factory
80
     */
81
    public static function set($property)
82
    {
83
        return new self($property);
84
    }
85
 
86
    /**
87
     * Matches if value (class, object, or array) does not have named $property.
88
     *
89
     * @factory
90
     */
91
    public static function notSet($property)
92
    {
93
        return new self($property, true);
94
    }
95
}