DebugClassLoaderTest.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451
  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. /**
  50. * @expectedException \Exception
  51. * @expectedExceptionMessage boo
  52. */
  53. public function testThrowingClass()
  54. {
  55. try {
  56. class_exists(__NAMESPACE__.'\Fixtures\Throwing');
  57. $this->fail('Exception expected');
  58. } catch (\Exception $e) {
  59. $this->assertSame('boo', $e->getMessage());
  60. }
  61. // the second call also should throw
  62. class_exists(__NAMESPACE__.'\Fixtures\Throwing');
  63. }
  64. public function testUnsilencing()
  65. {
  66. if (\PHP_VERSION_ID >= 70000) {
  67. $this->markTestSkipped('PHP7 throws exceptions, unsilencing is not required anymore.');
  68. }
  69. if (\defined('HHVM_VERSION')) {
  70. $this->markTestSkipped('HHVM is not handled in this test case.');
  71. }
  72. ob_start();
  73. $this->iniSet('log_errors', 0);
  74. $this->iniSet('display_errors', 1);
  75. // See below: this will fail with parse error
  76. // but this should not be @-silenced.
  77. @class_exists(__NAMESPACE__.'\TestingUnsilencing', true);
  78. $output = ob_get_clean();
  79. $this->assertStringMatchesFormat('%aParse error%a', $output);
  80. }
  81. public function testStacking()
  82. {
  83. // the ContextErrorException must not be loaded to test the workaround
  84. // for https://bugs.php.net/65322.
  85. if (class_exists('Symfony\Component\Debug\Exception\ContextErrorException', false)) {
  86. $this->markTestSkipped('The ContextErrorException class is already loaded.');
  87. }
  88. if (\defined('HHVM_VERSION')) {
  89. $this->markTestSkipped('HHVM is not handled in this test case.');
  90. }
  91. ErrorHandler::register();
  92. try {
  93. // Trigger autoloading + E_STRICT at compile time
  94. // which in turn triggers $errorHandler->handle()
  95. // that again triggers autoloading for ContextErrorException.
  96. // Error stacking works around the bug above and everything is fine.
  97. eval('
  98. namespace '.__NAMESPACE__.';
  99. class ChildTestingStacking extends TestingStacking { function foo($bar) {} }
  100. ');
  101. $this->fail('ContextErrorException expected');
  102. } catch (\ErrorException $exception) {
  103. // if an exception is thrown, the test passed
  104. $this->assertStringStartsWith(__FILE__, $exception->getFile());
  105. if (\PHP_VERSION_ID < 70000) {
  106. $this->assertRegExp('/^Runtime Notice: Declaration/', $exception->getMessage());
  107. $this->assertEquals(E_STRICT, $exception->getSeverity());
  108. } else {
  109. $this->assertRegExp('/^Warning: Declaration/', $exception->getMessage());
  110. $this->assertEquals(E_WARNING, $exception->getSeverity());
  111. }
  112. } finally {
  113. restore_error_handler();
  114. restore_exception_handler();
  115. }
  116. }
  117. /**
  118. * @expectedException \RuntimeException
  119. * @expectedExceptionMessage Case mismatch between loaded and declared class names
  120. */
  121. public function testNameCaseMismatch()
  122. {
  123. class_exists(__NAMESPACE__.'\TestingCaseMismatch', true);
  124. }
  125. /**
  126. * @expectedException \RuntimeException
  127. * @expectedExceptionMessage Case mismatch between class and real file names
  128. */
  129. public function testFileCaseMismatch()
  130. {
  131. if (!file_exists(__DIR__.'/Fixtures/CaseMismatch.php')) {
  132. $this->markTestSkipped('Can only be run on case insensitive filesystems');
  133. }
  134. class_exists(__NAMESPACE__.'\Fixtures\CaseMismatch', true);
  135. }
  136. /**
  137. * @expectedException \RuntimeException
  138. * @expectedExceptionMessage Case mismatch between loaded and declared class names
  139. */
  140. public function testPsr4CaseMismatch()
  141. {
  142. class_exists(__NAMESPACE__.'\Fixtures\Psr4CaseMismatch', true);
  143. }
  144. public function testNotPsr0()
  145. {
  146. $this->assertTrue(class_exists(__NAMESPACE__.'\Fixtures\NotPSR0', true));
  147. }
  148. public function testNotPsr0Bis()
  149. {
  150. $this->assertTrue(class_exists(__NAMESPACE__.'\Fixtures\NotPSR0bis', true));
  151. }
  152. public function testClassAlias()
  153. {
  154. $this->assertTrue(class_exists(__NAMESPACE__.'\Fixtures\ClassAlias', true));
  155. }
  156. /**
  157. * @dataProvider provideDeprecatedSuper
  158. */
  159. public function testDeprecatedSuper($class, $super, $type)
  160. {
  161. set_error_handler(function () { return false; });
  162. $e = error_reporting(0);
  163. @trigger_error('', E_USER_DEPRECATED);
  164. class_exists('Test\\'.__NAMESPACE__.'\\'.$class, true);
  165. error_reporting($e);
  166. restore_error_handler();
  167. $lastError = error_get_last();
  168. unset($lastError['file'], $lastError['line']);
  169. $xError = [
  170. 'type' => E_USER_DEPRECATED,
  171. '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.',
  172. ];
  173. $this->assertSame($xError, $lastError);
  174. }
  175. public function provideDeprecatedSuper()
  176. {
  177. return [
  178. ['DeprecatedInterfaceClass', 'DeprecatedInterface', 'implements'],
  179. ['DeprecatedParentClass', 'DeprecatedClass', 'extends'],
  180. ];
  181. }
  182. public function testInterfaceExtendsDeprecatedInterface()
  183. {
  184. set_error_handler(function () { return false; });
  185. $e = error_reporting(0);
  186. trigger_error('', E_USER_NOTICE);
  187. class_exists('Test\\'.__NAMESPACE__.'\\NonDeprecatedInterfaceClass', true);
  188. error_reporting($e);
  189. restore_error_handler();
  190. $lastError = error_get_last();
  191. unset($lastError['file'], $lastError['line']);
  192. $xError = [
  193. 'type' => E_USER_NOTICE,
  194. 'message' => '',
  195. ];
  196. $this->assertSame($xError, $lastError);
  197. }
  198. public function testDeprecatedSuperInSameNamespace()
  199. {
  200. set_error_handler(function () { return false; });
  201. $e = error_reporting(0);
  202. trigger_error('', E_USER_NOTICE);
  203. class_exists('Symfony\Bridge\Debug\Tests\Fixtures\ExtendsDeprecatedParent', true);
  204. error_reporting($e);
  205. restore_error_handler();
  206. $lastError = error_get_last();
  207. unset($lastError['file'], $lastError['line']);
  208. $xError = [
  209. 'type' => E_USER_NOTICE,
  210. 'message' => '',
  211. ];
  212. $this->assertSame($xError, $lastError);
  213. }
  214. public function testReservedForPhp7()
  215. {
  216. if (\PHP_VERSION_ID >= 70000) {
  217. $this->markTestSkipped('PHP7 already prevents using reserved names.');
  218. }
  219. set_error_handler(function () { return false; });
  220. $e = error_reporting(0);
  221. trigger_error('', E_USER_NOTICE);
  222. class_exists('Test\\'.__NAMESPACE__.'\\Float', true);
  223. error_reporting($e);
  224. restore_error_handler();
  225. $lastError = error_get_last();
  226. unset($lastError['file'], $lastError['line']);
  227. $xError = [
  228. 'type' => E_USER_DEPRECATED,
  229. 'message' => 'The "Test\Symfony\Component\Debug\Tests\Float" class uses the reserved name "Float", it will break on PHP 7 and higher',
  230. ];
  231. $this->assertSame($xError, $lastError);
  232. }
  233. public function testExtendedFinalClass()
  234. {
  235. $deprecations = [];
  236. set_error_handler(function ($type, $msg) use (&$deprecations) { $deprecations[] = $msg; });
  237. $e = error_reporting(E_USER_DEPRECATED);
  238. require __DIR__.'/Fixtures/FinalClasses.php';
  239. $i = 1;
  240. while (class_exists($finalClass = __NAMESPACE__.'\\Fixtures\\FinalClass'.$i++, false)) {
  241. spl_autoload_call($finalClass);
  242. class_exists('Test\\'.__NAMESPACE__.'\\Extends'.substr($finalClass, strrpos($finalClass, '\\') + 1), true);
  243. }
  244. error_reporting($e);
  245. restore_error_handler();
  246. $this->assertSame([
  247. '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".',
  248. '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".',
  249. '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".',
  250. '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".',
  251. '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".',
  252. '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".',
  253. '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".',
  254. '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".',
  255. ], $deprecations);
  256. }
  257. public function testExtendedFinalMethod()
  258. {
  259. $deprecations = [];
  260. set_error_handler(function ($type, $msg) use (&$deprecations) { $deprecations[] = $msg; });
  261. $e = error_reporting(E_USER_DEPRECATED);
  262. class_exists(__NAMESPACE__.'\\Fixtures\\ExtendedFinalMethod', true);
  263. error_reporting($e);
  264. restore_error_handler();
  265. $xError = [
  266. '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".',
  267. '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".',
  268. ];
  269. $this->assertSame($xError, $deprecations);
  270. }
  271. public function testExtendedDeprecatedMethodDoesntTriggerAnyNotice()
  272. {
  273. set_error_handler(function () { return false; });
  274. $e = error_reporting(0);
  275. trigger_error('', E_USER_NOTICE);
  276. class_exists('Test\\'.__NAMESPACE__.'\\ExtendsAnnotatedClass', true);
  277. error_reporting($e);
  278. restore_error_handler();
  279. $lastError = error_get_last();
  280. unset($lastError['file'], $lastError['line']);
  281. $this->assertSame(['type' => E_USER_NOTICE, 'message' => ''], $lastError);
  282. }
  283. public function testInternalsUse()
  284. {
  285. $deprecations = [];
  286. set_error_handler(function ($type, $msg) use (&$deprecations) { $deprecations[] = $msg; });
  287. $e = error_reporting(E_USER_DEPRECATED);
  288. class_exists('Test\\'.__NAMESPACE__.'\\ExtendsInternals', true);
  289. error_reporting($e);
  290. restore_error_handler();
  291. $this->assertSame($deprecations, [
  292. '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".',
  293. '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".',
  294. '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".',
  295. '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".',
  296. ]);
  297. }
  298. public function testUseTraitWithInternalMethod()
  299. {
  300. $deprecations = [];
  301. set_error_handler(function ($type, $msg) use (&$deprecations) { $deprecations[] = $msg; });
  302. $e = error_reporting(E_USER_DEPRECATED);
  303. class_exists('Test\\'.__NAMESPACE__.'\\UseTraitWithInternalMethod', true);
  304. error_reporting($e);
  305. restore_error_handler();
  306. $this->assertSame([], $deprecations);
  307. }
  308. public function testEvaluatedCode()
  309. {
  310. $this->assertTrue(class_exists(__NAMESPACE__.'\Fixtures\DefinitionInEvaluatedCode', true));
  311. }
  312. }
  313. class ClassLoader
  314. {
  315. public function loadClass($class)
  316. {
  317. }
  318. public function getClassMap()
  319. {
  320. return [__NAMESPACE__.'\Fixtures\NotPSR0bis' => __DIR__.'/Fixtures/notPsr0Bis.php'];
  321. }
  322. public function findFile($class)
  323. {
  324. $fixtureDir = __DIR__.\DIRECTORY_SEPARATOR.'Fixtures'.\DIRECTORY_SEPARATOR;
  325. if (__NAMESPACE__.'\TestingUnsilencing' === $class) {
  326. eval('-- parse error --');
  327. } elseif (__NAMESPACE__.'\TestingStacking' === $class) {
  328. eval('namespace '.__NAMESPACE__.'; class TestingStacking { function foo() {} }');
  329. } elseif (__NAMESPACE__.'\TestingCaseMismatch' === $class) {
  330. eval('namespace '.__NAMESPACE__.'; class TestingCaseMisMatch {}');
  331. } elseif (__NAMESPACE__.'\Fixtures\Psr4CaseMismatch' === $class) {
  332. return $fixtureDir.'psr4'.\DIRECTORY_SEPARATOR.'Psr4CaseMismatch.php';
  333. } elseif (__NAMESPACE__.'\Fixtures\NotPSR0' === $class) {
  334. return $fixtureDir.'reallyNotPsr0.php';
  335. } elseif (__NAMESPACE__.'\Fixtures\NotPSR0bis' === $class) {
  336. return $fixtureDir.'notPsr0Bis.php';
  337. } elseif ('Symfony\Bridge\Debug\Tests\Fixtures\ExtendsDeprecatedParent' === $class) {
  338. eval('namespace Symfony\Bridge\Debug\Tests\Fixtures; class ExtendsDeprecatedParent extends \\'.__NAMESPACE__.'\Fixtures\DeprecatedClass {}');
  339. } elseif ('Test\\'.__NAMESPACE__.'\DeprecatedParentClass' === $class) {
  340. eval('namespace Test\\'.__NAMESPACE__.'; class DeprecatedParentClass extends \\'.__NAMESPACE__.'\Fixtures\DeprecatedClass {}');
  341. } elseif ('Test\\'.__NAMESPACE__.'\DeprecatedInterfaceClass' === $class) {
  342. eval('namespace Test\\'.__NAMESPACE__.'; class DeprecatedInterfaceClass implements \\'.__NAMESPACE__.'\Fixtures\DeprecatedInterface {}');
  343. } elseif ('Test\\'.__NAMESPACE__.'\NonDeprecatedInterfaceClass' === $class) {
  344. eval('namespace Test\\'.__NAMESPACE__.'; class NonDeprecatedInterfaceClass implements \\'.__NAMESPACE__.'\Fixtures\NonDeprecatedInterface {}');
  345. } elseif ('Test\\'.__NAMESPACE__.'\Float' === $class) {
  346. eval('namespace Test\\'.__NAMESPACE__.'; class Float {}');
  347. } elseif (0 === strpos($class, 'Test\\'.__NAMESPACE__.'\ExtendsFinalClass')) {
  348. $classShortName = substr($class, strrpos($class, '\\') + 1);
  349. eval('namespace Test\\'.__NAMESPACE__.'; class '.$classShortName.' extends \\'.__NAMESPACE__.'\Fixtures\\'.substr($classShortName, 7).' {}');
  350. } elseif ('Test\\'.__NAMESPACE__.'\ExtendsAnnotatedClass' === $class) {
  351. eval('namespace Test\\'.__NAMESPACE__.'; class ExtendsAnnotatedClass extends \\'.__NAMESPACE__.'\Fixtures\AnnotatedClass {
  352. public function deprecatedMethod() { }
  353. }');
  354. } elseif ('Test\\'.__NAMESPACE__.'\ExtendsInternals' === $class) {
  355. eval('namespace Test\\'.__NAMESPACE__.'; class ExtendsInternals extends ExtendsInternalsParent {
  356. use \\'.__NAMESPACE__.'\Fixtures\InternalTrait;
  357. public function internalMethod() { }
  358. }');
  359. } elseif ('Test\\'.__NAMESPACE__.'\ExtendsInternalsParent' === $class) {
  360. eval('namespace Test\\'.__NAMESPACE__.'; class ExtendsInternalsParent extends \\'.__NAMESPACE__.'\Fixtures\InternalClass implements \\'.__NAMESPACE__.'\Fixtures\InternalInterface { }');
  361. } elseif ('Test\\'.__NAMESPACE__.'\UseTraitWithInternalMethod' === $class) {
  362. eval('namespace Test\\'.__NAMESPACE__.'; class UseTraitWithInternalMethod { use \\'.__NAMESPACE__.'\Fixtures\TraitWithInternalMethod; }');
  363. }
  364. }
  365. }