Query.php 9.78 KB
Newer Older
Olivier Lequeux's avatar
Olivier Lequeux committed
1 2 3 4 5 6 7 8 9 10 11 12
<?php

namespace Lavoisier;

/**
 * Created by JetBrains PhpStorm.
 * User: Olivier LEQUEUX
 * Date: 22/10/13
 */

use \Lavoisier\Hydrators\DefaultHydrator;
use \Lavoisier\Exceptions\HTTPStatusException;
Cyril L'Orphelin's avatar
Cyril L'Orphelin committed
13
use \Lavoisier\Exceptions\CurlLException;
14
use Lavoisier\Hydrators\IHydrator;
Olivier Lequeux's avatar
Olivier Lequeux committed
15 16 17 18 19

class Query
{
    static private $queryTemplates;

Olivier Lequeux's avatar
Olivier Lequeux committed
20
    private $secureMode;
Olivier Lequeux's avatar
Olivier Lequeux committed
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
    private $schema;
    private $hostname;
    private $port;
    private $operation;
    private $view;
    private $path;
    private $accept;

    private $hydrator;
    private $method; //can be set to 'GET' or 'POST'
    private $post_fields;
    private $connection_timeout_ms;
    private $timeout_ms;

    public static $HTTP_STATUS_MAP = array(
        '401' => '[HTTP 401] Lavoisier authentication problem',
        '403' => '[HTTP 403] Lavoisier authorization problem',
        '404' => '[HTTP 404] Lavoisier execution failed'

    );

    public function __construct($hostname, $view = '', $operation = 'lavoisier', $accept='xml')
    {
Olivier Lequeux's avatar
Olivier Lequeux committed
44
        $this->setSecureMode(false);
Thibaut Salanon's avatar
Thibaut Salanon committed
45 46 47 48 49 50 51 52 53 54 55 56

        if(parse_url($hostname,PHP_URL_HOST) != null){
            $this->hostname = parse_url($hostname,PHP_URL_HOST);
        }else{
            $this->hostname = parse_url($hostname,PHP_URL_PATH);
        }
        if(parse_url($hostname,PHP_URL_PORT) != null){
            $this->port = strval(parse_url($hostname,PHP_URL_PORT));
        }else{
            $this->port = '8080';
        }

Olivier Lequeux's avatar
Olivier Lequeux committed
57 58 59 60 61 62 63 64 65 66 67 68
        $this->operation = $operation;
        $this->view = $view;
        $this->path = '';
        $this->accept = $accept;

        $this->query_field = false;
        $this->method = 'GET';

        self::$queryTemplates = array(
            'lavoisier' => "%s%s:%s/%s/%s%s%saccept=%s",
            'lavoisier_base' => "%s%s:%s/%s/%s%s",
            'notify' => "%s%s:%s/%s/%s",
Olivier Lequeux's avatar
Olivier Lequeux committed
69 70
            'resources' => "%s%s:%s/%s/%s",
            'console' => '%s%s:%s/%s'
Olivier Lequeux's avatar
Olivier Lequeux committed
71 72 73 74 75 76 77 78 79 80
        );

        $this->hydrator = new DefaultHydrator();
        $this->timeout_ms = 500;
        $this->connect_timeout_ms = 500;
        $this->post_fields = array();


    }

Olivier Lequeux's avatar
Olivier Lequeux committed
81
    public function setSecureMode($is_secure)
Olivier Lequeux's avatar
Olivier Lequeux committed
82
    {
Olivier Lequeux's avatar
Olivier Lequeux committed
83 84
        $this->secureMode = $is_secure;
        if ($this->secureMode === true) {
Olivier Lequeux's avatar
Olivier Lequeux committed
85 86 87 88 89 90 91 92 93 94 95
            $this->schema = 'https://';
        } else {
            $this->schema = 'http://';
        }
    }

    public function setPort($port)
    {
        $this->port = $port;
    }

Thibaut Salanon's avatar
Thibaut Salanon committed
96 97 98 99 100 101 102 103 104 105 106 107 108 109 110
    public function getPort()
    {
        return $this->port;
    }

    public function getHostname()
    {
        return $this->hostname;
    }

    public function setHostname($hostname)
    {
        $this->hostname = $hostname;
    }

Olivier Lequeux's avatar
Olivier Lequeux committed
111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132
    public function setOperation($operation)
    {
        $this->operation = $operation;
    }

    public function setView($view)
    {
        $this->view = $view;
    }

    public function setPath($str)
    {
        $this->path = $str;
    }

    public function getPath()
    {
        return $this->path;
    }

    public function setMethod($method)
    {
Olivier Lequeux's avatar
Olivier Lequeux committed
133
        if (($method === 'GET') ||  ($method === 'POST')) {
Olivier Lequeux's avatar
Olivier Lequeux committed
134 135 136 137 138 139 140 141 142 143 144 145
            $this->method = $method;

        } else {
            throw new \Exception ("Please use 'GET' or 'POST' method, the '$method' method is unknown");
        }
    }

    public function getMethod()
    {
        return $this->method;
    }

146
    public function setHydrator(HydratorInterface $hydrator)
Olivier Lequeux's avatar
Olivier Lequeux committed
147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182
    {
        $this->hydrator = $hydrator;
    }

    public function setConnectionTimeoutMS($connect_timeout_ms)
    {
        $this->connect_timeout_ms = $connect_timeout_ms;
    }

    public function setTimeoutMS($connect_timeout_ms)
    {
        $this->timeout_ms = $connect_timeout_ms;
    }

    public function setPostFields(array $post_fields)
    {
        $this->post_fields = $post_fields;
    }

    public function getPostFields()
    {
        return $this->post_fields;
    }

    static public function getQueryTemplate($operation = null)
    {
        if ($operation === null) {
            return self::$queryTemplates;
        }
        if (!isset(self::$queryTemplates[$operation])) {
            throw new \Exception("$operation 'operation' is not recognized by Lavoisier service");
        } else {
            return self::$queryTemplates[$operation];
        }
    }

Olivier Lequeux's avatar
Olivier Lequeux committed
183 184 185 186 187 188 189 190 191 192 193 194 195
    public function isInstanceRunning() {

        $ch = curl_init(($this->getUrl(false, "console")));
        curl_setopt($ch, CURLOPT_CONNECT_ONLY, true);
         curl_exec($ch);
        $response = curl_getinfo($ch);
        $response['last_curl_error'] = curl_error($ch);
        curl_close($ch);
        return empty($response['last_curl_error']);

    }


Olivier Lequeux's avatar
Olivier Lequeux committed
196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287
    public function curl()
    {
        // init curl session
        $ch = curl_init(($this->getUrl(true)));
        curl_setopt($ch, CURLOPT_FRESH_CONNECT, true); // no cache, force new connection

        // timeout values
        curl_setopt($ch, CURLOPT_TIMEOUT, $this->timeout_ms);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $this->connection_timeout_ms);

        // header
        curl_setopt($ch, CURLOPT_HEADER, false); // no header in string returned
        curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)");
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // get result from request as string (otherwise through browser)

        if ($this->method === 'POST') {
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, self::urlify($this->post_fields));
        }

        $content = curl_exec($ch);
        $response = curl_getinfo($ch);
        $response['last_curl_error'] = curl_error($ch);
        $response['content'] = $content;

        curl_close($ch); // close  cURL session

        return $response;

    }

    static private function sprintfPredicate($key, $value, $entriesMode = null)
    {

        if ($entriesMode !== null) {
            return sprintf("%s='%s'", $key, $value);
        } else {
            if (is_array($value)) {
                $string = '';
                $counter = 0;
                foreach ($value as $subValue) {
                    if ($counter != 0) {
                        $string .= ' or ';
                    }
                    $string .= sprintf("(@key='%s' and text()='%s')", $key, $subValue);
                    $counter++;
                }
                return $string;
            } else {
                return sprintf("(@key='%s' and text()='%s')", $key, $value);
            }
        }

    }

    static private function genericBuildPredicate(array $values, $uniqueKey = null, $operator = 'or')
    {
        $predicate = 'true()';
        $compute = true;
        foreach ($values as $key => $value) {
            if(!empty($value)) {
                if ($uniqueKey !== null) $key = $uniqueKey;
                if (is_array($value)) $compute = (count($value) > 0 ? true : false);
                if (($predicate === 'true()') && ($compute)) {
                    $predicate = self::sprintfPredicate($key, $value, $uniqueKey);
                } else {
                    if ($compute) {
                        $predicate = sprintf(" %s %s %s",
                            $predicate, $operator, self::sprintfPredicate($key, $value, $uniqueKey));
                    }
                }
            }
        }
        $predicate = trim($predicate);

        return $predicate;
    }

    static public function buildPredicate($test, array $values, $operator = 'or')
    {
        return self::genericBuildPredicate($values, $test, $operator);
    }

    static public function buildEntriesPredicate(array $whereClauses, $operator = 'or')
    {
        return self::genericBuildPredicate($whereClauses, null, $operator);
    }

    /**
     * convert map to &key=value url style
     * @static
     * @param array $fields, tuple of key/values to convert
Olivier Lequeux's avatar
Olivier Lequeux committed
288
     * @return string
Olivier Lequeux's avatar
Olivier Lequeux committed
289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347
     */
    static public function urlify(array $fields)
    {
        $fields_string = array();
        foreach ($fields as $key => $value) {
            if(!empty($value)) {
                $fields_string[] = sprintf('%s=%s', $key, $value);
            }
        }
        return implode('&', $fields_string);
    }

    public function getUrl($urlencode = false, $template_name = null)
    {
        $url_chunks = array(
            $this->schema,
            $this->hostname,
            $this->port,
            $this->operation,
            $this->view,
        );

        $path = $this->path;
        if ($urlencode === true) {
            $path = rawurlencode($this->path);
        }

        if ($this->operation == 'lavoisier') {
            $url_chunks = array_merge($url_chunks, array(
                    $path,
                    (($this->query_field === true) ? '&' : '?'),
                    $this->accept)
            );
        }

        if(!$template_name) {
            $template = self::getQueryTemplate($this->operation);
        }
        else {
            $template = self::getQueryTemplate($template_name);
        }

        $qString = vsprintf(
            $template,
            $url_chunks
        );


        return $qString;
    }

    public function execute()
    {
        $resCURL = $this->curl();
        if ((isset($resCURL['http_code']) && isset(self::$HTTP_STATUS_MAP[$resCURL['http_code']]))) {
            throw new HTTPStatusException($this, $resCURL['http_code'], $resCURL['content']);
        }

        if (isset($resCURL['last_curl_error']) && (!empty($resCURL['last_curl_error']))) {
Cyril L'Orphelin's avatar
Cyril L'Orphelin committed
348
            throw new CurlLException($this, $resCURL['last_curl_error']);
Olivier Lequeux's avatar
Olivier Lequeux committed
349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365
        }

        if (($this->operation === 'lavoisier')) {
            $resHYDRATED = $this->hydrator->hydrate($resCURL['content']);
            return $resHYDRATED;
        } else {
            return $resCURL['content'];
        }
    }

    public function dump() {
        return array(
            'url' => $this->getUrl(),
            'post' => $this->getPostFields()
        );
    }

366
}