Completed
Pull Request — master (#582)
by ANTHONIUS
08:19
created

ConsoleController   A

Complexity

Total Complexity 25

Size/Duplication

Total Lines 197
Duplicated Lines 0 %

Test Coverage

Coverage 36.7%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 25
eloc 117
c 1
b 0
f 0
dl 0
loc 197
ccs 40
cts 109
cp 0.367
rs 10

6 Methods

Rating   Name   Duplication   Size   Complexity  
A factory() 0 4 1
A listExpiredJobs() 0 24 5
A __construct() 0 4 1
A pushFetchExternalImagesJobAction() 0 5 1
B setpermissionsAction() 0 44 8
B expireJobsAction() 0 97 9
1
<?php
2
3
/**
4
 * YAWIK
5
 *
6
 * @filesource
7
 * @copyright https://yawik.org/COPYRIGHT.php
8
 * @license   MIT
9
 */
10
11
/** ConsoleController of Jobs */
12
namespace Jobs\Controller;
13
14
use Core\Queue\LazyJob;
15
use Core\Repository\RepositoryService;
16
use Interop\Container\ContainerInterface;
17
use Jobs\Entity\StatusInterface;
18
use Jobs\Queue\FindJobsWithExternalImageJob;
19
use Laminas\Mvc\Console\Controller\AbstractConsoleController;
20
use Laminas\ProgressBar\ProgressBar;
21
use Core\Console\ProgressBar as CoreProgressBar;
22
use Laminas\ProgressBar\Adapter\Console as ConsoleAdapter;
23
use Laminas\Console\ColorInterface as ConsoleColor;
24
use Auth\Entity\UserInterface;
25
26
class ConsoleController extends AbstractConsoleController
27
{
28
    /**
29
     * @var RepositoryService
30
     */
31
    private $repositories;
32
33 1
    public function __construct(
34
        RepositoryService $repositories
35
    ) {
36 1
        $this->repositories = $repositories;
37
    }
38
39
    public static function factory(ContainerInterface $container)
40
    {
41
        return new self(
42
            $container->get('repositories')
43
        );
44
    }
45
46 1
    public function expireJobsAction()
47
    {
48 1
        $repositories = $this->repositories;
49
        /* @var \Jobs\Repository\Job $jobsRepo */
50 1
        $jobsRepo     = $repositories->get('Jobs/Job');
51 1
        $days = (int) $this->params('days');
52 1
        $limit = (string) $this->params('limit');
53 1
        $info = $this->params('info');
54 1
        $console = $this->console;
55
56 1
        if (!$days) {
57
            return 'Invalid value for --days. Must be integer.';
58
        }
59
60 1
        $date = new \DateTime('today');
61 1
        $date->sub(new \DateInterval('P' . $days . 'D'));
62
63
        $query        = [
64
            '$and' => [
65 1
                ['status.name' => StatusInterface::ACTIVE],
66
                ['$or' => [
67 1
                    ['datePublishStart.date' => ['$lt' => $date]],
68 1
                    ['datePublishEnd.date' => ['$lt' => new \DateTime('today midnight')]],
69
                ]],
70
                ['$or' => [
71
                    ['isDeleted' => ['$exists' => false]],
72
                    ['isDeleted' => false],
73
                ]]
74
            ]
75
        ];
76
77 1
        $offset = 0;
78 1
        if ($limit && false !== strpos($limit, ',')) {
79
            list($limit, $offset) = explode(',', $limit);
80
        }
81
82 1
        $jobs = $jobsRepo->findBy($query, null, (int) $limit, (int) $offset);
83 1
        $count = count($jobs);
84
85 1
        if (0 === $count) {
86
            $console->writeLine('No jobs found.', ConsoleColor::GREEN);
87
        }
88
89 1
        if ($info) {
90 1
            $output = count($jobs).' Jobs';
91 1
            if ($offset) {
92
                $output .= ' starting from ' . $offset;
93
            }
94 1
            $console->writeLine($output, ConsoleColor::YELLOW);
95 1
            $this->listExpiredJobs($jobs);
96 1
            return;
97
        }
98
99
//        foreach ($repositories->getEventManager()->getListeners('preUpdate') as $listener) {
100
//            $repositories->getEventManager()->removeEventListener('preUpdate', $listener);
101
//        }
102
//
103
        $console->writeLine("$count jobs found, which have to expire ...\n", ConsoleColor::GREEN);
104
105
        $progress     = new ProgressBar(
106
            new ConsoleAdapter(
107
                array(
108
                'elements' => array(
109
                    ConsoleAdapter::ELEMENT_TEXT,
110
                    ConsoleAdapter::ELEMENT_BAR,
111
                    ConsoleAdapter::ELEMENT_PERCENT,
112
                    ConsoleAdapter::ELEMENT_ETA
113
                ),
114
                'textWidth' => 20,
115
                'barLeftChar' => '-',
116
                'barRightChar' => ' ',
117
                'barIndicatorChar' => '>',
118
                )
119
            ),
120
            0,
121
            count($jobs)
122
        );
123
124
        $i = 0;
125
126
        /* @var \Jobs\Entity\Job $job */
127
        foreach ($jobs as $job) {
128
            $progress->update($i++, 'Job ' . $i . ' / ' . $count);
129
130
            $job->changeStatus('expired');
131
132
            if (0 == $i % 500) {
133
                $progress->update($i, 'Write to database...');
134
                $repositories->flush();
135
            }
136
        }
137
        $progress->update($i, 'Write to database...');
138
        $repositories->flush();
139
        $progress->update($i, 'Done');
140
        $progress->finish();
141
142
        return PHP_EOL;
143
    }
144
145
    public function setpermissionsAction()
146
    {
147
        $repositories = $this->repositories;
148
        $repository   = $repositories->get('Jobs/Job');
149
        $userRep      = $repositories->get('Auth/User');
150
        $jobs         = $repository->findAll();
151
        $count        = count($jobs);
152
        $progress     = new CoreProgressBar($count);
153
        $i            = 0;
154
        /* @var Job $job */
155
        foreach ($jobs as $job) {
156
            $progress->update($i++, 'Job ' . $i . ' / ' . $count);
157
158
            $permissions = $job->getPermissions();
159
            $user        = $job->getUser();
160
            if (!$user instanceof UserInterface) {
161
                continue;
162
            }
163
            try {
164
                $group       = $user->getGroup($job->getCompany());
0 ignored issues
show
Bug introduced by
The method getGroup() does not exist on Auth\Entity\UserInterface. Did you maybe mean getGroups()? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

164
                /** @scrutinizer ignore-call */ 
165
                $group       = $user->getGroup($job->getCompany());

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
165
            } catch (\Exception $e) {
166
                continue;
167
            }
168
            if ($group) {
169
                $permissions->grant($group, 'view');
170
            }
171
            foreach ($job->getApplications() as $application) {
172
                $progress->update($i, 'set app perms...');
173
                $perms = $application->getPermissions();
174
                $perms->inherit($permissions);
175
                $jobUser = $userRep->findOneByEmail($job->getContactEmail());
0 ignored issues
show
Bug introduced by
The method findOneByEmail() does not exist on Doctrine\Common\Persistence\ObjectRepository. Did you maybe mean findOneBy()? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

175
                /** @scrutinizer ignore-call */ 
176
                $jobUser = $userRep->findOneByEmail($job->getContactEmail());

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
176
                if ($jobUser) {
177
                    $perms->grant($jobUser, 'change');
178
                }
179
            }
180
            if (0 == $i % 500) {
181
                $progress->update($i, 'write to database...');
182
                $repositories->flush();
183
            }
184
        }
185
        $progress->update($i, 'write to database...');
186
        $repositories->flush();
187
        $progress->finish();
188
        return PHP_EOL;
189
    }
190
191 1
    private function listExpiredJobs($jobs)
192
    {
193 1
        $console = $this->console;
194
        /* @var \Jobs\Entity\JobInterface $job */
195 1
        foreach ($jobs as $job) {
196 1
            $id = $job->getId();
197 1
            $org = $job->getOrganization();
198 1
            if ($org) {
199
                $org = $org->getName();
200
            } else {
201 1
                $org = $job->getCompany();
202
            }
203
204 1
            $publishStart = is_null($job->getDatePublishStart()) ? 'N/A':$job->getDatePublishStart()->format('Y-m-d');
205 1
            $publishEnd = is_null($job->getDatePublishEnd()) ? 'N/A':$job->getDatePublishEnd()->format('Y-m-d');
206 1
            $output = sprintf(
207 1
                '%s   %s   %s   %-30s   %-20s' . PHP_EOL,
208
                $id,
209
                $publishStart,
210
                $publishEnd,
211 1
                substr($job->getTitle(), 0, 30),
212 1
                substr($org, 0, 20)
213
            );
214 1
            $console->writeLine($output, ConsoleColor::GREEN);
215
        }
216
    }
217
218
    public function pushFetchExternalImagesJobAction()
219
    {
220
        $this->queue('default')->pushJob(FindJobsWithExternalImageJob::create());
0 ignored issues
show
Bug introduced by
The method pushJob() does not exist on Laminas\Stdlib\DispatchableInterface. It seems like you code against a sub-type of Laminas\Stdlib\DispatchableInterface such as Laminas\Mvc\Controller\AbstractController. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

220
        $this->queue('default')->/** @scrutinizer ignore-call */ pushJob(FindJobsWithExternalImageJob::create());
Loading history...
Bug introduced by
The method queue() does not exist on Jobs\Controller\ConsoleController. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

220
        $this->/** @scrutinizer ignore-call */ 
221
               queue('default')->pushJob(FindJobsWithExternalImageJob::create());
Loading history...
221
222
        return 'Job pushed to queue.';
223
    }
224
}
225