DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
  1. DZone
  2. Coding
  3. Languages
  4. Replacing a Built-in PHP Function When Testing a Component

Replacing a Built-in PHP Function When Testing a Component

Sometimes you need to use a custom version of a built-in PHP function, for example when testing. We examine how to do that in this post.

Rob Allen user avatar by
Rob Allen
·
Oct. 18, 18 · Tutorial
Like (1)
Save
Tweet
Share
5.46K Views

Join the DZone community and get the full member experience.

Join For Free

Recently I needed to test part of Slim that uses the built-in PHP functions header() and headers_sent(). To do this, I took advantage of PHP's namespace resolution rules where it will find a function within the same namespace first before finding one with the same name in the global namespace. The idea of how to do this came courtesy of Matthew Weier O'Phinney where this approach is used for similar testing in Zend-Diactoros.

This is the relevant part of the code I want to test:

namespace Slim;

// use statements...

class App
{
    // ... 

    public function respond(ResponseInterface $response)
    {
        // Send response
        if (!headers_sent()) {
            // Headers
            foreach ($response->getHeaders() as $name => $values) {
                $first = stripos($name, 'Set-Cookie') === 0 ? false : true;
                foreach ($values as $value) {
                    header(sprintf('%s: %s', $name, $value), $first);
                    $first = false;
                }
            }
        }

        // method continues
    }

     // ... 
}


This is the relevant test (simplified):

namespace Slim\Tests;

// use statements...

class AppTest extends PHPUnit_Framework_TestCase
{
    // ... 

    public function testResponseReplacesPreviouslySetHeaders()
    {
        $app = new App();

        $response = new Response();
        $response = $response->withHeader('X-Foo', 'baz1')
                ->withAddedHeader('X-Foo', 'baz2');

        $app->respond($response);

        $expectedStack = [
            ['header' => 'X-Foo: baz1', 'replace' => true, 'status_code' => null],
            ['header' => 'X-Foo: baz2', 'replace' => false, 'status_code' => null],
        ];

        $this->assertSame($expectedStack, HeaderStackTestAsset::$headers);
    }

    // ... 
}

This code sets up a Response object with two X-Foo headers, it then calls respond() and tests that there were two calls to header() with the replace parameter set to true only for the first one.

For this to work, we need to override PHP's header() and replace it with our own that stores the parameters into an array within the HeaderStackTestAsset class.

This is done by creating our own HeaderStackTestAsset class along with headers_sent() and header() functions that are called rather than PHP's:

// test/Assets/HeaderFunctions.php

namespace Slim\Tests\Assets {

    class HeaderStackTestAsset
    {
        public static $headers = [];
    }
}

namespace Slim {

    function headers_sent()
    {
        return false;
    }

    function header($header, $replace = true, $statusCode = null)
    {
        \Slim\Tests\Assets\HeaderStackTestAsset::$headers[] = [
            'header' => $header,
            'replace' => $replace,
            'status_code' => $statusCode,
        ];
    }
}

The HeaderStackTestAsset class is trivial and exists entirely as a holder for our $headers array.

We then define our headers_sent() function to always return false and then header() is set up to store the function parameters to the HeaderStackTestAsset::$headers array.

The key thing here is that the headers_sent() and header() functions are in the Slim namespace. As App is also in the same namespace when header() is called within respond(); our version is invoked and so we can ensure that Slim does the right thing with the$replace   parameter.

This is a very handy trick when you need it and works for any PHP function that's called in the global namespace (as long as the file doesn't explicitly import it using use).

PHP

Published at DZone with permission of Rob Allen, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Utilize OpenAI API to Extract Information From PDF Files
  • Ultimate Guide to FaceIO
  • PHP vs React
  • AWS Cloud Migration: Best Practices and Pitfalls to Avoid

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: