|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Tests\Koded\Stdlib; |
| 4 | + |
| 5 | +use Error; |
| 6 | +use Koded\Stdlib\Arguments; |
| 7 | +use Koded\Stdlib\Config; |
| 8 | +use Koded\Stdlib\Tapped; |
| 9 | +use PHPUnit\Framework\TestCase; |
| 10 | +use function Koded\Stdlib\tap; |
| 11 | + |
| 12 | +class TapFunctionTest extends TestCase |
| 13 | +{ |
| 14 | + use ObjectPropertyTrait; |
| 15 | + |
| 16 | + public function test_object_with_callback() |
| 17 | + { |
| 18 | + $conf = tap(new Config, function(Config $c) { |
| 19 | + $c->silent(true); |
| 20 | + $c->foo = 'bar'; |
| 21 | + }); |
| 22 | + |
| 23 | + $this->assertInstanceOf(Config::class, $conf); |
| 24 | + $this->assertTrue($this->property($conf, 'silent')); |
| 25 | + $this->assertSame('bar', $conf->foo); |
| 26 | + } |
| 27 | + |
| 28 | + public function test_object_without_callback() |
| 29 | + { |
| 30 | + $conf = tap(new Config); |
| 31 | + $conf->foo = 'bar'; |
| 32 | + |
| 33 | + $this->assertInstanceOf(Tapped::class, $conf); |
| 34 | + $this->assertSame('bar', $conf->foo); |
| 35 | + } |
| 36 | + |
| 37 | + public function test_with_array_value() |
| 38 | + { |
| 39 | + $arr = tap([], function(&$data) { |
| 40 | + $data['foo'] = 'bar'; |
| 41 | + }); |
| 42 | + |
| 43 | + $this->assertSame(['foo' => 'bar'], $arr); |
| 44 | + } |
| 45 | + |
| 46 | + public function test_chainable_methods() |
| 47 | + { |
| 48 | + $data = tap(new Arguments(['foo' => 'bar']), function ($args) { |
| 49 | + $args |
| 50 | + ->set('bar', [1, 2 , 3]) |
| 51 | + ->delete('bar.1') |
| 52 | + ->import([ |
| 53 | + 100 => true, |
| 54 | + 101 => false, |
| 55 | + 102 => true |
| 56 | + ]); |
| 57 | + }); |
| 58 | + |
| 59 | + $this->assertSame( |
| 60 | + [ |
| 61 | + 'foo' => 'bar', |
| 62 | + 'bar' => [1, 2 ,3], |
| 63 | + 100 => true, |
| 64 | + 101 => false, |
| 65 | + 102 => true |
| 66 | + ], |
| 67 | + $data->toArray() |
| 68 | + ); |
| 69 | + } |
| 70 | + |
| 71 | + public function test_with_primitive_value() |
| 72 | + { |
| 73 | + $val1 = tap(42, function($v) { |
| 74 | + $v = 'fubar'; |
| 75 | + }); |
| 76 | + $this->assertSame(42, $val1, |
| 77 | + 'The tapped value is not changed'); |
| 78 | + |
| 79 | + $val2 = tap(42, function(&$v) { |
| 80 | + $v = 'fubar'; |
| 81 | + }); |
| 82 | + $this->assertSame('fubar', $val2, |
| 83 | + 'The tapped value is changed (passed by reference)'); |
| 84 | + } |
| 85 | + |
| 86 | + public function test_unreasonable_use() |
| 87 | + { |
| 88 | + $this->expectException(Error::class); |
| 89 | + $this->expectExceptionMessage('Attempt to assign property "foo" on int'); |
| 90 | + |
| 91 | + tap(42, function($v) { |
| 92 | + $v->foo = 'bar'; |
| 93 | + }); |
| 94 | + } |
| 95 | +} |
0 commit comments