/** * Imports units. * * @return array An array with the keys "skipped" and "imported" which contain the number of units skipped and imported * @throws \Exception If an error occured */ public function importUnits() { $path = $this->kernel->locateResource(self::UNIT_PATH . self::UNIT_DATA); $yaml = new Parser(); $data = $yaml->parse(file_get_contents($path)); $count = 0; $skipped = 0; foreach ($data as $unitName => $unitData) { $unit = $this->getUnit($unitName); if ($unit === null) { $unit = new Unit(); $unit->setName($unitName); $unit->setSymbol($unitData["symbol"]); if (array_key_exists("prefixes", $unitData)) { if (!is_array($unitData["prefixes"])) { throw new \Exception($unitName . " doesn't contain a prefix list, or the prefix list is not an array."); } foreach ($unitData["prefixes"] as $name) { $prefix = $this->getSiPrefix($name); if ($prefix === null) { throw new \Exception("Unable to find SI Prefix " . $name); } $unit->getPrefixes()->add($prefix); } } $this->entityManager->persist($unit); $this->entityManager->flush(); $count++; } else { $skipped++; } } return array("imported" => $count, "skipped" => $skipped); }
/** * @Route("/setup/_int_create_units") */ public function intCreateUnitsAction() { $response = array("success" => true, "errors" => [], "message" => "Default units successfully created/updated"); $path = $this->get("kernel")->locateResource(self::UNIT_PATH . self::UNIT_DATA); try { $yaml = new Parser(); $data = $yaml->parse(file_get_contents($path)); $entityManager = $this->get("doctrine.orm.default_entity_manager"); foreach ($data as $unitName => $unitData) { $unit = $this->getUnit($unitName); if ($unit === null) { $unit = new Unit(); $unit->setName($unitName); $unit->setSymbol($unitData["symbol"]); if (array_key_exists("prefixes", $unitData)) { if (!is_array($unitData["prefixes"])) { throw new \Exception($unitName . " doesn't contain a prefix list, or the prefix list is not an array."); } foreach ($unitData["prefixes"] as $name) { $prefix = $this->getSiPrefix($name); if ($prefix === null) { throw new \Exception("Unable to find SI Prefix " . $name); } $unit->getPrefixes()->add($prefix); } } $entityManager->persist($unit); $entityManager->flush(); } } } catch (\Exception $e) { $response["success"] = false; $response["message"] = "Unit creation error"; $response["errors"] = [$e->getMessage()]; } return new JsonResponse($response); }