Completed
Push — 2.0 ( 8b36d5...0f73ad )
by Marco
13:39
created

Runner::statusToEvent()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 15
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

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

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.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
185
        );
186
187
        return $runner->run($request);
188
189
    }
190
191
    protected function openWorklog(
192
        $uid,
193
        $puid,
194
        $pid,
195
        $name,
196
        $jid,
197
        $task,
198
        $parameters,
199
        $start
200
    ) {
201
202
        try {
203
204
            $em = Database::init($this->getConfiguration())->getEntityManager();
205
206
            $worklog = new Worklog();
207
208
            $worklog
209
                ->setUid($uid)
210
                ->setParentUid($puid)
211
                ->setPid($pid)
212
                ->setName($name)
213
                ->setStatus(Worklog::STATUS_RUN)
214
                ->setTask($task)
215
                ->setParameters($parameters)
216
                ->setStartTime($start);
217
218
            if ( $jid !== null ) {
219
                $schedule = $em->find('\Comodojo\Extender\Orm\Entities\Schedule', $jid);
220
                $worklog->setJid($schedule);
221
            }
222
223
            $em->persist($worklog);
224
            $em->flush();
225
226
            $this->worklog_id = $worklog->getId();
227
228
            //$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...
229
            $em->close();
230
231
        } catch (Exception $e) {
232
            throw $e;
233
        }
234
235
    }
236
237
    protected function closeWorklog(
238
        $status,
239
        $result,
240
        $end
241
    ) {
242
243
        try {
244
245
            $em = Database::init($this->getConfiguration())->getEntityManager();
246
247
            $worklog = $em->find('\Comodojo\Extender\Orm\Entities\Worklog', $this->worklog_id);
248
249
            $worklog
250
                ->setStatus($status)
251
                ->setResult($result)
252
                ->setEndTime($end);
253
254
            $jid = $worklog->getJid();
255
            if ( $jid !== null ) {
256
                $schedule = $em->find('\Comodojo\Extender\Orm\Entities\Schedule', $jid);
257
                $worklog->setJid($schedule);
258
            }
259
260
            $em->persist($worklog);
261
            $em->flush();
262
            //$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...
263
            $em->close();
264
265
        } catch (Exception $e) {
266
            throw $e;
267
        }
268
269
    }
270
271
    protected function statusToEvent($status) {
272
273
        switch ($status) {
274
            case Worklog::STATUS_COMPLETE:
275
                return 'complete';
276
                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...
277
            case Worklog::STATUS_ABORT:
278
                return 'abort';
279
                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...
280
            case Worklog::STATUS_ERROR:
281
                return 'error';
282
                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...
283
        }
284
285
    }
286
287
}
288