Passed
Pull Request — main (#557)
by Johan
10:46 queued 05:30
created

__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 0

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 0
nc 1
nop 4
dl 0
loc 6
rs 10
c 0
b 0
f 0
1
<?php
2
3
/**
4
 * Copyright 2014 SURFnet bv
5
 *
6
 * Licensed under the Apache License, Version 2.0 (the "License");
7
 * you may not use this file except in compliance with the License.
8
 * You may obtain a copy of the License at
9
 *
10
 *     http://www.apache.org/licenses/LICENSE-2.0
11
 *
12
 * Unless required by applicable law or agreed to in writing, software
13
 * distributed under the License is distributed on an "AS IS" BASIS,
14
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
 * See the License for the specific language governing permissions and
16
 * limitations under the License.
17
 */
18
19
namespace Surfnet\StepupMiddleware\MiddlewareBundle\Console\Command;
20
21
use Assert\Assertion;
22
use DateInterval;
23
use DateTime;
24
use Exception;
25
use InvalidArgumentException;
26
use Psr\Log\LoggerInterface;
27
use Ramsey\Uuid\Uuid;
28
use Surfnet\StepupMiddleware\CommandHandlingBundle\EventHandling\BufferedEventBus;
29
use Surfnet\StepupMiddleware\CommandHandlingBundle\Identity\Command\SendVerifiedSecondFactorRemindersCommand;
30
use Surfnet\StepupMiddleware\CommandHandlingBundle\Pipeline\TransactionAwarePipeline;
31
use Surfnet\StepupMiddleware\MiddlewareBundle\Service\DBALConnectionHelper;
32
use Symfony\Component\Console\Attribute\AsCommand;
33
use Symfony\Component\Console\Attribute\Option;
34
use Symfony\Component\Console\Command\Command;
35
use Symfony\Component\Console\Output\OutputInterface;
36
37
/**
38
 * The EmailVerifiedSecondFactorRemindersCommand can be run to send reminders to token registrants.
39
 *
40
 * The command utilizes a specific service for this task (VerifiedSecondFactorReminderService). Input validation is
41
 * performed on the incoming request parameters.
42
 *
43
 * @SuppressWarnings("PHPMD.CouplingBetweenObjects")
44
 */
45
#[AsCommand(
46
    name: 'middleware:cron:email-reminder',
47
    description: 'Sends email reminders to identities with verified tokens more than 7 days old.'
48
)]
49
final class EmailVerifiedSecondFactorRemindersCommand
50
{
51
    public function __construct(
52
        private readonly TransactionAwarePipeline $pipeline,
53
        private readonly BufferedEventBus $eventBus,
54
        private readonly DBALConnectionHelper $connection,
55
        private readonly LoggerInterface $logger
56
    ) {
57
    }
58
59
    public function __invoke(
60
        OutputInterface $output,
61
        #[Option(description: 'Run in dry mode, not sending any email', name: 'dry-run')]
62
        bool $dryRun = false,
63
        #[Option(description: 'The date (Y-m-d) that should be used for sending reminder email messages, defaults to TODAY - 7', name: 'date')]
64
        ?string $date = null,
65
    ): int {
66
        try {
67
            Assertion::nullOrDate(
68
                $date,
69
                'Y-m-d',
70
                'Expected date to be a string and formatted in the Y-m-d date format',
71
            );
72
        } catch (InvalidArgumentException $e) {
73
            $output->writeln('<error>' . $e->getMessage() . '</error>');
74
            $this->logger->error(sprintf('Invalid arguments passed to the %s', 'middleware:cron:email-reminder'), [$e->getMessage()]);
75
            return 1;
76
        }
77
78
        $now = new DateTime();
79
        $now->sub(new DateInterval('P7D'));
80
        if ($date) {
81
            $receivedDate = $date;
82
            $date = DateTime::createFromFormat('Y-m-d', $receivedDate);
83
            if ($date === false) {
84
                $output->writeln(
85
                    sprintf(
86
                        '<error>Error processing the "date" option. Please review the received input: "%s" </error>',
87
                        $receivedDate
88
                    )
89
                );
90
                return 1;
91
            }
92
        }
93
94
        $command = new SendVerifiedSecondFactorRemindersCommand();
95
        $command->requestedAt = $date ?: $now;
0 ignored issues
show
Documentation Bug introduced by
It seems like $date ?: $now can also be of type string. However, the property $requestedAt is declared as type DateTime. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
96
        $command->dryRun = $dryRun;
97
        $command->UUID = Uuid::uuid4()->toString();
98
99
        $this->connection->beginTransaction();
100
        try {
101
            $this->pipeline->process($command);
102
            $this->eventBus->flush();
103
104
            $this->connection->commit();
105
        } catch (Exception $e) {
106
            $output->writeln('<error>An Error occurred while sending reminder email messages.</error>');
107
            $this->connection->rollBack();
108
            throw $e;
109
        }
110
        return 0;
111
    }
112
}
113