93 lines
1.9 KiB
PHP
93 lines
1.9 KiB
PHP
<?php
|
|
|
|
namespace app\scaffold;
|
|
|
|
class ControllerCreator {
|
|
|
|
/**
|
|
* error message
|
|
*
|
|
* @var string
|
|
*/
|
|
protected $errMsg;
|
|
|
|
/**
|
|
* Class Name
|
|
*
|
|
* @var string
|
|
*/
|
|
protected $className;
|
|
|
|
/**
|
|
* class construct function
|
|
*
|
|
* @param string $table
|
|
*/
|
|
public function __construct($table)
|
|
{
|
|
$this->className = ucfirst(mb_strtolower($table)).'Controller';
|
|
|
|
$this->errMsg = $table;
|
|
}
|
|
|
|
public function create()
|
|
{
|
|
$path = $this->getPath($this->className,'controller');
|
|
$dir = dirname($path);
|
|
if (! is_dir($dir)) {
|
|
mkdir($dir, 0755, true);
|
|
}
|
|
if (file_exists($path)) {
|
|
throw new \Exception("Controller [$this->errMsg] already exists!");
|
|
}
|
|
$stub = file_get_contents($this->getStub());
|
|
$stub = $this->replaceClass($stub,$dir);
|
|
file_put_contents($path,$stub);
|
|
chmod($path,0777);
|
|
return $path;
|
|
}
|
|
|
|
/**
|
|
* Get controller namespace
|
|
*
|
|
* @param string $name
|
|
* @return string
|
|
*/
|
|
public function getNamespace($name)
|
|
{
|
|
return trim(implode('\\',array_slice(explode(DIRECTORY_SEPARATOR,$name),4)),'\\');
|
|
}
|
|
|
|
/**
|
|
* replace
|
|
*
|
|
* @param string $stub
|
|
* @param string $name
|
|
* @return string
|
|
*/
|
|
public function replaceClass($stub,$name)
|
|
{
|
|
return str_replace(['DummyClass', 'DummyNamespace'], [$this->className, $this->getNamespace($name)], $stub);
|
|
}
|
|
|
|
/**
|
|
* Get controller file path
|
|
*
|
|
* @param string $name
|
|
* @return string
|
|
*/
|
|
public function getPath($name,$type)
|
|
{
|
|
return (new Helper())->getPath($name,$type);
|
|
}
|
|
|
|
/**
|
|
* Get stub file path
|
|
*
|
|
* @return string
|
|
*/
|
|
public function getStub()
|
|
{
|
|
return __DIR__ .'/stubs/controller.stub';
|
|
}
|
|
} |