PHP code example of ctw / ctw-middleware

1. Go to this page and download the library: Download ctw/ctw-middleware library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

ctw / ctw-middleware example snippets


use Ctw\Middleware\AbstractMiddleware;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;

class MyCustomMiddleware extends AbstractMiddleware
{
    public function process(
        ServerRequestInterface $request,
        RequestHandlerInterface $handler
    ): ResponseInterface {
        $response = $handler->handle($request);

        // Only process HTML responses
        if (!$this->containsHtml($response)) {
            return $response;
        }

        // Your HTML processing logic here
        $original = $response->getBody()->getContents();
        $modified = $this->transformHtml($original);

        // Get statistics for the HTML comment suffix
        [$in, $out, $diff] = $this->getSuffixStatistics($original, $modified);

        // Append statistics comment
        $modified .= PHP_EOL . sprintf(self::HTML_SUFFIX, $in, $out, $diff);

        // Return modified response
        // ...
    }
}

if ($this->containsHtml($response)) {
    // Process HTML content
}

[$inputBytes, $outputBytes, $percentReduction] = $this->getSuffixStatistics($original, $transformed);

// Appends comment like: <!-- html: in 15420 b | out 12336 b | diff 20.0000 % -->