Skip to content

Commit ea5e349

Browse files
committed
Proxy.
1 parent f17d701 commit ea5e349

File tree

2 files changed

+90
-0
lines changed

2 files changed

+90
-0
lines changed

README.md

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -274,6 +274,71 @@ If you're using laravel sanctum, and want to explicitely use / generate a Bearer
274274

275275
If you're annoying to always scroll up to message in your test when `->dump()` the response, you can use `->dumpWithoutTrace()` instead, it will return you back everything except the long array of trace.
276276

277+
## Proxies
278+
279+
Often we're using common `Collection` or `EnumeratesValues` chain methods, but we cannot use those in other context.
280+
281+
### when
282+
`when` is one of the most useful methods, let's assume we have this class:
283+
284+
```php
285+
class DocumentGenerator
286+
{
287+
public static function make(...$arguments)
288+
{
289+
return new static(...$arguments);
290+
}
291+
292+
public function setItem(Item $item): self
293+
{
294+
$this->item = $item;
295+
296+
return $this;
297+
}
298+
299+
public function setOrder(Order $order): self
300+
{
301+
$this->order = $order;
302+
303+
return $this;
304+
}
305+
306+
public function generate(){
307+
//
308+
}
309+
}
310+
```
311+
312+
And you want to set the order for the class, and item unless it exists. The usual way to do so is:
313+
314+
```php
315+
$generator = DocumentGenerator::make()->setOrder($order);
316+
317+
if ($item) {
318+
$generator->setItem($item);
319+
}
320+
321+
$generator->generate();
322+
```
323+
324+
Using the `when` chain method, this code become fluent:
325+
326+
```php
327+
DocumentGenerator::make()
328+
->setOrder($order)
329+
->when($item, fn($generator) => $generator->setItem($order))
330+
->generate();
331+
```
332+
333+
To make it work, simply add the `Binarcode\LaravelDeveloper\Concerns\Proxies` trait:
334+
335+
```php
336+
class DocumentGenerator
337+
{
338+
use Binarcode\LaravelDeveloper\Concerns\Proxies;
339+
}
340+
```
341+
277342
## Testing
278343

279344
``` bash

src/Concerns/Proxies.php

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
<?php
2+
3+
namespace Binarcode\LaravelDeveloper\Concerns;
4+
5+
trait Proxies
6+
{
7+
/**
8+
* Apply the callback if the value is truthy.
9+
*
10+
* @param bool|mixed $value
11+
* @param callable|null $callback
12+
* @param callable|null $default
13+
* @return static|mixed
14+
*/
15+
public function when($value, callable $callback = null, callable $default = null)
16+
{
17+
if ($value) {
18+
return $callback($this, $value);
19+
} elseif ($default) {
20+
return $default($this, $value);
21+
}
22+
23+
return $this;
24+
}
25+
}

0 commit comments

Comments
 (0)