Skip to content

Instantly share code, notes, and snippets.

@sirbrillig
Last active October 4, 2019 00:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sirbrillig/5bae3cf58ec1848dfb353309709fa2cd to your computer and use it in GitHub Desktop.
Save sirbrillig/5bae3cf58ec1848dfb353309709fa2cd to your computer and use it in GitHub Desktop.
Example of PHP shell helper injection and test
<?php
// If this function were a class method, the injection could happen in the constructor instead
function printMessageAndExit(string $message, ?ShellHelper $shell): void {
$shell = $shell ?? new DefaultShell();
$shell->echo($message);
$shell->exit();
}
interface ShellHelper {
public function echo(string $message): void;
public function exit(): void;
}
class DefaultShell implements ShellHelper {
public function echo(string $message): void {
echo $message;
}
public function exit(): void {
exit();
}
}
<?php
class MyTest extends \PHPUnit\Framework\TestCase {
public function testPrintMessage() {
$helper = new class implements ShellHelper {
public $echoedMessage;
public $didExit;
public function echo(string $message): void {
$this->echoedMessage = $message;
}
public function exit(): void {
$this->didExit = true;
}
};
printMessageAndExit('hello', $helper);
$this->assertEquals('hello', $helper->echoedMessage);
$this->assertTrue($helper->didExit);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment