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
Push — master ( 6daa1e...29b462 )
by Maximilian
03:41
created

SessionCleanupCommand   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 164
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 14

Test Coverage

Coverage 74.63%

Importance

Changes 8
Bugs 3 Features 0
Metric Value
wmc 9
c 8
b 3
f 0
lcom 1
cbo 14
dl 0
loc 164
ccs 50
cts 67
cp 0.7463
rs 10

3 Methods

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