Skip to content

Instantly share code, notes, and snippets.

@ahsankhatri
Created August 1, 2016 08:43
Show Gist options
  • Save ahsankhatri/4d9f953f8f5170f987792b09d5e31969 to your computer and use it in GitHub Desktop.
Save ahsankhatri/4d9f953f8f5170f987792b09d5e31969 to your computer and use it in GitHub Desktop.
Alter/Modify global functions return value as per need without touching your code with just one variable
<?php
namespace {
// This allow us to configure the behavior of the "global mock"
$mockSocketCreate = false;
include_once './SomeClass.php';
/*$dummy = new \My\Nice\Namezpace\SomeClass;
var_dump($dummy->doSomething());*/
var_dump(\My\Nice\Namezpace\SomeClass::doSomething());
}
namespace My\Nice\Namezpace {
// And this here, does the trick: it will override the socket_create()
// function in your code *just for the namespace* where you are defining it.
// This relies on the code above calling the socket_create function without
// the leading backslash, so we trick SomeClass into calling our own function
// inside that namespace instead of the global socket_create function.
function strpos() {
global $mockSocketCreate;
// var_dump($mockSocketCreate);exit;
if (isset($mockSocketCreate) && $mockSocketCreate === true) {
return false;
} else {
return call_user_func_array('\strpos', func_get_args());
}
}
}
<?php
namespace My\Nice\Namezpace;
class SomeClass
{
public static function doSomething()
{
// Notice how the global function "socket_create" is called without
// the leading backslash (relative instead of absolute call in a
// namespaced environment). This will let us later mock the call
// by taking advantage of the relative-to-the-namespace call.
$socket = strpos('Full string', 'str');
if ($socket === false) {
throw new \Exception('Ooops!');
}
return true;
}
public function __construct(){}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment