Code Coverage |
||||||||||
Classes and Traits |
Functions and Methods |
Lines |
||||||||
| Total | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
CRAP | |
100.00% |
13 / 13 |
| OptinController | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
4 | |
100.00% |
13 / 13 |
| optin | |
100.00% |
1 / 1 |
4 | |
100.00% |
13 / 13 |
|||
| 1 | <?php |
| 2 | |
| 3 | namespace App\Http\Controllers\Api\V2; |
| 4 | |
| 5 | use App\Enums\ApiError; |
| 6 | use App\Exceptions\Api\V2\ApiErrorException; |
| 7 | use App\Exceptions\Api\V2\CrmException; |
| 8 | use App\Http\Controllers\Controller; |
| 9 | use App\Http\Requests\Api\V2\SingleOptinRequest; |
| 10 | use App\Models\CustomerInfo; |
| 11 | use App\Models\Service; |
| 12 | use App\Models\SingleOptin; |
| 13 | |
| 14 | class OptinController extends Controller |
| 15 | { |
| 16 | /** |
| 17 | * Creates a new Single optin or destroys it if exists |
| 18 | * |
| 19 | * @param SingleOptinRequest $request |
| 20 | * @param Service $service |
| 21 | * @return JsonResponse |
| 22 | * @throws ApiErrorException With ApiError::singleOptinCustomerExists if this email already has a full account. |
| 23 | * @throws CrmException If the single optin could not be added or removed. |
| 24 | */ |
| 25 | public function optin(SingleOptinRequest $request, Service $service) |
| 26 | { |
| 27 | if (CustomerInfo::getFromEmail($service->brand, $request->email)->exists()) { |
| 28 | throw new ApiErrorException(ApiError::singleOptinCustomerExists()); |
| 29 | } |
| 30 | |
| 31 | /** @var \App\Models\SingleOptin */ |
| 32 | $singleOptin = SingleOptin::where('email', $request->email) |
| 33 | ->whereHas('brand', function ($q) use ($service) { |
| 34 | $q->whereId($service->brand->id); |
| 35 | })->firstOrNew(); |
| 36 | |
| 37 | if ($request->opt_in) { |
| 38 | $singleOptin->fill($request->validated()); |
| 39 | $singleOptin->brand()->associate($service->brand); |
| 40 | $success = $singleOptin->save(); |
| 41 | } else { |
| 42 | $success = $singleOptin->delete() !== false; |
| 43 | } |
| 44 | |
| 45 | if (!$success) { |
| 46 | // @codeCoverageIgnoreStart |
| 47 | throw new CrmException('Api failed to update single optin.'); |
| 48 | // @codeCoverageIgnoreEnd |
| 49 | } |
| 50 | |
| 51 | return response()->json(); |
| 52 | } |
| 53 | } |