DebugClassLoaderTest.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\Debug\Tests;
  11. use PHPUnit\Framework\TestCase;
  12. use Symfony\Component\Debug\DebugClassLoader;
  13. use Symfony\Component\Debug\ErrorHandler;
  14. class DebugClassLoaderTest extends TestCase
  15. {
  16. /**
  17. * @var int Error reporting level before running tests
  18. */
  19. private $errorReporting;
  20. private $loader;
  21. protected function setUp()
  22. {
  23. $this->errorReporting = error_reporting(E_ALL);
  24. $this->loader = new ClassLoader();
  25. spl_autoload_register([$this->loader, 'loadClass'], true, true);
  26. DebugClassLoader::enable();
  27. }
  28. protected function tearDown()
  29. {
  30. DebugClassLoader::disable();
  31. spl_autoload_unregister([$this->loader, 'loadClass']);
  32. error_reporting($this->errorReporting);
  33. }
  34. public function testIdempotence()
  35. {
  36. DebugClassLoader::enable();
  37. $functions = spl_autoload_functions();
  38. foreach ($functions as $function) {
  39. if (\is_array($function) && $function[0] instanceof DebugClassLoader) {
  40. $reflClass = new \ReflectionClass($function[0]);
  41. $reflProp = $reflClass->getProperty('classLoader');
  42. $reflProp->setAccessible(true);
  43. $this->assertNotInstanceOf('Symfony\Component\Debug\DebugClassLoader', $reflProp->getValue($function[0]));
  44. return;
  45. }
  46. }
  47. $this->fail('DebugClassLoader did not register');
  48. }
  49. public function testThrowingClass()
  50. {
  51. $this->expectException('Exception');
  52. $this->expectExceptionMessage('boo');
  53. try {
  54. class_exists(__NAMESPACE__.'\Fixtures\Throwing');
  55. $this->fail('Exception expected');
  56. } catch (\Exception $e) {
  57. $this->assertSame('boo', $e->getMessage());
  58. }
  59. // the second call also should throw
  60. class_exists(__NAMESPACE__.'\Fixtures\Throwing');
  61. }
  62. public function testUnsilencing()
  63. {
  64. if (\PHP_VERSION_ID >= 70000) {
  65. $this->markTestSkipped('PHP7 throws exceptions, unsilencing is not required anymore.');
  66. }
  67. if (\defined('HHVM_VERSION')) {
  68. $this->markTestSkipped('HHVM is not handled in this test case.');
  69. }
  70. ob_start();
  71. $this->iniSet('log_errors', 0);
  72. $this->iniSet('display_errors', 1);
  73. // See below: this will fail with parse error
  74. // but this should not be @-silenced.
  75. @class_exists(__NAMESPACE__.'\TestingUnsilencing', true);
  76. $output = ob_get_clean();
  77. $this->assertStringMatchesFormat('%aParse error%a', $output);
  78. }
  79. public function testStacking()
  80. {
  81. // the ContextErrorException must not be loaded to test the workaround
  82. // for https://bugs.php.net/65322.
  83. if (class_exists('Symfony\Component\Debug\Exception\ContextErrorException', false)) {
  84. $this->markTestSkipped('The ContextErrorException class is already loaded.');
  85. }
  86. if (\defined('HHVM_VERSION')) {
  87. $this->markTestSkipped('HHVM is not handled in this test case.');
  88. }
  89. ErrorHandler::register();
  90. try {
  91. // Trigger autoloading + E_STRICT at compile time
  92. // which in turn triggers $errorHandler->handle()
  93. // that again triggers autoloading for ContextErrorException.
  94. // Error stacking works around the bug above and everything is fine.
  95. eval('
  96. namespace '.__NAMESPACE__.';
  97. class ChildTestingStacking extends TestingStacking { function foo($bar) {} }
  98. ');
  99. $this->fail('ContextErrorException expected');
  100. } catch (\ErrorException $exception) {
  101. // if an exception is thrown, the test passed
  102. $this->assertStringStartsWith(__FILE__, $exception->getFile());
  103. if (\PHP_VERSION_ID < 70000) {
  104. $this->assertRegExp('/^Runtime Notice: Declaration/', $exception->getMessage());
  105. $this->assertEquals(E_STRICT, $exception->getSeverity());
  106. } else {
  107. $this->assertRegExp('/^Warning: Declaration/', $exception->getMessage());
  108. $this->assertEquals(E_WARNING, $exception->getSeverity());
  109. }
  110. } finally {
  111. restore_error_handler();
  112. restore_exception_handler();
  113. }
  114. }
  115. public function testNameCaseMismatch()
  116. {
  117. $this->expectException('RuntimeException');
  118. $this->expectExceptionMessage('Case mismatch between loaded and declared class names');
  119. class_exists(__NAMESPACE__.'\TestingCaseMismatch', true);
  120. }
  121. public function testFileCaseMismatch()
  122. {
  123. $this->expectException('RuntimeException');
  124. $this->expectExceptionMessage('Case mismatch between class and real file names');
  125. if (!file_exists(__DIR__.'/Fixtures/CaseMismatch.php')) {
  126. $this->markTestSkipped('Can only be run on case insensitive filesystems');
  127. }
  128. class_exists(__NAMESPACE__.'\Fixtures\CaseMismatch', true);
  129. }
  130. public function testPsr4CaseMismatch()
  131. {
  132. $this->expectException('RuntimeException');
  133. $this->expectExceptionMessage('Case mismatch between loaded and declared class names');
  134. class_exists(__NAMESPACE__.'\Fixtures\Psr4CaseMismatch', true);
  135. }
  136. public function testNotPsr0()
  137. {
  138. $this->assertTrue(class_exists(__NAMESPACE__.'\Fixtures\NotPSR0', true));
  139. }
  140. public function testNotPsr0Bis()
  141. {
  142. $this->assertTrue(class_exists(__NAMESPACE__.'\Fixtures\NotPSR0bis', true));
  143. }
  144. public function testClassAlias()
  145. {
  146. $this->assertTrue(class_exists(__NAMESPACE__.'\Fixtures\ClassAlias', true));
  147. }
  148. /**
  149. * @dataProvider provideDeprecatedSuper
  150. */
  151. public function testDeprecatedSuper($class, $super, $type)
  152. {
  153. set_error_handler(function () { return false; });
  154. $e = error_reporting(0);
  155. @trigger_error('', E_USER_DEPRECATED);
  156. class_exists('Test\\'.__NAMESPACE__.'\\'.$class, true);
  157. error_reporting($e);
  158. restore_error_handler();
  159. $lastError = error_get_last();
  160. unset($lastError['file'], $lastError['line']);
  161. $xError = [
  162. 'type' => E_USER_DEPRECATED,
  163. 'message' => 'The "Test\Symfony\Component\Debug\Tests\\'.$class.'" class '.$type.' "Symfony\Component\Debug\Tests\Fixtures\\'.$super.'" that is deprecated but this is a test deprecation notice.',
  164. ];
  165. $this->assertSame($xError, $lastError);
  166. }
  167. public function provideDeprecatedSuper()
  168. {
  169. return [
  170. ['DeprecatedInterfaceClass', 'DeprecatedInterface', 'implements'],
  171. ['DeprecatedParentClass', 'DeprecatedClass', 'extends'],
  172. ];
  173. }
  174. public function testInterfaceExtendsDeprecatedInterface()
  175. {
  176. set_error_handler(function () { return false; });
  177. $e = error_reporting(0);
  178. trigger_error('', E_USER_NOTICE);
  179. class_exists('Test\\'.__NAMESPACE__.'\\NonDeprecatedInterfaceClass', true);
  180. error_reporting($e);
  181. restore_error_handler();
  182. $lastError = error_get_last();
  183. unset($lastError['file'], $lastError['line']);
  184. $xError = [
  185. 'type' => E_USER_NOTICE,
  186. 'message' => '',
  187. ];
  188. $this->assertSame($xError, $lastError);
  189. }
  190. public function testDeprecatedSuperInSameNamespace()
  191. {
  192. set_error_handler(function () { return false; });
  193. $e = error_reporting(0);
  194. trigger_error('', E_USER_NOTICE);
  195. class_exists('Symfony\Bridge\Debug\Tests\Fixtures\ExtendsDeprecatedParent', true);
  196. error_reporting($e);
  197. restore_error_handler();
  198. $lastError = error_get_last();
  199. unset($lastError['file'], $lastError['line']);
  200. $xError = [
  201. 'type' => E_USER_NOTICE,
  202. 'message' => '',
  203. ];
  204. $this->assertSame($xError, $lastError);
  205. }
  206. public function testReservedForPhp7()
  207. {
  208. if (\PHP_VERSION_ID >= 70000) {
  209. $this->markTestSkipped('PHP7 already prevents using reserved names.');
  210. }
  211. set_error_handler(function () { return false; });
  212. $e = error_reporting(0);
  213. trigger_error('', E_USER_NOTICE);
  214. class_exists('Test\\'.__NAMESPACE__.'\\Float', true);
  215. error_reporting($e);
  216. restore_error_handler();
  217. $lastError = error_get_last();
  218. unset($lastError['file'], $lastError['line']);
  219. $xError = [
  220. 'type' => E_USER_DEPRECATED,
  221. 'message' => 'The "Test\Symfony\Component\Debug\Tests\Float" class uses the reserved name "Float", it will break on PHP 7 and higher',
  222. ];
  223. $this->assertSame($xError, $lastError);
  224. }
  225. public function testExtendedFinalClass()
  226. {
  227. $deprecations = [];
  228. set_error_handler(function ($type, $msg) use (&$deprecations) { $deprecations[] = $msg; });
  229. $e = error_reporting(E_USER_DEPRECATED);
  230. require __DIR__.'/Fixtures/FinalClasses.php';
  231. $i = 1;
  232. while (class_exists($finalClass = __NAMESPACE__.'\\Fixtures\\FinalClass'.$i++, false)) {
  233. spl_autoload_call($finalClass);
  234. class_exists('Test\\'.__NAMESPACE__.'\\Extends'.substr($finalClass, strrpos($finalClass, '\\') + 1), true);
  235. }
  236. error_reporting($e);
  237. restore_error_handler();
  238. $this->assertSame([
  239. 'The "Symfony\Component\Debug\Tests\Fixtures\FinalClass1" class is considered final since version 3.3. It may change without further notice as of its next major version. You should not extend it from "Test\Symfony\Component\Debug\Tests\ExtendsFinalClass1".',
  240. 'The "Symfony\Component\Debug\Tests\Fixtures\FinalClass2" class is considered final. It may change without further notice as of its next major version. You should not extend it from "Test\Symfony\Component\Debug\Tests\ExtendsFinalClass2".',
  241. 'The "Symfony\Component\Debug\Tests\Fixtures\FinalClass3" class is considered final comment with @@@ and ***. It may change without further notice as of its next major version. You should not extend it from "Test\Symfony\Component\Debug\Tests\ExtendsFinalClass3".',
  242. 'The "Symfony\Component\Debug\Tests\Fixtures\FinalClass4" class is considered final. It may change without further notice as of its next major version. You should not extend it from "Test\Symfony\Component\Debug\Tests\ExtendsFinalClass4".',
  243. 'The "Symfony\Component\Debug\Tests\Fixtures\FinalClass5" class is considered final multiline comment. It may change without further notice as of its next major version. You should not extend it from "Test\Symfony\Component\Debug\Tests\ExtendsFinalClass5".',
  244. 'The "Symfony\Component\Debug\Tests\Fixtures\FinalClass6" class is considered final. It may change without further notice as of its next major version. You should not extend it from "Test\Symfony\Component\Debug\Tests\ExtendsFinalClass6".',
  245. 'The "Symfony\Component\Debug\Tests\Fixtures\FinalClass7" class is considered final another multiline comment... It may change without further notice as of its next major version. You should not extend it from "Test\Symfony\Component\Debug\Tests\ExtendsFinalClass7".',
  246. 'The "Symfony\Component\Debug\Tests\Fixtures\FinalClass8" class is considered final. It may change without further notice as of its next major version. You should not extend it from "Test\Symfony\Component\Debug\Tests\ExtendsFinalClass8".',
  247. ], $deprecations);
  248. }
  249. public function testExtendedFinalMethod()
  250. {
  251. $deprecations = [];
  252. set_error_handler(function ($type, $msg) use (&$deprecations) { $deprecations[] = $msg; });
  253. $e = error_reporting(E_USER_DEPRECATED);
  254. class_exists(__NAMESPACE__.'\\Fixtures\\ExtendedFinalMethod', true);
  255. error_reporting($e);
  256. restore_error_handler();
  257. $xError = [
  258. 'The "Symfony\Component\Debug\Tests\Fixtures\FinalMethod::finalMethod()" method is considered final since version 3.3. It may change without further notice as of its next major version. You should not extend it from "Symfony\Component\Debug\Tests\Fixtures\ExtendedFinalMethod".',
  259. 'The "Symfony\Component\Debug\Tests\Fixtures\FinalMethod::finalMethod2()" method is considered final. It may change without further notice as of its next major version. You should not extend it from "Symfony\Component\Debug\Tests\Fixtures\ExtendedFinalMethod".',
  260. ];
  261. $this->assertSame($xError, $deprecations);
  262. }
  263. public function testExtendedDeprecatedMethodDoesntTriggerAnyNotice()
  264. {
  265. set_error_handler(function () { return false; });
  266. $e = error_reporting(0);
  267. trigger_error('', E_USER_NOTICE);
  268. class_exists('Test\\'.__NAMESPACE__.'\\ExtendsAnnotatedClass', true);
  269. error_reporting($e);
  270. restore_error_handler();
  271. $lastError = error_get_last();
  272. unset($lastError['file'], $lastError['line']);
  273. $this->assertSame(['type' => E_USER_NOTICE, 'message' => ''], $lastError);
  274. }
  275. public function testInternalsUse()
  276. {
  277. $deprecations = [];
  278. set_error_handler(function ($type, $msg) use (&$deprecations) { $deprecations[] = $msg; });
  279. $e = error_reporting(E_USER_DEPRECATED);
  280. class_exists('Test\\'.__NAMESPACE__.'\\ExtendsInternals', true);
  281. error_reporting($e);
  282. restore_error_handler();
  283. $this->assertSame($deprecations, [
  284. 'The "Symfony\Component\Debug\Tests\Fixtures\InternalInterface" interface is considered internal. It may change without further notice. You should not use it from "Test\Symfony\Component\Debug\Tests\ExtendsInternalsParent".',
  285. 'The "Symfony\Component\Debug\Tests\Fixtures\InternalClass" class is considered internal since version 3.4. It may change without further notice. You should not use it from "Test\Symfony\Component\Debug\Tests\ExtendsInternalsParent".',
  286. 'The "Symfony\Component\Debug\Tests\Fixtures\InternalTrait" trait is considered internal. It may change without further notice. You should not use it from "Test\Symfony\Component\Debug\Tests\ExtendsInternals".',
  287. 'The "Symfony\Component\Debug\Tests\Fixtures\InternalClass::internalMethod()" method is considered internal since version 3.4. It may change without further notice. You should not extend it from "Test\Symfony\Component\Debug\Tests\ExtendsInternals".',
  288. ]);
  289. }
  290. public function testUseTraitWithInternalMethod()
  291. {
  292. $deprecations = [];
  293. set_error_handler(function ($type, $msg) use (&$deprecations) { $deprecations[] = $msg; });
  294. $e = error_reporting(E_USER_DEPRECATED);
  295. class_exists('Test\\'.__NAMESPACE__.'\\UseTraitWithInternalMethod', true);
  296. error_reporting($e);
  297. restore_error_handler();
  298. $this->assertSame([], $deprecations);
  299. }
  300. public function testEvaluatedCode()
  301. {
  302. $this->assertTrue(class_exists(__NAMESPACE__.'\Fixtures\DefinitionInEvaluatedCode', true));
  303. }
  304. }
  305. class ClassLoader
  306. {
  307. public function loadClass($class)
  308. {
  309. }
  310. public function getClassMap()
  311. {
  312. return [__NAMESPACE__.'\Fixtures\NotPSR0bis' => __DIR__.'/Fixtures/notPsr0Bis.php'];
  313. }
  314. public function findFile($class)
  315. {
  316. $fixtureDir = __DIR__.\DIRECTORY_SEPARATOR.'Fixtures'.\DIRECTORY_SEPARATOR;
  317. if (__NAMESPACE__.'\TestingUnsilencing' === $class) {
  318. eval('-- parse error --');
  319. } elseif (__NAMESPACE__.'\TestingStacking' === $class) {
  320. eval('namespace '.__NAMESPACE__.'; class TestingStacking { function foo() {} }');
  321. } elseif (__NAMESPACE__.'\TestingCaseMismatch' === $class) {
  322. eval('namespace '.__NAMESPACE__.'; class TestingCaseMisMatch {}');
  323. } elseif (__NAMESPACE__.'\Fixtures\Psr4CaseMismatch' === $class) {
  324. return $fixtureDir.'psr4'.\DIRECTORY_SEPARATOR.'Psr4CaseMismatch.php';
  325. } elseif (__NAMESPACE__.'\Fixtures\NotPSR0' === $class) {
  326. return $fixtureDir.'reallyNotPsr0.php';
  327. } elseif (__NAMESPACE__.'\Fixtures\NotPSR0bis' === $class) {
  328. return $fixtureDir.'notPsr0Bis.php';
  329. } elseif ('Symfony\Bridge\Debug\Tests\Fixtures\ExtendsDeprecatedParent' === $class) {
  330. eval('namespace Symfony\Bridge\Debug\Tests\Fixtures; class ExtendsDeprecatedParent extends \\'.__NAMESPACE__.'\Fixtures\DeprecatedClass {}');
  331. } elseif ('Test\\'.__NAMESPACE__.'\DeprecatedParentClass' === $class) {
  332. eval('namespace Test\\'.__NAMESPACE__.'; class DeprecatedParentClass extends \\'.__NAMESPACE__.'\Fixtures\DeprecatedClass {}');
  333. } elseif ('Test\\'.__NAMESPACE__.'\DeprecatedInterfaceClass' === $class) {
  334. eval('namespace Test\\'.__NAMESPACE__.'; class DeprecatedInterfaceClass implements \\'.__NAMESPACE__.'\Fixtures\DeprecatedInterface {}');
  335. } elseif ('Test\\'.__NAMESPACE__.'\NonDeprecatedInterfaceClass' === $class) {
  336. eval('namespace Test\\'.__NAMESPACE__.'; class NonDeprecatedInterfaceClass implements \\'.__NAMESPACE__.'\Fixtures\NonDeprecatedInterface {}');
  337. } elseif ('Test\\'.__NAMESPACE__.'\Float' === $class) {
  338. eval('namespace Test\\'.__NAMESPACE__.'; class Float {}');
  339. } elseif (0 === strpos($class, 'Test\\'.__NAMESPACE__.'\ExtendsFinalClass')) {
  340. $classShortName = substr($class, strrpos($class, '\\') + 1);
  341. eval('namespace Test\\'.__NAMESPACE__.'; class '.$classShortName.' extends \\'.__NAMESPACE__.'\Fixtures\\'.substr($classShortName, 7).' {}');
  342. } elseif ('Test\\'.__NAMESPACE__.'\ExtendsAnnotatedClass' === $class) {
  343. eval('namespace Test\\'.__NAMESPACE__.'; class ExtendsAnnotatedClass extends \\'.__NAMESPACE__.'\Fixtures\AnnotatedClass {
  344. public function deprecatedMethod() { }
  345. }');
  346. } elseif ('Test\\'.__NAMESPACE__.'\ExtendsInternals' === $class) {
  347. eval('namespace Test\\'.__NAMESPACE__.'; class ExtendsInternals extends ExtendsInternalsParent {
  348. use \\'.__NAMESPACE__.'\Fixtures\InternalTrait;
  349. public function internalMethod() { }
  350. }');
  351. } elseif ('Test\\'.__NAMESPACE__.'\ExtendsInternalsParent' === $class) {
  352. eval('namespace Test\\'.__NAMESPACE__.'; class ExtendsInternalsParent extends \\'.__NAMESPACE__.'\Fixtures\InternalClass implements \\'.__NAMESPACE__.'\Fixtures\InternalInterface { }');
  353. } elseif ('Test\\'.__NAMESPACE__.'\UseTraitWithInternalMethod' === $class) {
  354. eval('namespace Test\\'.__NAMESPACE__.'; class UseTraitWithInternalMethod { use \\'.__NAMESPACE__.'\Fixtures\TraitWithInternalMethod; }');
  355. }
  356. return null;
  357. }
  358. }