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

execute()   C

Complexity

Conditions 7
Paths 17

Size

Total Lines 49
Code Lines 34

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 49
rs 6.7272
c 0
b 0
f 0
cc 7
eloc 34
nc 17
nop 2
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 InvalidArgumentException;
25
use Rhumsaa\Uuid\Uuid;
26
use Surfnet\StepupMiddleware\CommandHandlingBundle\Identity\Command\SendVerifiedSecondFactorRemindersCommand;
27
use Symfony\Component\Console\Command\Command;
28
use Symfony\Component\Console\Input\InputInterface;
29
use Symfony\Component\Console\Input\InputOption;
30
use Symfony\Component\Console\Output\OutputInterface;
31
use Symfony\Component\DependencyInjection\Container;
32
33
/**
34
 * The EmailVerifiedSecondFactorRemindersCommand can be run to send reminders to token registrants.
35
 *
36
 * The command utilizes a specific service for this task (VerifiedSecondFactorReminderService). Input validation is
37
 * performed on the incoming request parameters.
38
 */
39
final class EmailVerifiedSecondFactorRemindersCommand extends Command
40
{
41
    protected function configure()
42
    {
43
        $this
44
            ->setName('middleware:cron:email-reminder')
45
            ->setDescription('Sends email reminders to identities with verified tokens more than 7 days old.')
46
            ->addOption(
47
                'dry-run',
48
                null,
49
                InputOption::VALUE_NONE,
50
                'Run in dry mode, not sending any email'
51
            )
52
            ->addOption(
53
                'date',
54
                null,
55
                InputOption::VALUE_OPTIONAL,
56
                'The date (Y-m-d) that should be used for sending reminder email messages, defaults to TODAY - 7'
57
            );
58
    }
59
60
    protected function execute(InputInterface $input, OutputInterface $output)
61
    {
62
        /** @var Container $container */
63
        $container = $this->getApplication()->getKernel()->getContainer();
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class Symfony\Component\Console\Application as the method getKernel() does only exist in the following sub-classes of Symfony\Component\Console\Application: Symfony\Bundle\FrameworkBundle\Console\Application. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

abstract class User
{
    /** @return string */
    abstract public function getPassword();
}

class MyUser extends User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different sub-classes of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
64
65
        $pipeline = $container->get('surfnet_stepup_middleware_command_handling.pipeline.transaction_aware_pipeline');
66
        $eventBus = $container->get('surfnet_stepup_middleware_command_handling.event_bus.buffered');
67
        $connection = $container->get('surfnet_stepup_middleware_middleware.dbal_connection_helper');
68
        $logger = $container->get('logger');
69
70
        try {
71
            $this->validateInput($input);
72
        } catch (InvalidArgumentException $e) {
73
            $output->writeln('<error>' . $e->getMessage() . '</error>');
74
            $logger->error(sprintf('Invalid arguments passed to the %s', $this->getName()), [$e->getMessage()]);
75
            return 1;
76
        }
77
78
        $date = new DateTime();
79
        $date->sub(new DateInterval('P7D'));
80
        if ($input->hasOption('date') && !is_null($input->getOption('date'))) {
81
            $date = DateTime::createFromFormat('Y-m-d', $input->getOption('date'));
82
        }
83
84
        $dryRun = false;
85
        if ($input->hasOption('dry-run') && !is_null($input->getOption('dry-run'))) {
86
            $dryRun = $input->getOption('dry-run');
87
        }
88
89
        $command = new SendVerifiedSecondFactorRemindersCommand();
90
        $command->requestedAt = $date;
0 ignored issues
show
Documentation Bug introduced by
It seems like $date can also be of type false. However, the property $requestedAt is declared as type object<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...
91
        $command->dryRun = $dryRun;
92
        $command->UUID = Uuid::uuid4()->toString();
93
94
        $connection->beginTransaction();
95
        try {
96
            $pipeline->process($command);
97
            $eventBus->flush();
98
99
            $connection->commit();
100
        } catch (Exception $e) {
0 ignored issues
show
Bug introduced by
The class Surfnet\StepupMiddleware...nsole\Command\Exception does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
101
            $output->writeln(sprintf(
102
                '<error>An Error occurred while sending reminder email messages.</error>',
103
                $e->getMessage()
104
            ));
105
            $connection->rollBack();
106
            throw $e;
107
        }
108
    }
109
110
    private function validateInput(InputInterface $input)
111
    {
112
        if ($input->hasOption('date')) {
113
            $date = $input->getOption('date');
114
            Assertion::nullOrDate($date, 'Y-m-d', 'Expected date to be a string and formatted in the Y-m-d date format');
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 121 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
115
        }
116
117
        if ($input->hasOption('dry-run')) {
118
            $dryRun = $input->getOption('dry-run');
119
            Assertion::nullOrBoolean($dryRun, 'Expected dry-run parameter to be a boolean value.');
120
        }
121
    }
122
}
123