GeneratedClassesAutoloader.php 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. namespace Magento\Framework\TestFramework\Unit\Autoloader;
  7. use Magento\Framework\Code\Generator\Io;
  8. /**
  9. * Autoloader that initiates auto-generation of requested classes
  10. */
  11. class GeneratedClassesAutoloader
  12. {
  13. /**
  14. * @var Io
  15. */
  16. private $generatorIo;
  17. /**
  18. * @var GeneratorInterface[]
  19. */
  20. private $generators;
  21. /**
  22. * @param GeneratorInterface[] $generators
  23. * @param Io $generatorIo
  24. */
  25. public function __construct(array $generators, Io $generatorIo)
  26. {
  27. foreach ($generators as $generator) {
  28. if (!($generator instanceof GeneratorInterface)) {
  29. throw new \InvalidArgumentException(
  30. sprintf(
  31. "Instance of '%s' is expected, instance of '%s' is received",
  32. \Magento\Framework\TestFramework\Unit\Autoloader\GeneratorInterface::class,
  33. get_class($generator)
  34. )
  35. );
  36. }
  37. }
  38. $this->generators = $generators;
  39. $this->generatorIo = $generatorIo;
  40. }
  41. /**
  42. * Load class
  43. *
  44. * @param string $className
  45. * @return bool
  46. */
  47. public function load($className)
  48. {
  49. $classSourceFile = $this->generatorIo->generateResultFileName($className);
  50. if ($this->generatorIo->fileExists($classSourceFile)) {
  51. include $classSourceFile;
  52. return true;
  53. } else {
  54. foreach ($this->generators as $generator) {
  55. $content = $generator->generate($className);
  56. if ($content) {
  57. $this->generatorIo->makeResultFileDirectory($className);
  58. $this->generatorIo->writeResultFile($classSourceFile, $content);
  59. include $classSourceFile;
  60. return true;
  61. }
  62. }
  63. }
  64. return false;
  65. }
  66. }