Created
August 1, 2016 08:43
-
-
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
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 | |
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()); | |
} | |
} | |
} |
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 | |
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