Clinner\Command\Callback::getCallbackCode PHP Method

getCallbackCode() public method

Get the code of the inner callback as string.
public getCallbackCode ( ) : string
return string
    public function getCallbackCode()
    {
        $reflection = new \ReflectionFunction($this->_callback);
        // Open file and seek to the first line of the closure
        $file = new \SplFileObject($reflection->getFileName());
        $file->seek($reflection->getStartLine() - 1);
        // Retrieve all of the lines that contain code for the closure
        $code = '';
        while ($file->key() < $reflection->getEndLine()) {
            $code .= $file->current();
            $file->next();
        }
        $begin = strpos($code, 'function');
        $end = strrpos($code, '}');
        $code = substr($code, $begin, $end - $begin + 1);
        return $code;
    }

Usage Example

Example #1
0
 public function testGetCallbackCode()
 {
     $closure = function () {
         echo 'Some nifty code';
     };
     $callback = new Callback($closure);
     $result = $callback->getCallbackCode();
     // Adding this ad-hoc regular expression to minimize the possible errors
     // that might occur while trying to match the source code string against an
     // expected value.
     $regexp = '#^\\s*function\\s*\\(\\s*\\)\\s*{\\s*echo\\s*\'Some nifty code\';\\s*}\\s*$#';
     $this->assertRegExp($regexp, $result);
 }