Completed
Push — develop ( a99b17...6a819c )
by
unknown
06:44
created

ConsoleController::setpermissionsAction()   C

Complexity

Conditions 8
Paths 15

Size

Total Lines 45
Code Lines 34

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 45
rs 5.3846
c 0
b 0
f 0
cc 8
eloc 34
nc 15
nop 0
1
<?php
2
3
/**
4
 * YAWIK
5
 *
6
 * @filesource
7
 * @copyright (c) 2013 - 2016 Cross Solution (http://cross-solution.de)
8
 * @license   MIT
9
 */
10
11
/** ConsoleController of Jobs */
12
namespace Jobs\Controller;
13
14
use Core\Repository\RepositoryService;
15
use Interop\Container\ContainerInterface;
16
use Jobs\Entity\StatusInterface;
17
use Zend\Mvc\Controller\AbstractActionController;
18
use Zend\ProgressBar\ProgressBar;
19
use Core\Console\ProgressBar as CoreProgressBar;
20
use Zend\ProgressBar\Adapter\Console as ConsoleAdapter;
21
use Auth\Entity\UserInterface;
22
23
class ConsoleController extends AbstractActionController
24
{
25
	/**
26
	 * @var RepositoryService
27
	 */
28
	private $repositories;
29
	
30
	public function __construct(
31
		RepositoryService $repositories
32
	)
33
	{
34
		$this->repositories = $repositories;
35
	}
36
	
37
	static public function factory(ContainerInterface $container)
0 ignored issues
show
Coding Style introduced by
As per PSR2, the static declaration should come after the visibility declaration.
Loading history...
38
	{
39
		return new self(
40
			$container->get('repositories')
41
		);
42
	}
43
	
44
	public function expireJobsAction()
45
    {
46
        $repositories = $this->repositories;
47
        /* @var \Jobs\Repository\Job $jobsRepo */
48
        $jobsRepo     = $repositories->get('Jobs/Job');
49
        $days = (int) $this->params('days');
50
        $limit = (string) $this->params('limit');
51
        $info = $this->params('info');
52
53
        if (!$days) {
54
            return 'Invalid value for --days. Must be integer.';
55
        }
56
57
        $date = new \DateTime('today');
58
        $date->sub(new \DateInterval('P' . $days . 'D'));
59
60
        $query        = [
61
            '$and' => [
62
                ['status.name' => StatusInterface::ACTIVE],
63
                ['$or' => [
64
                    ['datePublishStart.date' => ['$lt' => $date]],
65
                    ['datePublishEnd.date' => ['$lt' => new \DateTime('today midnight')]],
66
                ]],
67
                ['$or' => [
68
                    ['isDeleted' => ['$exists' => false]],
69
                    ['isDeleted' => false],
70
                ]]
71
            ]
72
        ];
73
74
        $offset = 0;
75
        if ($limit && false !== strpos($limit, ',')) {
76
            list($limit,$offset) = explode(',', $limit);
77
        }
78
79
        $jobs = $jobsRepo->findBy($query, null, (int) $limit, (int) $offset);
80
        $count = count($jobs);
81
82
        if (0 === $count) {
83
            return 'No jobs found.';
84
        }
85
86
        if ($info) {
87
            echo count($jobs) , ' Jobs';
88
            if ($offset) { echo ' starting from ' . $offset; }
89
            echo PHP_EOL . PHP_EOL;
90
            $this->listExpiredJobs($jobs);
91
            return;
92
        }
93
        
94
        foreach ($repositories->getEventManager()->getListeners('preUpdate') as $listener) {
0 ignored issues
show
Documentation Bug introduced by
The method getEventManager does not exist on object<Core\Repository\RepositoryService>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
95
            $repositories->getEventManager()->removeEventListener('preUpdate', $listener);
0 ignored issues
show
Documentation Bug introduced by
The method getEventManager does not exist on object<Core\Repository\RepositoryService>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
96
        }
97
        
98
        
99
        echo "$count jobs found, which have to expire ...\n";
100
        
101
        $progress     = new ProgressBar(
102
            new ConsoleAdapter(
103
                array(
104
                'elements' => array(
105
                    ConsoleAdapter::ELEMENT_TEXT,
106
                    ConsoleAdapter::ELEMENT_BAR,
107
                    ConsoleAdapter::ELEMENT_PERCENT,
108
                    ConsoleAdapter::ELEMENT_ETA
109
                ),
110
                'textWidth' => 20,
111
                'barLeftChar' => '-',
112
                'barRightChar' => ' ',
113
                'barIndicatorChar' => '>',
114
                )
115
            ),
116
            0,
117
            count($jobs)
118
        );
119
120
        $i = 0;
121
122
        /* @var \Jobs\Entity\Job $job */
123
        foreach ($jobs as $job) {
124
            $progress->update($i++, 'Job ' . $i . ' / ' . $count);
125
126
            $job->changeStatus('expired');
127
128
            if (0 == $i % 500) {
129
                $progress->update($i, 'Write to database...');
130
                $repositories->flush();
131
            }
132
        }
133
        $progress->update($i, 'Write to database...');
134
        $repositories->flush();
135
        $progress->update($i, 'Done');
136
        $progress->finish();
137
138
        return PHP_EOL;
139
    }
140
    
141
    public function setpermissionsAction()
142
    {
143
        $repositories = $this->repositories;
144
        $repository   = $repositories->get('Jobs/Job');
145
        $userRep      = $repositories->get('Auth/User');
146
        $jobs         = $repository->findAll();
147
        $count        = count($jobs);
148
        $progress     = new CoreProgressBar($count);
149
        $i            = 0;
150
        /* @var Job $job */
151
        foreach ($jobs as $job) {
152
            $progress->update($i++, 'Job ' . $i . ' / ' . $count);
153
            
154
            $permissions = $job->getPermissions();
155
            $user        = $job->getUser();
156
            if (!$user instanceof UserInterface) {
157
                continue;
158
            }
159
            try {
160
                $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()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
161
            } catch (\Exception $e) {
162
                continue;
163
            }
164
            if ($group) {
165
                $permissions->grant($group, 'view');
166
            }
167
            foreach ($job->getApplications() as $application) {
168
                $progress->update($i, 'set app perms...');
169
                $perms = $application->getPermissions();
170
                $perms->inherit($permissions);
171
                $jobUser = $userRep->findOneByEmail($job->getContactEmail());
172
                if ($jobUser) {
173
                    $perms->grant($jobUser, 'change');
174
                }
175
            }
176
            if (0 == $i % 500) {
177
                $progress->update($i, 'write to database...');
178
                $repositories->flush();
179
            }
180
        }
181
        $progress->update($i, 'write to database...');
182
        $repositories->flush();
183
        $progress->finish();
184
        return PHP_EOL;
185
    }
186
187
    private function listExpiredJobs($jobs)
188
    {
189
        /* @var \Jobs\Entity\JobInterface $job */
190
        foreach ($jobs as $job) {
191
            $id = $job->getId();
192
            $org = $job->getOrganization();
193
            if ($org) {
194
                $org = $org->getName();
195
            } else {
196
                $org = $job->getCompany();
197
            }
198
            printf(
199
                '%s   %s   %s   %-30s   %-20s' . PHP_EOL,
200
                $id,
201
                $job->getDatePublishStart()->format('Y-m-d'),
202
                $job->getDatePublishEnd()->format('Y-m-d'),
203
                substr($job->getTitle(), 0, 30),
204
                substr($org, 0, 20)
205
            );
206
        }
207
        return count($jobs) . ' Jobs.';
208
    }
209
}
210