/** * Returns the requested elements as JSON * * @param callable|null $configFactory A function for generating the config * @param array|null $config The API endpoint configuration * * @throws Exception * @throws HttpException */ public function actionGetElements($configFactory = null, array $config = null) { if ($configFactory !== null) { $params = craft()->urlManager->getRouteParams(); $variables = isset($params['variables']) ? $params['variables'] : null; $config = $this->_callWithParams($configFactory, $variables); } // Merge in default config options $config = array_merge(['paginate' => true, 'pageParam' => 'page', 'elementsPerPage' => 100, 'first' => false, 'transformer' => 'Craft\\ElementApi_ElementTransformer'], craft()->config->get('defaults', 'elementapi'), $config); if ($config['pageParam'] == 'p') { throw new Exception('The pageParam setting cannot be set to "p" because that’s the parameter Craft uses to check the requested path.'); } if (!isset($config['elementType'])) { throw new Exception('Element API configs must specify the elementType.'); } /** @var ElementCriteriaModel $criteria */ $criteria = craft()->elements->getCriteria($config['elementType'], ['limit' => null]); if (!empty($config['criteria'])) { $criteria->setAttributes($config['criteria']); } // Load Fractal $pluginPath = craft()->path->getPluginsPath() . 'elementapi/'; require $pluginPath . 'vendor/autoload.php'; $fractal = new Manager(); $fractal->setSerializer(new ArraySerializer()); // Define the transformer if (is_callable($config['transformer']) || $config['transformer'] instanceof TransformerAbstract) { $transformer = $config['transformer']; } else { Craft::import('plugins.elementapi.ElementApi_ElementTransformer'); $transformer = Craft::createComponent($config['transformer']); } if ($config['first']) { $element = $criteria->first(); if (!$element) { throw new HttpException(404); } $resource = new Item($element, $transformer); } else { if ($config['paginate']) { // Create the paginator require $pluginPath . 'ElementApi_PaginatorAdapter.php'; $paginator = new ElementApi_PaginatorAdapter($config['elementsPerPage'], $criteria->total(), $config['pageParam']); // Fetch this page's elements $criteria->offset = $config['elementsPerPage'] * ($paginator->getCurrentPage() - 1); $criteria->limit = $config['elementsPerPage']; $elements = $criteria->find(); $paginator->setCount(count($elements)); $resource = new Collection($elements, $transformer); $resource->setPaginator($paginator); } else { $resource = new Collection($criteria, $transformer); } } JsonHelper::sendJsonHeaders(); echo $fractal->createData($resource)->toJson(); // End the request craft()->end(); }
/** * Return JSON * * @param array $var */ private function returnJson($var = array()) { JsonHelper::sendJsonHeaders(); // Output it into a buffer, in case TasksService wants to close the connection prematurely ob_start(); echo JsonHelper::encode($var); craft()->end(); }
/** * Temporary nav until 2.5 is released. */ private function initMarketNav() { if (craft()->request->isCpRequest()) { craft()->templates->includeCssResource('market/market-nav.css'); craft()->templates->includeJsResource('market/market-nav.js'); $nav = [['url' => 'market/orders', 'title' => Craft::t("Orders"), 'selected' => craft()->request->getSegment(2) == 'orders' ? true : false], ['url' => 'market/products', 'title' => Craft::t("Products"), 'selected' => craft()->request->getSegment(2) == 'products' ? true : false], ['url' => 'market/promotions', 'title' => Craft::t("Promotions"), 'selected' => craft()->request->getSegment(2) == 'promotions' ? true : false], ['url' => 'market/customers', 'title' => Craft::t("Customers"), 'selected' => craft()->request->getSegment(2) == 'customers' ? true : false], ['url' => 'market/settings', 'title' => Craft::t("Settings"), 'selected' => craft()->request->getSegment(2) == 'settings' ? true : false]]; $navJson = JsonHelper::encode($nav); craft()->templates->includeJs('new Craft.MarketNav(' . $navJson . ');'); } }
/** * * @param Market_AddressModel $address */ public function setBillingAddress(Market_AddressModel $address) { $this->billingAddressData = JsonHelper::encode($address->attributes); $this->_billingAddress = $address; }
/** * @param Market_OrderModel $order * * @return bool * @throws \Exception */ public function save($order) { if (!$order->dateOrdered) { //raising event $event = new Event($this, ['order' => $order]); $this->onBeforeSaveOrder($event); } if (!$order->id) { $orderRecord = new Market_OrderRecord(); } else { $orderRecord = Market_OrderRecord::model()->findById($order->id); if (!$orderRecord) { throw new Exception(Craft::t('No order exists with the ID “{id}”', ['id' => $order->id])); } } // Set default shipping method if (!$order->shippingMethodId) { $method = craft()->market_shippingMethod->getDefault(); if ($method) { $order->shippingMethodId = $method->id; } } // Set default payment method if (!$order->paymentMethodId) { $methods = craft()->market_paymentMethod->getAllForFrontend(); if ($methods) { $order->paymentMethodId = $methods[0]->id; } } //Only set default addresses on carts if (!$order->dateOrdered) { // Set default shipping address if last used is available $lastShippingAddressId = craft()->market_customer->getCustomer()->lastUsedShippingAddressId; if (!$order->shippingAddressId && $lastShippingAddressId) { if ($address = craft()->market_address->getAddressById($lastShippingAddressId)) { $order->shippingAddressId = $address->id; $order->shippingAddressData = JsonHelper::encode($address->attributes); } } // Set default billing address if last used is available $lastBillingAddressId = craft()->market_customer->getCustomer()->lastUsedBillingAddressId; if (!$order->billingAddressId && $lastBillingAddressId) { if ($address = craft()->market_address->getAddressById($lastBillingAddressId)) { $order->billingAddressId = $address->id; $order->billingAddressData = JsonHelper::encode($address->attributes); } } } if (!$order->customerId) { $order->customerId = craft()->market_customer->getCustomerId(); } else { // if there is no email set and we have a customer, get their email. if (!$order->email) { $order->email = craft()->market_customer->getById($order->customerId)->email; } } // Will not adjust a completed order, we don't want totals to change. $this->calculateAdjustments($order); $oldStatusId = $orderRecord->orderStatusId; $orderRecord->number = $order->number; $orderRecord->itemTotal = $order->itemTotal; $orderRecord->email = $order->email; $orderRecord->dateOrdered = $order->dateOrdered; $orderRecord->datePaid = $order->datePaid; $orderRecord->billingAddressId = $order->billingAddressId; $orderRecord->shippingAddressId = $order->shippingAddressId; $orderRecord->shippingMethodId = $order->shippingMethodId; $orderRecord->paymentMethodId = $order->paymentMethodId; $orderRecord->orderStatusId = $order->orderStatusId; $orderRecord->couponCode = $order->couponCode; $orderRecord->baseDiscount = $order->baseDiscount; $orderRecord->baseShippingCost = $order->baseShippingCost; $orderRecord->totalPrice = $order->totalPrice; $orderRecord->totalPaid = $order->totalPaid; $orderRecord->customerId = $order->customerId; $orderRecord->returnUrl = $order->returnUrl; $orderRecord->cancelUrl = $order->cancelUrl; $orderRecord->message = $order->message; $orderRecord->shippingAddressData = $order->shippingAddressData; $orderRecord->billingAddressData = $order->billingAddressData; $orderRecord->validate(); $order->addErrors($orderRecord->getErrors()); MarketDbHelper::beginStackedTransaction(); try { if (!$order->hasErrors()) { if (craft()->elements->saveElement($order)) { //creating order history record if ($orderRecord->id && $oldStatusId != $orderRecord->orderStatusId) { if (!craft()->market_orderHistory->createFromOrder($order, $oldStatusId)) { throw new Exception('Error saving order history'); } } //saving order record $orderRecord->id = $order->id; $orderRecord->save(false); MarketDbHelper::commitStackedTransaction(); //raising event if (!$order->dateOrdered) { $event = new Event($this, ['order' => $order]); $this->onSaveOrder($event); } return true; } } } catch (\Exception $e) { MarketDbHelper::rollbackStackedTransaction(); throw $e; } MarketDbHelper::rollbackStackedTransaction(); return false; }
/** * Apply Body * * @return void */ private function applyBody() { if ($this->temp) { $body = \Craft\JsonHelper::encode($this->temp); $this->body->write($body); $this->body->rewind(); } }
/** * Apply Fractal * * @param Request $request Request * @param Response $response Response * * @return Response Response */ private function applyFractal(Request $request, Response $response) { $fractal = new Manager(); $transformer = $this->getTransformer($request); // if (isset($this->includes)) { // $this->manager->parseIncludes($this->includes); // } if ($response->getItem()) { if ($transformer) { $resource = new Item($response->getItem(), $transformer); } else { $resource = new Item($response->getItem()); } } if (is_array($response->getCollection())) { if ($transformer) { $resource = new Collection($response->getCollection(), $transformer); } else { $resource = new Collection($response->getCollection()); } if ($paginator = $this->getPaginator($response)) { $resource->setPaginator($paginator); } } if (isset($resource)) { $serializer = $this->getSerializer($request); $fractal->setSerializer($serializer); $resource = $fractal->createData($resource)->toArray(); $json = \Craft\JsonHelper::encode($resource); $response = $response->withJson($json); } return $response; }