Completed
Pull Request — develop (#201)
by
unknown
05:53 queued 02:58
created

execute()   B

Complexity

Conditions 6
Paths 5

Size

Total Lines 28
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 28
rs 8.439
c 0
b 0
f 0
cc 6
eloc 18
nc 5
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 Symfony\Component\Console\Command\Command;
26
use Symfony\Component\Console\Input\InputArgument;
27
use Symfony\Component\Console\Input\InputInterface;
28
use Symfony\Component\Console\Input\InputOption;
29
use Symfony\Component\Console\Output\OutputInterface;
30
use Symfony\Component\DependencyInjection\Container;
31
32
/**
33
 * The EmailVerifiedSecondFactorRemindersCommand can be run to send reminders to token registrants.
34
 *
35
 * The command utilizes a specific service for this task (VerifiedSecondFactorReminderService). Input validation is
36
 * performed on the incoming request parameters.
37
 */
38
final class EmailVerifiedSecondFactorRemindersCommand extends Command
39
{
40
    protected function configure()
41
    {
42
        $this
43
            ->setName('middleware:cron:email-reminder')
44
            ->setDescription('Sends email reminders to identities with verified tokens more than 7 days old.')
45
            ->addOption('dry-run', null,InputOption::VALUE_NONE, 'Run in dry mode, not sending any email')
46
            ->addOption(
47
                'date',
48
                null,
49
                InputOption::VALUE_OPTIONAL,
50
                'The date (Y-m-d) that should be used for sending reminder email messages, defaults to TODAY - 7'
51
            );
52
    }
53
54
    protected function execute(InputInterface $input, OutputInterface $output)
55
    {
56
        /** @var Container $container */
57
        $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...
58
59
        $service = $container->get('surfnet_stepup_middleware_middleware.verfied_second_factor_reminder');
60
        $logger = $container->get('logger');
61
62
        try {
63
            $this->validateInput($input);
64
        } catch (InvalidArgumentException $e) {
65
            $output->writeln('<error>' . $e->getMessage() . '</error>');
66
            $logger->error(sprintf('Invalid arguments passed to the %s', $this->getName()), [$e->getMessage()]);
67
            return 1;
68
        }
69
70
        $date = new DateTime();
71
        $date->sub(new DateInterval('P7D'));
72
        if ($input->hasOption('date') && !is_null($input->getOption('date'))) {
73
            $date = DateTime::createFromFormat('Y-m-d', $input->getOption('date'));
74
        }
75
76
        $dryRun = false;
77
        if ($input->hasOption('dry-run') && !is_null($input->getOption('dry-run'))) {
78
            $dryRun = $input->getOption('dry-run');
79
        }
80
        $service->sendReminders($date, $dryRun);
81
    }
82
83
    private function validateInput(InputInterface $input)
84
    {
85
        if ($input->hasOption('date')) {
86
            $date = $input->getOption('date');
87
            Assertion::nullOrDate($date, 'Y-m-d', 'Expected date to be a string and formatted as a Y-m-d');
88
        }
89
90
        if ($input->hasOption('dry-run')) {
91
            $dryRun = $input->getOption('dry-run');
92
            Assertion::nullOrBoolean($dryRun, 'Expected dry-run parameter to be a boolean value.');
93
        }
94
    }
95
}
96