ControllerCreator.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128
  1. <?php
  2. namespace Encore\Admin\Helpers\Scaffold;
  3. class ControllerCreator
  4. {
  5. /**
  6. * Controller full name.
  7. *
  8. * @var string
  9. */
  10. protected $name;
  11. /**
  12. * The filesystem instance.
  13. *
  14. * @var \Illuminate\Filesystem\Filesystem
  15. */
  16. protected $files;
  17. /**
  18. * ControllerCreator constructor.
  19. *
  20. * @param string $name
  21. * @param null $files
  22. */
  23. public function __construct($name, $files = null)
  24. {
  25. $this->name = $name;
  26. $this->files = $files ?: app('files');
  27. }
  28. /**
  29. * Create a controller.
  30. *
  31. * @param string $model
  32. *
  33. * @throws \Exception
  34. *
  35. * @return string
  36. */
  37. public function create($model)
  38. {
  39. $path = $this->getpath($this->name);
  40. if ($this->files->exists($path)) {
  41. throw new \Exception("Controller [$this->name] already exists!");
  42. }
  43. $stub = $this->files->get($this->getStub());
  44. $this->files->put($path, $this->replace($stub, $this->name, $model));
  45. return $path;
  46. }
  47. /**
  48. * @param string $stub
  49. * @param string $name
  50. * @param string $model
  51. *
  52. * @return string
  53. */
  54. protected function replace($stub, $name, $model)
  55. {
  56. $stub = $this->replaceClass($stub, $name);
  57. return str_replace(
  58. ['DummyModelNamespace', 'DummyModel'],
  59. [$model, class_basename($model)],
  60. $stub
  61. );
  62. }
  63. /**
  64. * Get controller namespace from giving name.
  65. *
  66. * @param string $name
  67. *
  68. * @return string
  69. */
  70. protected function getNamespace($name)
  71. {
  72. return trim(implode('\\', array_slice(explode('\\', $name), 0, -1)), '\\');
  73. }
  74. /**
  75. * Replace the class name for the given stub.
  76. *
  77. * @param string $stub
  78. * @param string $name
  79. *
  80. * @return string
  81. */
  82. protected function replaceClass($stub, $name)
  83. {
  84. $class = str_replace($this->getNamespace($name).'\\', '', $name);
  85. return str_replace(['DummyClass', 'DummyNamespace'], [$class, $this->getNamespace($name)], $stub);
  86. }
  87. /**
  88. * Get file path from giving controller name.
  89. *
  90. * @param $name
  91. *
  92. * @return string
  93. */
  94. public function getPath($name)
  95. {
  96. $segments = explode('\\', $name);
  97. array_shift($segments);
  98. return app_path(implode('/', $segments)).'.php';
  99. }
  100. /**
  101. * Get stub file path.
  102. *
  103. * @return string
  104. */
  105. public function getStub()
  106. {
  107. return __DIR__.'/stubs/controller.stub';
  108. }
  109. }