Lower-level API to support arbitary products

@param $sku
@param int $qty
@param $request
@return CartBuilder
323928
public function withProductRequest($sku, $qty = 1, $request = []) : CartBuilder
    {
        $result = clone $this;
        $requestInfo = array_merge(['qty'=> $qty], $request);
        $result->addToCartRequests[$sku][] = new DataObject($requestInfo);
        return $result;
    }
600721
private function _checkQty(&$qty)
    {
        if (!isset($qty)) {
            throw new Klarna_ArgumentNotSetException("Quantity");
        }
        if (is_numeric($qty) && !is_int($qty)) {
            $qty = intval($qty);
        }
        if (!is_int($qty)) {
            throw new Klarna_InvalidTypeException("Quantity", "integer");
        }
    }
435241
public function createAction(Request $request)
    {
        $warehouse = new Warehouse();
        $form = $this->createForm(WarehouseType::class, $warehouse);
        if ($form->handleRequest($request)->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->persist($warehouse);
            $em->flush();

            return $this->redirect($this->generateUrl('admin_warehouse_show', array('id' => $warehouse->getId())));
        }

        return array(
            'warehouse' => $warehouse,
            'form' => $form->createView(),
        );
    }
817245
public function mapSkuToEntityId($sku)
    {

        // query weather or not the SKU has been mapped
        if (isset($this->skuEntityIdMapping[$sku])) {
            return $this->skuEntityIdMapping[$sku];
        }

        // throw an exception if the SKU has not been mapped yet
        throw new \Exception(
            $this->appendExceptionSuffix(
                sprintf('Found not mapped entity ID mapping for SKU %s', $sku)
            )
        );
    }
1092539
public function selectPaymentAction(Request $request)
    {
        $form = $this->createChoosePaymentForm();
        $form->handleRequest($request);
        if ($form->isValid()) {
            $data = $form->getData();
            $paymentName = $data['payment_name'];

            $cartStorage = $this->getPayum()->getStorage('Acme\OtherExamplesBundle\Model\Cart');

            /** @var $cart Cart */
            $cart = $cartStorage->createModel();
            $cart->setPrice(1.23);
            $cart->setCurrency('USD');
            $cartStorage->updateModel($cart);

            $captureToken = $this->getTokenFactory()->createCaptureToken(
                $paymentName,
                $cart,
                'acme_payment_details_view' // TODO
            );

            return $this->redirect($captureToken->getTargetUrl());
        }
        
        return array(
            'form' => $form->createView()
        );
    }
998259
public function newAction(Request $request)
    {
        $product = new Product();
        $product->setSeller($this->getCurrentProfile());
        $form = $this->createForm(new ProductType($this->getCurrentProfile()), $product);

        // During the Eggbox stage, we'll hard code the Category
        $product->setCategory($this->getDoctrine()
            ->getRepository('HarvestCloudCoreBundle:Category')
            ->find(10));

        if ($request->getMethod() == 'POST')
        {
            $form->bindRequest($request);

            if ($form->isValid())
            {
                // If we don't have a Location yet, use the Seller's default
                if (!$product->getLocation())
                {
                  $product->setLocation($this->getCurrentProfile()->getDefaultLocation());
                }

                $em = $this->getDoctrine()->getEntityManager();
                $em->persist($product);
                $em->flush();

                return $this->redirect($this->generateUrl('Seller_product_show', array(
                    'id' => $product->getId(),
                )));
            }
        }

        return $this->render('HarvestCloudCoreBundle:Seller/Product:new.html.twig', array(
          'form' => $form->createView(),
        ));
    }
1015983
public function index($product_sku)
    {
        $product = Subbly::api('subbly.product')->find($product_sku);

        $options = $this->getParams('offset', 'limit', 'includes', 'order_by');

        $productImages = Subbly::api('subbly.product_image')->findByProduct($product, $options);

        return $this->jsonCollectionResponse('product_images', $productImages);
    }
524989
private function createCartItem($id, $name, $qty, $price, array $options)
    {
        if ($id instanceof Buyable) {
            $cartItem = CartItem::fromBuyable($id, $qty ?: []);
            $cartItem->setQuantity($name ?: 1);
            $cartItem->associate($id);
        } elseif (is_array($id)) {
            $cartItem = CartItem::fromArray($id);
            $cartItem->setQuantity($id['qty']);
        } else {
            $cartItem = CartItem::fromAttributes($id, $name, $price, $options);
            $cartItem->setQuantity($qty);
        }

        $cartItem->setTaxRate(config('cart.tax'));

        return $cartItem;
    }
110061
public function add(SKUTypeInterface $acm_sku_type) {
    $sku = $this->entityManager()
      ->getStorage('acm_sku')
      ->create(['type' => $acm_sku_type->id()]);

    $form = $this->entityFormBuilder()->getForm($sku);

    return $form;
  }
898369
def sku_update(self, product_id, properties, session, **kwargs):
        ''''''
        request = TOPRequest('taobao.fenxiao.product.sku.update')
        request['product_id'] = product_id
        request['properties'] = properties
        for k, v in kwargs.iteritems():
            if k not in ('quantity', 'standard_price', 'agent_cost_price', 'sku_number', 'dealer_cost_price') and v==None: continue
            request[k] = v
        self.create(self.execute(request, session), fields=['result','created'], models={'created':TOPDate})
        return self
247446
public function update(
        $sku,
        $variationSku,
        $variationQty = null,
        $variationEan = null,
        array $variationImages = [],
        array $variationSpecifications = []
    ) {
        $transformer = new Update(
            $variationSku,
            $variationQty,
            $variationEan,
            $variationImages,
            $variationSpecifications
        );

        $body = $transformer->output();

        /** @var \SkyHub\Api\Handler\Response\HandlerInterface $responseHandler */
        $responseHandler = $this->service()->put($this->baseUrlPath($sku), $body);
        return $responseHandler;
    }
270399
public function process($orderData, $cartProducts, $request)
    {
        $subTotal = 0;
        $taxTotal = 0;

        foreach ($cartProducts as $product) {
            $subTotal += $product->price() * $product->qty();
            $taxTotal += $product->tax() * $product->qty();
        }

        $total = (round($subTotal, 2) + round($taxTotal, 2)) * 100;

        $totalCents = (int) $total;
        $apiKey = Configuration::getConfiguration(self::CONFIG_SECRET_KEY);

        Stripe::setApiKey($apiKey);
        $currencyCode = Configuration::getConfiguration('general_site_currency');
        $response = Charge::create([
            'amount' => $totalCents,
            'currency' => $currencyCode,
            'source' => $request->get('stripeToken'), // obtained with Stripe.js
            'description' => 'AvoRed E commerce Payment',
        ]);

        return $response;
    }
206601
public function setQuantity($qty)
    {
        if(empty($qty) || ! is_numeric($qty))
            throw new \InvalidArgumentException('Please supply a valid quantity.');

        $this->qty = $qty;
    }
78783
public function deriveProductTree(SKU $sku) {
    static $cache = [];

    if (isset($cache[$sku->language()->getId()], $cache[$sku->language()->getId()][$sku->id()])) {
      return $cache[$sku->language()->getId()][$sku->id()];
    }

    $tree = [
      'parent' => $sku,
      'products' => self::getChildren($sku),
      'combinations' => [],
    ];

    $configurables = unserialize(
      $sku->get('field_configurable_attributes')->getString()
    );

    $tree['configurables'] = [];
    foreach ($configurables as $configurable) {
      $tree['configurables'][$configurable['code']] = $configurable;
    }

    $configurable_codes = array_keys($tree['configurables']);

    foreach ($tree['products'] ?? [] as $sku_code => $sku_entity) {
      $attributes = $sku_entity->get('attributes')->getValue();
      $attributes = array_column($attributes, 'value', 'key');
      foreach ($configurable_codes as $code) {
        $value = $attributes[$code] ?? '';

        if (empty($value)) {
          continue;
        }

        $tree['combinations']['by_sku'][$sku_code][$code] = $value;
      }
    }

    /** @var \Drupal\acm_sku\CartFormHelper $helper */
    $helper = \Drupal::service('acm_sku.cart_form_helper');

    $configurable_weights = $helper->getConfigurableAttributeWeights(
      $sku->get('attribute_set')->getString()
    );

    // Sort configurables based on the config.
    uasort($tree['configurables'], function ($a, $b) use ($configurable_weights) {
      return $configurable_weights[$a['code']] - $configurable_weights[$b['code']];
    });

    $tree['options'] = Configurable::recursiveConfigurableTree(
      $tree,
      $tree['configurables']
    );

    $cache[$sku->language()->getId()][$sku->id()] = $tree;

    return $tree;
  }
406910
private function manage($product_sku)
    {
        $product = Subbly::api('subbly.product')->find($product_sku);

        if (!Input::has('product_category')) {
            return $this->jsonErrorResponse('"product_category" is required.');
        }

        if (!is_array(Input::get('product_category'))) {
            return $this->jsonErrorResponse('"product_category" must be an array.');
        }

        Subbly::api('subbly.product_category')->create(Input::get('product_category'), $product);

        return $this->jsonResponse(array(),
        array(
            'status' => array(
                'code'    => 201,
                'message' => 'ProductCategory created',
            ),
        ));
    }
1252310
public function update($product_sku, $uid)
    {
        $product = Subbly::api('subbly.product')->find($product_sku);

        if (!Input::hasFile('product_image')) {
            return $this->jsonErrorResponse('"product_image" is required.');
        }

        $productImage = Subbly::api('subbly.product_image')->update($uid, array(
            'image' => Input::file('product_image'),
        ));

        return $this->jsonResponse(array(
            'product_image' => $productImage,
        ),
        array(
            'status' => array(
                'code'    => 200,
                'message' => 'ProductImage updated',
            ),
        ));
    }
256243
public function store(CreateCartItemRequest $request)
    {
        $errors = '';
        try {
            $this->cart->add(
                $request->shop_id,
                $request->product_id,
                $request->quantity,
                $request->get('option_values', []),
                $request->note
            );

            return response()->json([
                'errors' => false,
                'data' => $this->cart->items()
            ]);
        } catch (\Exception $e) {
            $errors = $e->getMessage();
        }

        return response()->json([
            'errors' => true,
            'message' => $errors,
            'data' => $this->cart->items()
        ]);
    }