From bfa2390d5a57a4319eb656fad9ca8b3d69a9462d Mon Sep 17 00:00:00 2001 From: SilverFire - Dmitry Naumenko Date: Wed, 1 Mar 2017 19:29:30 +0200 Subject: [PATCH] Added `yii\di\Instance::__set_state()` method --- framework/CHANGELOG.md | 1 + framework/di/Instance.php | 18 ++++++++++++++++++ tests/framework/di/InstanceTest.php | 27 +++++++++++++++++++++++++++ 3 files changed, 46 insertions(+) diff --git a/framework/CHANGELOG.md b/framework/CHANGELOG.md index b2de0b3c78..3db93dca18 100644 --- a/framework/CHANGELOG.md +++ b/framework/CHANGELOG.md @@ -40,6 +40,7 @@ Yii Framework 2 Change Log - Enh #13650: Improved `yii\base\Security::hkdf()` to take advantage of native `hash_hkdf()` implementation in PHP >= 7.1.2 (charlesportwoodii) - Bug #13379: Fixed `applyFilter` function in `yii.gridView.js` to work correctly when params in `filterUrl` are indexed (SilverFire) - Bug #13670: Fixed alias option from console when it includes `-` or `_` in option name (pana1990) +- Enh: Added `yii\di\Instance::__set_state()` method to restore object after serialization using `var_export()` function (silvefire) 2.0.11.2 February 08, 2017 diff --git a/framework/di/Instance.php b/framework/di/Instance.php index a11491a150..6a5e56761f 100644 --- a/framework/di/Instance.php +++ b/framework/di/Instance.php @@ -161,4 +161,22 @@ class Instance return Yii::$container->get($this->id); } } + + /** + * Restores class state after using `var_export()` + * + * @param array $state + * @return Instance + * @throws InvalidConfigException when $state property does not contain `id` parameter + * @see var_export() + * @since 2.0.12 + */ + public static function __set_state($state) + { + if (!isset($state['id'])) { + throw new InvalidConfigException('Failed to instantiate class "Instance". Required parameter "id" is missing'); + } + + return new self($state['id']); + } } diff --git a/tests/framework/di/InstanceTest.php b/tests/framework/di/InstanceTest.php index 2ac448d447..349b55ab9a 100644 --- a/tests/framework/di/InstanceTest.php +++ b/tests/framework/di/InstanceTest.php @@ -156,4 +156,31 @@ class InstanceTest extends TestCase $this->assertInstanceOf('yii\db\Connection', $db = $cache->db); $this->assertEquals('sqlite:path/to/file.db', $db->dsn); } + + public function testRestoreAfterVarExport() + { + $instance = Instance::of('something'); + $export = var_export($instance, true); + + $this->assertEquals(<<<'PHP' +yii\di\Instance::__set_state(array( + 'id' => 'something', +)) +PHP + , $export); + + $this->assertEquals($instance, Instance::__set_state([ + 'id' => 'something', + ])); + } + + public function testRestoreAfterVarExportRequiresId() + { + $this->setExpectedException( + 'yii\base\InvalidConfigException', + 'Failed to instantiate class "Instance". Required parameter "id" is missing' + ); + + Instance::__set_state([]); + } }