protected function barcodesAdd($barcodeStrings) { foreach ($barcodeStrings as $barcodeStr) { $barcode = new \Babesk\Schbas\Barcode(); if (!$barcode->initByBarcodeString($barcodeStr)) { dieHttp("Der Barcode '{$barcodeStr}' ist nicht korrekt", 400); } $books = $barcode->getMatchingBooks(); if (count($books) > 1) { dieHttp("Der Barcode '{$barcodeStr}' passt zu mehr als 1 Buch", 400); } else { if (count($books) == 0) { dieHttp("Zum Barcode '{$barcodeStr}' konnte kein passendes " . "Buch gefunden werden", 400); } else { $book = $books->first(); $inventory = new \Babesk\ORM\SchbasInventory(); $inventory->setBook($book); $inventory->setYearOfPurchase($barcode->getPurchaseYear()); $inventory->setExemplar($barcode->getExemplar()); $this->_em->persist($inventory); } } } try { $this->_em->flush(); } catch (\Doctrine\DBAL\DBALException $e) { if ($e->getPrevious()->getCode() === '23000') { dieHttp('Ein oder mehrere angegebene Barcodes gibt es schon!', 400); } else { throw $e; } } die('Die Buch-Exemplare wurden erfolgreich hinzugefügt.'); }
/** * Returns the barcodes and, if it fits to more than one book, the books * Dies with the following structure: { * unique: [ {barcode: <barcodeString>, bookId: <bookId> } ], * duplicated: [ * { * books: [ * {id: <bookId>, title: <bookTitle> } * ], * barcodes: [ <barcodeString> ] * } * ] * * } * * @param array $barcodes An array of strings representing barcodes */ protected function booksForBarcodesSend($barcodeStrings) { $extractIdsFromBooks = function ($book) { return $book->getId(); }; $uniqueBarcodes = []; $duplicatedBarcodes = []; foreach ($barcodeStrings as $barcodeStr) { $barcode = new \Babesk\Schbas\Barcode(); if ($barcode->initByBarcodeString($barcodeStr)) { // SQL-Request for every barcode, dont request too many :P $books = $barcode->getMatchingBooks($this->_em); if (count($books) == 1) { $uniqueBarcodes[] = ['barcode' => $barcodeStr, 'bookId' => $books[0]->getId()]; } else { // Make the combined book-ids the key of the array to group // the duplicated barcodes $bookIds = array_map($extractIdsFromBooks, $books); asort($bookIds); $key = implode('_', $bookIds); if (!isset($duplicatedBarcodes[$key])) { $duplicatedBarcodes[$key] = ['books' => [], 'barcodes' => []]; foreach ($books as $book) { $duplicatedBarcodes[$key]['books'][] = ['id' => $book->getId(), 'title' => $book->getTitle()]; } } $duplicatedBarcodes[$key]['barcodes'][] = $barcodeStr; } } else { dieHttp("Barcode '{$barcodeStr}' inkorrekt", 400); } } // Remove the keys so that it is a json-array $duplicatedBarcodes = array_values($duplicatedBarcodes); dieJson(['unique' => $uniqueBarcodes, 'duplicated' => $duplicatedBarcodes]); }