summaryrefslogtreecommitdiff
path: root/Postman/Postman-Mail/sendgrid-php-3.2.0/lib/SendGrid.php
blob: 5b775b212cccdb28ec0d04d8df216adf9bce031e (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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
<?php

class SendGrid
{
    const VERSION = '3.2.0';

    protected
        $namespace = 'SendGrid',
        $headers = array('Content-Type' => 'application/json'),
        $client,
        $options;

    public
        $apiUser,
        $apiKey,
        $url,
        $endpoint,
        $version = self::VERSION;

    public function __construct($apiUserOrKey, $apiKeyOrOptions = null, $options = array())
    {
        // Check if given a username + password or api key
        if (is_string($apiKeyOrOptions)) {
            // Username and password
            $this->apiUser = $apiUserOrKey;
            $this->apiKey = $apiKeyOrOptions;
            $this->options = $options;
        } elseif (is_array($apiKeyOrOptions) || $apiKeyOrOptions === null) {
            // API key
            $this->apiKey = $apiUserOrKey;
            $this->apiUser = null;

            // With options
            if (is_array($apiKeyOrOptions)) {
                $this->options = $apiKeyOrOptions;
            }
        } else {
            // Won't be thrown?
            throw new InvalidArgumentException('Need a username + password or api key!');
        }

        $this->options['turn_off_ssl_verification'] = (isset($this->options['turn_off_ssl_verification']) && $this->options['turn_off_ssl_verification'] == true);
        if (!isset($this->options['raise_exceptions'])) {
            $this->options['raise_exceptions'] = true;
        }
        $protocol = isset($this->options['protocol']) ? $this->options['protocol'] : 'https';
        $host = isset($this->options['host']) ? $this->options['host'] : 'api.sendgrid.com';
        $port = isset($this->options['port']) ? $this->options['port'] : '';

        $this->url = isset($this->options['url']) ? $this->options['url'] : $protocol . '://' . $host . ($port ? ':' . $port : '');
        $this->endpoint = isset($this->options['endpoint']) ? $this->options['endpoint'] : '/api/mail.send.json';

        $this->client = $this->prepareHttpClient();
    }

    /**
     * Prepares the HTTP client
     *
     * @return \Guzzle\Http\Client
     */
    private function prepareHttpClient()
    {
        $guzzleOption = array(
            'request.options' => array(
                'verify' => !$this->options['turn_off_ssl_verification'],
                'exceptions' => (isset($this->options['enable_guzzle_exceptions']) && $this->options['enable_guzzle_exceptions'] == true)
            )
        );

        // Using api key
        if ($this->apiUser === null) {
            $guzzleOption['request.options']['headers'] = array('Authorization' => 'Bearer ' . $this->apiKey);
        }

        // Using http proxy
        if (isset($this->options['proxy'])) {
            $guzzleOption['request.options']['proxy'] = $this->options['proxy'];
        }

        $client = new \Guzzle\Http\Client($this->url, $guzzleOption);
        $client->setUserAgent('sendgrid/' . $this->version . ';php');

        return $client;
    }

    /**
     * @return array The protected options array
     */
    public function getOptions()
    {
        return $this->options;
    }

    /**
     * Makes a post request to SendGrid to send an email
     *
     * @param SendGrid\Email $email Email object built
     *
     * @throws SendGrid\Exception if the response code is not 200
     * @return stdClass SendGrid response object
     */
    public function send(SendGrid\Email $email)
    {
        $form = $email->toWebFormat();

        // Using username password
        if ($this->apiUser !== null) {
            $form['api_user'] = $this->apiUser;
            $form['api_key'] = $this->apiKey;
        }

        $response = $this->postRequest($this->endpoint, $form);

        if ($response->code != 200 && $this->options['raise_exceptions']) {
            throw new SendGrid\Exception($response->raw_body, $response->code);
        }

        return $response;
    }

    /**
     * Makes the actual HTTP request to SendGrid
     *
     * @param $endpoint string endpoint to post to
     * @param $form array web ready version of SendGrid\Email
     *
     * @return SendGrid\Response
     */
    public function postRequest($endpoint, $form)
    {
        $req = $this->client->post($endpoint, null, $form);

        $res = $req->send();

        $response = new SendGrid\Response($res->getStatusCode(), $res->getHeaders(), $res->getBody(true), $res->json());

        return $response;
    }

    public static function register_autoloader()
    {
        spl_autoload_register(array('SendGrid', 'autoloader'));
    }

    public static function autoloader($class)
    {
        // Check that the class starts with 'SendGrid'
        if ($class == 'SendGrid' || stripos($class, 'SendGrid\\') === 0) {
            $file = str_replace('\\', '/', $class);

            if (file_exists(dirname(__FILE__) . '/' . $file . '.php')) {
                require_once(dirname(__FILE__) . '/' . $file . '.php');
            }
        }
    }
}