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   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\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