1: <?php declare(strict_types=1);
2:
3: namespace Salient\Core\Concern;
4:
5: use Salient\Contract\Core\Chainable;
6:
7: /**
8: * Implements Chainable
9: *
10: * @see Chainable
11: *
12: * @api
13: *
14: * @phpstan-require-implements Chainable
15: */
16: trait HasChainableMethods
17: {
18: /**
19: * @param callable(static): static $callback
20: * @return static
21: */
22: public function apply(callable $callback)
23: {
24: return $callback($this);
25: }
26:
27: /**
28: * @param (callable(static): bool)|bool $condition
29: * @param (callable(static): static)|null $then
30: * @param (callable(static): static)|null $else
31: * @return static
32: */
33: public function if($condition, ?callable $then = null, ?callable $else = null)
34: {
35: if (is_callable($condition)) {
36: $condition = $condition($this);
37: }
38: if (!$condition) {
39: return $else === null ? $this : $else($this);
40: }
41: return $then === null ? $this : $then($this);
42: }
43:
44: /**
45: * @template TKey
46: * @template TValue
47: *
48: * @param iterable<TKey,TValue> $list
49: * @param callable(static, TValue, TKey): static $callback
50: * @return static
51: */
52: public function withEach(iterable $list, callable $callback)
53: {
54: $instance = $this;
55: foreach ($list as $key => $value) {
56: $instance = $callback($instance, $value, $key);
57: }
58: return $instance;
59: }
60: }
61: