Last active
April 29, 2017 10:34
-
-
Save elmarputz/c0a6ba07b6a319eaca279f328e50df00 to your computer and use it in GitHub Desktop.
Controller.php
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
/** | |
* | |
* @param string $nameOnCard | |
* @param integer $cardNumber | |
* @return bool | |
*/ | |
protected function processCheckout(string $nameOnCard = null, string $cardNumber = null) : bool { | |
$errors = array(); | |
$nameOnCard = trim($nameOnCard); | |
if ($nameOnCard == null || strlen($nameOnCard) == 0) { | |
$errors[] = 'Invalid name on card.'; | |
} | |
if ($cardNumber == null || strlen($cardNumber) != 16 || !ctype_digit($cardNumber)) { | |
$errors[] = 'Invalid card number. Card number must be sixteen digits.'; | |
} | |
if (count($errors) > 0) { | |
$this->forwardRequest($errors); | |
return false; | |
} | |
//check cart | |
if (ShoppingCart::size() == 0) { | |
$this->forwardRequest(array('No items in cart.')); | |
return false; | |
} | |
//try to place a new order | |
$user = AuthenticationManager::getAuthenticatedUser(); | |
$orderId = \Data\DataManager::createOrder($user->getId(), ShoppingCart::getAll(), $nameOnCard, $cardNumber); | |
if (!$orderId) { | |
$this->forwardRequest(array('Could not create order.')); | |
return false; | |
} | |
//clear shopping card and redirect to success page | |
ShoppingCart::clear(); | |
Util::redirect('index.php?view=success&orderId=' . rawurlencode($orderId)); | |
return true; | |
} | |
/** | |
* | |
* @param array $errors : optional assign it to | |
* @param string $target : url for redirect of the request | |
*/ | |
protected function forwardRequest(array $errors = null, $target = null) { | |
//check for given target and try to fall back to previous page if needed | |
if ($target == null) { | |
if (!isset($_REQUEST[self::PAGE])) { | |
throw new Exception('Missing target for forward.'); | |
} | |
$target = $_REQUEST[self::PAGE]; | |
} | |
//forward request to target | |
// optional - add errors to redirect and process them in view | |
if (count($errors) > 0) | |
$target .= '&errors=' . urlencode(serialize($errors)); | |
header('location: ' . $target); | |
exit(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment