IsSuccessful::truncateStatus()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 4
nc 2
nop 1
dl 0
loc 8
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace SimpleSAML\SAML2\Response\Validation\ConstraintValidator;
6
7
use SimpleSAML\SAML2\Constants as C;
8
use SimpleSAML\SAML2\Response\Validation\ConstraintValidator;
9
use SimpleSAML\SAML2\Response\Validation\Result;
10
use SimpleSAML\SAML2\XML\samlp\Response;
11
use SimpleSAML\SAML2\XML\samlp\Status;
12
13
use function implode;
14
use function sprintf;
15
use function strlen;
16
use function substr;
17
18
class IsSuccessful implements ConstraintValidator
19
{
20
    /**
21
     * @param \SimpleSAML\SAML2\XML\samlp\Response $response
22
     * @param \SimpleSAML\SAML2\Response\Validation\Result $result
23
     */
24
    public function validate(
25
        Response $response,
26
        Result $result,
27
    ): void {
28
        if (!$response->isSuccess()) {
29
            $result->addError($this->buildMessage($response->getStatus()));
30
        }
31
    }
32
33
34
    /**
35
     * @param \SimpleSAML\SAML2\XML\samlp\Status $responseStatus
36
     *
37
     * @return string
38
     */
39
    private function buildMessage(Status $responseStatus): string
40
    {
41
        $subCodes = [];
42
        $statusCode = $responseStatus->getStatusCode();
43
44
        $codes = $statusCode->getSubCodes();
45
        if (!empty($codes)) {
46
            foreach ($codes as $code) {
47
                $subCodes[] = $this->truncateStatus($code->getValue()->getValue());
48
            }
49
        }
50
        $statusMessage = $responseStatus->getStatusMessage();
51
52
        return sprintf(
53
            '%s%s%s',
54
            $this->truncateStatus($statusCode->getValue()->getValue()),
55
            $subCodes ? '/' . implode('/', $subCodes) : '',
56
            $statusMessage ? ' ' . $statusMessage->getContent()->getValue() : '',
57
        );
58
    }
59
60
61
    /**
62
     * Truncate the status if it is prefixed by its urn.
63
     * @param string $status
64
     *
65
     * @return string
66
     */
67
    private function truncateStatus(string $status): string
68
    {
69
        if (!str_starts_with($status, C::STATUS_PREFIX)) {
70
            return $status;
71
        }
72
73
        $prefixLength = strlen(C::STATUS_PREFIX);
74
        return substr($status, $prefixLength);
75
    }
76
}
77