Completed
Push — 2.0 ( dbbe01...d43752 )
by Marco
11:55
created

Runner::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 20
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 20
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 11
nc 1
nop 4
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\Foundation\Base\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 Worklog
45
     */
46
    protected $worklog;
47
48
    /**
49
     * @var StopWatch
50
     */
51
    protected $stopwatch;
52
53
    public function __construct(
54
        Configuration $configuration,
55
        LoggerInterface $logger,
56
        TasksTable $table,
57
        EventsManager $events
58
    ) {
59
60
        // init components
61
        $this->setConfiguration($configuration);
62
        $this->setLogger($logger);
63
        $this->setEvents($events);
64
        $this->setTasksTable($table);
65
66
        // create StopWatch
67
        $this->stopwatch = new StopWatch();
68
69
        // init worklog manager
70
        $this->worklog = new Worklog();
71
72
    }
73
74
    public function run(Request $request) {
75
76
        $name = $request->getName();
77
        $task = $request->getTask();
78
        $uid = $request->getUid();
79
        $jid = $request->getJid();
80
        $puid = $request->getParentUid();
81
        $parameters = $request->getParameters();
82
83
        ob_start();
84
85
        try {
86
87
            $this->stopwatch->start();
88
89
            $this->logger->info("Starting new task $task ($name)");
90
91
            $thetask = $this->table->get($task)->getInstance($name, $parameters);
92
93
            $this->events->emit( new TaskEvent('start', $thetask) );
94
95
            $pid = $thetask->getPid();
96
97
            $this->openWorklog(
98
                $uid,
99
                $puid,
100
                $pid,
101
                $name,
102
                $jid,
103
                $task,
104
                $parameters,
105
                $this->stopwatch->getStartTime()
106
            );
107
108
            $this->events->emit( new TaskStatusEvent('start', $thetask) );
109
110
            try {
111
112
                $result = $thetask->run();
113
114
                $status = Worklog::STATUS_FINISHED;
115
116
            } catch (TaskException $te) {
117
118
                $status = Worklog::STATUS_ABORTED;
119
120
                $result = $te->getMessage();
121
122
            } catch (Exception $e) {
123
124
                $status = Worklog::STATUS_ERROR;
125
126
                $result = $e->getMessage();
127
128
            }
129
130
            $this->events->emit( new TaskStatusEvent($status ? 'success' : 'error', $thetask) );
131
132
            $this->events->emit( new TaskStatusEvent('stop', $thetask) );
133
134
            $this->events->emit( new TaskEvent('stop', $thetask) );
135
136
            $this->stopwatch->stop();
137
138
            $this->closeWorklog($status, $result, $this->stopwatch->getStopTime());
139
140
            $drift = $this->stopwatch->getDrift()->format('%s');
141
142
            $this->logger->notice("Task $name ($task) with pid $pid ends in ".($status ? 'success' : 'error')." in $drift secs");
143
144
        } catch (Exception $e) {
145
146
            ob_end_clean();
147
148
            throw $e;
149
150
        }
151
152
        $result = new Result([
153
            $uid,
154
            $pid,
155
            $jid,
156
            $name,
157
            $status,
158
            $this->stopwatch->getStartTime(),
159
            $this->stopwatch->getStopTime(),
160
            $result,
161
            $this->worklog->getId()
162
        ]);
163
164
        $this->stopwatch->clear();
165
166
        ob_end_clean();
167
168
        return $result;
169
170
    }
171
172
    public static function fastStart(
173
        Request $request,
174
        Configuration $configuration,
175
        LoggerInterface $logger,
176
        TasksTable $table,
177
        EventsManager $events,
178
        EntityManager $em = null
179
    ) {
180
181
        $runner = new Runner(
182
            $configuration,
183
            $logger,
184
            $table,
185
            $events,
186
            $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...
187
        );
188
189
        return $runner->run($request);
190
191
    }
192
193
    protected function openWorklog(
194
        $uid,
195
        $puid,
196
        $pid,
197
        $name,
198
        $jid,
199
        $task,
200
        $parameters,
201
        $start
202
    ) {
203
204
        $em = Database::init($this->getConfiguration())->getEntityManager();
205
206
        $this->worklog
207
            ->setUid($uid)
208
            ->setParentUid($puid)
209
            ->setPid($pid)
210
            ->setName($name)
211
            ->setStatus(Worklog::STATUS_RUNNING)
212
            ->setJid($jid)
213
            ->setTask($task)
214
            ->setParameters($parameters)
215
            ->setStartTime($start);
216
217
        $em->persist($this->worklog);
218
        $em->flush();
219
        //$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...
220
        $em->close();
221
222
    }
223
224
    protected function closeWorklog(
225
        $status,
226
        $result,
227
        $end
228
    ) {
229
230
        $em = Database::init($this->getConfiguration())->getEntityManager();
231
232
        $this->worklog
233
            ->setStatus($status)
234
            ->setResult($result)
235
            ->setEndTime($end);
236
237
        $em->persist($this->worklog);
238
        $em->flush();
239
        //$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...
240
        $em->close();
241
242
    }
243
244
}
245