Completed
Push — 2.0 ( bcdb61...f02592 )
by Marco
02:29
created

Runner   A

Complexity

Total Complexity 11

Size/Duplication

Total Lines 204
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 12

Importance

Changes 0
Metric Value
wmc 11
lcom 1
cbo 12
dl 0
loc 204
rs 10
c 0
b 0
f 0

5 Methods

Rating   Name   Duplication   Size   Complexity  
B __construct() 0 24 2
B run() 0 91 6
A fastStart() 0 20 1
B openWorklog() 0 26 1
A closeWorklog() 0 15 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\Extender\Events\TaskStatusEvent;
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\Extender\Traits\ConfigurationTrait;
12
use \Comodojo\Extender\Traits\TasksTableTrait;
13
use \Comodojo\Extender\Orm\Entities\Worklog;
14
use \Comodojo\Extender\Utils\StopWatch;
15
use \Psr\Log\LoggerInterface;
16
use \Doctrine\ORM\EntityManager;
17
use \Comodojo\Exception\TaskException;
18
use \Exception;
19
20
/**
21
* @package     Comodojo Extender
22
* @author      Marco Giovinazzi <[email protected]>
23
* @license     MIT
24
*
25
* LICENSE:
26
*
27
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
28
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
29
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
30
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
31
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
32
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
33
* THE SOFTWARE.
34
 */
35
36
class Runner {
37
38
    use LoggerTrait;
39
    use ConfigurationTrait;
40
    use EventsTrait;
41
    use TasksTableTrait;
42
43
    /**
44
     * @var EntityManager
45
     */
46
    protected $em;
47
48
    /**
49
     * @var Worklog
50
     */
51
    protected $worklog;
52
53
    /**
54
     * @var StopWatch
55
     */
56
    protected $stopwatch;
57
58
    public function __construct(
59
        Configuration $configuration,
60
        LoggerInterface $logger,
61
        TasksTable $table,
62
        EventsManager $events,
63
        EntityManager $em = null
64
    ) {
65
66
        // init components
67
        $this->setConfiguration($configuration);
68
        $this->setLogger($logger);
69
        $this->setEvents($events);
70
        $this->setTasksTable($table);
71
72
        // create StopWatch
73
        $this->stopwatch = new StopWatch();
74
75
        // init database
76
        $this->em = is_null($em) ? Database::init($configuration)->getEntityManager() : $em;
77
78
        // init worklog manager
79
        $this->worklog = new Worklog();
80
81
    }
82
83
    public function run(Request $request) {
84
85
        $name = $request->getName();
86
        $task = $request->getTask();
87
        $uid = $request->getUid();
88
        $jid = $request->getJid();
89
        $puid = $request->getParentUid();
90
        $parameters = $request->getParameters();
91
92
        try {
93
94
            $this->stopwatch->start();
95
96
            $this->logger->info("Starting new task $task ($name)");
97
98
            $thetask = $this->table->get($task)->getInstance($name, $parameters);
99
100
            $this->events->emit( new TaskEvent('start', $thetask) );
101
102
            $pid = $thetask->getPid();
103
104
            $this->openWorklog(
105
                $uid,
106
                $puid,
107
                $pid,
108
                $name,
109
                $jid,
110
                $task,
111
                $parameters,
112
                $this->stopwatch->getStartTime()
113
            );
114
115
            $this->events->emit( new TaskStatusEvent('start', $thetask) );
116
117
            try {
118
119
                $result = $thetask->run();
120
121
                $status = Worklog::STATUS_FINISHED;
122
123
            } catch (TaskException $te) {
124
125
                $status = Worklog::STATUS_ABORTED;
126
127
                $result = $te->getMessage();
128
129
            } catch (Exception $e) {
130
131
                $status = Worklog::STATUS_ERROR;
132
133
                $result = $e->getMessage();
134
135
            }
136
137
            $this->events->emit( new TaskStatusEvent($status ? 'success' : 'error', $thetask) );
138
139
            $this->events->emit( new TaskStatusEvent('stop', $thetask) );
140
141
            $this->events->emit( new TaskEvent('stop', $thetask) );
142
143
            $this->stopwatch->stop();
144
145
            $this->closeWorklog($status, $result, $this->stopwatch->getStopTime());
146
147
            $drift = $this->stopwatch->getDrift()->format('%s');
148
149
            $this->logger->notice("Task $name ($task) with pid $pid ends in ".($status ? 'success' : 'error')." in $drift secs");
150
151
        } catch (Exception $e) {
152
153
            throw $e;
154
155
        }
156
157
        $result = new Result([
158
            $uid,
159
            $pid,
160
            $jid,
161
            $name,
162
            $status,
163
            $this->stopwatch->getStartTime(),
164
            $this->stopwatch->getStopTime(),
165
            $result,
166
            $this->worklog->getId()
167
        ]);
168
169
        $this->stopwatch->clear();
170
171
        return $result;
172
173
    }
174
175
    public static function fastStart(
176
        Request $request,
177
        Configuration $configuration,
178
        LoggerInterface $logger,
179
        TasksTable $table,
180
        EventsManager $events,
181
        EntityManager $em = null
182
    ) {
183
184
        $runner = new Runner(
185
            $configuration,
186
            $logger,
187
            $table,
188
            $events,
189
            $em
190
        );
191
192
        return $runner->run($request);
193
194
    }
195
196
    protected function openWorklog(
197
        $uid,
198
        $puid,
199
        $pid,
200
        $name,
201
        $jid,
202
        $task,
203
        $parameters,
204
        $start
205
    ) {
206
207
        $this->worklog
208
            ->setUid($uid)
209
            ->setParentUid($puid)
210
            ->setPid($pid)
211
            ->setName($name)
212
            ->setStatus(Worklog::STATUS_RUNNING)
213
            ->setJid($jid)
214
            ->setTask($task)
215
            ->setParameters($parameters)
216
            ->setStartTime($start);
217
218
        $this->em->persist($this->worklog);
219
        $this->em->flush();
220
221
    }
222
223
    protected function closeWorklog(
224
        $status,
225
        $result,
226
        $end
227
    ) {
228
229
        $this->worklog
230
            ->setStatus($status)
231
            ->setResult($result)
232
            ->setEndTime($end);
233
234
        $this->em->persist($this->worklog);
235
        $this->em->flush();
236
237
    }
238
239
}
240