summaryrefslogtreecommitdiff
path: root/app/Integration/BitbucketWebhook.php
blob: 75fc1c81448d13d28567c41fbae9a525dc6557eb (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
90
91
92
93
94
95
96
97
<?php

namespace Integration;

use Event\TaskEvent;
use Model\Task;

/**
 * Bitbucket Webhook
 *
 * @package  integration
 * @author   Frederic Guillot
 */
class BitbucketWebhook extends \Core\Base
{
    /**
     * Events
     *
     * @var string
     */
    const EVENT_COMMIT = 'bitbucket.webhook.commit';

    /**
     * Project id
     *
     * @access private
     * @var integer
     */
    private $project_id = 0;

    /**
     * Set the project id
     *
     * @access public
     * @param  integer   $project_id   Project id
     */
    public function setProjectId($project_id)
    {
        $this->project_id = $project_id;
    }

    /**
     * Parse events
     *
     * @access public
     * @param  array   $payload   Gitlab event
     * @return boolean
     */
    public function parsePayload(array $payload)
    {
        if (! empty($payload['commits'])) {

            foreach ($payload['commits'] as $commit) {

                if ($this->handleCommit($commit)) {
                    return true;
                }
            }
        }

        return false;
    }

    /**
     * Parse commit
     *
     * @access public
     * @param  array   $commit   Gitlab commit
     * @return boolean
     */
    public function handleCommit(array $commit)
    {
        $task_id = $this->task->getTaskIdFromText($commit['message']);

        if (! $task_id) {
            return false;
        }

        $task = $this->taskFinder->getById($task_id);

        if (empty($task)) {
            return false;
        }

        if ($task['is_active'] == Task::STATUS_OPEN && $task['project_id'] == $this->project_id) {

            $this->container['dispatcher']->dispatch(
                self::EVENT_COMMIT,
                new TaskEvent(array('task_id' => $task_id) + $task)
            );

            return true;
        }

        return false;
    }
}