Completed
Push — 2.0 ( a11c65...7cb9cd )
by Marco
11:37
created

Runner::closeWorklog()   B

Complexity

Conditions 3
Paths 14

Size

Total Lines 33
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 33
rs 8.8571
c 0
b 0
f 0
cc 3
eloc 20
nc 14
nop 3
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_FINISHED;
109
110
            } catch (TaskException $te) {
111
112
                $status = Worklog::STATUS_ABORTED;
113
114
                $result = $te->getMessage();
115
116
            } catch (Exception $e) {
117
118
                $status = Worklog::STATUS_ERROR;
119
120
                $result = $e->getMessage();
121
122
            }
123
124
            $this->events->emit( new TaskEvent('stop', $thetask) );
125
126
            $this->stopwatch->stop();
127
128
            $this->closeWorklog($status, $result, $this->stopwatch->getStopTime());
129
130
            $drift = $this->stopwatch->getDrift()->format('%s');
131
132
            $this->logger->notice("Task $name ($task) with pid $pid ends in ".($status ? 'success' : 'error')." in $drift secs");
133
134
        } catch (Exception $e) {
135
136
            ob_end_clean();
137
138
            throw $e;
139
140
        }
141
142
        $result = new Result([
143
            $uid,
144
            $pid,
145
            $jid,
146
            $name,
147
            $status,
148
            $this->stopwatch->getStartTime(),
149
            $this->stopwatch->getStopTime(),
150
            $result,
151
            $this->worklog_id
152
        ]);
153
154
        $this->stopwatch->clear();
155
156
        ob_end_clean();
157
158
        return $result;
159
160
    }
161
162
    public static function fastStart(
163
        Request $request,
164
        Configuration $configuration,
165
        LoggerInterface $logger,
166
        TasksTable $table,
167
        EventsManager $events,
168
        EntityManager $em = null
169
    ) {
170
171
        $runner = new Runner(
172
            $configuration,
173
            $logger,
174
            $table,
175
            $events,
176
            $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...
177
        );
178
179
        return $runner->run($request);
180
181
    }
182
183
    protected function openWorklog(
184
        $uid,
185
        $puid,
186
        $pid,
187
        $name,
188
        $jid,
189
        $task,
190
        $parameters,
191
        $start
192
    ) {
193
194
        try {
195
196
            $em = Database::init($this->getConfiguration())->getEntityManager();
197
198
            $worklog = new Worklog();
199
200
            $worklog
201
                ->setUid($uid)
202
                ->setParentUid($puid)
203
                ->setPid($pid)
204
                ->setName($name)
205
                ->setStatus(Worklog::STATUS_RUNNING)
206
                ->setTask($task)
207
                ->setParameters($parameters)
208
                ->setStartTime($start);
209
210
            if ( $jid !== null ) {
211
                $schedule = $em->find('\Comodojo\Extender\Orm\Entities\Schedule', $jid);
212
                $worklog->setJid($schedule);
213
            }
214
215
            $em->persist($worklog);
216
            $em->flush();
217
218
            $this->worklog_id = $worklog->getId();
219
220
            //$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...
221
            $em->close();
222
223
        } catch (Exception $e) {
224
            throw $e;
225
        }
226
227
    }
228
229
    protected function closeWorklog(
230
        $status,
231
        $result,
232
        $end
233
    ) {
234
235
        try {
236
237
            $em = Database::init($this->getConfiguration())->getEntityManager();
238
239
            $worklog = $em->find('\Comodojo\Extender\Orm\Entities\Worklog', $this->worklog_id);
240
241
            $worklog
242
                ->setStatus($status)
243
                ->setResult($result)
244
                ->setEndTime($end);
245
246
            $jid = $worklog->getJid();
247
            if ( $jid !== null ) {
248
                $schedule = $em->find('\Comodojo\Extender\Orm\Entities\Schedule', $jid);
249
                $worklog->setJid($schedule);
250
            }
251
252
            $em->persist($worklog);
253
            $em->flush();
254
            //$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...
255
            $em->close();
256
257
        } catch (Exception $e) {
258
            throw $e;
259
        }
260
261
    }
262
263
}
264