Skip to content

Commit

Permalink
Adding Tappable trait
Browse files Browse the repository at this point in the history
  • Loading branch information
lukewatts committed Mar 6, 2024
1 parent 1598b4f commit 524f067
Show file tree
Hide file tree
Showing 3 changed files with 124 additions and 0 deletions.
34 changes: 34 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -97,3 +97,37 @@ return tap(new Psr7Response(), function ($response) {
$response->getBody()->write('foo');
});
```

## Traits

### SlimFacades\Traits\Tappable

```php
use SlimFacades\Support\Traits\Tappable;

class TappableClass
{
use Tappable;

private $name;

public static function make()
{
return new static;
}

public function setName($name)
{
$this->name = $name;
}

public function getName()
{
return $this->name;
}
}

$name = TappableClass::make()->tap(function ($tappable) {
$tappable->setName('MyName');
})->getName();
```
17 changes: 17 additions & 0 deletions src/Support/Traits/Tappable.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
<?php declare(strict_types=1);

namespace SlimFacades\Support\Traits;

trait Tappable
{
/**
* Call the given Closure with this instance then return the instance.
*
* @param callable|null $callback
* @return $this|\Illuminate\Support\HigherOrderTapProxy
*/
public function tap($callback = null)
{
return tap($this, $callback);
}
}
73 changes: 73 additions & 0 deletions tests/Support/Traits/TappableTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
<?php declare(strict_types=1);

use SlimFacades\Support\Traits\Tappable;
use PHPUnit\Framework\TestCase;

class TappableTest extends TestCase
{
public function testTappableClassWithCallback()
{
$name = TappableClass::make()->tap(function ($tappable) {
$tappable->setName('MyName');
})->getName();

$this->assertSame('MyName', $name);
}

public function testTappableClassWithInvokableClass()
{
$name = TappableClass::make()->tap(new class
{
public function __invoke($tappable)
{
$tappable->setName('MyName');
}
})->getName();

$this->assertSame('MyName', $name);
}

public function testTappableClassWithNoneInvokableClass()
{
$this->expectException('Error');

$name = TappableClass::make()->tap(new class
{
public function setName($tappable)
{
$tappable->setName('MyName');
}
})->getName();

$this->assertSame('MyName', $name);
}

public function testTappableClassWithoutCallback()
{
$name = TappableClass::make()->tap()->setName('MyName')->getName();

$this->assertSame('MyName', $name);
}
}

class TappableClass
{
use Tappable;

private $name;

public static function make()
{
return new static;
}

public function setName($name)
{
$this->name = $name;
}

public function getName()
{
return $this->name;
}
}

0 comments on commit 524f067

Please sign in to comment.