asmblah/php-code-shift

Installs: 3 611

Dependents: 4

Suggesters: 0

Security: 0

Stars: 1

Watchers: 2

Forks: 0

Open Issues: 0

Type:project

v0.1.8 2024-04-30 17:06 UTC

This package is auto-updated.

Last update: 2024-04-30 17:07:09 UTC


README

Build Status

[EXPERIMENTAL] Allows running PHP code to be monkey-patched on the fly.

Why?

To allow stubbing of built-in functions during testing, for example.

Usage

Install this package with Composer:

$ composer install asmblah/php-code-shift

Hooking built-in functions

runner.php

<?php

use Asmblah\PhpCodeShift\CodeShift;
use Asmblah\PhpCodeShift\Shifter\Filter\FileFilter;
use Asmblah\PhpCodeShift\Shifter\Shift\Shift\FunctionHook\FunctionHookShiftSpec;

require_once __DIR__ . '/vendor/autoload.php';

$codeShift = new CodeShift();

$codeShift->shift(
    new FunctionHookShiftSpec(
        'substr',
        function (callable $originalSubstr) {
            return function (string $string, int $offset, ?int $length = null) use ($originalSubstr) {
                return '[substr<' . $originalSubstr($string, $offset, $length) . '>]';
            };
        }
    ),
    new FileFilter(__DIR__ . '/substr_test.php')
);

include __DIR__ . '/substr_test.php';

substr_test.php

<?php
// NB: substr(...) will be hooked by the shift defined inside HookBuiltinFunctionTest.
$myResult = substr('my string', 1, 4) . ' and ' . substr('your string', 1, 2);

print $myResult;

The output will be:

[substr<y st>] and [substr<ou>]

Limitations

Functionality is extremely limited at the moment, you may well be better off using one of the alternatives listed in See also below.

  • Does not yet support eval(...).
  • FunctionHookShiftType does not yet support variable function calls.
  • FunctionHookShiftType does not yet support call_user_func(...) and friends, nor any other functions accepting callable parameters that may refer to functions.

See also