summaryrefslogtreecommitdiff
path: root/app/Core/Queue/JobHandler.php
blob: d7e7d0991c3370dd9c439a2ac34fb141648a3998 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
<?php

namespace Kanboard\Core\Queue;

use Exception;
use Kanboard\Core\Base;
use Kanboard\Job\BaseJob;
use SimpleQueue\Job;

/**
 * Class JobHandler
 *
 * @package Kanboard\Core\Queue
 * @author  Frederic Guillot
 */
class JobHandler extends Base
{
    /**
     * Serialize a job
     *
     * @access public
     * @param  BaseJob $job
     * @return Job
     */
    public function serializeJob(BaseJob $job)
    {
        return new Job(array(
            'class' => get_class($job),
            'params' => $job->getJobParams(),
            'user_id' => $this->userSession->getId(),
        ));
    }

    /**
     * Execute a job
     *
     * @access public
     * @param Job $job
     */
    public function executeJob(Job $job)
    {
        $payload = $job->getBody();

        try {
            $className = $payload['class'];
            $this->prepareJobSession($payload['user_id']);
            $this->prepareJobEnvironment();

            if (DEBUG) {
                $this->logger->debug(__METHOD__.' Received job => '.$className.' ('.getmypid().')');
                $this->logger->debug(__METHOD__.' => '.json_encode($payload));
            }

            $worker = new $className($this->container);
            call_user_func_array(array($worker, 'execute'), $payload['params']);
        } catch (Exception $e) {
            $this->logger->error(__METHOD__.': Error during job execution: '.$e->getMessage());
            $this->logger->error(__METHOD__ .' => '.json_encode($payload));
        }
    }

    /**
     * Create the session for the job
     *
     * @access protected
     * @param integer $user_id
     */
    protected function prepareJobSession($user_id)
    {
        session_flush();

        if ($user_id > 0) {
            $user = $this->userModel->getById($user_id);
            $this->userSession->initialize($user);
        }
    }

    /**
     * Flush in-memory caching and specific events
     *
     * @access protected
     */
    protected function prepareJobEnvironment()
    {
        $this->memoryCache->flush();
        $this->actionManager->removeEvents();
        $this->dispatcher->dispatch('app.bootstrap');
    }
}