Manager::removeByName()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 15
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 7
nc 2
nop 1
dl 0
loc 15
rs 10
c 0
b 0
f 0
1
<?php namespace Comodojo\Extender\Schedule;
2
3
use \Comodojo\Foundation\Base\Configuration;
4
use \Comodojo\Foundation\Events\Manager as EventsManager;
5
use \Comodojo\Foundation\Logging\LoggerTrait;
6
use \Comodojo\Foundation\Events\EventsTrait;
7
use \Comodojo\Extender\Components\Database;
8
use \Comodojo\Foundation\Base\ConfigurationTrait;
9
use \Comodojo\Extender\Traits\EntityManagerTrait;
10
use \Comodojo\Extender\Orm\Entities\Schedule;
11
use \Comodojo\Extender\Events\ScheduleEvent;
12
use \Doctrine\ORM\EntityManager;
13
use \Psr\Log\LoggerInterface;
14
use \DateTime;
15
use \InvalidArgumentException;
16
use \Exception;
17
18
/**
19
* @package     Comodojo Extender
20
* @author      Marco Giovinazzi <[email protected]>
21
* @license     MIT
22
*
23
* LICENSE:
24
*
25
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
26
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
27
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
28
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
29
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
30
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
31
* THE SOFTWARE.
32
 */
33
34
class Manager {
35
36
    use ConfigurationTrait;
37
    use LoggerTrait;
38
    use EventsTrait;
39
    use EntityManagerTrait;
40
41
    /**
42
     * If true, $em will be destroyed at shutdown
43
     *
44
     * @var bool
45
     */
46
    private $destroy_em = true;
47
48
    /**
49
     * Class constructor
50
     *
51
     * @param Configuration $configuration
52
     * @param LoggerInterface $logger
53
     * @param EventsManager $events
54
     * @param EntityManager $em
55
     */
56
    public function __construct(
57
        Configuration $configuration,
58
        LoggerInterface $logger,
59
        EventsManager $events,
60
        EntityManager $em = null
61
    ) {
62
63
        $this->setConfiguration($configuration);
64
        $this->setLogger($logger);
65
        $this->setEvents($events);
66
67
        if ( is_null($em) ) {
68
            $this->setEntityManager(
69
                Database::init($configuration)->getEntityManager()
70
            );
71
        } else {
72
            $this->setEntityManager($em);
73
            $this->destroy_em = false;
74
        }
75
76
    }
77
78
    public function __destruct() {
79
80
        if ($this->destroy_em) {
81
            $em = $this->getEntityManager();
82
            $em->getConnection()->close();
83
            $em->close();
84
        }
85
86
    }
87
88
    public function get($id) {
89
90
        $em = $this->getEntityManager();
91
92
        $data = $em->find('Comodojo\Extender\Orm\Entities\Schedule', $id);
93
94
        return $data;
95
96
    }
97
98
    public function getByName($name) {
99
100
        $em = $this->getEntityManager();
101
102
        $data = $em->getRepository('Comodojo\Extender\Orm\Entities\Schedule')->findBy(["name" => $name]);
103
104
        if ( empty($data) ) return null;
105
106
        return $data[0];
107
108
    }
109
110
    public function getAll($ready = false) {
111
112
        $logger = $this->getLogger();
113
114
        $time = new DateTime();
115
116
        $em = $this->getEntityManager();
117
118
        $standby = $em->getRepository('Comodojo\Extender\Orm\Entities\Schedule')->findAll();
119
120
        return $ready ? array_filter($standby, function($job) use ($time, $logger) {
121
122
            $name = $job->getName();
123
            $id = $job->getId();
124
            $enabled = $job->getEnabled();
125
            $firstrun = $job->getFirstrun();
126
            $lastrun = $job->getLastrun();
127
            $expression = $job->getExpression();
128
129
            if ( $lastrun !== null ) {
130
                $nextrun = $expression->getNextRunDate($lastrun);
131
            } else {
132
                $nextrun = $firstrun;
133
            }
134
135
            $shouldrun = $enabled === true ? ($nextrun <= $time) : false;
136
137
            $logger->debug("Job $name (id $id) will ".($shouldrun ? "" : "NOT ")."be executed", [
138
                'ENABLED' => $enabled,
139
                'NEXTRUN' => $nextrun->format('r'),
140
                'SHOULDRUN' => $shouldrun
141
            ]);
142
143
            return $shouldrun;
144
145
        }) : $standby;
146
147
    }
148
149
    public function add(Schedule $schedule) {
150
151
        $time = new DateTime();
152
153
        $schedule->setFirstrun($schedule->getNextPlannedRun($time));
154
155
        $this->getEvents()->emit( new ScheduleEvent('add', $schedule) );
156
157
        $em = $this->getEntityManager();
158
159
        $em->persist($schedule);
160
161
        $em->flush();
162
163
        return $schedule->getId();
164
165
    }
166
167
    public function addBulk(array $schedules) {
168
169
        $time = new DateTime();
170
        $records = [];
171
        $em = $this->getEntityManager();
172
173
        foreach ($schedules as $key => $schedule) {
174
175
            try {
176
177
                $schedule->setFirstrun($schedule->getNextPlannedRun($time));
178
179
                $this->getEvents()->emit( new ScheduleEvent('add', $schedule) );
180
181
                $em->persist($schedule);
182
183
                $em->flush();
184
185
            } catch (Exception $e) {
186
187
                $records[$key] = false;
188
189
                continue;
190
191
            }
192
193
            $records[$key] = $schedule->getId();
194
195
        }
196
197
        return $records;
198
199
    }
200
201
    public function edit(Schedule $schedule) {
202
203
        $em = $this->getEntityManager();
204
205
        $id = $schedule->getId();
206
207
        if ( empty($id) ) throw new InvalidArgumentException("Cannot edit scheule without id");
208
209
        $old_schedule = $this->get($schedule->getId());
210
211
        if ( empty($old_schedule) ) throw new InvalidArgumentException("Cannot find schedule with id $id");
212
213
        $this->getEvents()->emit( new ScheduleEvent('edit', $schedule, $old_schedule) );
214
215
        $old_schedule->merge($schedule);
216
217
        $em->persist($old_schedule);
218
219
        $em->flush();
220
221
        return true;
222
223
    }
224
225
    public function remove($id) {
226
227
        $em = $this->getEntityManager();
228
229
        $schedule = $this->get($id);
230
231
        if ( is_null($schedule) ) throw new InvalidArgumentException("Cannot find scheule $id");
232
233
        $this->getEvents()->emit( new ScheduleEvent('remove', $schedule) );
234
235
        $em->remove($schedule);
236
237
        $em->flush();
238
239
        return true;
240
241
    }
242
243
    public function removeByName($name) {
244
245
        $em = $this->getEntityManager();
246
247
        $schedule = $this->getByName($name);
248
249
        if ( is_null($schedule) ) throw new InvalidArgumentException("Cannot find scheule $name");
250
251
        $this->getEvents()->emit( new ScheduleEvent('remove', $schedule) );
252
253
        $em->remove($schedule);
254
255
        $em->flush();
256
257
        return true;
258
259
    }
260
261
    public function enable($id) {
262
263
        $em = $this->getEntityManager();
264
265
        $schedule = $this->get($id);
266
267
        if ( is_null($schedule) ) throw new InvalidArgumentException("Cannot find scheule $id");
268
269
        $this->getEvents()->emit( new ScheduleEvent('enable', $schedule) );
270
271
        $schedule->setEnabled(true);
272
273
        $em->persist($schedule);
274
275
        $em->flush();
276
277
        return true;
278
279
    }
280
281
    public function enableByName($name) {
282
283
        $em = $this->getEntityManager();
284
285
        $schedule = $this->getByName($name);
286
287
        if ( is_null($schedule) ) throw new InvalidArgumentException("Cannot find scheule $name");
288
289
        $this->getEvents()->emit( new ScheduleEvent('enable', $schedule) );
290
291
        $schedule->setEnabled(true);
292
293
        $em->persist($schedule);
294
295
        $em->flush();
296
297
        return true;
298
299
    }
300
301
    public function disable($id) {
302
303
        $em = $this->getEntityManager();
304
305
        $schedule = $this->get($id);
306
307
        if ( is_null($schedule) ) throw new InvalidArgumentException("Cannot find scheule $id");
308
309
        $this->getEvents()->emit( new ScheduleEvent('disable', $schedule) );
310
311
        $schedule->setEnabled(false);
312
313
        $em->persist($schedule);
314
315
        $em->flush();
316
317
        return true;
318
319
    }
320
321
    public function disableByName($name) {
322
323
        $em = $this->getEntityManager();
324
325
        $schedule = $this->getByName($name);
326
327
        if ( is_null($schedule) ) throw new InvalidArgumentException("Cannot find scheule $name");
328
329
        $this->getEvents()->emit( new ScheduleEvent('disable', $schedule) );
330
331
        $schedule->setEnabled(false);
332
333
        $em->persist($schedule);
334
335
        $em->flush();
336
337
        return true;
338
339
    }
340
341
}
342