Completed
Push — feature/send-vetting-reminder ( acaa4f )
by
unknown
03:20
created

execute()   B

Complexity

Conditions 6
Paths 5

Size

Total Lines 27
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

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