Skip to content
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,11 @@

class ObjectManagerTest extends \PHPUnit\Framework\TestCase
{
/**#@+
* Test class with type error
*/
const TEST_CLASS_WITH_TYPE_ERROR = \Magento\Framework\ObjectManager\TestAsset\ConstructorWithTypeError::class;

/**#@+
* Test classes for basic instantiation
*/
Expand Down Expand Up @@ -138,4 +143,17 @@ public function testNewInstance($actualClassName, array $properties = [], $expec
}
}
}

/**
* Test creating an object and passing incorrect type of arguments to the constructor.
*
* @expectedException \Magento\Framework\Exception\RuntimeException
* @expectedExceptionMessage Error occurred when creating object
*/
public function testNewInstanceWithTypeError()
{
self::$_objectManager->create(self::TEST_CLASS_WITH_TYPE_ERROR, [
'testArgument' => new \stdClass()
]);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);

namespace Magento\Framework\ObjectManager\TestAsset;

/**
* Test asset used to test invalid argument types on the constructor invocation.
*/
class ConstructorWithTypeError
{
/**
* @var Basic
*/
private $testArgument;

/**
* @param Basic $testArgument
*/
public function __construct(Basic $testArgument)
{
$this->testArgument = $testArgument;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,11 @@
*/
namespace Magento\Framework\ObjectManager\Factory;

use Magento\Framework\Exception\RuntimeException;
use Magento\Framework\ObjectManagerInterface;
use Magento\Framework\Phrase;
use Psr\Log\LoggerInterface;
use Magento\Framework\App\ObjectManager;

abstract class AbstractFactory implements \Magento\Framework\ObjectManager\FactoryInterface
{
Expand Down Expand Up @@ -104,11 +108,23 @@ public function getDefinitions()
* @param array $args
*
* @return object
*
* @throws RuntimeException
*/
protected function createObject($type, $args)
{
return new $type(...array_values($args));
try {
return new $type(...array_values($args));
} catch (\TypeError $exception) {
/** @var LoggerInterface $logger */
$logger = ObjectManager::getInstance()->get(LoggerInterface::class);
$logger->critical(
sprintf('Type Error occurred when creating object: %s, %s', $type, $exception->getMessage())
);

throw new RuntimeException(
new Phrase('Type Error occurred when creating object: %type', ['type' => $type])
);
}
}

/**
Expand Down