/** * @param string $cbdSubject * @param MongoGraph $cbdGraph * @param Collection $collection * @param string $context * @throws \Exception */ protected function saveCBD($cbdSubject, MongoGraph $cbdGraph, Collection $collection, $context) { $cbdSubject = $this->labeller->uri_to_alias($cbdSubject); if ($cbdGraph == null || $cbdGraph->is_empty()) { throw new \Exception("graph for {$cbdSubject} was null"); } try { $collection->insertOne($cbdGraph->to_tripod_array($cbdSubject, $context), array("w" => 1)); print "."; } catch (\Exception $e) { if (preg_match('/E11000/', $e->getMessage())) { print "M"; // key already exists, merge it $criteria = array("_id" => array("r" => $cbdSubject, "c" => $context)); $existingGraph = new MongoGraph(); $existingGraph->add_tripod_array($collection->findOne($criteria)); $existingGraph->add_graph($cbdGraph); try { $collection->updateOne($criteria, ['$set' => $existingGraph->to_tripod_array($cbdSubject, $context)], array("w" => 1)); } catch (\Exception $e2) { throw new \Exception($e2->getMessage()); // todo: would be good to have typed exception } } else { // retry print "CursorException on update: " . $e->getMessage() . ", retrying\n"; try { $collection->insertOne($cbdGraph->to_tripod_array($cbdSubject, $context), array("w" => 1)); } catch (\Exception $e2) { throw new \Exception($e2->getMessage()); // todo: would be good to have typed exception } } } }