Last active
September 4, 2015 07:46
-
-
Save carlcs/ef4664ceb281db7068fd to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Does a product order. | |
* | |
* @param string $name | |
* @param int $quantity | |
* @return bool | |
*/ | |
public function doProductOrder($name, $quantity) | |
{ | |
$entry = $this->_getMatchingEntryByName($name); | |
if ($entry) | |
{ | |
$oldStock = $entry->hardwareStock; | |
$newStock = $this->_reduceEntryInventory($entry, $quantity); | |
return $oldStock != $newStock; | |
} | |
Craft::log('No entry found for this product name.', LogLevel::Error); | |
return false; | |
} | |
/** | |
* Reduce the inventory value for an entry, by the supplied quantity | |
* | |
* @param EntryModel $entry a Craft entry | |
* @param int $quantity the value to subtract from the current inventory | |
* @return int the new adjusted inventory value | |
*/ | |
private function _reduceEntryInventory($entry, $quantity) | |
{ | |
$currentStock = $entry->hardwareStock; | |
if ($currentStock >= $quantity) | |
{ | |
$currentStock = $currentStock - $quantity; | |
$entry->setContentFromPost(array( | |
'fieldToChange' => $currentStock | |
)); | |
// Let's see if it saves. | |
// Field validation should happen automatically | |
if (craft()->entries->saveEntry($entry)) | |
{ | |
Craft::log('Entry updated (ID: '.$entry->id.').'); | |
} | |
else | |
{ | |
Craft::log('Could not updated the entry (ID: '.$entry->id.').', LogLevel::Error); | |
} | |
} | |
return $currentStock; | |
} | |
/** | |
* Fetches an entry model by its product name. | |
* | |
* @param string $name | |
* @return null|EntryModel | |
*/ | |
private function _getMatchingEntryByName($name) | |
{ | |
$criteria = craft()->elements->getCriteria(ElementType::Entry); | |
$criteria->productName = $name; | |
return $criteria->first(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment