Server.php
<?php
namespace Tlf\Tester;
/**
* convenience methods for server-related tests
* Server-related assertions may go here too
*
* @todo stop using file_get_contents() so I check for redirects & stuff
*/
trait Server {
/**
*
* @param $path the path component of a url
* @param $params an array of paramaters to pass in the url
*
* @note $path cannot contain query string if params are passed
* @warning this early implementation will change
*
* @usage $response_content = $this->get('/', ['cat'=>'Jefurry']);
*/
public function get($path, $params=[]){
// $protocol = $this->cli->get_server_protocol();
// $host = $this->cli->get_server_host();
// $url = $protocol.$host.$path;
// if ($params!=[])$url .= '?'.http_build_query($params);
// try {
// $content = file_get_contents($url);
// } catch (\ErrorException $e){
// echo "\nFailed to load $url\n...Is the server running?\n...run [phptest server]\n";
// throw $e;
// }
// return $content;
$protocol = $this->cli->get_server_protocol();
$host = $this->cli->get_server_host();
$url = $protocol.$host.$path;
if ($params!=[]) $url .= '?' . http_build_query($params);
$ch = curl_init();
curl_setopt_array($ch,
[
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => false,
// CURLOPT_POSTFIELDS => http_build_query($params),
// CURLOPT_POSTFIELDS => $params,
CURLOPT_FOLLOWLOCATION => true,
]
);
$output = curl_exec($ch);
curl_close($ch);
return $output;
}
/**
*
* @param $path the path component of a url
* @param $params an array of paramaters to pass via $_POST
* @param $files key=>value array of files where key = short file name & value = local file path
*
* @note $params['key'] will be overwritten by $files['key'] for the upload
* @note(jan 4, 2022) follows redirects ('Location:' header)
*
* @note $path cannot contain query string if params are passed
*
* @usage $response_content = $this->get('/', ['cat'=>'Jefurry']);
*/
public function post($path, $params=[], $files=[]){
$protocol = $this->cli->get_server_protocol();
$host = $this->cli->get_server_host();
$url = $protocol.$host.$path;
$ch = curl_init();
foreach ($files as $name=>$path){
$mimetype = mime_content_type($path);
// $mimetype = false;
if ($mimetype==false){
$ext = pathinfo($path,PATHINFO_EXTENSION);
$list = require(dirname(__DIR__).'/mime_type_map.php');
$mimetype = $list['mimes'][$ext][0];
}
$params[$name] = new \CURLFile($path, $mimetype, basename($path));
}
curl_setopt_array($ch,
[
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
// CURLOPT_POSTFIELDS => http_build_query($params),
CURLOPT_POSTFIELDS => $params,
CURLOPT_FOLLOWLOCATION => true,
]
);
$output = curl_exec($ch);
curl_close($ch);
return $output;
}
}