Last active
December 11, 2019 22:46
-
-
Save azjezz/10eef0806d4b5c33be23b0b9c0294ca7 to your computer and use it in GitHub Desktop.
Improve the performance of your PHP 7.4 application
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
declare(strict_types=1); | |
namespace BetterApplication; | |
use FFI; | |
use Closure; | |
abstract class AbstractZendWriter | |
{ | |
protected FFI $zend; | |
private ?FFI\CData $writer = null; | |
public function __construct() | |
{ | |
$this->zend = FFI::cdef(" | |
typedef int (*zend_write_func_t)(const char *str, size_t str_length); | |
extern zend_write_func_t zend_write; | |
"); | |
} | |
abstract protected function replace(string $text): string; | |
final public function register(): void | |
{ | |
if (null !== $this->writer) { | |
throw new \RuntimeException(\sprintf('%s writer is already registered.', static::class)); | |
} | |
$this->writer = clone $this->zend->zend_write; | |
$this->zend->zend_write = $this->getCallback(); | |
} | |
final public function unregister(): void | |
{ | |
if (null === $this->writer) { | |
throw new \RuntimeException(\sprintf('%s writer is not registered.', static::class)); | |
} | |
$this->zend->zend_write = $this->writer; | |
$this->writer = null; | |
} | |
final private function getCallback(): Closure | |
{ | |
return function(string $str, int $_): int { | |
$output = $this->replace($str); | |
return ($this->writer)($output, \strlen($output)); | |
}; | |
} | |
} | |
class NicolasCageWriter extends AbstractZendWriter | |
{ | |
protected function replace(string $text): string | |
{ | |
return '<img src="https://upload.wikimedia.org/wikipedia/commons/c/c0/Nicolas_Cage_Deauville_2013.jpg" alt="Nicolas Cage" />'; | |
} | |
} | |
$nicolas = new NicolasCageWriter(); | |
$nicolas->register(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment