GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Completed
Pull Request — master (#31)
by Maximilian
02:55
created

SessionCleanupCommand::execute()   C

Complexity

Conditions 7
Paths 107

Size

Total Lines 78
Code Lines 45

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 34
CRAP Score 8.8143

Importance

Changes 6
Bugs 1 Features 0
Metric Value
c 6
b 1
f 0
dl 0
loc 78
ccs 34
cts 51
cp 0.6667
rs 6.2312
cc 7
eloc 45
nc 107
nop 2
crap 8.8143

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace Ma27\ApiKeyAuthenticationBundle\Command;
4
5
use Doctrine\Common\Collections\ArrayCollection;
6
use Doctrine\Common\Collections\Criteria;
7
use Doctrine\Common\Collections\ExpressionBuilder;
8
use Doctrine\Common\Collections\Selectable;
9
use Doctrine\Common\Persistence\ObjectManager;
10
use Ma27\ApiKeyAuthenticationBundle\Event\OnAfterCleanupEvent;
11
use Ma27\ApiKeyAuthenticationBundle\Event\OnApiKeyCleanupErrorEvent;
12
use Ma27\ApiKeyAuthenticationBundle\Event\OnBeforeSessionCleanupEvent;
13
use Ma27\ApiKeyAuthenticationBundle\Event\OnSuccessfulCleanupEvent;
14
use Ma27\ApiKeyAuthenticationBundle\Ma27ApiKeyAuthenticationEvents;
15
use Ma27\ApiKeyAuthenticationBundle\Model\Login\AuthenticationHandlerInterface;
16
use Ma27\ApiKeyAuthenticationBundle\Model\User\ClassMetadata;
17
use Ma27\ApiKeyAuthenticationBundle\Model\User\UserInterface;
18
use Psr\Log\LoggerInterface;
19
use Symfony\Component\Console\Command\Command;
20
use Symfony\Component\Console\Input\InputInterface;
21
use Symfony\Component\Console\Output\OutputInterface;
22
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
23
24
/**
25
 * Command which is responsible for the session cleanup.
26
 */
27
class SessionCleanupCommand extends Command
28
{
29
    /**
30
     * @var ObjectManager
31
     */
32
    private $om;
33
34
    /**
35
     * @var AuthenticationHandlerInterface
36
     */
37
    private $handler;
38
39
    /**
40
     * @var LoggerInterface
41
     */
42
    private $logger;
43
44
    /**
45
     * @var EventDispatcherInterface
46
     */
47
    private $eventDispatcher;
48
49
    /**
50
     * @var string
51
     */
52
    private $modelName;
53
54
    /**
55
     * @var ClassMetadata
56
     */
57
    private $classMetadata;
58
59
    /**
60
     * Constructor.
61
     *
62
     * @param ObjectManager                  $om
63
     * @param AuthenticationHandlerInterface $authenticationHandler
64
     * @param EventDispatcherInterface       $eventDispatcher
65
     * @param string                         $modelName
66
     * @param ClassMetadata                  $classMetadata
67
     * @param LoggerInterface                $logger
68
     */
69 1
    public function __construct(
70
        ObjectManager $om,
71
        AuthenticationHandlerInterface $authenticationHandler,
72
        EventDispatcherInterface $eventDispatcher,
73
        $modelName,
74
        ClassMetadata $classMetadata,
75
        LoggerInterface $logger = null
76
    ) {
77 1
        $this->om = $om;
78 1
        $this->handler = $authenticationHandler;
79 1
        $this->logger = $logger;
80 1
        $this->eventDispatcher = $eventDispatcher;
81 1
        $this->modelName = (string) $modelName;
82 1
        $this->classMetadata = $classMetadata;
83
84 1
        parent::__construct();
85 1
    }
86
87
    /**
88
     * {@inheritdoc}
89
     */
90 1
    protected function configure()
91
    {
92 1
        $this
93 1
            ->setName('ma27:auth:session-cleanup')
94 1
            ->setDescription('Cleans all outdated sessions')
95 1
            ->setHelp(<<<EOF
96
The <info>ma27:auth:session-cleanup</info> command purges all api keys of users that were inactive for at least 5 days
97
98
The usage is pretty simple:
99
100
    <info>php app/console ma27:auth:session-cleanup</info>
101
102
NOTE: you have to enable the cleanup section of that bundle (please review the docs for more information)
103
104
<info>It's recommended to use a cronjob that purges old api keys every day/two days</info>
105
EOF
106 1
            );
107 1
    }
108
109
    /**
110
     * {@inheritdoc}
111
     */
112 1
    protected function execute(InputInterface $input, OutputInterface $output)
113
    {
114
        try {
115 1
            $dateTime = new \DateTime();
116 1
            if (null !== $this->logger) {
117
                $now = $dateTime->format('m/d/Y H:i:s');
118
119
                $this->logger->notice(sprintf('Starting session purge at %s', $now));
120
            }
121
122
            // search query
123 1
            $latestActivationPropertyName = $this->classMetadata->getPropertyName(ClassMetadata::LAST_ACTION_PROPERTY);
124 1
            $criteria                     = Criteria::create()
125 1
                ->where(Criteria::expr()->lte($latestActivationPropertyName, new \DateTime('-5 days')))
126 1
                ->andWhere(
127 1
                    Criteria::expr()->neq(
128 1
                        $this->classMetadata->getPropertyName(ClassMetadata::API_KEY_PROPERTY),
129
                        null
130 1
                    )
131 1
                );
132
133 1
            $repository = $this->om->getRepository($this->modelName);
134
135 1
            if ($repository instanceof Selectable) {
136
                // orm and mongodb have a Selectable implementation, so it is possible to query for old users
137
                $filteredUsers = $repository->matching($criteria);
138
            } else {
139
                // couchdb and phpcr unfortunately don't implement that feature,
140
                // so all users must be queried and filtered using the array collection
141 1
                $allUsers = new ArrayCollection($repository->findAll());
142 1
                $filteredUsers = $allUsers->matching($criteria);
143
            }
144
145 1
            $processedObjects = 0;
146
147 1
            $affectedUsers = $filteredUsers->toArray();
148 1
            $event = new OnBeforeSessionCleanupEvent($affectedUsers);
149 1
            $this->eventDispatcher->dispatch(Ma27ApiKeyAuthenticationEvents::BEFORE_CLEANUP, $event);
150
151
            // purge filtered users
152 1
            foreach ($filteredUsers as $user) {
153 1
                $this->handler->removeSession($user, true);
154 1
                ++$processedObjects;
155 1
            }
156
157 1
            if (null !== $this->logger) {
158
                $this->logger->notice(sprintf('Processed %d items successfully', $processedObjects));
159
            }
160
161 1
            $afterEvent = new OnSuccessfulCleanupEvent($affectedUsers);
162 1
            $this->eventDispatcher->dispatch(Ma27ApiKeyAuthenticationEvents::CLEANUP_SUCCESS, $afterEvent);
163
164 1
            $this->om->flush();
165
166 1
            if (null !== $this->logger) {
167
                $endTime = new \DateTime();
168
                $end = $endTime->format('m/d/Y H:i:s');
169
170
                $diff = $endTime->getTimestamp() - $dateTime->getTimestamp();
171
172
                $this->logger->notice(sprintf('Stopped cleanup at %s after %d seconds', $end, $diff));
173
            }
174 1
        } catch (\Exception $ex) {
175
            $this->eventDispatcher->dispatch(
176
                Ma27ApiKeyAuthenticationEvents::CLEANUP_ERROR,
177
                new OnApiKeyCleanupErrorEvent($ex)
178
            );
179
180
            throw $ex;
181
        }
182
183 1
        $this->eventDispatcher->dispatch(
184 1
            Ma27ApiKeyAuthenticationEvents::AFTER_CLEANUP,
185 1
            new OnAfterCleanupEvent($affectedUsers)
186 1
        );
187
188 1
        return 0;
189
    }
190
}
191