public function save(PriceHistoryEntity $price)
{
if (!isset($price->platform) || !isset($price->cloudLocation)) {
throw new \InvalidArgumentException(sprintf("Both platform and cloudLocation properties must be set"));
}
if (!isset($price->applied)) {
$price->applied = new \DateTime('now', new \DateTimeZone('UTC'));
} else {
if (!$price->applied instanceof \DateTime) {
$price->applied = new \DateTime($price->applied, new \DateTimeZone('UTC'));
}
}
if (!$price->priceId) {
//Trying to find if the price already exists on this day
$found = PriceHistoryEntity::findOne([['platform' => $price->platform], ['url' => $price->url ?: ''], ['cloudLocation' => $price->cloudLocation], ['accountId' => $price->accountId ?: 0], ['applied' => $price->applied->format('Y-m-d')]]);
if ($found) {
$price->priceId = $found->priceId;
}
}
if (!$price->priceId) {
$bNew = true;
$price->priceId = \Scalr::GenerateUID();
} else {
$bNew = false;
}
$sId = "`price_id` = " . $price->qstr('priceId');
$this->cadb->BeginTrans();
try {
$this->cadb->Execute("\n " . ($bNew ? "INSERT" : "UPDATE") . " " . $price->table() . "\n SET " . ($bNew ? $sId . "," : "") . "\n platform = ?,\n url = ?,\n cloud_location = ?,\n account_id = ?,\n applied = ?,\n deny_override = ?\n " . ($bNew ? "" : "WHERE " . $sId . " LIMIT 1") . "\n ", [$price->platform, $price->url ?: '', $price->cloudLocation, $price->accountId ?: 0, $price->applied->format('Y-m-d'), $price->denyOverride ? 1 : 0]);
//Removes previous values
if (!$bNew) {
$this->cadb->Execute("DELETE FROM `prices` WHERE price_id = " . $price->qstr('priceId'));
}
$stmt = "";
foreach ($price->getDetails() as $priceEntity) {
if ($priceEntity instanceof PriceEntity) {
$stmt .= ", (" . $price->qstr('priceId') . ", " . $priceEntity->qstr('instanceType') . ", " . $priceEntity->qstr('os') . ", " . $priceEntity->qstr('name') . ", " . $priceEntity->qstr('cost') . ")";
} else {
throw new \InvalidArgumentException(sprintf("Details should contain collection of the PriceEntity objects. %s given.", gettype($priceEntity)));
}
}
if ($stmt !== '') {
$this->cadb->Execute("REPLACE `prices` (`price_id`,`instance_type`, `os`, `name`, `cost`) VALUES " . ltrim($stmt, ','));
}
$this->cadb->CommitTrans();
} catch (\Exception $e) {
$this->cadb->RollbackTrans();
throw $e;
}
}