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
Branch develop (4efcd8)
by Maximilian
04:45
created

SessionCleanupCommand::execute()   B

Complexity

Conditions 3
Paths 10

Size

Total Lines 33
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 18
CRAP Score 3.0924

Importance

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