Skip to content

Commit d66b0bd

Browse files
committed
Merge branch 'develop'
* develop: specify next release add shortcut to define optional keys on a shape
2 parents 7932fe6 + 0ce52c3 commit d66b0bd

File tree

3 files changed

+40
-2
lines changed

3 files changed

+40
-2
lines changed

CHANGELOG.md

+6
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,11 @@
11
# Changelog
22

3+
## 1.2.0 - 2024-03-05
4+
5+
### Added
6+
7+
- You can now do `Shape::of(...)->optional('key', $constraint)` instead of `Shape::of(...)->with('key', $constraint)->optional('key')` thus avoiding to repeat the key name
8+
39
## 1.1.1 - 2024-02-24
410

511
### Fixed

proofs/shape.php

+27
Original file line numberDiff line numberDiff line change
@@ -132,4 +132,31 @@ static function($assert) {
132132
);
133133
},
134134
);
135+
136+
yield test(
137+
'Shape with optional key with constraint directly specified',
138+
static function($assert) {
139+
$assert->true(
140+
Shape::of('foo', Is::int())
141+
->optional('bar', Is::bool())
142+
->asPredicate()([
143+
'foo' => 42,
144+
]),
145+
);
146+
$assert->same(
147+
[
148+
'foo' => 42,
149+
],
150+
Shape::of('foo', Is::int())
151+
->optional('bar', Is::bool())([
152+
'foo' => 42,
153+
'baz' => 'invalid',
154+
])
155+
->match(
156+
static fn($value) => $value,
157+
static fn() => null,
158+
),
159+
);
160+
},
161+
);
135162
};

src/Shape.php

+7-2
Original file line numberDiff line numberDiff line change
@@ -94,12 +94,17 @@ public function with(string $key, Constraint $constraint): self
9494
/**
9595
* @param non-empty-string $key
9696
*/
97-
public function optional(string $key): self
97+
public function optional(string $key, Constraint $constraint = null): self
9898
{
9999
$optional = $this->optional;
100100
$optional[] = $key;
101+
$constraints = $this->constraints;
102+
103+
if ($constraint instanceof Constraint) {
104+
$constraints[$key] = $constraint;
105+
}
101106

102-
return new self($this->constraints, $optional);
107+
return new self($constraints, $optional);
103108
}
104109

105110
public function and(Constraint $constraint): Constraint

0 commit comments

Comments
 (0)