_id
stringlengths
2
7
title
stringlengths
3
151
partition
stringclasses
3 values
text
stringlengths
83
13k
language
stringclasses
1 value
meta_information
dict
q248400
TelegramTemplateCompiler.compileKeyboard
validation
protected function compileKeyboard(Keyboard $keyboard) { $firstButton = collect($keyboard->getButtons())->first(); if ($firstButton instanceof PayloadButton || $firstButton instanceof UrlButton) { return $this->compileInlineKeyboard($keyboard); } return $this->compileReplyKeyboard($keyboard); }
php
{ "resource": "" }
q248401
ViewBuilder.buildSaleView
validation
public function buildSaleView(Model\SaleInterface $sale, array $options = []) { $this->initialize($sale, $options); $this->amountCalculator->calculateSale($sale); // Gross total view $grossResult = $sale->getGrossResult(); $this->view->setGross(new TotalView( $this->formatter->currency($grossResult->getGross($this->view->isAti())), $this->formatter->currency($grossResult->getDiscount($this->view->isAti())), $this->formatter->currency($grossResult->getBase($this->view->isAti())) )); // Final total view $finalResult = $sale->getFinalResult(); $this->view->setFinal(new TotalView( $this->formatter->currency($finalResult->getBase()), $this->formatter->currency($finalResult->getTax()), $this->formatter->currency($finalResult->getTotal()) )); if ($this->options['private'] && null !== $margin = $this->marginCalculator->calculateSale($sale)) { $prefix = $margin->isAverage() ? '~' : ''; $this->view->setMargin(new MarginView( $prefix . $this->formatter->currency($margin->getAmount()), $prefix . $this->formatter->percent($margin->getPercent()) )); $this->view->vars['show_margin'] = true; } // Items lines $this->buildSaleItemsLinesViews($sale); // Discounts lines $this->buildSaleDiscountsLinesViews($sale); // Shipment line $this->buildShipmentLine($sale); // Taxes views $this->buildSaleTaxesViews($sale); // Extends foreach ($this->types as $type) { $type->buildSaleView($sale, $this->view, $this->options); } $columnsCount = 6; if ($this->view->vars['show_availability']) { $columnsCount++; } if ($this->view->vars['show_discounts'] = 0 < count($grossResult->getDiscountAdjustments())) { $columnsCount += 3; } if ($this->view->vars['show_taxes'] = 1 < count($finalResult->getTaxAdjustments())) { $columnsCount++; } if ($this->view->vars['show_margin']) { $columnsCount++; } if ($this->options['editable']) { $columnsCount++; } $this->view->vars['columns_count'] = $columnsCount; return $this->view; }
php
{ "resource": "" }
q248402
ViewBuilder.initialize
validation
private function initialize(Model\SaleInterface $sale, array $options = []) { $this->lineNumber = 1; $this->view = new SaleView(); $this->types = $this->registry->getTypesForSale($sale); foreach ($this->types as $type) { $type->configureOptions($sale, $this->view, $options); } $this->options = $this->getOptionsResolver()->resolve($options); $this->view->setTemplate($this->options['template']); if (!is_null($this->options['ati'])) { $this->view->setAti($this->options['ati']); } else { $this->view->setAti($sale->isAtiDisplayMode()); } $this->formatter = $this->formatterFactory->create($this->options['locale'], $sale->getCurrency()->getCode()); foreach ($this->types as $type) { $type->setFormatter($this->formatter); } }
php
{ "resource": "" }
q248403
ViewBuilder.buildSaleTaxesViews
validation
private function buildSaleTaxesViews(Model\SaleInterface $sale) { if (!$this->options['taxes_view']) { return; } $amounts = $this->amountCalculator->calculateSale($sale); foreach ($amounts->getTaxAdjustments() as $tax) { $this->view->addTax(new TaxView( $tax->getName(), $this->formatter->currency($tax->getAmount()) )); } }
php
{ "resource": "" }
q248404
ViewBuilder.buildSaleItemsLinesViews
validation
private function buildSaleItemsLinesViews(Model\SaleInterface $sale) { if (!$sale->hasItems()) { return; } foreach ($sale->getItems() as $item) { // We don't need to test if null is returned as root items can't be private. $this->view->addItem($this->buildSaleItemLineView($item)); } }
php
{ "resource": "" }
q248405
ViewBuilder.buildSaleDiscountsLinesViews
validation
private function buildSaleDiscountsLinesViews(Model\SaleInterface $sale) { if (!$sale->hasAdjustments(Model\AdjustmentTypes::TYPE_DISCOUNT)) { return; } foreach ($sale->getAdjustments(Model\AdjustmentTypes::TYPE_DISCOUNT) as $adjustment) { $this->view->addDiscount($this->buildDiscountLine($adjustment)); } }
php
{ "resource": "" }
q248406
ViewBuilder.buildDiscountLine
validation
private function buildDiscountLine(Model\SaleAdjustmentInterface $adjustment, $level = 0) { if (Model\AdjustmentTypes::TYPE_DISCOUNT !== $adjustment->getType()) { throw new InvalidArgumentException("Unexpected adjustment type."); } $lineNumber = $this->lineNumber++; $view = new LineView( 'adjustment_' . ($lineNumber - 1), 'adjustment_' . $adjustment->getId(), $lineNumber, $level ); if (empty($designation = $adjustment->getDesignation())) { $designation = 'Discount '; if ($adjustment->getMode() === Model\AdjustmentModes::MODE_PERCENT) { $designation .= $this->formatter->percent($adjustment->getAmount()); } } $result = $adjustment->getResult(); $view ->setDesignation($designation) ->setBase($this->formatter->currency($result->getBase())) ->setTaxAmount($this->formatter->currency($result->getTax())) ->setTotal($this->formatter->currency($result->getTotal())); foreach ($this->types as $type) { $type->buildAdjustmentView($adjustment, $view, $this->options); } return $view; }
php
{ "resource": "" }
q248407
ViewBuilder.buildShipmentLine
validation
private function buildShipmentLine(Model\SaleInterface $sale) { if (null === $sale->getShipmentMethod() && !$this->options['private']) { return; } $lineNumber = $this->lineNumber++; $view = new LineView( 'shipment', 'shipment', $lineNumber, 0 ); // Method title $designation = 'Shipping cost'; if (null !== $method = $sale->getShipmentMethod()) { $designation = $method->getTitle(); } // Total weight $designation .= ' (' . $this->formatter->number($sale->getWeightTotal()) . ' kg)'; $result = $sale->getShipmentResult(); $view ->setDesignation($designation) ->setBase($this->formatter->currency($result->getBase())) ->setTaxRates($this->formatter->rates(...$result->getTaxAdjustments())) ->setTaxAmount($this->formatter->currency($result->getTax())) ->setTotal($this->formatter->currency($result->getTotal())); foreach ($this->types as $type) { $type->buildShipmentView($sale, $view, $this->options); } $this->view->setShipment($view); }
php
{ "resource": "" }
q248408
ViewBuilder.getOptionsResolver
validation
private function getOptionsResolver() { if (null !== $this->optionsResolver) { return $this->optionsResolver; } $resolver = new OptionsResolver(); $resolver ->setDefaults([ 'private' => false, 'editable' => false, 'taxes_view' => true, 'ati' => null, 'locale' => \Locale::getDefault(), 'template' => function (Options $options) { if (true === $options['editable']) { return $this->editableTemplate; } return $this->defaultTemplate; }, ]) ->setAllowedTypes('private', 'bool') ->setAllowedTypes('editable', 'bool') ->setAllowedTypes('taxes_view', 'bool') ->setAllowedTypes('ati', ['null', 'bool']) ->setAllowedTypes('locale', 'string') ->setAllowedTypes('template', ['null', 'string']); return $this->optionsResolver = $resolver; }
php
{ "resource": "" }
q248409
FormConfig.updateTab
validation
public function updateTab($tabLabel, array $formInputs) { $tabExists = false; foreach ($this->getTabs() as $tabIndex => $tabInfo) { if (array_get($tabInfo, 'label') === $tabLabel) { $this->currentTab = $tabIndex; $this->currentInputsGroup = null; if (count((array)array_get($tabInfo, 'groups', [])) === 1 && is_int(array_keys($tabInfo['groups'])[0])) { $this->currentInputsGroup = array_keys($tabInfo['groups'])[0]; } $tabExists = true; break; } } if (!$tabExists) { $this->newTab($tabLabel); } $this->setFormInputs($formInputs); $this->currentTab = null; $this->currentInputsGroup = null; return $this; }
php
{ "resource": "" }
q248410
TaxResolver.resolveSaleTaxRule
validation
public function resolveSaleTaxRule(SaleInterface $sale): ?TaxRuleInterface { return $this->resolveTaxRule($this->resolveTargetCountry($sale), $sale->isBusiness()); }
php
{ "resource": "" }
q248411
TaxResolver.resolveTargetCountry
validation
protected function resolveTargetCountry($target): CountryInterface { if (null === $target) { return $this->countryProvider->getCountry(); } if ($target instanceof CountryInterface) { return $target; } if ($target instanceof SaleInterface) { $country = $this->resolveSaleTargetCountry($target); } elseif ($target instanceof CustomerInterface) { $country = $this->resolveCustomerTargetCountry($target); } elseif(is_string($target) && 2 == strlen($target)) { $country = $this->getCountryByCode($target); } else { throw new InvalidArgumentException("Unexpected taxation target."); } return $country ?: $this->countryProvider->getCountry(); }
php
{ "resource": "" }
q248412
TaxResolver.resolveTaxRule
validation
protected function resolveTaxRule(CountryInterface $country, $business = false): ?TaxRuleInterface { if ($business) { return $this->taxRuleRepository->findOneByCountryForBusiness($country); } return $this->taxRuleRepository->findOneByCountryForCustomer($country); }
php
{ "resource": "" }
q248413
TaxResolver.resolveSaleTargetCountry
validation
protected function resolveSaleTargetCountry(SaleInterface $sale): ?CountryInterface { // Get the country from the sale's delivery address if (null !== $country = $sale->getDeliveryCountry()) { return $country; } // If none, resolves the customer's taxation target address if (null !== $customer = $sale->getCustomer()) { return $this->resolveCustomerTargetCountry($customer); } return null; }
php
{ "resource": "" }
q248414
TaxResolver.resolveCustomerTargetCountry
validation
protected function resolveCustomerTargetCountry(CustomerInterface $customer): ?CountryInterface { if (null !== $address = $customer->getDefaultDeliveryAddress()) { return $address->getCountry(); } return null; }
php
{ "resource": "" }
q248415
Arr.path
validation
public static function path($array, $path, $default = null, $delimiter = null) { if (!static::is_array($array)) { // This is not an array! return $default; } if (is_array($path)) { // The path has already been separated into keys $keys = $path; } else { if (array_key_exists($path, $array)) { // No need to do extra processing return $array[$path]; } if (!$delimiter) { // Use the default delimiter $delimiter = static::$delimiter; } // Remove delimiters and spaces $path = trim($path, "{$delimiter} "); // Split the keys by delimiter $keys = explode($delimiter, $path); } do { $key = array_shift($keys); if (ctype_digit($key)) { // Make the key an integer $key = (int)$key; } if (isset($array[$key])) { if (!$keys) { // Found the path requested return $array[$key]; } if (!static::is_array($array[$key])) { // Unable to dig deeper break; } // Dig down into the next part of the path $array = $array[$key]; } else { // Unable to dig deeper break; } } while ($keys); // Unable to find the value requested return $default; }
php
{ "resource": "" }
q248416
Arr.set_path
validation
public static function set_path(&$array, $path, $value, $delimiter = null): void { if (!$delimiter) { // Use the default delimiter $delimiter = static::$delimiter; } // The path has already been separated into keys $keys = $path; if (!is_array($path)) { // Split the keys by delimiter $keys = explode($delimiter, $path); } // Set current $array to inner-most array path while (count($keys) > 1) { $key = array_shift($keys); if (is_string($key) && ctype_digit($key)) { // Make the key an integer $key = (int)$key; } if (!isset($array[$key])) { $array[$key] = array(); } $array =& $array[$key]; } // Set key on inner-most array $array[array_shift($keys)] = $value; }
php
{ "resource": "" }
q248417
Arr.extract
validation
public static function extract($array, array $paths, $default = null) { $found = array(); foreach ($paths as $path) { static::set_path($found, $path, static::path($array, $path, $default)); } return $found; }
php
{ "resource": "" }
q248418
Arr.pluck
validation
public static function pluck($array, $key) { $values = array(); foreach ($array as $row) { if (isset($row[$key])) { // Found a value in this row $values[] = $row[$key]; } } return $values; }
php
{ "resource": "" }
q248419
PhoneNumber.isValidType
validation
public function isValidType($type) { return in_array($type, array( self::ANY, self::FIXED_LINE, self::MOBILE, self::PAGER, self::PERSONAL_NUMBER, self::PREMIUM_RATE, self::SHARED_COST, self::TOLL_FREE, self::UAN, self::VOIP, self::VOICEMAIL, ), true); }
php
{ "resource": "" }
q248420
PhoneNumber.getType
validation
public function getType() { if (is_string($this->type)) { $type = $this->type; } elseif (is_array($this->type)) { $type = reset($this->type); } else { $type = null; } return $this->isValidType($type) ? $type : self::ANY; }
php
{ "resource": "" }
q248421
PhoneNumber.getTypes
validation
public function getTypes() { if (is_string($this->type)) { $types = array($this->type); } elseif (is_array($this->type)) { $types = $this->type; } else { $types = array(); } $types = array_filter($types, array($this, 'isValidType')); return empty($types) ? array(self::ANY) : $types; }
php
{ "resource": "" }
q248422
AbstractPaymentListener.generateNumber
validation
protected function generateNumber(PaymentInterface $payment) { if (0 == strlen($payment->getNumber())) { $this->numberGenerator->generate($payment); return true; } return false; }
php
{ "resource": "" }
q248423
AbstractPaymentListener.generateKey
validation
protected function generateKey(PaymentInterface $payment) { if (0 == strlen($payment->getKey())) { $this->keyGenerator->generate($payment); return true; } return false; }
php
{ "resource": "" }
q248424
AbstractPaymentListener.updateExchangeRate
validation
protected function updateExchangeRate(PaymentInterface $payment) { if (null !== $payment->getExchangeRate()) { return false; } $date = new \DateTime(); $rate = $this->currencyConverter->getRate( $this->currencyConverter->getDefaultCurrency(), $payment->getCurrency()->getCode(), $date ); $payment ->setExchangeRate($rate) ->setExchangeDate($date); return true; }
php
{ "resource": "" }
q248425
ShipmentMethodRepository.getFindAvailableByCountryAndWeightQuery
validation
private function getFindAvailableByCountryAndWeightQuery() { if (null === $this->findAvailableByCountryAndWeightQuery) { $qb = $this->getCollectionQueryBuilder(); $this->findAvailableByCountryAndWeightQuery = $qb ->join('o.prices', 'p') ->join('p.zone', 'z') ->andWhere($qb->expr()->isMemberOf(':country', 'z.countries')) ->andWhere($qb->expr()->gte('p.weight', ':weight')) ->andWhere($qb->expr()->eq('o.enabled', ':enabled')) ->andWhere($qb->expr()->eq('o.available', ':available')) ->addOrderBy('o.position', 'ASC') ->getQuery(); } return $this->findAvailableByCountryAndWeightQuery; }
php
{ "resource": "" }
q248426
UnitCandidate.build
validation
public static function build(StockUnitInterface $unit, SaleInterface $sale) { $releasable = 0; $map = []; foreach ($unit->getStockAssignments() as $a) { // Ignore assignments from the same sale (Should be impossible) /** @var \Ekyna\Component\Commerce\Shipment\Model\ShipmentSubjectInterface $s */ if ($sale === $s = $a->getSaleItem()->getSale()) { continue; } // Ignore assignments from preparation sales if ($s->getShipmentState() === ShipmentStates::STATE_PREPARATION) { continue; } if (0 < $d = $a->getSoldQuantity() - $a->getShippedQuantity()) { $releasable += $d; $map[$a->getId()] = $d; } } arsort($map, \SORT_NUMERIC); $candidate = new static; $candidate->unit = $unit; $candidate->shippable = $unit->getShippableQuantity(); $candidate->reservable = $unit->getReservableQuantity(); $candidate->releasable = $releasable; $candidate->map = $map; return $candidate; }
php
{ "resource": "" }
q248427
UnitCandidate.getCombination
validation
public function getCombination($quantity, $reset = false) { if (null !== $this->combination && !$reset) { return $this->combination; } $this->combination = null; if (!empty($combinations = $this->buildCombinations($quantity))) { // Sort combinations: prefer closest, then greater, then lower, finally smaller usort($combinations, function (AssignmentCombination $a, AssignmentCombination $b) use ($quantity) { if ($a->diff == $b->diff) { if ($a->size == $b->size) { return 0; } return $a->size < $b->size ? -1 : 1; } if (0 <= $a->diff) { return intval(0 > $b->diff ? -1 : $a->diff - $b->diff); } return intval(0 < $b->diff ? 1 : $b->diff - $a->diff); }); $this->combination = reset($combinations); } return $this->combination; }
php
{ "resource": "" }
q248428
UnitCandidate.getAssignmentById
validation
public function getAssignmentById($id) { foreach ($this->unit->getStockAssignments() as &$assignment) { if ($assignment->getId() === $id) { return $assignment; } } return null; }
php
{ "resource": "" }
q248429
UnitCandidate.buildCombinations
validation
private function buildCombinations($quantity) { if (empty($this->map)) { return []; } $combinations = []; // Size 1 foreach ($this->map as $id => $qty) { $combinations[] = new AssignmentCombination([$id => $qty], $diff = $qty - $quantity); if ($diff == 0) { return $combinations; } } // Size 1 < size < max for ($length = 2; $length < count($this->map); $length++) { foreach (combine_assoc($this->map, $length) as $map) { $combinations[] = new AssignmentCombination($map, $diff = array_sum($map) - $quantity); if ($diff == 0) { return $combinations; } } } // Size max $combinations[] = new AssignmentCombination($this->map, array_sum($this->map) - $quantity); return $combinations; }
php
{ "resource": "" }
q248430
SaleCopier.copyAdjustment
validation
private function copyAdjustment(Model\AdjustmentInterface $source, Model\AdjustmentInterface $target) { $this->copy($source, $target, [ 'designation', 'type', 'mode', 'amount', 'immutable', ]); }
php
{ "resource": "" }
q248431
SaleCopier.copyAttachment
validation
private function copyAttachment(Model\SaleAttachmentInterface $source, Model\SaleAttachmentInterface $target) { $this->copy($source, $target, [ 'path', 'title', 'type', 'size', 'internal', 'createdAt', 'updatedAt', ]); }
php
{ "resource": "" }
q248432
SaleCopier.copyNotification
validation
private function copyNotification(Model\SaleNotificationInterface $source, Model\SaleNotificationInterface $target) { $this->copy($source, $target, [ 'type', 'data', 'sentAt', 'details' ]); }
php
{ "resource": "" }
q248433
SaleCopier.copyItem
validation
private function copyItem(Model\SaleItemInterface $source, Model\SaleItemInterface $target) { $this->copy($source, $target, [ 'designation', 'description', 'reference', 'taxGroup', 'netPrice', 'weight', 'quantity', 'position', 'compound', 'immutable', 'configurable', 'private', 'data', ]); // SubjectIdentity $this->copy($source->getSubjectIdentity(), $target->getSubjectIdentity(), [ 'provider', 'identifier', ]); // Adjustments foreach ($source->getAdjustments() as $sourceAdjustment) { $targetAdjustment = $this->saleFactory->createAdjustmentForItem($target); $target->addAdjustment($targetAdjustment); $this->copyAdjustment($sourceAdjustment, $targetAdjustment); } // Children foreach ($source->getChildren() as $sourceChild) { $targetChild = $this->saleFactory->createItemForSale($target->getSale()); $target->addChild($targetChild); $this->copyItem($sourceChild, $targetChild); } }
php
{ "resource": "" }
q248434
SaleCopier.copy
validation
private function copy($source, $target, array $properties) { $properties = (array)$properties; foreach ($properties as $property) { $this->accessor->setValue($target, $property, $this->accessor->getValue($source, $property)); } }
php
{ "resource": "" }
q248435
Iac_Attach_Media.get_thumbnail_file
validation
public static function get_thumbnail_file( $meta, $size = 'medium' ) { if ( ! isset( $meta[ 'sizes' ][ $size ] ) ) { $file = FALSE; } else { $dir = wp_upload_dir(); $file_parts = array( $dir[ 'basedir' ], dirname( $meta[ 'file' ] ), $meta[ 'sizes' ][ $size ][ 'file' ] ); $file = implode( DIRECTORY_SEPARATOR, $file_parts ); } return apply_filters( 'iac_attach_media_thumbnail_file', $file, $meta, $size ); }
php
{ "resource": "" }
q248436
OrderListener.onPrepare
validation
public function onPrepare(ResourceEventInterface $event) { $order = $this->getSaleFromEvent($event); if (!OrderStates::isStockableState($order->getState())) { throw new IllegalOperationException( "Order is not ready for shipment preparation" ); } }
php
{ "resource": "" }
q248437
OrderListener.handleReleasedChange
validation
public function handleReleasedChange(OrderInterface $order) { if ($this->persistenceHelper->isChanged($order , 'sample')) { if ($order->isReleased() && !$order->isSample()) { throw new IllegalOperationException("Can't turn 'sample' into false if order is released."); } } if (!$this->persistenceHelper->isChanged($order , 'released')) { return false; } // Orders that are not samples can't be released. if (!$order->isSample() && $order->isReleased()) { $order->setReleased(false); return true; } if (!OrderStates::isStockableState($order->getState())) { return false; } foreach ($order->getItems() as $item) { $this->applySaleItemRecursively($item); } return false; }
php
{ "resource": "" }
q248438
OrderListener.setIsFirst
validation
protected function setIsFirst(OrderInterface $order) { if (null !== $customer = $order->getCustomer()) { if ($customer->hasParent()) { $customer = $customer->getParent(); } $first = !$this->orderRepository->existsForCustomer($customer); } else { $first = !$this->orderRepository->existsForEmail($order->getEmail()); } if ($first != $order->isFirst()) { $order->setFirst($first); return true; } return false; }
php
{ "resource": "" }
q248439
OrderListener.fixCustomers
validation
protected function fixCustomers(OrderInterface $order) { $changed = false; $originCustomer = $order->getOriginCustomer(); $customer = $order->getCustomer(); if (is_null($customer)) { if ($originCustomer && $originCustomer->hasParent()) { $order->setCustomer($originCustomer->getParent()); $changed = true; } } elseif ($customer->hasParent()) { $order->setCustomer($customer->getParent()); if (null === $order->getOriginCustomer()) { $order->setOriginCustomer($customer); } $changed = true; } if ($changed) { $this->persistenceHelper->persistAndRecompute($order, false); } return $changed; }
php
{ "resource": "" }
q248440
OrderListener.assignSaleItemRecursively
validation
protected function assignSaleItemRecursively(SaleItemInterface $item) { $this->stockAssigner->assignSaleItem($item); foreach ($item->getChildren() as $child) { $this->assignSaleItemRecursively($child); } }
php
{ "resource": "" }
q248441
OrderListener.detachSaleItemRecursively
validation
protected function detachSaleItemRecursively(SaleItemInterface $item) { $this->stockAssigner->detachSaleItem($item); foreach ($item->getChildren() as $child) { $this->detachSaleItemRecursively($child); } }
php
{ "resource": "" }
q248442
Amount.getUnit
validation
public function getUnit(bool $ati = false): float { return $ati ? $this->ati($this->unit) : $this->unit; }
php
{ "resource": "" }
q248443
Amount.getGross
validation
public function getGross(bool $ati = false): float { return $ati ? $this->ati($this->gross) : $this->gross; }
php
{ "resource": "" }
q248444
Amount.addDiscountAdjustment
validation
public function addDiscountAdjustment(Adjustment $discount): void { foreach ($this->discounts as $d) { if ($d->isSameAs($discount)) { $d->addAmount($discount->getAmount()); return; } } $this->discounts[] = clone $discount; }
php
{ "resource": "" }
q248445
Amount.getDiscount
validation
public function getDiscount(bool $ati = false): float { return $ati ? $this->ati($this->discount) : $this->discount; }
php
{ "resource": "" }
q248446
Amount.getBase
validation
public function getBase(bool $ati = false): float { return $ati ? $this->ati($this->base) : $this->base; }
php
{ "resource": "" }
q248447
Amount.addTaxAdjustment
validation
public function addTaxAdjustment(Adjustment $tax): void { foreach ($this->taxes as $t) { if ($t->isSameAs($tax)) { $t->addAmount($tax->getAmount()); return; } } $this->taxes[] = clone $tax; }
php
{ "resource": "" }
q248448
Amount.finalize
validation
public function finalize(): void { $this->round(); $old = $this->taxes; // Sort by amount usort($old, function (Adjustment $a, Adjustment $b): int { if ($a->getAmount() == $b->getAmount()) { return 0; } return $a->getAmount() > $b->getAmount() ? 1 : -1; }); $new = []; $total = 0; foreach ($old as $tax) { $amount = Money::round($tax->getAmount(), $this->currency); // Fix overflow if ($total + $amount > $this->tax) { $amount = $this->tax - $total; } $total += $amount; $new[] = new Adjustment($tax->getName(), $amount, $tax->getRate()); } // Sort by rate usort($new, function (Adjustment $a, Adjustment $b): int { return $a->getRate() > $b->getRate() ? 1 : -1; }); $this->taxes = $new; }
php
{ "resource": "" }
q248449
Amount.round
validation
public function round(): void { $this->unit = Money::round($this->unit, $this->currency); $this->gross = Money::round($this->gross, $this->currency); $this->discount = Money::round($this->discount, $this->currency); $this->base = Money::round($this->base, $this->currency); $this->total = Money::round($this->total, $this->currency); $this->tax = Money::round($this->total - $this->base, $this->currency); }
php
{ "resource": "" }
q248450
Amount.createFinalFromGross
validation
public static function createFinalFromGross(Amount $gross): Amount { $final = new Amount( $gross->getCurrency(), $gross->getBase(), $gross->getBase(), 0, $gross->getBase(), $gross->getTax(), $gross->getTotal() ); foreach ($gross->getTaxAdjustments() as $t) { $final->addTaxAdjustment($t); } return $final; }
php
{ "resource": "" }
q248451
AutoLoginTrait.getAutoLoginUrl
validation
public function getAutoLoginUrl( array $autoUrl, array $redirectUrl = null, string $expireInterval = '1 day', bool $addRememberMeCookie = true ): string { $autoUrl['?']['t'] = $this->generateLoginToken( $redirectUrl, $expireInterval, $addRememberMeCookie ); $url = Router::url($autoUrl, true); $urlLength = strlen($url); if (strlen($url) > 2080) { throw new \Exception('Generated url "' . $url . '" is too long'); } return $url; }
php
{ "resource": "" }
q248452
AutoLoginTrait.validateLoginToken
validation
public function validateLoginToken(string $token): ?array { $token = base64_decode($token); $serializedData = Security::decrypt($token, $this->getKey(), $this->getSalt()); if ($serializedData === false) { return null; } $data = unserialize($serializedData); if (!empty($data['expireInterval']) && !empty($data['timestamp'])) { $tokenCreated = new Time($data['timestamp']); if (!$tokenCreated->wasWithinLast($data['expireInterval'])) { return null; } } return $data; }
php
{ "resource": "" }
q248453
AutoLoginTrait.generateLoginToken
validation
public function generateLoginToken( array $redirectUrl = null, string $expireInterval = '1 day', bool $addRememberMeCookie = true ): string { $data = [ 'url' => $redirectUrl, 'timestamp' => Time::now()->toUnixString(), 'expireInterval' => $expireInterval, 'addRememberMeCookie' => $addRememberMeCookie ]; $serializedData = serialize($data); $token = Security::encrypt($serializedData, $this->getKey(), $this->getSalt()); return base64_encode($token); }
php
{ "resource": "" }
q248454
AccountingWriter.configure
validation
public function configure($subject) { if ($subject instanceof InvoiceInterface) { $this->date = $subject->getCreatedAt()->format('Y-m-d'); } elseif ($subject instanceof PaymentInterface) { $this->date = $subject->getCompletedAt()->format('Y-m-d'); } else { throw new InvalidArgumentException( "Expected instance of " . InvoiceInterface::class . " or " . PaymentInterface::class ); } $this->number = $subject->getNumber(); $sale = $subject->getSale(); if ($customer = $sale->getCustomer()) { $this->identity = $customer->getFirstName() . ' ' . $customer->getLastName(); } else { $this->identity = $sale->getFirstName() . ' ' . $sale->getLastName(); } }
php
{ "resource": "" }
q248455
AccountingWriter.debit
validation
public function debit($account, $amount, \DateTime $date) { $data = [ $this->date, $account, $this->identity, null, $amount, $this->number, $date->format('Y-m-d'), ]; if (false === fputcsv($this->handle, $data, ';', '"')) { throw new RuntimeException("Failed to write line."); } }
php
{ "resource": "" }
q248456
TaxGroupListener.fixDefault
validation
protected function fixDefault(TaxGroupInterface $taxGroup) { if (!$this->persistenceHelper->isChanged($taxGroup, ['default'])) { return; } if ($taxGroup->isDefault()) { try { $previousTaxGroup = $this->taxGroupRepository->findDefault(); } catch (RuntimeException $e) { return; } if (null === $previousTaxGroup || $previousTaxGroup === $taxGroup) { return; } $previousTaxGroup->setDefault(false); $this->persistenceHelper->persistAndRecompute($previousTaxGroup, false); } }
php
{ "resource": "" }
q248457
TaxGroupListener.getTaxGroupFromEvent
validation
protected function getTaxGroupFromEvent(ResourceEventInterface $event) { $resource = $event->getResource(); if (!$resource instanceof TaxGroupInterface) { throw new InvalidArgumentException('Expected instance of ' . TaxGroupInterface::class); } return $resource; }
php
{ "resource": "" }
q248458
CmfApiDocumentationModule.getDocumentationClassesList
validation
public function getDocumentationClassesList(): array { $classNames = $this->getCmfConfig()->config('api_documentation.classes', []); if (empty($classNames)) { $classNames = $this->loadClassesFromFileSystem(); } return $classNames; }
php
{ "resource": "" }
q248459
Migrate.create
validation
public function create($argv) { $custom_name = false; if ($argv && count($argv)) { $custom_name = mb_strtolower($argv[0], 'utf-8'); } DB::begin(); try { $name = 'm' . gmdate('ymd_His'); if ($custom_name) $name = $name . '_' . $custom_name; $file = '<?php // ' . strftime('%F %T') . ' use mii\db\Migration; use mii\db\DB; class ' . $name . ' extends Migration { public function up() { } public function down() { return false; } public function safe_up() { } public function safe_down() { return false; } } '; reset($this->migrations_paths); file_put_contents(current($this->migrations_paths) . '/' . $name . '.php', $file); DB::commit(); $this->info('migration :name created', [':name' => $name]); } catch (\Exception $e) { DB::rollback(); throw $e; } }
php
{ "resource": "" }
q248460
Migrate.up
validation
public function up($limit = null) { $applied = 0; $migrations = $this->migrations_list; $limit = (int)$limit; if ($limit > 0) { $migrations = array_slice($migrations, 0, $limit); } foreach ($migrations as $migration) { if ($migration['applied']) continue; $name = $migration['name']; $this->info('Loading migration #:name', [':name' => $name]); $obj = $this->load_migration($migration); $obj->init(); if ($obj->up() === false) { $this->error('Migration #:name failed. Stop.', [':name' => $name]); return; }; DB::begin(); try { $obj->safe_up(); DB::commit(); } catch (\Throwable $e) { DB::rollback(); } DB::insert('INSERT INTO`' . $this->migrate_table . '`(`name`, `date`) VALUES(:name, :date)', [ ':name' => $name, ':date' => time() ]); $this->info('Migration up successfully', [':name' => $name]); $applied++; } if (!$applied) { $this->warning('No new migration found'); } }
php
{ "resource": "" }
q248461
Response.json
validation
public static function json($content, $code = 200) { // If collection get array if (is_a($content, "SnooPHP\Model\Collection")) $content = $content->array(); // Return json content return new static( to_json($content), $code, ["Content-Type" => "application/json; charset=utf-8"] ); }
php
{ "resource": "" }
q248462
AbstractGateway.createLabel
validation
protected function createLabel($content, $type, $format, $size) { $label = new OrderShipmentLabel(); // TODO use SaleFactory ? $label ->setContent($content) ->setType($type) ->setFormat($format) ->setSize($size); return $label; }
php
{ "resource": "" }
q248463
AbstractGateway.clearShipment
validation
protected function clearShipment(Shipment\ShipmentInterface $shipment) { if (empty($shipment->getTrackingNumber()) && !$shipment->hasLabels()) { return false; } $shipment->setTrackingNumber(null); foreach ($shipment->getLabels() as $label) { $shipment->removeLabel($label); } return true; }
php
{ "resource": "" }
q248464
AbstractGateway.clearParcel
validation
protected function clearParcel(Shipment\ShipmentParcelInterface $parcel) { if (empty($parcel->getTrackingNumber()) && !$parcel->hasLabels()) { return false; } $parcel->setTrackingNumber(null); foreach ($parcel->getLabels() as $label) { $parcel->removeLabel($label); } return true; }
php
{ "resource": "" }
q248465
Curl.exec
validation
public function exec($keepAlive = false) { $this->lastResult = curl_exec($this->curl); $this->info = curl_getinfo($this->curl); // Close session if (!$keepAlive) curl_close($this->curl); return $this->lastResult !== false; }
php
{ "resource": "" }
q248466
Curl.content
validation
public function content($decodeJson = false) { return $decodeJson && preg_match("~^application/json.*~", $this->lastResultType) && $this->lastResult ? from_json($this->lastResult) : $this->lastResult; }
php
{ "resource": "" }
q248467
Curl.info
validation
public function info($name = null) { if ($name) { return $this->info ? $this->info[$name] : curl_getinfo($this->curl, "CURLINFO".strtoupper($name)); } else { return $this->info ?: curl_getinfo($this->curl); } }
php
{ "resource": "" }
q248468
Curl.url
validation
public function url($url = null) { if ($url) { $this->url = $url; $this->option([CURLOPT_URL => $url]); } return $this->url; }
php
{ "resource": "" }
q248469
Curl.parseHeader
validation
protected function parseHeader($curl, $header) { if (preg_match("/^([^:\s]+)\:\s+(.*)$/", $header, $matches)) { // Add to header list $matches[2] = trim($matches[2]); $this->lastHeader[$matches[1]] = $matches[2]; // Set result type $this->lastResultType = $matches[1] === "Content-Type" ? $matches[2] : $this->lastResultType; } return strlen($header); }
php
{ "resource": "" }
q248470
Curl.create
validation
public static function create($method, $url, $data = "", array $headers = [], array $options = [], $initOnly = false) { // Null if method is not valid $curl = null; // Compare method if (!strcasecmp($method, "GET")) $curl = new static($url, $options + [ CURLOPT_CUSTOMREQUEST => "GET", CURLOPT_RETURNTRANSFER => true ], $headers, $initOnly); else if (!strcasecmp($method, "POST")) $curl = new static($url, $options + [ CURLOPT_CUSTOMREQUEST => "POST", CURLOPT_POSTFIELDS => $data, CURLOPT_RETURNTRANSFER => true ], $headers, $initOnly); else if (!strcasecmp($method, "PUT")) $curl = new static($url, $options + [ CURLOPT_CUSTOMREQUEST => "PUT", CURLOPT_POSTFIELDS => $data, CURLOPT_RETURNTRANSFER => true ], $headers, $initOnly); else if (!strcasecmp($method, "DELETE")) $curl = new static($url, $options + [ CURLOPT_CUSTOMREQUEST => "DELETE", CURLOPT_RETURNTRANSFER => true ], $headers, $initOnly); return $curl; }
php
{ "resource": "" }
q248471
OrderStat.getMarginPercent
validation
public function getMarginPercent() { if (0 < $this->margin && 0 < $this->revenue) { return round($this->margin * 100 / $this->revenue, 1); } return 0; }
php
{ "resource": "" }
q248472
OrderStat.loadResult
validation
public function loadResult(array $result) { $changed = false; foreach (['revenue', 'shipping', 'margin', 'orders', 'items', 'average', 'details'] as $property) { if ($this->{$property} != $result[$property]) { $this->{$property} = $result[$property]; $changed = true; } } return $changed; }
php
{ "resource": "" }
q248473
PricesMapNotFoundException.createFromCurrency
validation
public static function createFromCurrency($currency, $code = 0, \Exception $prev = null) { $message = sprintf('Not found prices by currency "%s".', $currency); return new static($message, $code, $prev); }
php
{ "resource": "" }
q248474
CartItem.assertSaleClass
validation
protected function assertSaleClass(Common\SaleInterface $sale) { if (!$sale instanceof Model\CartInterface) { throw new InvalidArgumentException("Expected instance of " . Model\CartInterface::class); } }
php
{ "resource": "" }
q248475
CartItem.assertItemClass
validation
protected function assertItemClass(Common\SaleItemInterface $child) { if (!$child instanceof Model\CartItemInterface) { throw new InvalidArgumentException("Expected instance of " . Model\CartItemInterface::class); } }
php
{ "resource": "" }
q248476
CartItem.assertItemAdjustmentClass
validation
protected function assertItemAdjustmentClass(Common\AdjustmentInterface $adjustment) { if (!$adjustment instanceof Model\CartItemAdjustmentInterface) { throw new InvalidArgumentException("Expected instance of " . Model\CartItemAdjustmentInterface::class); } }
php
{ "resource": "" }
q248477
AddressNormalizer.phoneNumberCountry
validation
private function phoneNumberCountry(PhoneNumber $phoneNumber = null) { if ($phoneNumber) { return $this->phoneNumberUtil->getRegionCodeForNumber($phoneNumber); } return null; }
php
{ "resource": "" }
q248478
CustomerAddressListener.fixInvoiceDefault
validation
protected function fixInvoiceDefault(CustomerAddressInterface $address) { if (!$this->persistenceHelper->isChanged($address, ['invoiceDefault'])) { return; } $customer = $address->getCustomer(); if ($address->isInvoiceDefault()) { foreach ($customer->getAddresses() as $a) { if ($a === $address) { continue; } if ($a->isInvoiceDefault()) { $a->setInvoiceDefault(false); $this->persistenceHelper->persistAndRecompute($a, false); } } } elseif (null === $customer->getDefaultInvoiceAddress(true)) { $address->setInvoiceDefault(true); $this->persistenceHelper->persistAndRecompute($address, false); } }
php
{ "resource": "" }
q248479
CustomerAddressListener.fixDeliveryDefault
validation
protected function fixDeliveryDefault(CustomerAddressInterface $address) { if (!$this->persistenceHelper->isChanged($address, ['deliveryDefault'])) { return; } $customer = $address->getCustomer(); if ($address->isDeliveryDefault()) { foreach ($customer->getAddresses() as $a) { if ($a === $address) { continue; } if ($a->isDeliveryDefault()) { $a->setDeliveryDefault(false); $this->persistenceHelper->persistAndRecompute($a, false); } } } elseif (null === $customer->getDefaultDeliveryAddress(true)) { $address->setDeliveryDefault(true); $this->persistenceHelper->persistAndRecompute($address, false); } }
php
{ "resource": "" }
q248480
CustomerAddressListener.getAddressFromEvent
validation
protected function getAddressFromEvent(ResourceEventInterface $event) { $resource = $event->getResource(); if (!$resource instanceof CustomerAddressInterface) { throw new InvalidArgumentException('Expected instance of ' . CustomerAddressInterface::class); } return $resource; }
php
{ "resource": "" }
q248481
SaleFactory.resolveClassAndCreateObject
validation
private function resolveClassAndCreateObject($type, $subject) { foreach ($this->classes[$type] as $source => $target) { if ($subject instanceof $source) { return new $target; } } throw new InvalidArgumentException('Unsupported object class.'); }
php
{ "resource": "" }
q248482
SaleFactory.getDefaultClasses
validation
private function getDefaultClasses() { // TODO use constants for keys return [ 'address' => [ Cart\Model\CartInterface::class => Cart\Entity\CartAddress::class, Order\Model\OrderInterface::class => Order\Entity\OrderAddress::class, Quote\Model\QuoteInterface::class => Quote\Entity\QuoteAddress::class, ], 'attachment' => [ Cart\Model\CartInterface::class => Cart\Entity\CartAttachment::class, Order\Model\OrderInterface::class => Order\Entity\OrderAttachment::class, Quote\Model\QuoteInterface::class => Quote\Entity\QuoteAttachment::class, ], 'notification' => [ Cart\Model\CartInterface::class => Cart\Entity\CartNotification::class, Order\Model\OrderInterface::class => Order\Entity\OrderNotification::class, Quote\Model\QuoteInterface::class => Quote\Entity\QuoteNotification::class, ], 'item' => [ Cart\Model\CartInterface::class => Cart\Entity\CartItem::class, Order\Model\OrderInterface::class => Order\Entity\OrderItem::class, Quote\Model\QuoteInterface::class => Quote\Entity\QuoteItem::class, ], 'adjustment' => [ Cart\Model\CartInterface::class => Cart\Entity\CartAdjustment::class, Order\Model\OrderInterface::class => Order\Entity\OrderAdjustment::class, Quote\Model\QuoteInterface::class => Quote\Entity\QuoteAdjustment::class, ], 'item_adjustment' => [ Cart\Model\CartItemInterface::class => Cart\Entity\CartItemAdjustment::class, Order\Model\OrderItemInterface::class => Order\Entity\OrderItemAdjustment::class, Quote\Model\QuoteItemInterface::class => Quote\Entity\QuoteItemAdjustment::class, ], 'item_stock_assignment' => [ Order\Model\OrderItemInterface::class => Order\Entity\OrderItemStockAssignment::class, ], 'payment' => [ Cart\Model\CartInterface::class => Cart\Entity\CartPayment::class, Order\Model\OrderInterface::class => Order\Entity\OrderPayment::class, Quote\Model\QuoteInterface::class => Quote\Entity\QuotePayment::class, ], 'shipment' => [ Order\Model\OrderInterface::class => Order\Entity\OrderShipment::class, ], 'shipment_item' => [ Order\Model\OrderShipmentInterface::class => Order\Entity\OrderShipmentItem::class, ], 'invoice' => [ Order\Model\OrderInterface::class => Order\Entity\OrderInvoice::class, ], 'invoice_line' => [ Order\Model\OrderInvoiceInterface::class => Order\Entity\OrderInvoiceLine::class, ], ]; }
php
{ "resource": "" }
q248483
Iac_Settings.validate
validation
public function validate( $request ) { if ( ! empty( $request[ 'send_by_bcc' ] ) && '1' === $request[ 'send_by_bcc' ] ) $request[ 'send_by_bcc' ] = '1'; else $request[ 'send_by_bcc' ] = '0'; if ( ! empty( $request[ 'send_attachments' ] ) && '1' === $request[ 'send_attachments' ] ) $request[ 'send_attachments' ] = '1'; else $request[ 'send_attachments' ] = '0'; return $request; }
php
{ "resource": "" }
q248484
Iac_Settings.description
validation
public function description() { # monitor the current status of user-selection (opt-in or opt-out) $default = Inform_About_Content::default_opt_in( NULL ); // Misleading terminology, known issue: https://github.com/inpsyde/Inform-about-Content/issues/23 $subscribed_by_default = apply_filters( 'iac_default_opt_in', $default ); $description = $subscribed_by_default ? __( 'Note: Users must opt-out from e-mail notifications by default', Inform_About_Content::TEXTDOMAIN ) : __( 'Note: Users must opt-in to e-mail notifications by default', Inform_About_Content::TEXTDOMAIN ); printf( '<p class="description">%s</p>', $description ); }
php
{ "resource": "" }
q248485
Iac_Settings.load_options
validation
public function load_options() { $options = get_option( self::OPTION_KEY, '' ); if ( ! is_array( $options ) ) { $options = self::$default_options; update_option( self::OPTION_KEY, $options ); } else { foreach ( self::$default_options as $key => $value ) { if ( ! isset( $options[ $key ] ) ) $options[ $key ] = $value; } } $this->options = $options; }
php
{ "resource": "" }
q248486
ShipmentCalculator.buildSaleItemRemaining
validation
private function buildSaleItemRemaining( Common\SaleItemInterface $saleItem, Shipment\RemainingList $list, array $shipments ) { // Not for compound item with only public children if (!($saleItem->isCompound() && !$saleItem->hasPrivateChildren())) { $quantity = $saleItem->getTotalQuantity(); foreach ($shipments as $shipment) { foreach ($shipment->getItems() as $item) { if ($item->getSaleItem() === $saleItem) { $quantity += $shipment->isReturn() ? $item->getQuantity() : -$item->getQuantity(); continue 2; } } } if (0 < $quantity) { $entry = new Shipment\RemainingEntry(); $entry ->setSaleItem($saleItem) ->setQuantity($quantity); $list->addEntry($entry); } } foreach ($saleItem->getChildren() as $child) { $this->buildSaleItemRemaining($child, $list, $shipments); } }
php
{ "resource": "" }
q248487
ShipmentCalculator.hasStockableSubject
validation
private function hasStockableSubject(Common\SaleItemInterface $saleItem) { if (!$saleItem instanceof Stock\StockAssignmentsInterface) { return false; } if (null === $subject = $this->subjectHelper->resolve($saleItem)) { return false; } if (!$subject instanceof Stock\StockSubjectInterface) { return false; } if ($subject->isStockCompound()) { return false; } if ($subject->getStockMode() === Stock\StockSubjectModes::MODE_DISABLED) { return false; } return true; }
php
{ "resource": "" }
q248488
SalePreparer.purge
validation
protected function purge(ShipmentInterface $shipment) { foreach ($shipment->getItems() as $item) { if (0 == $item->getAvailable()) { $shipment->removeItem($item); } } }
php
{ "resource": "" }
q248489
SalePreparer.dispatchPrepareEvent
validation
protected function dispatchPrepareEvent(SaleInterface $sale) { if (!$sale instanceof OrderInterface) { throw new InvalidArgumentException("Expected instance of " . OrderInterface::class); } $event = $this->eventDispatcher->createResourceEvent($sale); try { $this->eventDispatcher->dispatch(OrderEvents::PREPARE, $event); } catch (IllegalOperationException $e) { return false; } return true; }
php
{ "resource": "" }
q248490
SaleValidator.validateShipmentMethodRequirements
validation
protected function validateShipmentMethodRequirements(SaleInterface $sale, Constraint $constraint) { if (null === $method = $sale->getShipmentMethod()) { return; } if ($sale->isSameAddress()) { $address = $sale->getInvoiceAddress(); $path = 'invoiceAddress'; } else { $address = $sale->getDeliveryAddress(); $path = 'deliveryAddress'; } if (null === $address) { return; } $gateway = $this->gatewayRegistry->getGateway($method->getGatewayName()); if ($gateway->requires(Gateway\GatewayInterface::REQUIREMENT_MOBILE)) { if (is_null($address->getMobile())) { $this->context ->buildViolation($constraint->shipment_method_require_mobile) ->atPath($path . '.mobile') ->addViolation(); } } }
php
{ "resource": "" }
q248491
SaleValidator.validateDeliveryAddress
validation
protected function validateDeliveryAddress(SaleInterface $sale, Constraint $constraint) { /** @var Sale $constraint */ if (!$sale->isSameAddress() && null === $sale->getDeliveryAddress()) { $this->context ->buildViolation($constraint->delivery_address_is_required) ->atPath('deliveryAddress') ->addViolation(); } elseif ($sale->isSameAddress() && null !== $sale->getDeliveryAddress()) { $this->context ->buildViolation($constraint->delivery_address_should_be_null) ->atPath('deliveryAddress') ->addViolation(); } }
php
{ "resource": "" }
q248492
SaleValidator.validateIdentity
validation
protected function validateIdentity(SaleInterface $sale, Constraint $constraint) { /** @var Sale $constraint */ if (null === $sale->getCustomer()) { if (null === $sale->getCustomerGroup()) { $this->context ->buildViolation($constraint->customer_group_is_required_if_no_customer) ->atPath('customerGroup') ->addViolation(); } if (0 == strlen($sale->getEmail())) { $this->context ->buildViolation($constraint->email_is_required_if_no_customer) ->atPath('email') ->addViolation(); } IdentityValidator::validateIdentity($this->context, $sale); } }
php
{ "resource": "" }
q248493
SaleValidator.validatePaymentTermAndOutstandingLimit
validation
protected function validatePaymentTermAndOutstandingLimit(SaleInterface $sale, Constraint $constraint) { if (0 >= $sale->getOutstandingLimit()) { return; } if (null === $term = $sale->getPaymentTerm()) { if (null !== $customer = $sale->getCustomer()) { // From parent if available if ($customer->hasParent()) { $term = $customer->getParent()->getPaymentTerm(); } else { $term = $customer->getPaymentTerm(); } } } if (null === $term) { /** @var Sale $constraint */ $this->context ->buildViolation($constraint->outstanding_limit_require_term) ->atPath('outstandingLimit') ->addViolation(); } }
php
{ "resource": "" }
q248494
ShipmentMethodListener.getShipmentMethodFromEvent
validation
private function getShipmentMethodFromEvent(ResourceEventInterface $event) { $resource = $event->getResource(); if (!$resource instanceof ShipmentMethodInterface) { throw new InvalidArgumentException('Expected instance of ' . ShipmentMethodInterface::class); } return $resource; }
php
{ "resource": "" }
q248495
StockSubjectStates.isBetterState
validation
static public function isBetterState($stateA, $stateB) { // TODO Find something more explicit than 'better' (availability ?) // TODO assert valid states ? if ($stateA === static::STATE_IN_STOCK) { return $stateB !== static::STATE_IN_STOCK; } elseif ($stateA === static::STATE_PRE_ORDER) { return $stateB === static::STATE_OUT_OF_STOCK; } return false; }
php
{ "resource": "" }
q248496
AuthHelper.loggedIn
validation
public function loggedIn() { if ($this->_viewAuth) { return $this->sessionKey && $this->request->session()->check($this->sessionKey); } return false; }
php
{ "resource": "" }
q248497
AuthHelper.user
validation
public function user($key = null) { if ($this->sessionKey && $this->request->session()->check($this->sessionKey)) { $user = $this->request->session()->read($this->sessionKey); } else { return null; } if ($key === null) { return $user; } return Hash::get($user, $key); }
php
{ "resource": "" }
q248498
AuthHelper.urlAllowed
validation
public function urlAllowed($url) { if ($this->_viewAuth) { return $this->_viewAuth['AuthActions']->urlAllowed($this->user(), $url); } return false; }
php
{ "resource": "" }
q248499
AmountCalculator.mergeItemsResults
validation
protected function mergeItemsResults(Model\SaleItemInterface $item, Amount $result): void { // At this points items result are calculated and set. foreach ($item->getChildren() as $child) { if ($child->isPrivate()) { continue; } // Skip compound with only public children if (!($child->isCompound() && !$child->hasPrivateChildren())) { $result->merge($child->getResult()); } if ($child->hasChildren()) { $this->mergeItemsResults($child, $result); } } }
php
{ "resource": "" }