How to use Closure class

Best Mockery code snippet using Closure

SerializableClosure.php

Source:SerializableClosure.php Github

copy

Full Screen

1<?php namespace SuperClosure;2use Closure;3use SuperClosure\Exception\ClosureUnserializationException;4/**5 * This class acts as a wrapper for a closure, and allows it to be serialized.6 *7 * With the combined power of the Reflection API, code parsing, and the infamous8 * `eval()` function, you can serialize a closure, unserialize it somewhere9 * else (even a different PHP process), and execute it.10 */11class SerializableClosure implements \Serializable12{13 /**14 * The closure being wrapped for serialization.15 *16 * @var Closure17 */18 private $closure;19 /**20 * The serializer doing the serialization work.21 *22 * @var SerializerInterface23 */24 private $serializer;25 /**26 * The data from unserialization.27 *28 * @var array29 */30 private $data;31 /**32 * Create a new serializable closure instance.33 *34 * @param Closure $closure35 * @param SerializerInterface|null $serializer36 */37 public function __construct(38 \Closure $closure,39 SerializerInterface $serializer = null40 ) {41 $this->closure = $closure;42 $this->serializer = $serializer ?: new Serializer;43 }44 /**45 * Return the original closure object.46 *47 * @return Closure48 */49 public function getClosure()50 {51 return $this->closure;52 }53 /**54 * Delegates the closure invocation to the actual closure object.55 *56 * Important Notes:57 *58 * - `ReflectionFunction::invokeArgs()` should not be used here, because it59 * does not work with closure bindings.60 * - Args passed-by-reference lose their references when proxied through61 * `__invoke()`. This is an unfortunate, but understandable, limitation62 * of PHP that will probably never change.63 *64 * @return mixed65 */66 public function __invoke()67 {68 return call_user_func_array($this->closure, func_get_args());69 }70 /**71 * Clones the SerializableClosure with a new bound object and class scope.72 *73 * The method is essentially a wrapped proxy to the Closure::bindTo method.74 *75 * @param mixed $newthis The object to which the closure should be bound,76 * or NULL for the closure to be unbound.77 * @param mixed $newscope The class scope to which the closure is to be78 * associated, or 'static' to keep the current one.79 * If an object is given, the type of the object will80 * be used instead. This determines the visibility of81 * protected and private methods of the bound object.82 *83 * @return SerializableClosure84 * @link http://www.php.net/manual/en/closure.bindto.php85 */86 public function bindTo($newthis, $newscope = 'static')87 {88 return new self(89 $this->closure->bindTo($newthis, $newscope),90 $this->serializer91 );92 }93 /**94 * Serializes the code, context, and binding of the closure.95 *96 * @return string|null97 * @link http://php.net/manual/en/serializable.serialize.php98 */99 public function serialize()100 {101 try {102 $this->data = $this->data ?: $this->serializer->getData($this->closure, true);103 return serialize($this->data);104 } catch (\Exception $e) {105 trigger_error(106 'Serialization of closure failed: ' . $e->getMessage(),107 E_USER_NOTICE108 );109 // Note: The serialize() method of Serializable must return a string110 // or null and cannot throw exceptions.111 return null;112 }113 }114 /**115 * Unserializes the closure.116 *117 * Unserializes the closure's data and recreates the closure using a118 * simulation of its original context. The used variables (context) are119 * extracted into a fresh scope prior to redefining the closure. The120 * closure is also rebound to its former object and scope.121 *122 * @param string $serialized123 *124 * @throws ClosureUnserializationException125 * @link http://php.net/manual/en/serializable.unserialize.php126 */127 public function unserialize($serialized)128 {129 // Unserialize the closure data and reconstruct the closure object.130 $this->data = unserialize($serialized);131 $this->closure = __reconstruct_closure($this->data);132 // Throw an exception if the closure could not be reconstructed.133 if (!$this->closure instanceof Closure) {134 throw new ClosureUnserializationException(135 'The closure is corrupted and cannot be unserialized.'136 );137 }138 // Rebind the closure to its former binding and scope.139 if ($this->data['binding'] || $this->data['isStatic']) {140 $this->closure = $this->closure->bindTo(141 $this->data['binding'],142 $this->data['scope']143 );144 }145 }146 /**147 * Returns closure data for `var_dump()`.148 *149 * @return array150 */151 public function __debugInfo()152 {153 return $this->data ?: $this->serializer->getData($this->closure, true);154 }155}156/**157 * Reconstruct a closure.158 *159 * HERE BE DRAGONS!160 *161 * The infamous `eval()` is used in this method, along with the error162 * suppression operator, and variable variables (i.e., double dollar signs) to163 * perform the unserialization logic. I'm sorry, world!164 *165 * This is also done inside a plain function instead of a method so that the166 * binding and scope of the closure are null.167 *168 * @param array $__data Unserialized closure data.169 *170 * @return Closure|null171 * @internal172 */173function __reconstruct_closure(array $__data)174{175 // Simulate the original context the closure was created in.176 foreach ($__data['context'] as $__var_name => &$__value) {177 if ($__value instanceof SerializableClosure) {178 // Unbox any SerializableClosures in the context.179 $__value = $__value->getClosure();180 } elseif ($__value === Serializer::RECURSION) {181 // Track recursive references (there should only be one).182 $__recursive_reference = $__var_name;183 }184 // Import the variable into this scope.185 ${$__var_name} = $__value;186 }187 // Evaluate the code to recreate the closure.188 try {189 if (isset($__recursive_reference)) {190 // Special handling for recursive closures.191 @eval("\${$__recursive_reference} = {$__data['code']};");192 $__closure = ${$__recursive_reference};193 } else {...

Full Screen

Full Screen

ClosureParserTest.php

Source:ClosureParserTest.php Github

copy

Full Screen

1<?php2namespace Jeremeamia\SuperClosure\Test;3use Jeremeamia\SuperClosure\ClosureParser;4class ClosureParserTest extends \PHPUnit_Framework_TestCase5{6 /**7 * @covers \Jeremeamia\SuperClosure\ClosureParser::__construct8 * @covers \Jeremeamia\SuperClosure\ClosureParser::getReflection9 */10 public function testCanGetReflectionBackFromParser()11 {12 $closure = function () {};13 $reflection = new \ReflectionFunction($closure);14 $parser = new ClosureParser($reflection);15 $this->assertSame($reflection, $parser->getReflection());16 }17 /**18 * @covers \Jeremeamia\SuperClosure\ClosureParser::fromClosure19 */20 public function testCanUseFactoryMethodToCreateParser()21 {22 $parser = ClosureParser::fromClosure(function () {});23 $this->assertInstanceOf('Jeremeamia\SuperClosure\ClosureParser', $parser);24 }25 /**26 * @covers \Jeremeamia\SuperClosure\ClosureParser::__construct27 */28 public function testRaisesErrorWhenNonClosureIsProvided()29 {30 $this->setExpectedException('InvalidArgumentException');31 $reflection = new \ReflectionFunction('strpos');32 $parser = new ClosureParser($reflection);33 }34 /**35 * @covers \Jeremeamia\SuperClosure\ClosureParser::getCode36 */37 public function testCanGetCodeFromParser()38 {39 $closure = function () {};40 $expectedCode = "function () {\n \n};";41 $parser = new ClosureParser(new \ReflectionFunction($closure));42 $actualCode = $parser->getCode();43 $this->assertEquals($expectedCode, $actualCode);44 }45 /**46 * @covers \Jeremeamia\SuperClosure\ClosureParser::getUsedVariables47 */48 public function testCanGetUsedVariablesFromParser()49 {50 $foo = 1;51 $bar = 2;52 $closure = function () use ($foo, $bar) {};53 $expectedVars = array('foo' => 1, 'bar' => 2);54 $parser = new ClosureParser(new \ReflectionFunction($closure));55 $actualVars = $parser->getUsedVariables();56 $this->assertEquals($expectedVars, $actualVars);57 }58 /**59 * @covers \Jeremeamia\SuperClosure\ClosureParser::getUsedVariables60 */61 public function testCanGetUsedVariablesWhenOneIsNullFromParser()62 {63 $foo = null;64 $bar = 2;65 $closure = function () use ($foo, $bar) {};66 $expectedVars = array('foo' => null, 'bar' => 2);67 $parser = new ClosureParser(new \ReflectionFunction($closure));68 $actualVars = $parser->getUsedVariables();69 $this->assertEquals($expectedVars, $actualVars);70 }71 /**72 * @covers \Jeremeamia\SuperClosure\ClosureParser::clearCache73 */74 public function testCanClearCache()75 {76 $parserClass = 'Jeremeamia\SuperClosure\ClosureParser';77 $p = new \ReflectionProperty($parserClass, 'cache');78 $p->setAccessible(true);79 $p->setValue(null, array('foo' => 'bar'));80 $this->assertEquals(array('foo' => 'bar'), $this->readAttribute($parserClass, 'cache'));81 ClosureParser::clearCache();82 $this->assertEquals(array(), $this->readAttribute($parserClass, 'cache'));83 }84 /**85 * @covers \Jeremeamia\SuperClosure\ClosureParser::getClosureAbstractSyntaxTree86 * @covers \Jeremeamia\SuperClosure\ClosureParser::getFileAbstractSyntaxTree87 */88 public function testCanGetClosureAst()89 {90 $closure = function () {};91 $parser = new ClosureParser(new \ReflectionFunction($closure));92 $ast = $parser->getClosureAbstractSyntaxTree();93 $this->assertInstanceOf('PHPParser_Node_Expr_Closure', $ast);94 }95}...

Full Screen

Full Screen

Closure

Using AI Code Generation

copy

Full Screen

1use Mockery as m;2use PHPUnit_Framework_MockObject_Matcher_Closure as Closure;3use Mockery as m;4use PHPUnit_Framework_MockObject_Matcher_Closure as Closure;5use Mockery as m;6use PHPUnit_Framework_MockObject_Matcher_Closure as Closure;7use Mockery as m;8use PHPUnit_Framework_MockObject_Matcher_Closure as Closure;9include_once 'PHPUnit.php';10include_once 'PHPUnit.php';11include_once 'PHPUnit.php';

Full Screen

Full Screen

Closure

Using AI Code Generation

copy

Full Screen

1use Mockery as m;2{3 public function tearDown()4 {5 m::close();6 }7 public function testMockery()8 {9 $mock = m::mock('alias:Mockery');10 $mock->shouldReceive('shouldReceive')->once()->andReturn('foo');11 $this->assertEquals('foo', $mock->shouldReceive());12 }13}14use Mockery as m;15{16 public function tearDown()17 {18 m::close();19 }20 public function testMockery()21 {22 $mock = m::mock('alias:Mockery');23 $mock->shouldReceive('shouldReceive')->once()->andReturn('foo');24 $this->assertEquals('foo', $mock->shouldReceive());25 }26}

Full Screen

Full Screen

Closure

Using AI Code Generation

copy

Full Screen

1use Mockery as m;2{3 public function tearDown()4 {5 m::close();6 }7 public function testSomething()8 {9 $closure = m::mock('Closure');10 $closure->shouldReceive('__invoke')->with(1, 2, 3)->once()->andReturn('foo');11 $this->assertEquals('foo', $closure(1, 2, 3));12 }13}14use Mockery as m;15{16 public function tearDown()17 {18 m::close();19 }20 public function testSomething()21 {22 $closure = m::mock('Closure');23 $closure->shouldReceive('__invoke')->with(1, 2, 3)->once()->andReturn('foo');24 $this->assertEquals('foo', $closure(1, 2, 3));25 }26}27use Mockery as m;28{29 public function tearDown()30 {31 m::close();32 }33 public function testSomething()34 {35 $closure = m::mock('Closure');36 $closure->shouldReceive('__invoke')->with(1, 2, 3)->once()->andReturn('foo');37 $this->assertEquals('foo', $closure(1, 2, 3));38 }39}40use Mockery as m;41{42 public function tearDown()43 {44 m::close();45 }46 public function testSomething()47 {48 $closure = m::mock('Closure');49 $closure->shouldReceive('__invoke')->with(1, 2, 3)->once()->andReturn('foo');50 $this->assertEquals('foo', $closure(1, 2, 3));51 }52}53use Mockery as m;54{55 public function tearDown()56 {57 m::close();58 }59 public function testSomething()60 {61 $closure = m::mock('Closure');62 $closure->shouldReceive('__invoke')->with(1, 2,

Full Screen

Full Screen

Closure

Using AI Code Generation

copy

Full Screen

1use Mockery as m;2use PHPUnit\Framework\TestCase;3use PHPSpec2\ObjectBehavior;4{5 public function testSomething()6 {7 $mock = m::mock('MyClass');8 $mock->shouldReceive('foo')->once()->andReturn(1);9 $mock->shouldReceive('bar')->once()->andReturn(2);10 $mock->shouldReceive('baz')->once()->andReturn(3);11 $mock->shouldReceive('qux')->once()->andReturn(4);12 $this->assertEquals(1, $mock->foo());13 $this->assertEquals(2, $mock->bar());14 $this->assertEquals(3, $mock->baz());15 $this->assertEquals(4, $mock->qux());16 }17}18{19 public function it_should_do_something()20 {21 $mock = m::mock('MyClass');22 $mock->shouldReceive('foo')->once()->andReturn(1);23 $mock->shouldReceive('bar')->once()->andReturn(2);24 $mock->shouldReceive('baz')->once()->andReturn(3);25 $mock->shouldReceive('qux')->once()->andReturn(4);26 $this->assertEquals(1, $mock->foo());27 $this->assertEquals(2, $mock->bar());28 $this->assertEquals(3, $mock->baz());29 $this->assertEquals(4, $mock->qux());30 }31}32use Mockery as m;33use PHPUnit\Framework\TestCase;34use PHPSpec2\ObjectBehavior;35{36 public function testSomething()37 {38 $mock = m::mock('MyClass');39 $mock->shouldReceive('foo')->once()->andReturn(1);40 $mock->shouldReceive('bar')->once()->andReturn(2);41 $mock->shouldReceive('baz')->once()->andReturn(3);42 $mock->shouldReceive('qux')->once()->andReturn(4);43 $this->assertEquals(1, $mock->foo());44 $this->assertEquals(2, $mock->bar());45 $this->assertEquals(3, $mock->baz

Full Screen

Full Screen

Closure

Using AI Code Generation

copy

Full Screen

1use Mockery as m;2use PHPUnit\Framework\TestCase;3{4 public function testClosure()5 {6 $closure = function () {7 return 'foo';8 };9 $mock = m::mock($closure);10 $mock->shouldReceive('foo')->andReturn('bar');11 $this->assertSame('bar', $mock->foo());12 }13}

Full Screen

Full Screen

Closure

Using AI Code Generation

copy

Full Screen

1use Mockery as m;2use PHPUnit\Framework\TestCase as PHPUnitTestCase;3{4 public function testFoo()5 {6 $mock = m::mock('Foo');7 $mock->shouldReceive('bar')->andReturnUsing(function ($a, $b) {8 return $a + $b;9 });10 $this->assertEquals(3, $mock->bar(1, 2));11 }12 public function tearDown()13 {14 m::close();15 }16}17use Mockery as m;18use PHPUnit\Framework\TestCase as PHPUnitTestCase;19{20 public function testFoo()21 {22 $mock = m::mock('Foo');23 $mock->shouldReceive('bar')->andReturnUsing(function ($a, $b) {24 return $a + $b;25 });26 $this->assertEquals(3, $mock->bar(1, 2));27 }28 public function tearDown()29 {30 m::close();31 }32}33use Mockery as m;34use PHPUnit\Framework\TestCase as PHPUnitTestCase;35{36 public function testFoo()37 {38 $mock = m::mock('Foo');39 $mock->shouldReceive('bar')->andReturnUsing(function ($a, $b) {40 return $a + $b;41 });42 $this->assertEquals(3, $mock->bar(1, 2));43 }44 public function tearDown()45 {46 m::close();47 }48}49use Mockery as m;50use PHPUnit\Framework\TestCase as PHPUnitTestCase;51{52 public function testFoo()53 {54 $mock = m::mock('Foo');55 $mock->shouldReceive('bar')->andReturnUsing(function ($a, $b) {56 return $a + $b;57 });58 $this->assertEquals(3, $mock->bar(1, 2));59 }60 public function tearDown()61 {62 m::close();63 }64}65use Mockery as m;66use PHPUnit\Framework\TestCase as PHPUnitTestCase;67{68 public function testFoo()69 {70 $mock = m::mock('Foo');71 $mock->shouldReceive('bar')->andReturn

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Mockery automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Most used methods in Closure

Run Selenium Automation Tests on LambdaTest Cloud Grid

Trigger Selenium automation tests on a cloud-based Grid of 3000+ real browsers and operating systems.

Test now for Free

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful