aboutsummaryrefslogtreecommitdiffhomepage
path: root/crates/shirabe/src/util/http/response.rs
blob: d505bde408c91d3fc4ed5850f6107a5c6e00b757 (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
//! ref: composer/src/Composer/Util/Http/Response.php

use crate::json::JsonFile;
use shirabe_php_shim::{PhpMixed, php_regex, preg_is_match, preg_match, preg_quote};

#[derive(Debug)]
pub struct Response {
    url: String,
    code: i64,
    headers: Vec<String>,
    body: Option<String>,
}

impl Response {
    pub fn new(url: String, code: Option<i64>, headers: Vec<String>, body: Option<String>) -> Self {
        Self {
            url,
            code: code.unwrap_or(0),
            headers,
            body,
        }
    }

    /// The url of the request this response answered. PHP keeps the whole request array in a
    /// private property with no getter, and the plugin boundary codec needs the url out of it to
    /// rebuild the value in the child.
    pub(crate) fn request_url(&self) -> &str {
        &self.url
    }

    pub fn get_status_code(&self) -> i64 {
        self.code
    }

    pub fn get_status_message(&self) -> Option<String> {
        let mut value = None;
        for header in &self.headers {
            if preg_is_match(php_regex!(r"{^HTTP/\S+ \d+}i"), header) {
                // In case of redirects, headers contain the headers of all responses
                // so we can not return directly and need to keep iterating
                value = Some(header.clone());
            }
        }
        value
    }

    pub fn get_headers(&self) -> &Vec<String> {
        &self.headers
    }

    pub fn get_header(&self, name: &str) -> Option<String> {
        Self::find_header_value(&self.headers, name)
    }

    pub fn get_body(&self) -> Option<&str> {
        self.body.as_deref()
    }

    pub fn decode_json(&self) -> anyhow::Result<PhpMixed> {
        JsonFile::parse_json(self.body.as_deref(), Some(self.url.as_str()))
    }

    pub fn collect(&mut self) {
        self.url = String::new();
        self.code = 0;
        self.headers = vec![];
        self.body = None;
    }

    pub fn find_header_value(headers: &[String], name: &str) -> Option<String> {
        let mut value = None;
        let pattern = format!("{{^{}:\\s*(.+?)\\s*$}}i", preg_quote(name, None));
        for header in headers {
            if let Some(matches) = preg_match(&pattern, header)
                && let Some(s) = matches.get(1)
            {
                value = Some(s.to_string());
            }
        }
        value
    }
}