summaryrefslogtreecommitdiff
path: root/app/Core/HttpClient.php
blob: 0803ec7aed33422d91b4a01381cba19b95a62922 (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
<?php

namespace Core;

use Pimple\Container;

/**
 * HTTP client
 *
 * @package  core
 * @author   Frederic Guillot
 */
class HttpClient
{
    /**
     * HTTP connection timeout in seconds
     *
     * @var integer
     */
    const HTTP_TIMEOUT = 2;

    /**
     * Number of maximum redirections for the HTTP client
     *
     * @var integer
     */
    const HTTP_MAX_REDIRECTS = 2;

    /**
     * HTTP client user agent
     *
     * @var string
     */
    const HTTP_USER_AGENT = 'Kanboard Webhook';

    /**
     * Container instance
     *
     * @access protected
     * @var \Pimple\Container
     */
    protected $container;

    /**
     * Constructor
     *
     * @access public
     * @param  \Pimple\Container   $container
     */
    public function __construct(Container $container)
    {
        $this->container = $container;
    }

    /**
     * Send a POST HTTP request
     *
     * @access public
     * @param  string  $url
     * @param  array   $data
     * @return string
     */
    public function post($url, array $data)
    {
        if (empty($url)) {
            return '';
        }

        $headers = array(
            'User-Agent: '.self::HTTP_USER_AGENT,
            'Content-Type: application/json',
            'Connection: close',
        );

        $context = stream_context_create(array(
            'http' => array(
                'method' => 'POST',
                'protocol_version' => 1.1,
                'timeout' => self::HTTP_TIMEOUT,
                'max_redirects' => self::HTTP_MAX_REDIRECTS,
                'header' => implode("\r\n", $headers),
                'content' => json_encode($data)
            )
        ));

        $response = @file_get_contents(trim($url), false, $context);

        if (DEBUG) {
            $this->container['logger']->debug($url);
            $this->container['logger']->debug(var_export($data, true));
            $this->container['logger']->debug($response);
        }

        return $response;
    }
}