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:09
created

SessionCleanupCommand   A

Complexity

Total Complexity 11

Size/Duplication

Total Lines 170
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 14

Test Coverage

Coverage 72.22%

Importance

Changes 7
Bugs 2 Features 0
Metric Value
wmc 11
c 7
b 2
f 0
lcom 1
cbo 14
dl 0
loc 170
rs 10
ccs 52
cts 72
cp 0.7222

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 17 1
A configure() 0 18 1
C execute() 0 84 9
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 2
     */
69
    public function __construct(
70
        ObjectManager $om,
71
        AuthenticationHandlerInterface $authenticationHandler,
72
        EventDispatcherInterface $eventDispatcher,
73
        $modelName,
74
        ClassMetadata $classMetadata,
75
        LoggerInterface $logger = null
76 2
    ) {
77 2
        $this->om = $om;
78 2
        $this->handler = $authenticationHandler;
79 2
        $this->logger = $logger;
80 2
        $this->eventDispatcher = $eventDispatcher;
81 2
        $this->modelName = (string) $modelName;
82
        $this->classMetadata = $classMetadata;
83 2
84 2
        parent::__construct();
85
    }
86
87
    /**
88
     * {@inheritdoc}
89 2
     */
90
    protected function configure()
91 2
    {
92 2
        $this
93 2
            ->setName('ma27:auth:session-cleanup')
94 2
            ->setDescription('Cleans all outdated sessions')
95
            ->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 2
EOF
106 2
            );
107
    }
108
109
    /**
110
     * {@inheritdoc}
111 2
     */
112
    protected function execute(InputInterface $input, OutputInterface $output)
113
    {
114 2
        try {
115 2
            $dateTime = new \DateTime();
116
            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 2
            // search query
123 2
            $expressions = new ExpressionBuilder();
124
            $expr = $expressions->lte(
125 2
                $this->classMetadata->getPropertyName(ClassMetadata::LAST_ACTION_PROPERTY),
126 2
                new \DateTime('-5 days')
127
            );
128 2
129
            $filterCriteria = new Criteria($expr);
130
            $repository = $this->om->getRepository($this->modelName);
131
132
            if ($repository instanceof Selectable) {
133 2
                // orm and mongodb have a Selectable implementation, so it is possible to query for old users
134 2
                $filteredUsers = $repository->matching($filterCriteria);
135
            } else {
136
                // couchdb and phpcr unfortunately don't implement that feature,
137 2
                // so all users must be queried and filtered using the array collection
138
                $allUsers = new ArrayCollection($repository->findAll());
139 2
                $filteredUsers = $allUsers->matching($filterCriteria);
140 2
            }
141 2
142
            $processedObjects = 0;
143
144 2
            $affectedUsers = $filteredUsers->toArray();
145 2
            $event = new OnBeforeSessionCleanupEvent($affectedUsers);
146 1
            $this->eventDispatcher->dispatch(Ma27ApiKeyAuthenticationEvents::BEFORE_CLEANUP, $event);
147
148
            // purge filtered users
149
            foreach ($filteredUsers as $user) {
150
                $apiKey = $this->classMetadata->getPropertyValue($user, ClassMetadata::LAST_ACTION_PROPERTY, true);
151
                if (empty($apiKey)) {
152 1
                    if (null !== $this->logger) {
153
                        $this->logger->notice(sprintf('Skipping unauthorized user "%s"', $user->getUsername()));
154 1
                    }
155
156
                    continue;
157 1
                }
158
159
                $this->handler->removeSession($user, true);
160
                ++$processedObjects;
161
            }
162
163
            if (null !== $this->logger) {
164
                $this->logger->notice(sprintf('Processed %d items successfully', $processedObjects));
165 1
            }
166 1
167 1
            $afterEvent = new OnSuccessfulCleanupEvent($affectedUsers);
168
            $this->eventDispatcher->dispatch(Ma27ApiKeyAuthenticationEvents::CLEANUP_SUCCESS, $afterEvent);
169 1
170
            $this->om->flush();
171
172
            if (null !== $this->logger) {
173 1
                $endTime = new \DateTime();
174 1
                $end = $endTime->format('m/d/Y H:i:s');
175
176 1
                $diff = $endTime->getTimestamp() - $dateTime->getTimestamp();
177
178 1
                $this->logger->notice(sprintf('Stopped cleanup at %s after %d seconds', $end, $diff));
179
            }
180
        } catch (\Exception $ex) {
181
            $this->eventDispatcher->dispatch(
182
                Ma27ApiKeyAuthenticationEvents::CLEANUP_ERROR,
183
                new OnApiKeyCleanupErrorEvent($ex)
184
            );
185
186 2
            throw $ex;
187 1
        }
188 1
189 1
        $this->eventDispatcher->dispatch(
190 1
            Ma27ApiKeyAuthenticationEvents::AFTER_CLEANUP,
191
            new OnAfterCleanupEvent($affectedUsers)
192 1
        );
193
194
        return 0;
195 1
    }
196
}
197