/** * @param Reservation $reservation * @param User $user * @param array $inputs * @return Reservation * @throws PreconditionException */ protected function store(Reservation $reservation, User $user, array $inputs) { /** @var Book $book */ $book = Book::where('asin', $inputs['asin'])->first(); if (empty($book)) { throw new PreconditionException('book_not_found'); } if ($book->inventory < $inputs['quantity']) { throw new PreconditionException('not_enough_book_inventory'); } DB::transaction(function () use($user, $book, &$reservation, $inputs) { $affectedRows = $book->decrementInventory($inputs['quantity']); if ($affectedRows !== 1) { throw new PreconditionException('not_enough_book_inventory'); } $reservation->user_id = $user->id; $reservation->book_id = $book->id; $reservation->quantity = $inputs['quantity']; if (empty($reservation->reservation_code)) { $reservation->reservation_code = $reservation->generateReservationCode(); } $reservation->save(); }); return $reservation; }
/** * @test */ public function delete() { $headers = ['HTTP_' . ApiAuthFilter::APPLICATION_TOKEN => 'token1']; $this->client->request('DELETE', '/api/reservation/code1', [], [], $headers); $this->assertResponseOk(); $book = Book::where('asin', 'asin1')->first(); $this->assertSame(11, $book->inventory); $this->assertSame(2, Reservation::count()); $this->assertFalse(Reservation::where('reservation_code', 'code1')->exists()); }