Completed
Push — feature/implement-state-handli... ( bd5ae0 )
by Michiel
01:52
created

SamlEntityRepository::createSpIfNotExists()   B

Complexity

Conditions 3
Paths 3

Size

Total Lines 57

Duplication

Lines 11
Ratio 19.3 %

Importance

Changes 0
Metric Value
dl 11
loc 57
rs 8.9381
c 0
b 0
f 0
cc 3
nc 3
nop 3

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace Surfnet\StepupGateway\Behat\Repository;
4
5
use Exception;
6
use PDO;
7
use Ramsey\Uuid\Uuid;
8
9
/**
10
 * A poor mans repository, a pdo connection to the test database is established in the constructor
11
 */
12
class SamlEntityRepository
13
{
14
    const SP_ACS_LOCATION = 'https://gateway.stepup.example.com/test/authentication/consume-assertion';
15
16
    /**
17
     * @var Connection
18
     */
19
    private $connection;
20
21
    public function __construct(Connection $connection)
22
    {
23
        $this->connection = $connection;
24
    }
25
26
    public function createSpIfNotExists($entityId, $certificate, $sfoEnabled = false)
27
    {
28
        // Does the SP exist?
29
        $stmt = $this->connection->prepare('SELECT * FROM saml_entity WHERE entity_id=:entityId LIMIT 1');
30
        $stmt->bindParam('entityId', $entityId, PDO::PARAM_STR);
31
        $stmt->execute();
32
        if ($stmt->rowCount() === 0) {
33
            // If not, create it
34
            $uuid = Uuid::uuid4()->toString();
35
            $type = 'sp';
36
            $configuration['acs'] = [self::SP_ACS_LOCATION];
0 ignored issues
show
Coding Style Comprehensibility introduced by
$configuration was never initialized. Although not strictly required by PHP, it is generally a good practice to add $configuration = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
37
            $configuration['public_key'] = $certificate;
38
            $configuration['loa'] = ['__default__' => 'http://stepup.example.com/assurance/loa1'];
39
            $configuration['second_factor_only'] = $sfoEnabled;
40
            $configuration['second_factor_only_nameid_patterns'] = [
41
                'urn:collab:person:stepup.example.com:admin',
42
                'urn:collab:person:stepup.example.com:*',
43
            ];
44
45
            $data = [
46
                'entityId' => $entityId,
47
                'type' => $type,
48
                'configuration' => json_encode($configuration),
49
                'id' => $uuid,
50
            ];
51
            $sql = <<<SQL
52
            INSERT INTO saml_entity (
53
                `entity_id`,
54
                `type`,
55
                `configuration`,
56
                `id`
57
            )
58
            VALUES (
59
                :entityId, 
60
                :type, 
61
                :configuration, 
62
                :id                
63
            )
64
SQL;
65
            $stmt = $this->connection->prepare($sql);
66
            if ($stmt->execute($data)) {
67
                return $data;
68
            }
69
70
            throw new Exception('Unable to insert the new SP saml_entity');
71 View Code Duplication
        } else {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
72
            // Return the SP data
73
            $results = reset($stmt->fetchAll());
0 ignored issues
show
Bug introduced by
$stmt->fetchAll() cannot be passed to reset() as the parameter $array expects a reference.
Loading history...
74
            $data = [
75
                'entityId' => $results['entity_id'],
76
                'type' => $results['type'],
77
                'configuration' => $results['configuration'],
78
                'id' => $results['id'],
79
            ];
80
            return $data;
81
        }
82
    }
83
84
    public function createIdpIfNotExists($entityId, $certificate)
85
    {
86
        // Does the SP exist?
87
        $stmt = $this->connection->prepare('SELECT * FROM saml_entity WHERE entity_id=:entityId LIMIT 1');
88
        $stmt->bindParam('entityId', $entityId, PDO::PARAM_STR);
89
        $stmt->execute();
90
        if ($stmt->rowCount() === 0) {
91
            // If not, create it
92
            $uuid = Uuid::uuid4()->toString();
93
            $type = 'idp';
94
95
            $configuration['public_key'] = $certificate;
0 ignored issues
show
Coding Style Comprehensibility introduced by
$configuration was never initialized. Although not strictly required by PHP, it is generally a good practice to add $configuration = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
96
97
            $data = [
98
                'entityId' => $entityId,
99
                'type' => $type,
100
                'configuration' => json_encode($configuration),
101
                'id' => $uuid,
102
            ];
103
            $sql = <<<SQL
104
            INSERT INTO saml_entity (
105
                `entity_id`,
106
                `type`,
107
                `configuration`,
108
                `id`
109
            )
110
            VALUES (
111
                :entityId, 
112
                :type, 
113
                :configuration, 
114
                :id                
115
            )
116
SQL;
117
            $stmt = $this->connection->prepare($sql);
118
            if ($stmt->execute($data)) {
119
                return $data;
120
            }
121
122
            throw new Exception('Unable to insert the new SP saml_entity');
123 View Code Duplication
        } else {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
124
            // Return the SP data
125
            $results = reset($stmt->fetchAll());
0 ignored issues
show
Bug introduced by
$stmt->fetchAll() cannot be passed to reset() as the parameter $array expects a reference.
Loading history...
126
            $data = [
127
                'entityId' => $results['entity_id'],
128
                'type' => $results['type'],
129
                'configuration' => $results['configuration'],
130
                'id' => $results['id'],
131
            ];
132
            return $data;
133
        }
134
    }
135
}
136