Completed
Push — 2.0 ( 4129d9...bcdb61 )
by Marco
02:16
created

Manager::getAll()   B

Complexity

Conditions 4
Paths 2

Size

Total Lines 38
Code Lines 23

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 38
rs 8.5806
cc 4
eloc 23
nc 2
nop 1
1
<?php namespace Comodojo\Extender\Schedule;
2
3
use \Comodojo\Foundation\Base\Configuration;
4
use \Comodojo\Foundation\Events\Manager as EventsManager;
5
use \Comodojo\Daemon\Traits\LoggerTrait;
6
use \Comodojo\Daemon\Traits\EventsTrait;
7
use \Comodojo\Extender\Traits\ConfigurationTrait;
8
use \Comodojo\Extender\Traits\EntityManagerTrait;
9
use \Comodojo\Extender\Orm\Entities\Schedule;
10
use \Doctrine\ORM\EntityManager;
11
use \Psr\Log\LoggerInterface;
12
use \DateTime;
13
use \Exception;
14
15
/**
16
* @package     Comodojo Extender
17
* @author      Marco Giovinazzi <[email protected]>
18
* @license     MIT
19
*
20
* LICENSE:
21
*
22
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
23
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
24
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
25
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
26
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
27
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
28
* THE SOFTWARE.
29
 */
30
31
class Manager {
32
33
    use ConfigurationTrait;
34
    use LoggerTrait;
35
    use EventsTrait;
36
    use EntityManagerTrait;
37
38
    // protected $locker;
39
40
    /**
41
     * Class constructor
42
     *
43
     * @param string $manager_name
0 ignored issues
show
Bug introduced by
There is no parameter named $manager_name. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
44
     * @param Configuration $configuration
45
     * @param LoggerInterface $logger
46
     * @param TasksTable $tasks
0 ignored issues
show
Bug introduced by
There is no parameter named $tasks. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
47
     * @param EventsManager $events
48
     * @param EntityManager $em
49
     */
50 View Code Duplication
    public function __construct(
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
51
        Configuration $configuration,
52
        LoggerInterface $logger,
53
        EventsManager $events,
54
        EntityManager $em = null
55
    ) {
56
57
        $this->setConfiguration($configuration);
58
        $this->setLogger($logger);
59
        $this->setEvents($events);
60
61
        $em = is_null($em) ? Database::init($configuration)->getEntityManager() : $em;
62
        $this->setEntityManager($em);
63
64
        // $lock_path = $configuration->get('lockfiles-path');
0 ignored issues
show
Unused Code Comprehensibility introduced by
59% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
65
        // $this->locker = new Locker("$lock_path/schedule.lock");
0 ignored issues
show
Unused Code Comprehensibility introduced by
50% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
66
        // $this->locker->lock(0);
0 ignored issues
show
Unused Code Comprehensibility introduced by
70% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
67
    }
68
69
    public function get($id) {
70
71
        $em = $this->getEntityManager();
72
73
        $data = $em->find('Comodojo\Extender\Orm\Entities\Schedule', $id);
74
75
        //if ( empty($data) ) return null;
0 ignored issues
show
Unused Code Comprehensibility introduced by
67% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
76
77
        //return $data[0];
0 ignored issues
show
Unused Code Comprehensibility introduced by
86% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
78
79
        return $data;
80
81
    }
82
83
    public function getByName($name) {
84
85
        $em = $this->getEntityManager();
86
87
        $data = $em->getRepository('Comodojo\Extender\Orm\Entities\Schedule')->findBy(["name" => $name]);
88
89
        if ( empty($data) ) return null;
90
91
        return $data[0];
92
93
    }
94
95
    public function getAll($ready = false) {
96
97
        $logger = $this->getLogger();
98
99
        $time = new DateTime();
100
101
        $em = $this->getEntityManager();
102
103
        $standby = $em->getRepository('Comodojo\Extender\Orm\Entities\Schedule')->findAll();
104
105
        return $ready ? array_filter($standby, function($job) use ($time, $logger) {
106
107
            $name = $job->getName();
108
            $id = $job->getId();
109
            $enabled = $job->getEnabled();
110
            $firstrun = $job->getFirstrun();
111
            $lastrun = $job->getLastrun();
112
            $expression = $job->getExpression();
113
114
            if ( $lastrun !== null ) {
115
                $nextrun = $expression->getNextRunDate($lastrun);
116
            } else {
117
                $nextrun = $expression->getNextRunDate($firstrun);
118
            }
119
120
            $shouldrun = $nextrun <= $time;
121
122
            $logger->debug("Job $name (id $id) will ".($shouldrun ? "" : "NOT ")."be executed", [
123
                'ENABLED' => $enabled,
124
                'NEXTRUN' => $nextrun->format('r'),
125
                'SHOULDRUN' => $shouldrun
126
            ]);
127
128
            return $shouldrun;
129
130
        }) : $standby;
131
132
    }
133
134
    public function getNextCycleTimestamp() {
135
136
        $items = $this->getAll();
137
138
        $date = new DateTime();
139
        $timestamps = [];
140
141
        foreach ($items as $schedule) {
142
143
            $timestamps[] = $schedule->getNextPlannedRun($date)->getTimestamp();
144
145
        }
146
147
        return empty($timestamps) ? 0 : min($timestamps);
148
149
    }
150
151
    public function updateFromResults(array $results) {
152
153
        $em = $this->getEntityManager();
154
155
        foreach ($results as $result) {
156
157
            $id = $result->jid;
158
159
            if ( $id === null ) continue;
160
161
            $job = $this->get($id);
162
163
            if ( $job === null ) continue;
164
165
            if ( $job->getFirstrun() === null ) $job->setFirstrun($result->start);
166
167
            $job->setLastrun($result->start);
168
169
            $em->persist($job);
170
171
        }
172
173
        $em->flush();
174
175
    }
176
177
    public function add(Schedule $schedule) {
178
179
        $time = new DateTime();
180
181
        $schedule->setFirstrun($schedule->getNextPlannedRun($time));
182
183
        $em = $this->getEntityManager();
184
185
        $em->persist($schedule);
186
187
        $em->flush();
188
189
        return $schedule->getId();
190
191
    }
192
193
    public function addBulk(array $schedules) {
194
195
        $em = $this->getEntityManager();
196
197
        $records = [];
198
199
        foreach ($schedules as $key => $schedule) {
200
201
            try {
202
203
                $em->persist($schedule);
204
205
                $em->flush();
206
207
            } catch (Exception $e) {
208
209
                $records[$key] = false;
210
211
                continue;
212
213
            }
214
215
            $records[$key] = $scheudle->getId();
0 ignored issues
show
Bug introduced by
The variable $scheudle does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
216
217
        }
218
219
        return $records;
220
221
    }
222
223
    public function remove(Schedule $schedule) {
224
225
        $em = $this->getEntityManager();
226
227
        $em->remove($schedule);
228
229
        $em->flush();
230
231
    }
232
233
    public function edit(Schedule $schedule) {
234
235
        $em = $this->getEntityManager();
236
237
        $id = $schedule->getId();
238
239
        if ( empty($id) ) throw new Exception("Cannot edit scheule without id");
240
241
        $old_schedule = $this->get($schedule->getId());
242
243
        if ( empty($old_schedule) ) throw new Exception("Cannot find schedule with id $id");
244
245
        $old_schedule->merge($schedule);
246
247
        $em->persist($old_schedule);
248
249
        $em->flush();
250
251
        return true;
252
253
    }
254
255 View Code Duplication
    public function enable($name) {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
256
257
        $em = $this->getEntityManager();
258
259
        $schedule = $this->getByName($name);
260
261
        if ( is_null($schedule) ) throw new Exception("Cannot find scheule $name");
262
263
        $schedule->setEnabled(true);
264
265
        $em->persist($schedule);
266
267
        $em->flush();
268
269
        return true;
270
271
    }
272
273 View Code Duplication
    public function disable($name) {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
274
275
        $em = $this->getEntityManager();
276
277
        $schedule = $this->getByName($name);
278
279
        if ( is_null($schedule) ) throw new Exception("Cannot find scheule $name");
280
281
        $schedule->setEnabled(false);
282
283
        $em->persist($schedule);
284
285
        $em->flush();
286
287
        return true;
288
289
    }
290
291
}
292