public function testClosureFactory() { $container = new Container(); $container->closure('obj1', function () { return new stdClass(); }); // all same $object1 = $container['obj1']; static::assertSame($object1, $container['obj1']); static::assertSame($object1, $container['obj1']); static::assertSame($object1, $container['obj1']); $container->closure('obj2', function () { return new stdClass(); })->factory(true); $object2 = $container['obj2']; // all not same $object2_1 = $container['obj2']; static::assertNotSame($object2, $object2_1); static::assertEquals($object2, $object2_1); $object2_2 = $container['obj2']; static::assertNotSame($object2, $object2_2); static::assertEquals($object2, $object2_2); static::assertNotSame($object2_1, $object2_2); static::assertEquals($object2_1, $object2_2); }
public function testClosureExtend() { $container = new Container(); $container->closure('closure', function () { return new ExtendTestJsonRenderer(); }); $container->extend('closure', function ($item) { $item->contents = 'closure contents'; return $item; }); // extended static::assertEquals('closure contents', $container['closure']->contents); static::assertSame($container['closure'], $container['closure']); }
public function testFrozen() { $container = new Container(); $container->instance('instance', 'instance string'); $container->closure('closure', function () { return 'closure string'; }); $container->alias('alias', 'closure'); // all change $container->instance('instance', 'instance string changed'); $container->closure('closure', function () { return 'closure string changed'; }); $container->alias('alias', 'instance'); // call, then it freeze all values. $container->get('instance'); $container->get('closure'); $container->get('alias'); // now cannot change try { $container->instance('instance', 'instance string changed 2'); static::fail(); } catch (CannotChangeException $exception) { static::assertEquals('It cannot be changed; instance', $exception->getMessage()); } try { $container->closure('closure', function () { return 'closure string change 2'; }); static::fail(); } catch (CannotChangeException $exception) { static::assertEquals('It cannot be changed; closure', $exception->getMessage()); } try { $container->alias('alias', 'closure'); static::fail(); } catch (CannotChangeException $exception) { static::assertEquals('It cannot be changed; alias', $exception->getMessage()); } // also cannot remove try { $container->offsetUnset('instance'); static::fail(); } catch (CannotChangeException $exception) { static::assertEquals('It cannot be changed; instance', $exception->getMessage()); } try { $container->offsetUnset('closure'); static::fail(); } catch (CannotChangeException $exception) { static::assertEquals('It cannot be changed; closure', $exception->getMessage()); } try { $container->offsetUnset('alias'); static::fail(); } catch (CannotChangeException $exception) { static::assertEquals('It cannot be changed; alias', $exception->getMessage()); } }