Guest User

Untitled

a guest
Dec 12th, 2017
463
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.46 KB | None | 0 0
  1. <?php
  2.  
  3. namespace App\Console\Commands;
  4.  
  5. use App\User;
  6. use Hyn\Tenancy\Contracts\Repositories\CustomerRepository;
  7. use Hyn\Tenancy\Contracts\Repositories\HostnameRepository;
  8. use Hyn\Tenancy\Contracts\Repositories\WebsiteRepository;
  9. use Hyn\Tenancy\Environment;
  10. use Hyn\Tenancy\Models\Customer;
  11. use Hyn\Tenancy\Models\Hostname;
  12. use Hyn\Tenancy\Models\Website;
  13. use Illuminate\Console\Command;
  14. use Illuminate\Support\Facades\Hash;
  15.  
  16. class CreateTenant extends Command
  17. {
  18. protected $signature = 'tenant:create {name} {email}';
  19.  
  20. protected $description = 'Creates a tenant with the provided name and email address e.g. php artisan tenant:create boise boise@example.com';
  21.  
  22. public function handle()
  23. {
  24. $name = $this->argument('name');
  25. $email = $this->argument('email');
  26.  
  27. if ($this->tenantExists($name, $email)) {
  28. $this->error("A tenant with name '{$name}' and/or '{$email}' already exists.");
  29.  
  30. return;
  31. }
  32.  
  33. $hostname = $this->registerTenant($name, $email);
  34. app(Environment::class)->hostname($hostname);
  35.  
  36. // we'll create a random secure password for our to-be admin
  37. $password = str_random();
  38. $this->addAdmin($name, $email, $password);
  39.  
  40. $this->info("Tenant '{$name}' is created and is now accessible at {$hostname->fqdn}");
  41. $this->info("Admin {$email} can log in using password {$password}");
  42. }
  43.  
  44. private function tenantExists($name, $email)
  45. {
  46. return Customer::where('name', $name)->orWhere('email', $email)->exists();
  47. }
  48.  
  49. private function registerTenant($name, $email)
  50. {
  51. // create a customer
  52. $customer = new Customer;
  53. $customer->name = $name;
  54. $customer->email = $email;
  55. app(CustomerRepository::class)->create($customer);
  56.  
  57. // associate the customer with a website
  58. $website = new Website;
  59. $website->customer()->associate($customer);
  60. app(WebsiteRepository::class)->create($website);
  61.  
  62. // associate the website with a hostname
  63. $hostname = new Hostname;
  64. $baseUrl = config('app.url_base');
  65. $hostname->fqdn = "{$name}.{$baseUrl}";
  66. $hostname->customer()->associate($customer);
  67. app(HostnameRepository::class)->attach($hostname, $website);
  68.  
  69. return $hostname;
  70. }
  71.  
  72. private function addAdmin($name, $email, $password)
  73. {
  74. $admin = User::create(['name' => $name, 'email' => $email, 'password' => Hash::make($password)]);
  75.  
  76. return $admin;
  77. }
  78. }
Add Comment
Please, Sign In to add comment