webhook support
[phorkie.git] / src / phorkie / Notificator.php
1 <?php
2 namespace phorkie;
3
4 /**
5  * Send out webhook callbacks when something happens
6  */
7 class Notificator
8 {
9     /**
10      * A repository has been created
11      */
12     public function create(Repository $repo)
13     {
14         $this->send('create', $repo);
15     }
16
17     /**
18      * A repository has been modified
19      */
20     public function edit(Repository $repo)
21     {
22         $this->send('edit', $repo);
23     }
24
25     /**
26      * A repository has been deleted
27      */
28     public function delete(Repository $repo)
29     {
30         $this->send('delete', $repo);
31     }
32
33     /**
34      * Call webhook URLs with our payload
35      */
36     protected function send($event, Repository $repo)
37     {
38         if (count($GLOBALS['phorkie']['cfg']['webhooks']) == 0) {
39             return;
40         }
41         
42         /* slightly inspired by
43            https://help.github.com/articles/post-receive-hooks */
44         $payload = (object) array(
45             'event'  => $event,
46             'author' => array(
47                 'name'  => $_SESSION['name'],
48                 'email' => $_SESSION['email']
49             ),
50             'repository' => array(
51                 'name'        => $repo->getTitle(),
52                 'url'         => $repo->getLink('display', null, true),
53                 'description' => $repo->getDescription(),
54                 'owner'       => $repo->getOwner()
55             )
56         );
57         foreach ($GLOBALS['phorkie']['cfg']['webhooks'] as $url) {
58             $req = new \HTTP_Request2($url);
59             $req->setMethod(\HTTP_Request2::METHOD_POST)
60                 ->setHeader('Content-Type: application/vnd.phorkie.webhook+json')
61                 ->setBody(json_encode($payload));
62             try {
63                 $response = $req->send();
64                 //FIXME log response codes != 200
65             } catch (HTTP_Request2_Exception $e) {
66                 //FIXME log exceptions
67             }
68         }
69     }
70 }
71 ?>