Passed
Push — master ( fa3522...10d9fd )
by Alexander
30:01 queued 17:33
created

TrustedHostsNetworkResolver::getUrl()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 15
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 4.0312

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 4
eloc 7
c 1
b 0
f 0
nc 4
nop 2
dl 0
loc 15
ccs 7
cts 8
cp 0.875
crap 4.0312
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Yii\Middleware;
6
7
use InvalidArgumentException;
8
use Psr\Http\Message\RequestInterface;
9
use Psr\Http\Message\ResponseInterface;
10
use Psr\Http\Message\ServerRequestInterface;
11
use Psr\Http\Server\MiddlewareInterface;
12
use Psr\Http\Server\RequestHandlerInterface;
13
use RuntimeException;
14
use Yiisoft\Http\HeaderValueHelper;
15
use Yiisoft\NetworkUtilities\IpHelper;
16
use Yiisoft\Validator\Rule\Ip;
17
use Yiisoft\Validator\ValidatorInterface;
18
19
use function array_diff;
20
use function array_pad;
21
use function array_reverse;
22
use function array_shift;
23
use function array_unshift;
24
use function count;
25
use function explode;
26
use function in_array;
27
use function is_array;
28
use function is_callable;
29
use function filter_var;
30
use function is_string;
31
use function preg_match;
32
use function str_replace;
33
use function strtolower;
34
use function trim;
35
36
/**
37
 * Trusted hosts network resolver.
38
 *
39
 * ```php
40
 * (new TrustedHostsNetworkResolver($responseFactory))
41
 * ->withAddedTrustedHosts(
42
 *   // List of secure hosts including $_SERVER['REMOTE_ADDR'], can specify IPv4, IPv6, domains and aliases {@see Ip}.
43
 *   ['1.1.1.1', '2.2.2.1/3', '2001::/32', 'localhost'].
44
 *   // IP list headers. For advanced handling headers {@see TrustedHostsNetworkResolver::IP_HEADER_TYPE_RFC7239}.
45
 *   // Headers containing multiple sub-elements (e.g. RFC 7239) must also be listed for other relevant types
46
 *   // (e.g. host headers), otherwise they will only be used as an IP list.
47
 *   ['x-forwarded-for', [TrustedHostsNetworkResolver::IP_HEADER_TYPE_RFC7239, 'forwarded']]
48
 *   // Protocol headers with accepted protocols and values. Matching of values is case-insensitive.
49
 *   ['front-end-https' => ['https' => 'on']],
50
 *   // Host headers
51
 *   ['forwarded', 'x-forwarded-for']
52
 *   // URL headers
53
 *   ['x-rewrite-url'],
54
 *   // Port headers
55
 *   ['x-rewrite-port'],
56
 *   // Trusted headers. It is a good idea to list all relevant headers.
57
 *   ['x-forwarded-for', 'forwarded', ...],
58
 * );
59
 * ```
60
 */
61
class TrustedHostsNetworkResolver implements MiddlewareInterface
62
{
63
    public const IP_HEADER_TYPE_RFC7239 = 'rfc7239';
64
65
    public const DEFAULT_TRUSTED_HEADERS = [
66
        // common:
67
        'x-forwarded-for',
68
        'x-forwarded-host',
69
        'x-forwarded-proto',
70
        'x-forwarded-port',
71
72
        // RFC:
73
        'forward',
74
75
        // Microsoft:
76
        'front-end-https',
77
        'x-rewrite-url',
78
    ];
79
80
    private const DATA_KEY_HOSTS = 'hosts';
81
    private const DATA_KEY_IP_HEADERS = 'ipHeaders';
82
    private const DATA_KEY_HOST_HEADERS = 'hostHeaders';
83
    private const DATA_KEY_URL_HEADERS = 'urlHeaders';
84
    private const DATA_KEY_PROTOCOL_HEADERS = 'protocolHeaders';
85
    private const DATA_KEY_TRUSTED_HEADERS = 'trustedHeaders';
86
    private const DATA_KEY_PORT_HEADERS = 'portHeaders';
87
88
    private array $trustedHosts = [];
89
    private ?string $attributeIps = null;
90
91 35
    public function __construct(private ValidatorInterface $validator)
92
    {
93
    }
94
95
    /**
96
     * Returns a new instance with the added trusted hosts and related headers.
97
     *
98
     * The header lists are evaluated in the order they were specified.
99
     * If you specify multiple headers by type (e.g. IP headers), you must ensure that the irrelevant header is removed
100
     * e.g. web server application, otherwise spoof clients can be use this vulnerability.
101
     *
102
     * @param string[] $hosts List of trusted hosts IP addresses. If {@see isValidHost()} method is extended,
103
     * then can use domain names with reverse DNS resolving e.g. yiiframework.com, * .yiiframework.com.
104
     * @param array $ipHeaders List of headers containing IP lists.
105
     * @param array $protocolHeaders List of headers containing protocol. e.g.
106
     * ['x-forwarded-for' => ['http' => 'http', 'https' => ['on', 'https']]].
107
     * @param string[] $hostHeaders List of headers containing HTTP host.
108
     * @param string[] $urlHeaders List of headers containing HTTP URL.
109
     * @param string[] $portHeaders List of headers containing port number.
110
     * @param string[]|null $trustedHeaders List of trusted headers. Removed from the request, if in checking process
111
     * are classified as untrusted by hosts.
112
     *
113
     * @return self
114
     */
115 32
    public function withAddedTrustedHosts(
116
        array $hosts,
117
        // Defining default headers is not secure!
118
        array $ipHeaders = [],
119
        array $protocolHeaders = [],
120
        array $hostHeaders = [],
121
        array $urlHeaders = [],
122
        array $portHeaders = [],
123
        ?array $trustedHeaders = null
124
    ): self {
125 32
        $new = clone $this;
126
127 32
        foreach ($ipHeaders as $ipHeader) {
128 16
            if (is_string($ipHeader)) {
129 5
                continue;
130
            }
131
132 11
            if (!is_array($ipHeader)) {
133 1
                throw new InvalidArgumentException('Type of IP header is not a string and not array.');
134
            }
135
136 10
            if (count($ipHeader) !== 2) {
137 1
                throw new InvalidArgumentException('The IP header array must have exactly 2 elements.');
138
            }
139
140 9
            [$type, $header] = $ipHeader;
141
142 9
            if (!is_string($type)) {
143 1
                throw new InvalidArgumentException('The IP header type is not a string.');
144
            }
145
146 8
            if (!is_string($header)) {
147 1
                throw new InvalidArgumentException('The IP header value is not a string.');
148
            }
149
150 7
            if ($type === self::IP_HEADER_TYPE_RFC7239) {
151 6
                continue;
152
            }
153
154 1
            throw new InvalidArgumentException("Not supported IP header type: $type.");
155
        }
156
157 27
        if ($hosts === []) {
158 8
            throw new InvalidArgumentException('Empty hosts not allowed.');
159
        }
160
161 19
        $trustedHeaders = $trustedHeaders ?? self::DEFAULT_TRUSTED_HEADERS;
162 19
        $protocolHeaders = $this->prepareProtocolHeaders($protocolHeaders);
163
164 15
        $this->checkTypeStringOrArray($hosts, 'hosts');
165 12
        $this->checkTypeStringOrArray($trustedHeaders, 'trustedHeaders');
166 12
        $this->checkTypeStringOrArray($hostHeaders, 'hostHeaders');
167 12
        $this->checkTypeStringOrArray($urlHeaders, 'urlHeaders');
168 12
        $this->checkTypeStringOrArray($portHeaders, 'portHeaders');
169
170 12
        foreach ($hosts as $host) {
171 12
            $host = str_replace('*', 'wildcard', $host); // wildcard is allowed in host
172
173 12
            if (filter_var($host, FILTER_VALIDATE_DOMAIN) === false) {
174 1
                throw new InvalidArgumentException("\"$host\" host is not a domain and not an IP address.");
175
            }
176
        }
177
178 11
        $new->trustedHosts[] = [
179
            self::DATA_KEY_HOSTS => $hosts,
180
            self::DATA_KEY_IP_HEADERS => $ipHeaders,
181
            self::DATA_KEY_PROTOCOL_HEADERS => $protocolHeaders,
182
            self::DATA_KEY_TRUSTED_HEADERS => $trustedHeaders,
183
            self::DATA_KEY_HOST_HEADERS => $hostHeaders,
184
            self::DATA_KEY_URL_HEADERS => $urlHeaders,
185
            self::DATA_KEY_PORT_HEADERS => $portHeaders,
186
        ];
187
188 11
        return $new;
189
    }
190
191
    /**
192
     * Returns a new instance without the trusted hosts and related headers.
193
     *
194
     * @return self
195
     */
196 1
    public function withoutTrustedHosts(): self
197
    {
198 1
        $new = clone $this;
199 1
        $new->trustedHosts = [];
200 1
        return $new;
201
    }
202
203
    /**
204
     * Returns a new instance with the specified request's attribute name to which trusted path data is added.
205
     *
206
     * @param string|null $attribute The request attribute name.
207
     *
208
     * @see getElementsByRfc7239()
209
     *
210
     * @return self
211
     */
212 3
    public function withAttributeIps(?string $attribute): self
213
    {
214 3
        if ($attribute === '') {
215 1
            throw new RuntimeException('Attribute should not be empty string.');
216
        }
217
218 2
        $new = clone $this;
219 2
        $new->attributeIps = $attribute;
220 2
        return $new;
221
    }
222
223 12
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
224
    {
225 12
        $actualHost = $request->getServerParams()['REMOTE_ADDR'] ?? null;
226
227 12
        if ($actualHost === null) {
228
            // Validation is not possible.
229 1
            return $this->handleNotTrusted($request, $handler);
230
        }
231
232 11
        $trustedHostData = null;
233 11
        $trustedHeaders = [];
234
235 11
        foreach ($this->trustedHosts as $data) {
236
            // collect all trusted headers
237 10
            $trustedHeaders = array_merge($trustedHeaders, $data[self::DATA_KEY_TRUSTED_HEADERS]);
238
239 10
            if ($trustedHostData !== null) {
240
                // trusted hosts already found
241
                continue;
242
            }
243
244 10
            if ($this->isValidHost($actualHost, $data[self::DATA_KEY_HOSTS])) {
245 8
                $trustedHostData = $data;
246
            }
247
        }
248
249
        /** @psalm-suppress PossiblyNullArgument, PossiblyNullArrayAccess */
250 11
        $untrustedHeaders = array_diff($trustedHeaders, $trustedHostData[self::DATA_KEY_TRUSTED_HEADERS] ?? []);
251 11
        $request = $this->removeHeaders($request, $untrustedHeaders);
252
253 11
        if ($trustedHostData === null) {
254
            // No trusted host at all.
255 3
            return $this->handleNotTrusted($request, $handler);
256
        }
257
258 8
        [$ipListType, $ipHeader, $hostList] = $this->getIpList($request, $trustedHostData[self::DATA_KEY_IP_HEADERS]);
259 8
        $hostList = array_reverse($hostList); // the first item should be the closest to the server
260
261 8
        if ($ipListType === null) {
262 2
            $hostList = $this->getFormattedIpList($hostList);
263 6
        } elseif ($ipListType === self::IP_HEADER_TYPE_RFC7239) {
264 6
            $hostList = $this->getElementsByRfc7239($hostList);
265
        }
266
267 8
        array_unshift($hostList, ['ip' => $actualHost]); // server's ip to first position
268 8
        $hostDataList = [];
269
270
        do {
271 8
            $hostData = array_shift($hostList);
272 8
            if (!isset($hostData['ip'])) {
273
                $hostData = $this->reverseObfuscate($hostData, $hostDataList, $hostList, $request);
274
275
                if ($hostData === null) {
276
                    continue;
277
                }
278
279
                if (!isset($hostData['ip'])) {
280
                    break;
281
                }
282
            }
283
284 8
            $ip = $hostData['ip'];
285
286 8
            if (!$this->isValidHost($ip, ['any'])) {
287
                // invalid IP
288
                break;
289
            }
290
291 8
            $hostDataList[] = $hostData;
292
293 8
            if (!$this->isValidHost($ip, $trustedHostData[self::DATA_KEY_HOSTS])) {
294
                // not trusted host
295 8
                break;
296
            }
297 8
        } while (count($hostList) > 0);
298
299 8
        if ($this->attributeIps !== null) {
300
            $request = $request->withAttribute($this->attributeIps, $hostDataList);
301
        }
302
303 8
        $uri = $request->getUri();
304
        // find HTTP host
305 8
        foreach ($trustedHostData[self::DATA_KEY_HOST_HEADERS] as $hostHeader) {
306 4
            if (!$request->hasHeader($hostHeader)) {
307
                continue;
308
            }
309
310
            if (
311 4
                $hostHeader === $ipHeader
312 4
                && $ipListType === self::IP_HEADER_TYPE_RFC7239
313 4
                && isset($hostData['httpHost'])
314
            ) {
315 2
                $uri = $uri->withHost($hostData['httpHost']);
316 2
                break;
317
            }
318
319 2
            $host = $request->getHeaderLine($hostHeader);
320
321 2
            if (filter_var($host, FILTER_VALIDATE_DOMAIN) !== false) {
322 2
                $uri = $uri->withHost($host);
323 2
                break;
324
            }
325
        }
326
327
        // find protocol
328 8
        foreach ($trustedHostData[self::DATA_KEY_PROTOCOL_HEADERS] as $protocolHeader => $protocols) {
329 4
            if (!$request->hasHeader($protocolHeader)) {
330
                continue;
331
            }
332
333
            if (
334 4
                $protocolHeader === $ipHeader
335 4
                && $ipListType === self::IP_HEADER_TYPE_RFC7239
336 4
                && isset($hostData['protocol'])
337
            ) {
338 4
                $uri = $uri->withScheme($hostData['protocol']);
339 4
                break;
340
            }
341
342 2
            $protocolHeaderValue = $request->getHeaderLine($protocolHeader);
343
344 2
            foreach ($protocols as $protocol => $acceptedValues) {
345 2
                if (in_array($protocolHeaderValue, $acceptedValues, true)) {
346
                    $uri = $uri->withScheme($protocol);
347
                    break 2;
348
                }
349
            }
350
        }
351
352 8
        $urlParts = $this->getUrl($request, $trustedHostData[self::DATA_KEY_URL_HEADERS]);
353
354 8
        if ($urlParts !== null) {
355 3
            [$path, $query] = $urlParts;
356 3
            $uri = $uri->withPath($path);
357
358 3
            if ($query !== null) {
359 3
                $uri = $uri->withQuery($query);
360
            }
361
        }
362
363
        // find port
364 8
        foreach ($trustedHostData[self::DATA_KEY_PORT_HEADERS] as $portHeader) {
365 1
            if (!$request->hasHeader($portHeader)) {
366
                continue;
367
            }
368
369
            if (
370 1
                $portHeader === $ipHeader
371 1
                && $ipListType === self::IP_HEADER_TYPE_RFC7239
372 1
                && isset($hostData['port'])
373 1
                && $this->checkPort((string) $hostData['port'])
374
            ) {
375 1
                $uri = $uri->withPort($hostData['port']);
376 1
                break;
377
            }
378
379
            $port = $request->getHeaderLine($portHeader);
380
381
            if ($this->checkPort($port)) {
382
                $uri = $uri->withPort((int) $port);
383
                break;
384
            }
385
        }
386
387 8
        return $handler->handle($request
388 8
            ->withUri($uri)
389 8
            ->withAttribute('requestClientIp', $hostData['ip'] ?? null));
390
    }
391
392
    /**
393
     * Validate host by range.
394
     *
395
     * This method can be extendable by overwriting e.g. with reverse DNS verification.
396
     */
397 10
    protected function isValidHost(string $host, array $ranges): bool
398
    {
399 10
        $validationResult = $this->validator->validate(
400 10
            ['host' => $host],
401 10
            ['host' => [new Ip(ranges: $ranges, allowNegation: false, allowSubnet: false)]]
402
        );
403 10
        return $validationResult->isValid();
404
    }
405
406
    /**
407
     * Reverse obfuscating host data
408
     *
409
     * RFC 7239 allows to use obfuscated host data. In this case, either specifying the
410
     * IP address or dropping the proxy endpoint is required to determine validated route.
411
     *
412
     * By default it does not perform any transformation on the data. You can override this method.
413
     *
414
     * @param array $hostData
415
     * @param array $hostDataListValidated
416
     * @param array $hostDataListRemaining
417
     * @param RequestInterface $request
418
     *
419
     * @return array|null reverse obfuscated host data or null.
420
     * In case of null data is discarded and the process continues with the next portion of host data.
421
     * If the return value is an array, it must contain at least the `ip` key.
422
     *
423
     * @see getElementsByRfc7239()
424
     * @link https://tools.ietf.org/html/rfc7239#section-6.2
425
     * @link https://tools.ietf.org/html/rfc7239#section-6.3
426
     */
427
    protected function reverseObfuscate(
428
        array $hostData,
429
        array $hostDataListValidated,
0 ignored issues
show
Unused Code introduced by
The parameter $hostDataListValidated is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

429
        /** @scrutinizer ignore-unused */ array $hostDataListValidated,

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
430
        array $hostDataListRemaining,
0 ignored issues
show
Unused Code introduced by
The parameter $hostDataListRemaining is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

430
        /** @scrutinizer ignore-unused */ array $hostDataListRemaining,

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
431
        RequestInterface $request
0 ignored issues
show
Unused Code introduced by
The parameter $request is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

431
        /** @scrutinizer ignore-unused */ RequestInterface $request

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
432
    ): ?array {
433
        return $hostData;
434
    }
435
436 4
    private function handleNotTrusted(
437
        ServerRequestInterface $request,
438
        RequestHandlerInterface $handler
439
    ): ResponseInterface {
440 4
        if ($this->attributeIps !== null) {
441 1
            $request = $request->withAttribute($this->attributeIps, null);
442
        }
443
444 4
        return $handler->handle($request->withAttribute('requestClientIp', null));
445
    }
446
447 19
    private function prepareProtocolHeaders(array $protocolHeaders): array
448
    {
449 19
        $output = [];
450
451 19
        foreach ($protocolHeaders as $header => $protocolAndAcceptedValues) {
452 8
            $header = strtolower($header);
453
454 8
            if (is_callable($protocolAndAcceptedValues)) {
455
                $output[$header] = $protocolAndAcceptedValues;
456
                continue;
457
            }
458
459 8
            if (!is_array($protocolAndAcceptedValues)) {
460 1
                throw new RuntimeException('Accepted values is not an array nor callable.');
461
            }
462
463 7
            if ($protocolAndAcceptedValues === []) {
464 1
                throw new RuntimeException('Accepted values cannot be an empty array.');
465
            }
466
467 6
            $output[$header] = [];
468
469 6
            foreach ($protocolAndAcceptedValues as $protocol => $acceptedValues) {
470 6
                if (!is_string($protocol)) {
471 1
                    throw new RuntimeException('The protocol must be a string.');
472
                }
473
474 5
                if ($protocol === '') {
475 1
                    throw new RuntimeException('The protocol cannot be empty.');
476
                }
477
478 4
                $output[$header][$protocol] = array_map('\strtolower', (array)$acceptedValues);
479
            }
480
        }
481
482 15
        return $output;
483
    }
484
485 11
    private function removeHeaders(ServerRequestInterface $request, array $headers): ServerRequestInterface
486
    {
487 11
        foreach ($headers as $header) {
488
            $request = $request->withoutAttribute($header);
489
        }
490
491 11
        return $request;
492
    }
493
494 8
    private function getIpList(RequestInterface $request, array $ipHeaders): array
495
    {
496 8
        foreach ($ipHeaders as $ipHeader) {
497 8
            $type = null;
498
499 8
            if (is_array($ipHeader)) {
500 6
                $type = array_shift($ipHeader);
501 6
                $ipHeader = array_shift($ipHeader);
502
            }
503
504 8
            if ($request->hasHeader($ipHeader)) {
505 8
                return [$type, $ipHeader, $request->getHeader($ipHeader)];
506
            }
507
        }
508
509
        return [null, null, []];
510
    }
511
512
    /**
513
     * @see getElementsByRfc7239
514
     */
515 2
    private function getFormattedIpList(array $forwards): array
516
    {
517 2
        $list = [];
518
519 2
        foreach ($forwards as $ip) {
520 2
            $list[] = ['ip' => $ip];
521
        }
522
523 2
        return $list;
524
    }
525
526
    /**
527
     * Forwarded elements by RFC7239.
528
     *
529
     * The structure of the elements:
530
     * - `host`: IP or obfuscated hostname or "unknown"
531
     * - `ip`: IP address (only if presented)
532
     * - `by`: used user-agent by proxy (only if presented)
533
     * - `port`: port number received by proxy (only if presented)
534
     * - `protocol`: protocol received by proxy (only if presented)
535
     * - `httpHost`: HTTP host received by proxy (only if presented)
536
     *
537
     * The list starts with the server and the last item is the client itself.
538
     *
539
     * @link https://tools.ietf.org/html/rfc7239
540
     *
541
     * @return array Proxy data elements.
542
     */
543 6
    private function getElementsByRfc7239(array $forwards): array
544
    {
545 6
        $list = [];
546
547 6
        foreach ($forwards as $forward) {
548 6
            $data = HeaderValueHelper::getParameters($forward);
549
550 6
            if (!isset($data['for'])) {
551
                // Invalid item, the following items will be dropped
552
                break;
553
            }
554
555 6
            $pattern = '/^(?<host>' . IpHelper::IPV4_PATTERN . '|unknown|_[\w\.-]+|[[]'
556
                . IpHelper::IPV6_PATTERN . '[]])(?::(?<port>[\w\.-]+))?$/';
557
558 6
            if (preg_match($pattern, $data['for'], $matches) === 0) {
559
                // Invalid item, the following items will be dropped
560
                break;
561
            }
562
563 6
            $ipData = [];
564 6
            $host = $matches['host'];
565 6
            $obfuscatedHost = $host === 'unknown' || str_starts_with($host, '_');
566
567 6
            if (!$obfuscatedHost) {
568
                // IPv4 & IPv6
569 6
                $ipData['ip'] = str_starts_with($host, '[') ? trim($host /* IPv6 */, '[]') : $host;
570
            }
571
572 6
            $ipData['host'] = $host;
573
574 6
            if (isset($matches['port'])) {
575 1
                $port = $matches['port'];
576
577 1
                if (!$obfuscatedHost && !$this->checkPort($port)) {
578
                    // Invalid port, the following items will be dropped
579
                    break;
580
                }
581
582 1
                $ipData['port'] = $obfuscatedHost ? $port : (int)$port;
583
            }
584
585
            // copy other properties
586 6
            foreach (['proto' => 'protocol', 'host' => 'httpHost', 'by' => 'by'] as $source => $destination) {
587 6
                if (isset($data[$source])) {
588 4
                    $ipData[$destination] = $data[$source];
589
                }
590
            }
591
592 6
            if (isset($ipData['httpHost']) && filter_var($ipData['httpHost'], FILTER_VALIDATE_DOMAIN) === false) {
593
                // remove not valid HTTP host
594
                unset($ipData['httpHost']);
595
            }
596
597 6
            $list[] = $ipData;
598
        }
599
600 6
        return $list;
601
    }
602
603 8
    private function getUrl(RequestInterface $request, array $urlHeaders): ?array
604
    {
605 8
        foreach ($urlHeaders as $header) {
606 3
            if (!$request->hasHeader($header)) {
607
                continue;
608
            }
609
610 3
            $url = $request->getHeaderLine($header);
611
612 3
            if (str_starts_with($url, '/')) {
613 3
                return array_pad(explode('?', $url, 2), 2, null);
614
            }
615
        }
616
617 5
        return null;
618
    }
619
620 1
    private function checkPort(string $port): bool
621
    {
622 1
        return preg_match('/^\d{1,5}$/', $port) === 1 && (int)$port <= 65535;
623
    }
624
625 15
    private function checkTypeStringOrArray(array $array, string $field): void
626
    {
627 15
        foreach ($array as $item) {
628 15
            if (!is_string($item)) {
629 1
                throw new InvalidArgumentException("$field must be string type");
630
            }
631
632 14
            if (trim($item) === '') {
633 2
                throw new InvalidArgumentException("$field cannot be empty strings");
634
            }
635
        }
636
    }
637
}
638