config = $config; $this->input = $input; } /** * Output the data to the client */ public function __destruct() { // Output the headers $this->_output_headers(); // Echo the response echo $this->type_wrapper; } /** * Add a header to be output * * @param mixed $header * @return void */ public function set_header($header) { if (is_array($header)) { array_merge($this->headers, $header); } else { $this->headers[] = $header; } } /** * Set the data to be output to the endpoint * * @param string $type - The data format to send * @param mixed $data - The data to send * @return void */ public function set_data($type = 'html', $data = NULL) { if (is_null($data) && ! empty($this->data)) { $data = $this->data; } // Set instance data $this->data = $data; // Get the appropriate output format for the client // And set the data $this->get_accepted_type($type, $this->data); } // -------------------------------------------------------------------------- // ! Private helper methods // -------------------------------------------------------------------------- /** * Get the type more accepted for output * * @param mixed $types * @param mixed $data * @return void */ protected function get_accepted_type($types, $data) { $types = (array) $types; $types = array_map('strtoupper', $types); $headers = $this->input->header_array(); $accept = array_flip($headers['accept']); $type_map = []; $accepted = []; $classes = []; foreach($types as $t) { $type_class = "Sleepy\\Type\\{$t}"; $classes[$type_class] = new $type_class($data); $mime = $classes[$type_class]->get_mime(); $type_map[$mime] = $type_class; } // Order type preference first by // input, then by accept flags foreach($type_map as $type => $obj) { if (\array_key_exists($type, $accept)) { $q = $accept[$type]; if ($q >= 1) { $accepted[] = $type; } else { $accepted[$q] = $type; } } } // Default to html fow wildcard accept values if (empty($accepted) && \array_key_exists('*/*', $accept)) { $accepted[1] = 'text/html'; } // Use the first output type to output the data $class = $type_map[current($accepted)]; $this->type_wrapper = $classes[$class]; // Make sure to set the content-type header if (empty($this->headers)) { $mime = $this->type_wrapper->get_mime(); $this->set_header("Content-type: {$mime}"); } } /** * Set the applicable response headers * * @return void */ protected function _output_headers() { foreach($this->headers as $name => $val) { if (is_numeric($name)) { $output_header = $val; } else { $output_header = implode(": ", [$name, $val]); } @header($output_header); } } } // End of Core/Output.php