Runner::closeWorklog()   A
last analyzed

Complexity

Conditions 3
Paths 16

Size

Total Lines 32
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 17
nc 16
nop 3
dl 0
loc 32
rs 9.7
c 0
b 0
f 0
1
<?php namespace Comodojo\Extender\Task;
2
3
use \Comodojo\Extender\Components\Database;
4
use \Comodojo\Extender\Task\Table as TasksTable;
5
use \Comodojo\Extender\Events\TaskEvent;
6
use \Comodojo\Extender\Events\WorklogEvent;
7
use \Comodojo\Foundation\Base\Configuration;
8
use \Comodojo\Foundation\Events\Manager as EventsManager;
9
use \Comodojo\Foundation\Logging\LoggerTrait;
10
use \Comodojo\Foundation\Events\EventsTrait;
11
use \Comodojo\Foundation\Base\ConfigurationTrait;
12
use \Comodojo\Extender\Traits\TasksTableTrait;
13
use \Comodojo\Extender\Traits\TaskErrorHandlerTrait;
14
use \Comodojo\Extender\Orm\Entities\Worklog;
15
use \Comodojo\Extender\Utils\StopWatch;
16
use \Psr\Log\LoggerInterface;
17
use \Doctrine\ORM\EntityManager;
18
use \Comodojo\Exception\TaskException;
19
use \Exception;
20
21
/**
22
* @package     Comodojo Extender
23
* @author      Marco Giovinazzi <[email protected]>
24
* @license     MIT
25
*
26
* LICENSE:
27
*
28
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
29
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
30
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
31
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
32
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
33
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
34
* THE SOFTWARE.
35
 */
36
37
class Runner {
38
39
    use LoggerTrait;
40
    use ConfigurationTrait;
41
    use EventsTrait;
42
    use TasksTableTrait;
43
    use TaskErrorHandlerTrait;
44
45
    /**
46
     * @var int
47
     */
48
    protected $worklog_id;
49
50
    /**
51
     * @var StopWatch
52
     */
53
    protected $stopwatch;
54
55
    public function __construct(
56
        Configuration $configuration,
57
        LoggerInterface $logger,
58
        TasksTable $table,
59
        EventsManager $events
60
    ) {
61
62
        // init components
63
        $this->setConfiguration($configuration);
64
        $this->setLogger($logger);
65
        $this->setEvents($events);
66
        $this->setTasksTable($table);
67
68
        // create StopWatch
69
        $this->stopwatch = new StopWatch();
70
71
    }
72
73
    public function run(Request $request) {
74
75
        $name = $request->getName();
76
        $task = $request->getTask();
77
        $uid = $request->getUid();
78
        $jid = $request->getJid();
79
        $puid = $request->getParentUid();
80
        $pid = 0;
81
        $parameters = $request->getParameters();
82
83
        ob_start();
84
85
        try {
86
87
            $this->stopwatch->start();
88
89
            $this->logger->notice("Starting new task $name ($task)");
90
91
            $task_def = $this->table->get($name);
92
93
            if ( $task_def === null ) throw new Exception("Task $name not found, aborting");
94
95
            $thetask = $task_def->getInstance($name, $parameters);
96
97
            $this->events->emit( new TaskEvent('start', $thetask) );
98
99
            $pid = $thetask->getPid();
100
101
            $this->openWorklog(
102
                $uid,
103
                $puid,
104
                $pid,
105
                $name,
106
                $jid,
107
                $task,
108
                $parameters,
109
                $this->stopwatch->getStartTime()
110
            );
111
112
            $this->installErrorHandler();
113
114
            try {
115
116
                $result = $thetask->run();
117
118
                $status = Worklog::STATUS_COMPLETE;
119
120
                $this->events->emit( new TaskEvent('complete', $thetask) );
121
122
            } catch (TaskException $te) {
123
124
                $status = Worklog::STATUS_ABORT;
125
126
                $result = $te->getMessage();
127
128
                $this->events->emit( new TaskEvent('abort', $thetask) );
129
130
            } catch (Exception $e) {
131
132
                $status = Worklog::STATUS_ERROR;
133
134
                $result = $e->getMessage();
135
136
                $this->events->emit( new TaskEvent('error', $thetask) );
137
138
            }
139
140
            $this->restoreErrorHandler();
141
142
            $this->events->emit( new TaskEvent('stop', $thetask) );
143
144
            $this->stopwatch->stop();
145
146
            $this->closeWorklog($status, $result, $this->stopwatch->getStopTime());
147
148
            $drift = $this->stopwatch->getDrift()->format('%s');
149
150
            $this->logger->notice("Task $name ($task) pid $pid ends in ".($status === Worklog::STATUS_COMPLETE ? 'success' : 'error')." in $drift secs");
151
152
            $result = new Result([
153
                $uid,
154
                $pid,
155
                $jid,
156
                $name,
157
                $status === Worklog::STATUS_COMPLETE ? true : false,
158
                $this->stopwatch->getStartTime(),
159
                $this->stopwatch->getStopTime(),
160
                $result,
161
                $this->worklog_id
162
            ]);
163
164
            $this->events->emit( new TaskEvent(self::statusToEvent($status), $thetask, $result) );
0 ignored issues
show
Bug Best Practice introduced by
The method Comodojo\Extender\Task\Runner::statusToEvent() is not static, but was called statically. ( Ignorable by Annotation )

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

164
            $this->events->emit( new TaskEvent(self::/** @scrutinizer ignore-call */ statusToEvent($status), $thetask, $result) );
Loading history...
165
166
        } catch (Exception $e) {
167
168
            // ob_end_clean();
0 ignored issues
show
Unused Code Comprehensibility introduced by
60% 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...
169
            // throw $e;
0 ignored issues
show
Unused Code Comprehensibility introduced by
60% 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...
170
171
            if ( $this->stopwatch->isActive() ) {
172
                $this->stopwatch->stop();
173
            }
174
175
            $result = new Result([
176
                $uid,
177
                $pid,
178
                $jid,
179
                $name,
180
                false,
181
                $this->stopwatch->getStartTime(),
182
                $this->stopwatch->getStopTime(),
183
                $e->getMessage(),
184
                $this->worklog_id
185
            ]);
186
187
        }
188
189
        $this->stopwatch->clear();
190
191
        ob_end_clean();
192
193
        return $result;
194
195
    }
196
197
    public static function fastStart(
198
        Request $request,
199
        Configuration $configuration,
200
        LoggerInterface $logger,
201
        TasksTable $table,
202
        EventsManager $events,
203
        EntityManager $em = null
204
    ) {
205
206
        $runner = new Runner(
207
            $configuration,
208
            $logger,
209
            $table,
210
            $events,
211
            $em
0 ignored issues
show
Unused Code introduced by
The call to Comodojo\Extender\Task\Runner::__construct() has too many arguments starting with $em. ( Ignorable by Annotation )

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

211
        $runner = /** @scrutinizer ignore-call */ new Runner(

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
212
        );
213
214
        return $runner->run($request);
215
216
    }
217
218
    protected function openWorklog(
219
        $uid,
220
        $puid,
221
        $pid,
222
        $name,
223
        $jid,
224
        $task,
225
        $parameters,
226
        $start
227
    ) {
228
229
        try {
230
231
            $em = Database::init($this->getConfiguration())->getEntityManager();
232
233
            $worklog = new Worklog();
234
235
            $worklog
236
                ->setUid($uid)
237
                ->setParentUid($puid)
238
                ->setPid($pid)
239
                ->setName($name)
240
                ->setStatus(Worklog::STATUS_RUN)
241
                ->setTask($task)
242
                ->setParameters($parameters)
243
                ->setStartTime($start);
244
245
            if ( $jid !== null ) {
246
                $schedule = $em->find('\Comodojo\Extender\Orm\Entities\Schedule', $jid);
247
                $worklog->setJid($schedule);
248
            }
249
250
            $this->events->emit( new WorklogEvent('open', $worklog) );
251
252
            $em->persist($worklog);
253
            $em->flush();
254
255
            $this->worklog_id = $worklog->getId();
256
257
            //$em->getConnection()->close();
0 ignored issues
show
Unused Code Comprehensibility introduced by
80% 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...
258
            $em->close();
259
260
        } catch (Exception $e) {
261
            throw $e;
262
        }
263
264
    }
265
266
    protected function closeWorklog(
267
        $status,
268
        $result,
269
        $end
270
    ) {
271
272
        try {
273
274
            $em = Database::init($this->getConfiguration())->getEntityManager();
275
276
            $worklog = $em->find('\Comodojo\Extender\Orm\Entities\Worklog', $this->worklog_id);
277
278
            $worklog
279
                ->setStatus($status)
280
                ->setResult($result)
281
                ->setEndTime($end);
282
283
            $jid = $worklog->getJid();
284
            if ( $jid !== null ) {
285
                $schedule = $em->find('\Comodojo\Extender\Orm\Entities\Schedule', $jid);
286
                $worklog->setJid($schedule);
287
            }
288
289
            $this->events->emit( new WorklogEvent('close', $worklog) );
290
291
            $em->persist($worklog);
292
            $em->flush();
293
            //$em->getConnection()->close();
0 ignored issues
show
Unused Code Comprehensibility introduced by
80% 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...
294
            $em->close();
295
296
        } catch (Exception $e) {
297
            throw $e;
298
        }
299
300
    }
301
302
    protected function statusToEvent($status) {
303
304
        switch ($status) {
305
            case Worklog::STATUS_COMPLETE:
306
                return 'complete';
307
                break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
308
            case Worklog::STATUS_ABORT:
309
                return 'abort';
310
                break;
311
            case Worklog::STATUS_ERROR:
312
                return 'error';
313
                break;
314
        }
315
316
    }
317
318
}
319