Debian Codegraph @

vendor/zircote/swagger-php/src/Pipeline.php

raw
1 <?php declare(strict_types=1);
2
3 /**
4 * @license Apache 2.0
5 */
6
7 namespace OpenApi;
8
9 class Pipeline
10 {
11 /**
12 * @var array<callable>
13 */
14 protected $pipes = [];
15
16 public function __construct(array $pipes = [])
17 {
18 $this->pipes = $pipes;
19 }
20
21 public function add(callable $pipe): Pipeline
22 {
23 $this->pipes[] = $pipe;
24
25 return $this;
26 }
27
28 /**
29 * @param callable|class-string|null $pipe
30 */
31 public function remove($pipe = null, ?callable $matcher = null): Pipeline
32 {
33 if (!$pipe && !$matcher) {
34 throw new OpenApiException('pipe or callable must not be empty');
35 }
36
37 // allow matching on class name if $pipe in a string
38 if (is_string($pipe) && !$matcher) {
39 $pipeClass = $pipe;
40 $matcher = (static fn ($pipe): bool => !$pipe instanceof $pipeClass);
41 }
42
43 if ($matcher) {
44 $tmp = [];
45 foreach ($this->pipes as $pipe) {
46 if ($matcher($pipe)) {
47 $tmp[] = $pipe;
48 }
49 }
50
51 $this->pipes = $tmp;
52 } else {
53 if (false === ($key = array_search($pipe, $this->pipes, true))) {
54 return $this;
55 }
56
57 unset($this->pipes[$key]);
58
59 $this->pipes = array_values($this->pipes);
60 }
61
62 return $this;
63 }
64
65 /**
66 * @param callable|class-string $matcher used to determine the position to insert
67 * either an <code>int</code> from a callable or, in the case of <code>$matcher</code> being
68 * a <code>class-string</code>, the position before the first pipe of that class
69 */
70 public function insert(callable $pipe, $matcher): Pipeline
71 {
72 if (is_string($matcher)) {
73 $before = $matcher;
74 $matcher = static function (array $pipes) use ($before): int|string|null {
75 foreach ($pipes as $ii => $current) {
76 if ($current instanceof $before) {
77 return $ii;
78 }
79 }
80
81 return null;
82 };
83 }
84
85 $index = $matcher($this->pipes);
86 if (null === $index || $index < 0 || $index > count($this->pipes)) {
87 throw new OpenApiException('Matcher result out of range');
88 }
89
90 array_splice($this->pipes, $index, 0, [$pipe]);
91
92 return $this;
93 }
94
95 public function walk(callable $walker): Pipeline
96 {
97 foreach ($this->pipes as $pipe) {
98 $walker($pipe);
99 }
100
101 return $this;
102 }
103
104 /**
105 * @return mixed
106 */
107 public function process(mixed $payload)
108 {
109 foreach ($this->pipes as $pipe) {
110 $payload = $pipe($payload) ?: $payload;
111 }
112
113 return $payload;
114 }
115 }