Skip to content

Commit 4f7349e

Browse files
committed
PHPLIB-141: Static method for immutable BadMethodCallException
1 parent c02f127 commit 4f7349e

File tree

3 files changed

+47
-4
lines changed

3 files changed

+47
-4
lines changed

src/Exception/BadMethodCallException.php

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,17 @@
44

55
class BadMethodCallException extends \BadMethodCallException implements Exception
66
{
7+
/**
8+
* Thrown when a mutable method is invoked on an immutable object.
9+
*
10+
* @param string $class Class name
11+
* @return self
12+
*/
13+
public static function classIsImmutable($class)
14+
{
15+
return new static(sprintf('%s is immutable', $class));
16+
}
17+
718
/**
819
* Thrown when accessing a result field on an unacknowledged write result.
920
*

src/Model/IndexInfo.php

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -151,21 +151,21 @@ public function offsetGet($key)
151151
* Not supported.
152152
*
153153
* @see http://php.net/arrayaccess.offsetset
154-
* @throws BadMethodCallException IndexInfo is immutable
154+
* @throws BadMethodCallException
155155
*/
156156
public function offsetSet($key, $value)
157157
{
158-
throw new BadMethodCallException('IndexInfo is immutable');
158+
throw BadMethodCallException::classIsImmutable(__CLASS__);
159159
}
160160

161161
/**
162162
* Not supported.
163163
*
164164
* @see http://php.net/arrayaccess.offsetunset
165-
* @throws BadMethodCallException IndexInfo is immutable
165+
* @throws BadMethodCallException
166166
*/
167167
public function offsetUnset($key)
168168
{
169-
throw new BadMethodCallException('IndexInfo is immutable');
169+
throw BadMethodCallException::classIsImmutable(__CLASS__);
170170
}
171171
}

tests/Model/IndexInfoTest.php

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -96,4 +96,36 @@ public function testDebugInfo()
9696
$info = new IndexInfo($expectedInfo);
9797
$this->assertSame($expectedInfo, $info->__debugInfo());
9898
}
99+
100+
/**
101+
* @expectedException MongoDB\Exception\BadMethodCallException
102+
* @expectedExceptionMessage MongoDB\Model\IndexInfo is immutable
103+
*/
104+
public function testOffsetSetCannotBeCalled()
105+
{
106+
$info = new IndexInfo([
107+
'v' => 1,
108+
'key' => ['x' => 1],
109+
'name' => 'x_1',
110+
'ns' => 'foo.bar',
111+
]);
112+
113+
$info['v'] = 2;
114+
}
115+
116+
/**
117+
* @expectedException MongoDB\Exception\BadMethodCallException
118+
* @expectedExceptionMessage MongoDB\Model\IndexInfo is immutable
119+
*/
120+
public function testOffsetUnsetCannotBeCalled()
121+
{
122+
$info = new IndexInfo([
123+
'v' => 1,
124+
'key' => ['x' => 1],
125+
'name' => 'x_1',
126+
'ns' => 'foo.bar',
127+
]);
128+
129+
unset($info['v']);
130+
}
99131
}

0 commit comments

Comments
 (0)