Skip to content

Commit 0c8a8bd

Browse files
Merge pull request #42 from chrjean/master
add ifSetOr function
2 parents d626871 + 6b1fde6 commit 0c8a8bd

File tree

3 files changed

+54
-0
lines changed

3 files changed

+54
-0
lines changed

README.md

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@ Funct\firstValueNotEmpty($a, $b, $c)
3232
* [false](#falsevalue)
3333
* [firstValue](#firstvaluevaluea)
3434
* [firstValueNotEmpty](#firstvaluenotemptyvaluea-valueb)
35+
* [ifSetOr](#ifSetOr)
3536
* [notEmpty](#notemptyvalue)
3637
* [notInArray](#notinarrayneedle-haystack-strict--null)
3738
* [notNull](#notnullvalue)
@@ -222,6 +223,15 @@ Funct\firstValueNotEmpty('', 'foo_bar'); // => 'foo_bar'
222223
Funct\firstValueNotEmpty('', null, 'foo_bar'); // => 'foo_bar'
223224
```
224225

226+
### ifSetOr($value, $default)
227+
Return the first param if isset or the second one or null if it doesn't
228+
229+
```PHP
230+
$bar = 'bar';
231+
Funct\ifSetOr($foo); // => 'NULL'
232+
Funct\ifSetOr($foo, 'foo_bar'); // => 'foo_bar'
233+
Funct\ifSetOr($bar, 'foo_bar'); // => 'bar' ($bar value)
234+
```
225235

226236
### notEmpty($value)
227237

src/General.php

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -153,3 +153,20 @@ function true($value)
153153
{
154154
return true === $value;
155155
}
156+
157+
158+
/**
159+
* Returns the first param if isset or the second one or null if it doesn't
160+
*
161+
* @param mixed $value
162+
* @param mixed $default
163+
* @return mixed
164+
* @author Christophe Jean <cj@myjob.company>
165+
*/
166+
function ifSetOr(&$value, $default = null)
167+
{
168+
if (isset($value)) {
169+
return $value;
170+
}
171+
return $default;
172+
}

src/Tests/IfSetOrTest.php

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
<?php
2+
3+
namespace Funct\Tests;
4+
5+
use Funct as Funct;
6+
7+
/**
8+
* Class IfSetOrTest
9+
*
10+
* @package Funct\Tests
11+
* @author Christophe Jean <cj@myjob.company>
12+
*/
13+
class IfSetOrTest extends \PHPUnit_Framework_TestCase
14+
{
15+
public function testIsNotSet()
16+
{
17+
$this->assertNull(Funct\ifSetOr($foo));
18+
$this->assertEquals('bar', Funct\ifSetOr($foo2, 'bar'));
19+
}
20+
21+
public function testIsSet()
22+
{
23+
$foo = 'foo';
24+
$this->assertEquals('foo', Funct\ifSetOr($foo));
25+
$this->assertEquals('foo', Funct\ifSetOr($foo, 'x'));
26+
}
27+
}

0 commit comments

Comments
 (0)