From 5f40cab3e796235a3bf6dfd2bddd451ca1019860 Mon Sep 17 00:00:00 2001 From: Haralan Dobrev Date: Mon, 20 Jul 2015 17:30:15 +0300 Subject: [PATCH] Use late static binding for Parsedown::instance() Fixes erusev/parsedown-extra#67. This introduces PHP 5.3+ late static binding to the Singleton pattern in Parsedown. It will return an instance of Parsedown which inherits the class which called the `instance()` method rather than always returning instance of just `Parsedown`. Tests are testing this feature with a test class which inherits from Parsedown. Notice that calling `instance()` with the default arguments after an instance of `Parsedown` was already created, it will return it even though it is from just an instance of `Parsedown`. So this is fixing the problem just partially. --- Parsedown.php | 2 +- test/ParsedownTest.php | 20 ++++++++++++++++++++ test/TestParsedown.php | 5 +++++ 3 files changed, 26 insertions(+), 1 deletion(-) create mode 100644 test/TestParsedown.php diff --git a/Parsedown.php b/Parsedown.php index 3a2803a..d2e34ba 100755 --- a/Parsedown.php +++ b/Parsedown.php @@ -1475,7 +1475,7 @@ class Parsedown return self::$instances[$name]; } - $instance = new self(); + $instance = new static(); self::$instances[$name] = $instance; diff --git a/test/ParsedownTest.php b/test/ParsedownTest.php index 759b8fd..c922ab1 100644 --- a/test/ParsedownTest.php +++ b/test/ParsedownTest.php @@ -136,4 +136,24 @@ EXPECTED_HTML; $parsedownWithNoMarkup->setMarkupEscaped(true); $this->assertEquals($expectedHtml, $parsedownWithNoMarkup->text($markdownWithHtml)); } + + public function testLateStaticBinding() + { + include 'test/TestParsedown.php'; + + $parsedown = Parsedown::instance(); + $this->assertInstanceOf('Parsedown', $parsedown); + + // After instance is already called on Parsedown + // subsequent calls with the same arguments return the same instance + $sameParsedown = TestParsedown::instance(); + $this->assertInstanceOf('Parsedown', $sameParsedown); + $this->assertSame($parsedown, $sameParsedown); + + $testParsedown = TestParsedown::instance('test late static binding'); + $this->assertInstanceOf('TestParsedown', $testParsedown); + + $sameInstanceAgain = TestParsedown::instance('test late static binding'); + $this->assertSame($testParsedown, $sameInstanceAgain); + } } diff --git a/test/TestParsedown.php b/test/TestParsedown.php new file mode 100644 index 0000000..7024dfb --- /dev/null +++ b/test/TestParsedown.php @@ -0,0 +1,5 @@ +