Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHPUnit - getallheaders not work

I'm testing my code, and i have some problem with header. In each api i use

$headers = getallheaders();

to get that, and this works fine when i test with the app or crhome postman extension. When i lauch my test, like this

 $client = $this->createClient();
    $client->request('GET', '/api/shotcard',
        ['qrcode'=>'D0m1c173'], [],
        ['HTTP_API_TOKEN' => 'abc123']
    );

    $this->assertEquals(200, $client->getResponse()->getStatusCode());

where i try to shot a card with that qrcode with a user with that test token (not the token i'll use in the application), i see a call like this here: https://stackoverflow.com/a/11681422/5475228 . The test fails in this way:

PHP Fatal error: Call to undefined function AppBackendBundle\Controller\getallheaders() in /var/www/pitstop/src/AppBackendBundle/Controller/ApiController.php on line 42

like image 565
NicolaPez Avatar asked Jan 02 '17 13:01

NicolaPez


1 Answers

From this article:

If you use Nginx, PHP-FPM or any other FastCGI method of running PHP you’ve probably noticed that the function getallheaders() does not exist. There are many creative workarounds in the wild, but PHP offers two very nice features to ease your pain.

From user contributed comments at getallheaders() function on PHP manual by joyview at gmail dot com

if (!function_exists('getallheaders')) {
    function getallheaders() {
    $headers = [];
    foreach ($_SERVER as $name => $value) {
        if (substr($name, 0, 5) == 'HTTP_') {
            $headers[str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($name, 5)))))] = $value;
        }
    }
    return $headers;
    }
}
like image 128
Matteo Avatar answered Dec 20 '22 10:12

Matteo