-
Notifications
You must be signed in to change notification settings - Fork 0
/
MakeTrait.php
80 lines (64 loc) · 2.19 KB
/
MakeTrait.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
<?php
namespace Butcherman\ArtisanDevCommands\Commands;
use Illuminate\Console\Command;
class MakeTrait extends Command
{
protected $signature = 'make:trait
{name : Name of the trait to be created}';
protected $description = 'Create a new Trait Class';
protected $basePath;
// Create the new Page
public function handle()
{
$this->basePath = app_path('Traits');
// Get the name and path the Page will be placed
$nameArr = explode('/', $this->argument('name'));
$path = $this->basePath.DIRECTORY_SEPARATOR.implode(DIRECTORY_SEPARATOR, $nameArr).'.php';
$pathInfo = pathinfo($path);
$traitName = end($nameArr);
// Determine if the /app/Traits directory exists - if not, create it
if(!is_dir($this->basePath))
{
mkdir($this->basePath);
}
// If the page already exists, we will trigger an error
if(file_exists($path))
{
$this->error('This page already exists');
return 0;
}
if(!is_dir($pathInfo['dirname']))
{
mkdir($pathInfo['dirname']);
}
$this->generateStub($path, $traitName);
$this->info('New page created successfully');
return 0;
}
protected function getStubVariables($traitName)
{
return [
'TRAIT_NAME' => ucwords($traitName),
];
}
// Get the stub file for the generator.
protected function getStub()
{
if(file_exists(base_path('stubs/dev_commands/TraitStub.stub')))
{
return base_path('stubs/dev_commands/TraitStub.stub');
}
return base_path('vendor/butcherman/artisan-dev-commands/src/Stubs/TraitStub.stub');
}
// Create the stub and write it to the file system
protected function generateStub($path, $traitName)
{
$contents = file_get_contents($this->getStub());
$variables = $this->getStubVariables($traitName);
foreach($variables as $search => $replace)
{
$contents = str_replace('$'.$search, $replace, $contents);
}
file_put_contents($path, $contents);
}
}