Skip to content

Commit 7aadb25

Browse files
phananlstrojny
authored andcommitted
feat: Add default value for with() (#194)
1 parent dbf8a44 commit 7aadb25

File tree

3 files changed

+22
-3
lines changed

3 files changed

+22
-3
lines changed

docs/functional-php.md

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -500,7 +500,9 @@ Functional PHP comes with a set of invocation helpers that ease calling function
500500

501501

502502
## with()
503-
Invoke a callback on a value if the value is not null
503+
Invoke a callback on a value if the value is not null.
504+
505+
``Function\with(mixed $value, callable $callback, bool $invokeValue = true, mixed $default = null): mixed``
504506

505507
```php
506508
<?php
@@ -516,6 +518,8 @@ $retval = with($value, function($value) {
516518
`with()` returns whatever the callback returns. In the above example
517519
`$retval` would be `'my_result'`.
518520

521+
If the value of `$value` is `null`, `with()` will return `$default` which defaults to be `null`.
522+
519523
## invoke_if()
520524

521525
``mixed Functional\invoke_if(mixed $object, string $methodName[, array $methodArguments, mixed $defaultValue])``

src/Functional/With.php

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,14 +18,15 @@
1818
* @param mixed $value
1919
* @param callable $callback
2020
* @param bool $invokeValue Set to false to not invoke $value if it is a callable. Will be removed in 2.0
21+
* @param mixed $default The default value to return if $value is null
2122
* @return mixed
2223
*/
23-
function with($value, callable $callback, $invokeValue = true)
24+
function with($value, callable $callback, $invokeValue = true, $default = null)
2425
{
2526
InvalidArgumentException::assertCallback($callback, __FUNCTION__, 2);
2627

2728
if ($value === null) {
28-
return null;
29+
return $default;
2930
}
3031

3132
if ($invokeValue && \is_callable($value)) {

tests/Functional/WithTest.php

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -62,4 +62,18 @@ public function testPassNonCallable()
6262
$this->expectArgumentError("Argument 2 passed to Functional\with() must be callable");
6363
with(null, 'undefinedFunction');
6464
}
65+
66+
public function testDefaultValue()
67+
{
68+
$this->assertSame(
69+
'foo',
70+
with(
71+
null,
72+
function () {
73+
},
74+
true,
75+
'foo'
76+
)
77+
);
78+
}
6579
}

0 commit comments

Comments
 (0)