|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace App\Domains\Subscriptions\Services; |
| 4 | + |
| 5 | +use App\Domains\Subscriptions\Validations\Customer\CreateNewCustomerValidation; |
| 6 | +use App\Domains\Subscriptions\Entities\Customer; |
| 7 | +use App\Support\Services\ServiceInterface; |
| 8 | +use App\Support\Validation\ValidationException; |
| 9 | + |
| 10 | +class CreateNewCustomer implements ServiceInterface |
| 11 | +{ |
| 12 | + private ?string $name; |
| 13 | + private ?string $lastname; |
| 14 | + private ?string $email; |
| 15 | + private ?string $status; |
| 16 | + |
| 17 | + /** |
| 18 | + * CreateNewCustomer constructor. |
| 19 | + * |
| 20 | + * TIP: |
| 21 | + * Setting up all variable as null allow you to treat it in Validation layer. |
| 22 | + * on this way, you doesn't have anyone problem with data origin passed to the args. |
| 23 | + * |
| 24 | + * That means that, you can pass value from a array (with non existing key, by example) or |
| 25 | + * from a magic property from a request, etc. |
| 26 | + * |
| 27 | + * @param string|null $name |
| 28 | + * @param string|null $lastname |
| 29 | + * @param string|null $email |
| 30 | + * @param string|null $status |
| 31 | + */ |
| 32 | + public function __construct( |
| 33 | + string $name = null, |
| 34 | + string $lastname = null, |
| 35 | + string $email = null, |
| 36 | + string $status = null |
| 37 | + ) { |
| 38 | + $this->name = $name; |
| 39 | + $this->lastname = $lastname; |
| 40 | + $this->email = $email; |
| 41 | + $this->status = $status; |
| 42 | + } |
| 43 | + |
| 44 | + /** |
| 45 | + * @return array |
| 46 | + * |
| 47 | + * @throws ValidationException |
| 48 | + */ |
| 49 | + public function handle(): array |
| 50 | + { |
| 51 | + $data = [ |
| 52 | + 'name' => $this->name, |
| 53 | + 'lastname' => $this->lastname, |
| 54 | + 'email' => $this->email, |
| 55 | + 'status' => $this->status |
| 56 | + ]; |
| 57 | + |
| 58 | + // Validate... |
| 59 | + (new CreateNewCustomerValidation($data))->validate(); |
| 60 | + |
| 61 | + // store... |
| 62 | + $customer = new Customer(); |
| 63 | + $customer->name = $this->name; |
| 64 | + $customer->lastname = $this->lastname; |
| 65 | + $customer->email = $this->email; |
| 66 | + // we can create a ValueObject to work with the customer status. |
| 67 | + $customer->status = Customer::$status[$this->status]; |
| 68 | + $customer->save(); |
| 69 | + |
| 70 | + // trigger a event when a new customer was created... |
| 71 | + // event(new NewCustomerCreated($customer)); |
| 72 | + |
| 73 | + // grants that a array will be returned instead of a Model instance. |
| 74 | + // After creation of the new customer, what you need, a Model instance or the model data? |
| 75 | + // Probably you will need the data. |
| 76 | + return $customer->toArray(); |
| 77 | + } |
| 78 | +} |
0 commit comments