From f170c0f46a43d1964e29f22add01e44781c82a5a Mon Sep 17 00:00:00 2001 From: Sergii Pryz Date: Tue, 4 Apr 2017 22:20:24 +0300 Subject: [PATCH] Added class_exists check. Fixed bug in readme example. --- CHANGELOG.md | 5 +++++ README.md | 2 +- src/ObjectManager.php | 8 ++++++-- tests/unit/src/ObjectManagerTest.php | 10 +++++++++- 4 files changed, 21 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4949efa..5608ad6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,11 @@ CHANGELOG ========= +1.2.0 (2017-04-04) +------------------ +* Added ``class_exists`` check for creating object with construct's arguments +* Fixed bug in readme example + 1.1.0 (2017-04-01) ------------------ * Optimized performance. Moved result of ``__construct`` method exist check to internal cache. diff --git a/README.md b/README.md index 1bd8f54..f3dd4ac 100644 --- a/README.md +++ b/README.md @@ -70,7 +70,7 @@ class UserRepository public function __construct() { - $this->connection = ObjectManagerSingleton::getInstance()->create(); + $this->connection = ObjectManagerSingleton::getInstance()->create('Connection'); } } ``` diff --git a/src/ObjectManager.php b/src/ObjectManager.php index 998f9c3..a4a9b42 100644 --- a/src/ObjectManager.php +++ b/src/ObjectManager.php @@ -22,6 +22,7 @@ class ObjectManager implements ObjectManagerInterface public function create($className, array $arguments = []) { if (empty($arguments)) { + // for performance reason ``class_exists`` is not checked here return new $className(); } @@ -42,8 +43,11 @@ private function getReflection($className) return $this->reflectionContainer[$className]; } - // construction does not available - if (method_exists($className, '__construct') === false) { + if (!class_exists($className)) { + throw new RuntimeException(sprintf('Class "%s" does not exist', $className)); + } + + if (!method_exists($className, '__construct')) { throw new RuntimeException(sprintf('Class "%s" does not have __construct', $className)); } diff --git a/tests/unit/src/ObjectManagerTest.php b/tests/unit/src/ObjectManagerTest.php index aeb3888..cf2cc23 100644 --- a/tests/unit/src/ObjectManagerTest.php +++ b/tests/unit/src/ObjectManagerTest.php @@ -35,7 +35,15 @@ public function testCreate(array $arguments) /** * @expectedException \Picamator\ObjectManager\Exception\RuntimeException */ - public function testFailCreate() + public function testFailNoClassCreate() + { + $this->objectManager->create('NotExistingClass', [1, 2]); + } + + /** + * @expectedException \Picamator\ObjectManager\Exception\RuntimeException + */ + public function testFailNoConstructCreate() { $this->objectManager->create('Picamator\ObjectManager\ObjectManager', [1, 2]); }