SmartName::process()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 5
nc 2
nop 1
dl 0
loc 10
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace SimpleSAML\Module\smartattributes\Auth\Process;
6
7
use SimpleSAML\Assert\Assert;
8
use SimpleSAML\Auth;
9
10
/**
11
 * Filter to set name in a smart way, based on available name attributes.
12
 *
13
 * @package SimpleSAMLphp
14
 */
15
class SmartName extends Auth\ProcessingFilter
16
{
17
    /**
18
     * @param array $attributes
19
     * @return string|null
20
     */
21
    private function getFullName(array $attributes): ?string
22
    {
23
        if (isset($attributes['displayName'])) {
24
            return $attributes['displayName'][0];
25
        }
26
27
        if (isset($attributes['cn'])) {
28
            if (count(explode(' ', $attributes['cn'][0])) > 1) {
29
                return $attributes['cn'][0];
30
            }
31
        }
32
33
        if (isset($attributes['sn']) && isset($attributes['givenName'])) {
34
            return $attributes['givenName'][0] . ' ' . $attributes['sn'][0];
35
        }
36
37
        if (isset($attributes['cn'])) {
38
            return $attributes['cn'][0];
39
        }
40
41
        if (isset($attributes['sn'])) {
42
            return $attributes['sn'][0];
43
        }
44
45
        if (isset($attributes['givenName'])) {
46
            return $attributes['givenName'][0];
47
        }
48
49
        if (isset($attributes['eduPersonPrincipalName'])) {
50
            $localname = $this->getLocalUser($attributes['eduPersonPrincipalName'][0]);
51
            if (isset($localname)) {
52
                return $localname;
53
            }
54
        }
55
56
        return null;
57
    }
58
59
60
    /**
61
     * @param string $userid
62
     * @return string|null
63
     */
64
    private function getLocalUser(string $userid): ?string
65
    {
66
        if (strpos($userid, '@') === false) {
67
            return null;
68
        }
69
        $decomposed = explode('@', $userid);
70
        if (count($decomposed) === 2) {
71
            return $decomposed[0];
72
        }
73
        return null;
74
    }
75
76
77
    /**
78
     * Apply filter to add or replace attributes.
79
     *
80
     * Add or replace existing attributes with the configured values.
81
     *
82
     * @param array &$state  The current request
83
     */
84
    public function process(array &$state): void
85
    {
86
        Assert::keyExists($state, 'Attributes');
87
88
        $attributes = &$state['Attributes'];
89
90
        $fullname = $this->getFullName($attributes);
91
92
        if (isset($fullname)) {
93
            $state['Attributes']['smartname-fullname'] = [$fullname];
94
        }
95
    }
96
}
97