Completed
Pull Request — master (#735)
by Guilherme
03:50
created

GenerateSubjectIdentifiersCommand::execute()   B

Complexity

Conditions 4
Paths 4

Size

Total Lines 74
Code Lines 52

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 52
nc 4
nop 2
dl 0
loc 74
rs 8.6628
c 0
b 0
f 0

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
 * This file is part of the login-cidadao project or it's bundles.
4
 *
5
 * (c) Guilherme Donato <guilhermednt on github>
6
 *
7
 * For the full copyright and license information, please view the LICENSE
8
 * file that was distributed with this source code.
9
 */
10
11
namespace LoginCidadao\OpenIDBundle\Command;
12
13
use Doctrine\ORM\EntityManagerInterface;
14
use LoginCidadao\CoreBundle\Entity\Authorization;
15
use LoginCidadao\CoreBundle\Entity\AuthorizationRepository;
16
use LoginCidadao\OAuthBundle\Entity\Client;
17
use LoginCidadao\OpenIDBundle\Entity\ClientMetadata;
18
use LoginCidadao\OpenIDBundle\Entity\SubjectIdentifier;
19
use LoginCidadao\OpenIDBundle\Service\SubjectIdentifierService;
20
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
21
use Symfony\Component\Console\Input\InputInterface;
22
use Symfony\Component\Console\Output\OutputInterface;
23
use Symfony\Component\Console\Style\SymfonyStyle;
24
25
class GenerateSubjectIdentifiersCommand extends ContainerAwareCommand
26
{
27
    /** @var EntityManagerInterface */
28
    private $em;
29
30
    /** @var array */
31
    private $clientMetadata = [];
32
33
    protected function configure()
34
    {
35
        $this
36
            ->setName('lc:oidc:generate-subject-identifiers')
37
            ->setDescription("Generates and persists Subject Identifiers for Authorizations that don't have it.")
38
            ->setHelp(
39
                "This command will persist the Subject Identifiers for all Authorizations that do not have it yet since it's a new feature."
40
            );
41
    }
42
43
    protected function execute(InputInterface $input, OutputInterface $output)
44
    {
45
        $io = new SymfonyStyle($input, $output);
46
47
        $io->title('Generate Missing Subject Identifiers');
48
49
        $this->em = $this->getContainer()->get('doctrine.orm.entity_manager');
50
51
        $io->section("Searching Authorizations with missing Subject Identifiers...");
52
53
        $repo = $this->getAuthorizationRepository();
54
        $count = $repo->createQueryBuilder('a')
55
            ->select('COUNT(a)')
56
            ->leftJoin(
57
                'LoginCidadaoOpenIDBundle:SubjectIdentifier',
58
                's',
59
                'WITH',
60
                's.person = a.person AND s.client = a.client'
61
            )
62
            ->where('s.subjectIdentifier IS NULL')
63
            ->getQuery()
64
            ->getSingleScalarResult();
65
66
        if ($count === 0) {
67
            $io->success("No changes needed. You're all set!");
68
69
            return;
70
        }
71
72
        $io->text("{$count} entries found");
73
74
        $missingSubId = $repo->createQueryBuilder('a')
75
            ->leftJoin(
76
                'LoginCidadaoOpenIDBundle:SubjectIdentifier',
77
                's',
78
                'WITH',
79
                's.person = a.person AND s.client = a.client'
80
            )
81
            ->where('s.subjectIdentifier IS NULL')
82
            ->getQuery()->iterate();
83
84
        $io->section("Generating Sector Identifiers...");
85
86
        /** @var SubjectIdentifierService $subIdService */
87
        $subIdService = $this->getContainer()->get('oidc.subject_identifier.service');
88
89
        $io->progressStart($count);
90
        $current = 0;
91
        foreach ($missingSubId as $row) {
92
            /** @var Authorization $auth */
93
            $auth = $row[0];
94
            $subId = $subIdService->getSubjectIdentifier(
95
                $auth->getPerson(),
0 ignored issues
show
Bug introduced by
It seems like $auth->getPerson() can be null; however, getSubjectIdentifier() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
96
                $this->getClientMetadata($auth->getClient()),
0 ignored issues
show
Bug introduced by
It seems like $auth->getClient() can be null; however, getClientMetadata() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
97
                false
98
            );
99
            $sub = new SubjectIdentifier();
100
            $sub
101
                ->setPerson($auth->getPerson())
0 ignored issues
show
Bug introduced by
It seems like $auth->getPerson() can be null; however, setPerson() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
102
                ->setClient($auth->getClient())
0 ignored issues
show
Bug introduced by
It seems like $auth->getClient() can be null; however, setClient() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
103
                ->setSubjectIdentifier($subId);
104
            $this->em->persist($sub);
105
            if ($current++ % 50 === 0) {
106
                $this->em->flush();
107
                $this->em->clear();
108
            }
109
            $io->progressAdvance();
110
        }
111
        $this->em->flush();
112
        $this->em->clear();
113
        $io->progressFinish();
114
115
        $io->success("Done! {$count} Authorizations updated!");
116
    }
117
118
    /**
119
     * @return AuthorizationRepository
120
     */
121
    private function getAuthorizationRepository()
122
    {
123
        /** @var AuthorizationRepository $repo */
124
        $repo = $this->em->getRepository('LoginCidadaoCoreBundle:Authorization');
125
126
        return $repo;
127
    }
128
129
    /**
130
     * @param Client $client
131
     * @return ClientMetadata
132
     */
133
    private function getClientMetadata(Client $client)
134
    {
135
        $id = $client->getId();
136
        if (array_key_exists($id, $this->clientMetadata)) {
137
            $metadata = $this->clientMetadata[$id];
138
        } else {
139
            $metadata = $client->getMetadata();
140
            $this->clientMetadata[$id] = $metadata;
141
        }
142
143
        return $metadata;
144
    }
145
}
146