Completed
Push — master ( 64908a...328605 )
by
unknown
03:10
created

VerifiedSecondFactorReminderService   A

Complexity

Total Complexity 12

Size/Duplication

Total Lines 119
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 7

Importance

Changes 0
Metric Value
wmc 12
lcom 1
cbo 7
dl 0
loc 119
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 11 1
C sendReminders() 0 46 8
A buildCollection() 0 23 3
1
<?php
2
/**
3
 * Copyright 2017 SURFnet bv
4
 *
5
 * Licensed under the Apache License, Version 2.0 (the "License");
6
 * you may not use this file except in compliance with the License.
7
 * You may obtain a copy of the License at
8
 *
9
 *     http://www.apache.org/licenses/LICENSE-2.0
10
 *
11
 * Unless required by applicable law or agreed to in writing, software
12
 * distributed under the License is distributed on an "AS IS" BASIS,
13
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
 * See the License for the specific language governing permissions and
15
 * limitations under the License.
16
 */
17
18
namespace Surfnet\StepupMiddleware\MiddlewareBundle\Service;
19
20
use Assert\Assertion;
21
use DateTime;
22
use InvalidArgumentException;
23
use Psr\Log\LoggerInterface;
24
use Surfnet\StepupMiddleware\ApiBundle\Identity\Repository\IdentityRepository;
25
use Surfnet\StepupMiddleware\ApiBundle\Identity\Repository\VerifiedSecondFactorRepository;
26
use Surfnet\StepupMiddleware\ApiBundle\Identity\Value\VerifiedTokenInformation;
27
28
/**
29
 * Retrieves tokens (second factors) that got registered at a given date. That data is then used to send a reminder
30
 * message to the identity the token belongs to, informing them to vet the token.
31
 */
32
class VerifiedSecondFactorReminderService
33
{
34
    /**
35
     * @var VerifiedSecondFactorRepository
36
     */
37
    private $verifiedRepository;
38
39
    /**
40
     * @var IdentityRepository
41
     */
42
    private $identityRepository;
43
44
    /**
45
     * @var VerifiedSecondFactorReminderMailService
46
     */
47
    private $mailService;
48
49
    /**
50
     * @var LoggerInterface
51
     */
52
    private $logger;
53
54
    /**
55
     * @param VerifiedSecondFactorRepository $verifiedRepository
56
     * @param IdentityRepository $identityRepository
57
     * @param VerifiedSecondFactorReminderMailService $mailService
58
     * @param LoggerInterface $logger
59
     */
60
    public function __construct(
61
        VerifiedSecondFactorRepository $verifiedRepository,
62
        IdentityRepository $identityRepository,
63
        VerifiedSecondFactorReminderMailService $mailService,
64
        LoggerInterface $logger
65
    ) {
66
        $this->verifiedRepository = $verifiedRepository;
67
        $this->identityRepository = $identityRepository;
68
        $this->mailService = $mailService;
69
        $this->logger = $logger;
70
    }
71
72
    /**
73
     * @param DateTime $date
74
     * @param bool $dryRun
75
     */
76
    public function sendReminders(DateTime $date, $dryRun)
77
    {
78
        $this->logger->info(
79
            sprintf(
80
                'Sending reminders for date: %s. dry run mode is %s',
81
                $date->format('Y-m-d'),
82
                ($dryRun ? 'enabled' : 'disabled')
83
            )
84
        );
85
86
        $totalNumberSent = 0;
87
88
        $tokenInformationCollection = $this->buildCollection($date);
89
90
        if (!empty($tokenInformationCollection)) {
91
            $this->logger->info(sprintf('%d token reminder(s) will be sent', count($tokenInformationCollection)));
92
93
            foreach ($tokenInformationCollection as $tokenInformation) {
94
                if (!$dryRun) {
95
                    $numberSent = $this->mailService->sendReminder($tokenInformation);
96
                } else {
97
                    $numberSent = 1;
98
                }
99
100
                $this->logger->info(
101
                    sprintf(
102
                        'Message %s sent %sto "%s" with token id "%s" of type "%s"',
103
                        ($numberSent === 1 ? 'successfully' : 'was not'),
104
                        ($dryRun ? 'in dry run mode ' : ''),
105
                        $tokenInformation->getEmail(),
106
                        $tokenInformation->getTokenId(),
107
                        $tokenInformation->getTokenType()
108
                    )
109
                );
110
                $totalNumberSent += $numberSent;
111
            }
112
        }
113
114
        $this->logger->info(
115
            sprintf(
116
                '%d reminders %s been sent',
117
                $totalNumberSent,
118
                ($dryRun ? 'would have' : 'have')
119
            )
120
        );
121
    }
122
123
    /**
124
     * @param DateTime $date
125
     * @return VerifiedTokenInformation[]
126
     */
127
    private function buildCollection(DateTime $date)
128
    {
129
        $collection = [];
130
131
        foreach ($this->verifiedRepository->findByDate($date) as $token) {
132
            try {
133
                $identity = $this->identityRepository->find($token->identityId);
134
                Assertion::isObject(
135
                    $identity,
136
                    sprintf(
137
                        'Identity not found with id "%s" for second factor token "%s"',
138
                        $token->identityId,
139
                        $token->id
140
                    )
141
                );
142
                $collection[] = VerifiedTokenInformation::fromEntity($token, $identity);
0 ignored issues
show
Bug introduced by
It seems like $identity defined by $this->identityRepositor...ind($token->identityId) on line 133 can be null; however, Surfnet\StepupMiddleware...formation::fromEntity() 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...
143
            } catch (InvalidArgumentException $e) {
144
                $this->logger->alert($e->getMessage());
145
            }
146
        }
147
148
        return $collection;
149
    }
150
}
151