_id
stringlengths
2
7
title
stringlengths
3
151
partition
stringclasses
3 values
text
stringlengths
83
13k
language
stringclasses
1 value
meta_information
dict
q248100
SolsticeEquinoxTrait.solsticeDecember
validation
protected static function solsticeDecember($year, $vsop = true) { $month = 12; if ($vsop) return static::accurate($year, static::meanTerms($month, $year), $month); else return static::approx($year, static::meanTerms($month, $year)); }
php
{ "resource": "" }
q248101
SolsticeEquinoxTrait.horner
validation
private static function horner($x, $c) { if (count($c) == 0) throw new InvalidArgumentException('No coefficients were provided'); $i = count($c) - 1; $y = $c[$i]; while ($i > 0) { $i--; $y = $y * $x + $c[$i]; } return $y; }
php
{ "resource": "" }
q248102
AbstractValueViewer.doDefaultValueConversionByType
validation
public function doDefaultValueConversionByType($value, $type, array $record) { switch ($type) { case static::TYPE_DATETIME: return date(static::FORMAT_DATETIME, is_numeric($value) ? $value : strtotime($value)); case static::TYPE_DATE: return date(static::FORMAT_DATE, is_numeric($value) ? $value : strtotime($value)); case static::TYPE_TIME: return date(static::FORMAT_TIME, is_numeric($value) ? $value : strtotime($value)); case static::TYPE_MULTILINE: return '<pre class="multiline-text">' . $value . '</pre>'; case static::TYPE_JSON: case static::TYPE_JSONB: if (!is_array($value) && $value !== null) { if (is_string($value) || is_numeric($value) || is_bool($value)) { $value = json_decode($value, true); if ($value === null && strtolower($value) !== 'null') { $value = 'Failed to decode JSON: ' . print_r($value, true); } } else { $value = 'Invalid value for JSON: ' . print_r($value, true); } } return '<pre class="json-text">' . htmlentities(stripslashes(json_encode($value, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE))) . '</pre>'; break; } return $value; }
php
{ "resource": "" }
q248103
NotifyMeServiceProvider.registerFactory
validation
protected function registerFactory() { $this->app->singleton('notifyme.factory', function () { return new NotifyMeFactory(); }); $this->app->alias('notifyme.factory', NotifyMeFactory::class); $this->app->alias('notifyme.factory', FactoryInterface::class); }
php
{ "resource": "" }
q248104
NotifyMeServiceProvider.registerManager
validation
protected function registerManager() { $this->app->singleton('notifyme', function ($app) { $config = $app['config']; $factory = $app['notifyme.factory']; return new NotifyMeManager($config, $factory); }); $this->app->alias('notifyme', NotifyMeManager::class); $this->app->alias('notifyme', ManagerInterface::class); }
php
{ "resource": "" }
q248105
AbstractInvoiceListener.updateTotals
validation
protected function updateTotals(InvoiceInterface $invoice) { $changed = $this->invoiceCalculator->calculate($invoice); if ($changed) { foreach ($invoice->getLines() as $line) { $this->persistenceHelper->persistAndRecompute($line, false); } } return $changed; }
php
{ "resource": "" }
q248106
AbstractInvoiceListener.updateCustomerBalance
validation
protected function updateCustomerBalance(InvoiceInterface $invoice) { // Abort if not credit if (!InvoiceTypes::isCredit($invoice)) { return; } $sale = $this->getSaleFromInvoice($invoice); // Abort if no customer if (null === $customer = $sale->getCustomer()) { return; } $methodCs = $this->persistenceHelper->getChangeSet($invoice, 'paymentMethod'); $amountCs = $this->persistenceHelper->getChangeSet($invoice, 'grandTotal'); // Debit grand total if invoice is removed // TODO Multiple call will credit too much ! if ($this->persistenceHelper->isScheduledForRemove($invoice)) { $method = empty($methodCs) ? $invoice->getPaymentMethod() : $methodCs[0]; $amount = empty($amountCs) ? $invoice->getGrandTotal(): $amountCs[0]; if ($method && $method->isCredit() && 0 != Money::compare($amount, 0, $invoice->getCurrency())) { $this->customerUpdater->updateCreditBalance($customer, -$amount, true); } return; } // Abort if nothing has changed if (empty($methodCs) && empty($amountCs)) { return; } // Debit old method customer balance /** @var \Ekyna\Component\Commerce\Payment\Model\PaymentMethodInterface $method */ if (!empty($methodCs) && null !== $method = $methodCs[0]) { $amount = empty($amountCs) ? $invoice->getGrandTotal(): $amountCs[0]; if ($method->isCredit() && 0 != Money::compare($amount, 0, $invoice->getCurrency())) { $this->customerUpdater->updateCreditBalance($customer, -$amount, true); } } // Credit new method customer balance if (empty($methodCs)) { $method = $invoice->getPaymentMethod(); $amount = empty($amountCs) ? $invoice->getGrandTotal(): $amountCs[1] - $amountCs[0]; } else { /** @var \Ekyna\Component\Commerce\Payment\Model\PaymentMethodInterface $method */ $method = $methodCs[1]; $amount = empty($amountCs) ? $invoice->getGrandTotal(): $amountCs[1]; } if ($method && $method->isCredit() && 0 != Money::compare($amount, 0, $invoice->getCurrency())) { $this->customerUpdater->updateCreditBalance($customer, $amount, true); } }
php
{ "resource": "" }
q248107
AbstractInvoiceListener.preventForbiddenChange
validation
protected function preventForbiddenChange(InvoiceInterface $invoice) { if ($this->persistenceHelper->isChanged($invoice, 'type')) { list($old, $new) = $this->persistenceHelper->getChangeSet($invoice, 'type'); if ($old != $new) { throw new Exception\IllegalOperationException( "Changing the invoice type is not yet supported." ); } } }
php
{ "resource": "" }
q248108
AbstractInvoiceListener.getSaleFromInvoice
validation
protected function getSaleFromInvoice(InvoiceInterface $invoice) { if (null === $sale = $invoice->getSale()) { $cs = $this->persistenceHelper->getChangeSet($invoice, $this->getSalePropertyPath()); if (!empty($cs)) { $sale = $cs[0]; } } if (!$sale instanceof SaleInterface) { throw new Exception\RuntimeException("Failed to retrieve invoice's sale."); } return $sale; }
php
{ "resource": "" }
q248109
InvoicePaymentResolver.buildInvoicePayments
validation
protected function buildInvoicePayments(SaleInterface $sale) { $currency = $sale->getCurrency()->getCode(); // TODO Deal with currency conversions. $payments = $this->buildPaymentList($sale); /** @var IM\InvoiceSubjectInterface $sale */ $invoices = $this->buildInvoiceList($sale); foreach ($invoices as $x => &$i) { $oid = spl_object_id($i['invoice']); $this->cache[$oid] = []; foreach ($payments as $y => &$p) { $r = new IM\InvoicePayment(); $r->setPayment($p['payment']); $c = Money::compare($i['total'], $p['amount'], $currency); if (0 === $c) { // Equal $r->setAmount($p['amount']); $i['total'] = 0; $p['amount'] = 0; unset($payments[$y]); } elseif (1 === $c) { // invoice > payment $r->setAmount($p['amount']); $i['total'] -= $p['amount']; $p['amount'] = 0; unset($payments[$y]); } else { // payment > invoice $r->setAmount($i['total']); $p['amount'] -= $i['total']; $i['total'] = 0; } $this->cache[$oid][] = $r; unset($p); } unset($i); } }
php
{ "resource": "" }
q248110
InvoicePaymentResolver.buildInvoiceList
validation
protected function buildInvoiceList(IM\InvoiceSubjectInterface $subject) { $invoices = $subject->getInvoices(true)->toArray(); usort($invoices, function (IM\InvoiceInterface $a, IM\InvoiceInterface $b) { return $a->getCreatedAt()->getTimestamp() - $b->getCreatedAt()->getTimestamp(); }); return array_map(function (IM\InvoiceInterface $invoice) { return [ 'invoice' => $invoice, 'total' => $invoice->getGrandTotal(), ]; }, $invoices); }
php
{ "resource": "" }
q248111
InvoicePaymentResolver.buildPaymentList
validation
protected function buildPaymentList(PM\PaymentSubjectInterface $subject) { // TODO Deal with refund when implemented $payments = array_filter($subject->getPayments()->toArray(), function (PM\PaymentInterface $p) { if ($p->getMethod()->isOutstanding()) { return false; } if (!PM\PaymentStates::isPaidState($p->getState())) { return false; } return true; }); usort($payments, function (PM\PaymentInterface $a, PM\PaymentInterface $b) { return $a->getCompletedAt()->getTimestamp() - $b->getCompletedAt()->getTimestamp(); }); // TODO Currency conversion return array_map(function (PM\PaymentInterface $payment) { return [ 'payment' => $payment, 'amount' => $payment->getAmount(), ]; }, $payments); }
php
{ "resource": "" }
q248112
ShipmentBuilder.initializeMethod
validation
private function initializeMethod(ShipmentInterface $shipment) { // Abort if shipment's method is defined if (null !== $shipment->getMethod()) { return; } $sale = $shipment->getSale(); // Abort if default method is not defined if (null === $method = $sale->getShipmentMethod()) { return; } $gateway = $this->registry->getGateway($method->getGatewayName()); // Set shipment method if supported if (!$shipment->isReturn() && $gateway->supports(GatewayInterface::CAPABILITY_SHIPMENT)) { $shipment->setMethod($method); return; } // Set return method if supported if ($shipment->isReturn() && $gateway->supports(GatewayInterface::CAPABILITY_RETURN)) { $shipment->setMethod($method); return; } }
php
{ "resource": "" }
q248113
ShipmentBuilder.initializeRelayPoint
validation
private function initializeRelayPoint(ShipmentInterface $shipment) { // Abort if shipment method is not defined if (null === $method = $shipment->getMethod()) { // Clear the relay point if it is set if (null !== $shipment->getRelayPoint()) { $shipment->setRelayPoint(null); } return; } $gateway = $this->registry->getGateway($method->getGatewayName()); // If gateway does not support relay point if (!$gateway->supports(GatewayInterface::CAPABILITY_RELAY)) { // Clear the relay point if it is set if (null !== $shipment->getRelayPoint()) { $shipment->setRelayPoint(null); } return; } // Set default relay point if (null !== $relayPoint = $shipment->getSale()->getRelayPoint()) { $shipment->setRelayPoint($relayPoint); } }
php
{ "resource": "" }
q248114
ShipmentBuilder.buildItem
validation
protected function buildItem(SaleItemInterface $saleItem, ShipmentInterface $shipment) { // If compound with only private children if ($saleItem->isCompound()) { // Resolve available and expected quantities by building children $available = $expected = null; foreach ($saleItem->getChildren() as $childSaleItem) { if (null !== $child = $this->buildItem($childSaleItem, $shipment)) { $saleItemQty = $childSaleItem->getQuantity(); $e = $child->getExpected() / $saleItemQty; if (null === $expected || $expected > $e) { $expected = $e; } $a = $child->getAvailable() / $saleItemQty; if (null === $available || $available > $a) { $available = $a; } } } // If any children is expected if (0 < $expected) { return $this->findOrCreateItem($shipment, $saleItem, $expected, $available); } return null; } $item = null; // Skip compound with only public children if (!($saleItem->isCompound() && !$saleItem->hasPrivateChildren())) { $expected = $shipment->isReturn() ? $this->calculator->calculateReturnableQuantity($saleItem, $shipment) : $this->calculator->calculateShippableQuantity($saleItem, $shipment); if (0 < $expected) { $item = $this->findOrCreateItem($shipment, $saleItem, $expected); } } // Build children if ($saleItem->hasChildren()) { foreach ($saleItem->getChildren() as $childSaleItem) { $this->buildItem($childSaleItem, $shipment); } } return $item; }
php
{ "resource": "" }
q248115
ShipmentBuilder.findOrCreateItem
validation
private function findOrCreateItem(ShipmentInterface $shipment, SaleItemInterface $saleItem, $expected, $available = null) { $item = null; if (0 >= $expected) { return $item; } // Existing item lookup foreach ($shipment->getItems() as $i) { if ($i->getSaleItem() === $saleItem) { $item = $i; break; } } // Not found, create it if (null === $item) { $item = $this->factory->createItemForShipment($shipment); $item->setShipment($shipment); $item->setSaleItem($saleItem); } // Set expected quantity $item->setExpected($expected); if ($shipment->isReturn()) { // Set expected quantity as available $item->setAvailable($expected); } else { if (null === $available) { $available = $this->calculator->calculateAvailableQuantity($saleItem, $shipment); } // Set available quantity $item->setAvailable($available); // Set default quantity for new non return shipment items if (null === $shipment->getId()) { $item->setQuantity(min($expected, $available)); } } return $item; }
php
{ "resource": "" }
q248116
Db.query
validation
public static function query($queryString, array $queryParams = [], $dbName = "master", $fetchResults = true) { // Prepare query $query = static::instance($dbName)->prepare($queryString); foreach ($queryParams as $column => $val) $query->bindValue(is_int($column) ? $column + 1 : ":".$column, $val); // Execute if ($query->execute()) return $fetchResults ? $query->fetchAll(PDO::FETCH_ASSOC) : $query->rowCount(); return false; }
php
{ "resource": "" }
q248117
OrderStatRepository.findRevenues
validation
private function findRevenues($type, \DateTime $from, \DateTime $to = null, $detailed = false) { if ($type === OrderStat::TYPE_DAY) { if (null === $to) { $from = (clone $from)->modify('first day of this month'); $to = (clone $from)->modify('last day of this month'); } $interval = new \DateInterval('P1D'); $format = 'Y-m-d'; } elseif ($type === OrderStat::TYPE_MONTH) { if (null === $to) { $from = (clone $from)->modify('first day of january ' . $from->format('Y')); $to = (clone $from)->modify('last day of december ' . $from->format('Y')); } $interval = new \DateInterval('P1M'); $format = 'Y-m'; } else { throw new InvalidArgumentException("Unexpected order stat type."); } $result = $this ->getRevenueQuery() ->setParameters([ 'type' => $type, 'from' => $from->format($format), 'to' => $to->format($format), ]) ->getScalarResult(); $data = $this->buildRevenueData($result, $detailed); $period = new \DatePeriod($from, $interval, $to); $defaults = $detailed ? [] : 0; if ($detailed) { foreach (SaleSources::getSources() as $source) { $defaults[$source] = 0; } } /** @var \DateTime $d */ foreach ($period as $d) { $index = $d->format($format); if (!isset($data[$index])) { $data[$index] = $defaults; }; } ksort($data); return $data; }
php
{ "resource": "" }
q248118
OrderStatRepository.buildRevenueData
validation
private function buildRevenueData(array $result, $detailed = false) { $data = []; foreach ($result as $r) { $data[$r['date']] = $detailed ? json_decode($r['details'], true) : $r['revenue']; } return $data; }
php
{ "resource": "" }
q248119
OrderStatRepository.getRevenueQuery
validation
private function getRevenueQuery() { if (null !== $this->revenueQuery) { return $this->revenueQuery; } $qb = $this->createQueryBuilder('o'); $expr = $qb->expr(); return $this->revenueQuery = $qb ->select(['o.date', 'o.revenue', 'o.details']) ->andWhere($expr->eq('o.type', ':type')) ->andWhere($expr->gte('o.date', ':from')) ->andWhere($expr->lte('o.date', ':to')) ->addOrderBy('o.date') ->getQuery(); }
php
{ "resource": "" }
q248120
DataGridConfig.finish
validation
public function finish() { parent::finish(); if ($this->isRowActionsEnabled() && !$this->hasValueViewer(static::ROW_ACTIONS_COLUMN_NAME)) { $this->addValueViewer(static::ROW_ACTIONS_COLUMN_NAME, null); } if ($this->isNestedViewEnabled() && !$this->hasValueViewer($this->getColumnNameForNestedView())) { $this->addValueViewer($this->getColumnNameForNestedView(), DataGridColumn::create()->setIsVisible(false)); } if ($this->isRowsReorderingEnabled()) { $reorderingColumns = $this->getRowsPositioningColumns(); $allowedColumnTypes = [Column::TYPE_INT, Column::TYPE_FLOAT, Column::TYPE_UNIX_TIMESTAMP]; foreach ($reorderingColumns as $columnName) { if (!$this->hasValueViewer($columnName)) { throw new NotFoundException( "Column '$columnName' provided for reordering was not found within declared data grid columns" ); } $valueViewer = $this->getValueViewer($columnName); if (!$valueViewer->isLinkedToDbColumn() && $valueViewer->getTableColumn()->isItExistsInDb()) { throw new \UnexpectedValueException( "Column '$columnName' provided for reordering must be linked to a column that exists in database" ); } $colType = $valueViewer->getTableColumn()->getType(); if (!in_array($colType, $allowedColumnTypes, true)) { throw new \UnexpectedValueException( "Column '$columnName' provided for reordering should be of a numeric type (int, float, unix ts)." . "'{$colType}' type is not acceptable'" ); } $valueViewer->setIsSortable(true); } } }
php
{ "resource": "" }
q248121
ShipmentAddressTransformer.transform
validation
public function transform($data) { $address = new ShipmentAddress(); if (!is_array($data) || empty($data)) { return $address; } foreach ($this->fields as $field) { if (isset($data[$field])) { $value = $data[$field]; if ($field === 'country') { if (0 >= $value) { throw new InvalidArgumentException("Invalid country id."); } $value = $this->countryRepository->find($value); if (null === $value) { throw new InvalidArgumentException("Country not found."); } } elseif ($field === 'phone' || $field === 'mobile') { $value = unserialize($value); if (!$value instanceof PhoneNumber) { throw new InvalidArgumentException("Invalid phone number."); } } $this->accessor->setValue($address, $field, $value); } // TODO Check required fields ? } return $address; }
php
{ "resource": "" }
q248122
ShipmentAddressTransformer.reverseTransform
validation
public function reverseTransform($address) { if (null === $address) { return null; } if (!$address instanceof ShipmentAddress) { throw new InvalidArgumentException("Expected instance of " . ShipmentAddress::class); } $data = []; foreach ($this->fields as $field) { $value = $this->accessor->getValue($address, $field); if (empty($value)) { continue; } if ($value instanceof CountryInterface) { $value = $value->getId(); } elseif ($value instanceof StateInterface) { $value = $value->getId(); } elseif ($value instanceof PhoneNumber) { $value = serialize($value); } $data[$field] = $value; } if (empty($data)) { return null; } return $data; }
php
{ "resource": "" }
q248123
Num.format
validation
public static function format($number, $places, $monetary = FALSE) { $info = localeconv(); if ($monetary) { $decimal = $info['mon_decimal_point']; $thousands = $info['mon_thousands_sep']; } else { $decimal = $info['decimal_point']; $thousands = $info['thousands_sep']; } return number_format($number, $places, $decimal, $thousands); }
php
{ "resource": "" }
q248124
NotificationTypes.getTypes
validation
static public function getTypes() { return [ static::MANUAL, static::CART_REMIND, static::ORDER_ACCEPTED, static::QUOTE_REMIND, static::PAYMENT_CAPTURED, static::PAYMENT_EXPIRED, static::SHIPMENT_SHIPPED, static::SHIPMENT_PARTIAL, static::RETURN_PENDING, static::RETURN_RECEIVED, ]; }
php
{ "resource": "" }
q248125
NotificationTypes.isValidType
validation
static public function isValidType($type, $throw = true) { if (in_array($type, static::getTypes(), true)) { return true; } if ($throw) { throw new InvalidArgumentException('Invalid notification type.'); } return false; }
php
{ "resource": "" }
q248126
Client.lookupPostcodeAddresses
validation
public function lookupPostcodeAddresses( $postcode ){ $path = self::PATH_LOOKUP_POSTCODE; $response = $this->httpGet( $path, [ 'postcode' => $postcode ] ); return Response\AddressList::buildFromResponse( $response ); }
php
{ "resource": "" }
q248127
Client.lookupPostcodeMetadata
validation
public function lookupPostcodeMetadata( $postcode ){ $path = sprintf( self::PATH_LOOKUP_METADATA, $postcode ); $response = $this->httpGet( $path ); return Response\PostcodeInfo::buildFromResponse( $response ); }
php
{ "resource": "" }
q248128
Client.httpGet
validation
private function httpGet( $path, array $query = array() ){ $url = new Uri( $this->baseUrl . $path ); foreach( $query as $name => $value ){ $url = Uri::withQueryValue($url, $name, $value ); } //--- $request = new Request( 'GET', $url, $this->buildHeaders() ); try { $response = $this->getHttpClient()->sendRequest( $request ); } catch (\RuntimeException $e){ throw new Exception\PostcodeException( $e->getMessage(), $e->getCode(), $e ); } //--- if( $response->getStatusCode() != 200 ){ throw $this->createErrorException( $response ); } return $response; }
php
{ "resource": "" }
q248129
Client.createErrorException
validation
protected function createErrorException( ResponseInterface $response ){ $body = json_decode($response->getBody(), true); $message = "HTTP:{$response->getStatusCode()} - "; $message .= (is_array($body)) ? print_r($body, true) : 'Unexpected response from server'; return new Exception\ApiException( $message, $response->getStatusCode(), $response ); }
php
{ "resource": "" }
q248130
StockUnitAssigner.getAssignments
validation
protected function getAssignments($item) { if ($item instanceof ShipmentItemInterface) { $item = $item->getSaleItem(); } elseif ($item instanceof InvoiceLineInterface) { if (!$item = $item->getSaleItem()) { return null; } } if (!$this->supportsAssignment($item)) { return null; } return $item->getStockAssignments()->toArray(); }
php
{ "resource": "" }
q248131
StockUnitAssigner.removeAssignment
validation
protected function removeAssignment(StockAssignmentInterface $assignment) { $this->unitUpdater->updateSold($assignment->getStockUnit(), -$assignment->getSoldQuantity(), true); $assignment ->setSaleItem(null) ->setStockUnit(null); $this->persistenceHelper->remove($assignment); }
php
{ "resource": "" }
q248132
StockUnitAssigner.createAssignmentsForQuantity
validation
protected function createAssignmentsForQuantity(SaleItemInterface $item, $quantity) { if (0 >= $quantity) { return; } // Find enough available stock units $stockUnits = $this->sortStockUnits($this->unitResolver->findAssignable($item)); foreach ($stockUnits as $stockUnit) { $assignment = $this->saleFactory->createStockAssignmentForItem($item); $assignment ->setSaleItem($item) ->setStockUnit($stockUnit); $quantity -= $this->assignmentUpdater->updateSold($assignment, $quantity); if (0 == $quantity) { return; } } // Remaining quantity if (0 < $quantity) { $stockUnit = $this->unitResolver->createBySubjectRelative($item); $assignment = $this->saleFactory->createStockAssignmentForItem($item); $assignment ->setSaleItem($item) ->setStockUnit($stockUnit); $quantity -= $this->assignmentUpdater->updateSold($assignment, $quantity); } if (0 < $quantity) { throw new StockLogicException(sprintf( 'Failed to create assignments for item "%s".', $item->getDesignation() )); } }
php
{ "resource": "" }
q248133
StockUnitAssigner.resolveSoldDeltaQuantity
validation
protected function resolveSoldDeltaQuantity(SaleItemInterface $item) { $old = $new = $item->getQuantity(); // Own item quantity changes if ($this->persistenceHelper->isChanged($item, 'quantity')) { list($old, $new) = $this->persistenceHelper->getChangeSet($item, 'quantity'); } // Parent items quantity changes $parent = $item; while (null !== $parent = $parent->getParent()) { if ($this->persistenceHelper->isChanged($parent, 'quantity')) { list($parentOld, $parentNew) = $this->persistenceHelper->getChangeSet($parent, 'quantity'); } else { $parentOld = $parentNew = $parent->getQuantity(); } $old *= $parentOld; $new *= $parentNew; } // Sale released change $sale = $item->getSale(); $shippedOld = $shippedNew = 0; $f = $t = false; if ($this->persistenceHelper->isChanged($sale, 'released')) { list($f, $t) = $this->persistenceHelper->getChangeSet($sale, 'released'); } elseif ($item->getSale()->isReleased()) { $f = $t = true; } if ($f || $t) { /** @var StockAssignmentsInterface $item */ foreach ($item->getStockAssignments() as $assignment) { if ($this->persistenceHelper->isChanged($assignment, 'shippedQuantity')) { list($o, $n) = $this->persistenceHelper->getChangeSet($assignment, 'shippedQuantity'); } else { $o = $n = $assignment->getShippedQuantity(); } if ($f) { $shippedOld += $o; } if ($t) { $shippedNew += $n; } } if ($f) { $old = min($old, $shippedOld); } if ($t) { $new = min($new, $shippedNew); } } return $new - $old; }
php
{ "resource": "" }
q248134
StockUnitAssigner.sortAssignments
validation
protected function sortAssignments(array $assignments) { usort($assignments, function (StockAssignmentInterface $a1, StockAssignmentInterface $a2) { $u1 = $a1->getStockUnit(); $u2 = $a2->getStockUnit(); return $this->compareStockUnit($u1, $u2); }); return $assignments; }
php
{ "resource": "" }
q248135
StockUnitAssigner.compareStockUnitByPrice
validation
protected function compareStockUnitByPrice(StockUnitInterface $u1, StockUnitInterface $u2) { $u1HasPrice = 0 < $u1->getNetPrice(); $u2HasPrice = 0 < $u2->getNetPrice(); if (!$u1HasPrice && $u2HasPrice) { return 1; } if ($u1HasPrice && !$u2HasPrice) { return -1; } if ($u1->getNetPrice() != $u2->getNetPrice()) { return $u1->getNetPrice() > $u2->getNetPrice() ? 1 : -1; } return 0; }
php
{ "resource": "" }
q248136
StockUnitAssigner.compareStockUnitByEda
validation
protected function compareStockUnitByEda(StockUnitInterface $u1, StockUnitInterface $u2) { $u1HasEda = null !== $u1->getEstimatedDateOfArrival(); $u2HasEda = null !== $u2->getEstimatedDateOfArrival(); if (!$u1HasEda && $u2HasEda) { return 1; } if ($u1HasEda && !$u2HasEda) { return -1; } if ($u1->getEstimatedDateOfArrival() != $u2->getEstimatedDateOfArrival()) { return $u1->getEstimatedDateOfArrival() > $u2->getEstimatedDateOfArrival() ? 1 : -1; } return 0; }
php
{ "resource": "" }
q248137
Session.set
validation
public function set($key, $value) { $this->open(); $this->_data[$key] = $value; return $this; }
php
{ "resource": "" }
q248138
Session.bind
validation
public function bind($key, & $value) { $this->open(); $this->_data[$key] =& $value; return $this; }
php
{ "resource": "" }
q248139
Session.delete
validation
public function delete(...$args) { $this->open(); foreach ($args as $key) { unset($this->_data[$key]); } return $this; }
php
{ "resource": "" }
q248140
Session.regenerate
validation
public function regenerate($delete_old = false) { if ($this->is_active()) { // Regenerate the session id @session_regenerate_id($delete_old); } else { $this->open(); } return session_id(); }
php
{ "resource": "" }
q248141
Session.close
validation
public function close(): void { if ($this->is_active()) { // Set the last active timestamp $this->_data['last_active'] = time(); // Write and close the session config('debug') ? session_write_close() : @session_write_close(); } }
php
{ "resource": "" }
q248142
Session.destroy
validation
public function destroy(): void { if ($this->is_active()) { session_unset(); session_destroy(); $this->_data = []; // Make sure the session cannot be restarted Cookie::delete($this->name); } }
php
{ "resource": "" }
q248143
Pagination.url
validation
public function url($page = 1) { // Clean the page number $page = max(1, (int)$page); // No page number in URLs to first page if ($page === 1 AND !$this->first_page_in_url) { $page = NULL; } switch ($this->current_page_source) { case 'query_string': case 'mixed': return URL::site($this->request->uri() . $this->query([$this->current_page_source_key => $page])); case 'route': return URL::site($this->route->url(array_merge($this->route_params, array($this->current_page_source_key => $page))) . $this->query()); } return '#'; }
php
{ "resource": "" }
q248144
Pagination.render
validation
public function render($block = null) { // Automatically hide pagination whenever it is superfluous if ($this->auto_hide === true AND $this->total_pages <= 1) return ''; if ($block === null) { // Use the view from config $block = $this->block; } if (!$block instanceof Block) { // Load the view file $block = block($block); } // Pass on the whole Pagination object return $block->set(get_object_vars($this))->set('page', $this)->render(); }
php
{ "resource": "" }
q248145
Chains.runWild
validation
public function runWild(){ foreach ($this->handlers as $handler){ $rtn = $handler instanceof Closure ? $this->context->call($handler,$this->req) : $this->context->callInClass($handler,$this->action,$this->req); if (!is_null($rtn)) return $rtn; } return null; }
php
{ "resource": "" }
q248146
Notify.removeRecipient
validation
public function removeRecipient(Recipient $recipient) { if ($this->recipients->contains($recipient)) { $this->recipients->removeElement($recipient); } return $this; }
php
{ "resource": "" }
q248147
Notify.addExtraRecipient
validation
public function addExtraRecipient(Recipient $recipient) { if (!$this->extraRecipients->contains($recipient)) { $this->extraRecipients->add($recipient); } return $this; }
php
{ "resource": "" }
q248148
Notify.removeExtraRecipient
validation
public function removeExtraRecipient(Recipient $recipient) { if ($this->extraRecipients->contains($recipient)) { $this->extraRecipients->removeElement($recipient); } return $this; }
php
{ "resource": "" }
q248149
Notify.addCopy
validation
public function addCopy(Recipient $copy) { if (!$this->copies->contains($copy)) { $this->copies->add($copy); } return $this; }
php
{ "resource": "" }
q248150
Notify.removeCopy
validation
public function removeCopy(Recipient $copy) { if ($this->copies->contains($copy)) { $this->copies->removeElement($copy); } return $this; }
php
{ "resource": "" }
q248151
Notify.addExtraCopy
validation
public function addExtraCopy(Recipient $copy) { if (!$this->extraCopies->contains($copy)) { $this->extraCopies->add($copy); } return $this; }
php
{ "resource": "" }
q248152
Notify.removeExtraCopy
validation
public function removeExtraCopy(Recipient $copy) { if ($this->extraCopies->contains($copy)) { $this->extraCopies->removeElement($copy); } return $this; }
php
{ "resource": "" }
q248153
Notify.addInvoice
validation
public function addInvoice(InvoiceInterface $invoice) { if (!$this->invoices->contains($invoice)) { $this->invoices->add($invoice); } return $this; }
php
{ "resource": "" }
q248154
Notify.addShipment
validation
public function addShipment(ShipmentInterface $shipment) { if (!$this->shipments->contains($shipment)) { $this->shipments->add($shipment); } return $this; }
php
{ "resource": "" }
q248155
Notify.removeShipment
validation
public function removeShipment(ShipmentInterface $shipment) { if ($this->shipments->contains($shipment)) { $this->shipments->removeElement($shipment); } return $this; }
php
{ "resource": "" }
q248156
Notify.addAttachment
validation
public function addAttachment(AttachmentInterface $attachment) { if (!$this->attachments->contains($attachment)) { $this->attachments->add($attachment); } return $this; }
php
{ "resource": "" }
q248157
Notify.removeAttachment
validation
public function removeAttachment(AttachmentInterface $attachment) { if ($this->attachments->contains($attachment)) { $this->attachments->removeElement($attachment); } return $this; }
php
{ "resource": "" }
q248158
Notify.isEmpty
validation
public function isEmpty() { return empty($this->subject) || (empty($this->customMessage) && empty($this->paymentMessage) && empty($this->shipmentMessage)); }
php
{ "resource": "" }
q248159
AdjustableTrait.hasAdjustments
validation
public function hasAdjustments($type = null) { if (null !== $type) { AdjustmentTypes::isValidType($type); return $this->getAdjustments($type)->count(); } return 0 < $this->adjustments->count(); }
php
{ "resource": "" }
q248160
AdjustableTrait.getAdjustments
validation
public function getAdjustments($type = null) { if (null !== $type) { AdjustmentTypes::isValidType($type); return $this ->adjustments ->filter(function (AdjustmentInterface $a) use ($type) { return $a->getType() === $type; }); } return $this->adjustments; }
php
{ "resource": "" }
q248161
IdentityValidator.validateIdentity
validation
static public function validateIdentity( ExecutionContextInterface $context, IdentityInterface $identity, array $config = [], $pathPrefix = null ) { $violationList = $context->getValidator()->validate($identity, [new Identity($config)]); if (!empty($pathPrefix)) { $pathPrefix = rtrim($pathPrefix, '.') . '.'; } /** @var \Symfony\Component\Validator\ConstraintViolationInterface $violation */ foreach ($violationList as $violation) { $context ->buildViolation($violation->getMessage()) ->atPath($pathPrefix . $violation->getPropertyPath()) ->addViolation(); } }
php
{ "resource": "" }
q248162
ResolvedTaxesCache.get
validation
public function get(TaxGroupInterface $taxGroup, CountryInterface $country, $business = false) { $key = $this->buildKey($taxGroup, $country, $business); if (isset($this->taxes[$key])) { return $this->taxes[$key]; } return null; }
php
{ "resource": "" }
q248163
ResolvedTaxesCache.set
validation
public function set(TaxGroupInterface $taxGroup, CountryInterface $country, $business = false, array $taxes) { $key = $this->buildKey($taxGroup, $country, $business); $this->taxes[$key] = $taxes; }
php
{ "resource": "" }
q248164
ResolvedTaxesCache.buildKey
validation
private function buildKey(TaxGroupInterface $taxGroup, CountryInterface $country, $business = false) { return sprintf('%s-%s-%s', $taxGroup->getId(), $country->getId(), (int)$business); }
php
{ "resource": "" }
q248165
ShipmentRuleRepository.getFindOneBySaleQuery
validation
protected function getFindOneBySaleQuery() { if (null !== $this->findOneBySaleQuery) { return $this->findOneBySaleQuery; } $qb = $this->createQueryBuilder('r'); $e = $qb->expr(); return $this->findOneBySaleQuery = $qb ->andWhere($e->orX( $e->andX( $e->eq('r.vatMode', ':net_mode'), $e->lte('r.baseTotal', ':net_base') ), $e->andX( $e->eq('r.vatMode', ':ati_mode'), $e->lte('r.baseTotal', ':ati_base') ) )) ->andWhere($e->orX( 'r.methods IS EMPTY', $e->isMemberOf(':method', 'r.methods') )) ->andWhere($e->orX( 'r.countries IS EMPTY', $e->isMemberOf(':country', 'r.countries') )) ->andWhere($e->orX( 'r.customerGroups IS EMPTY', $e->isMemberOf(':group', 'r.customerGroups') )) ->andWhere($e->orX( 'r.startAt IS NULL', $e->lte('r.startAt', ':date') )) ->andWhere($e->orX( 'r.endAt IS NULL', $e->gte('r.endAt', ':date') )) ->getQuery() ->setMaxResults(1) ->useQueryCache(true); }
php
{ "resource": "" }
q248166
ShipmentPriceRepository.getFindOneByCountryAndMethodAndWeightQuery
validation
private function getFindOneByCountryAndMethodAndWeightQuery() { if (null === $this->findOneByCountryAndMethodAndWeightQuery) { $qb = $this->getCollectionQueryBuilder('o'); $qb ->join('o.zone', 'z') ->join('o.method', 'm') ->andWhere($qb->expr()->isMemberOf(':country', 'z.countries')) ->andWhere($qb->expr()->gte('o.weight', ':weight')) ->andWhere($qb->expr()->eq('o.method', ':method')) ->addOrderBy('o.weight', 'ASC') ->setMaxResults(1) ; $this->findOneByCountryAndMethodAndWeightQuery = $qb->getQuery(); } return $this->findOneByCountryAndMethodAndWeightQuery; }
php
{ "resource": "" }
q248167
AbstractNotifyListener.didStateChangeTo
validation
protected function didStateChangeTo($resource, $state) { if (empty($stateCs = $this->tracker->getChangeSet($resource, 'state'))) { return false; } if ($stateCs[1] === $state && $stateCs[0] !== $state) { return true; } return false; }
php
{ "resource": "" }
q248168
AbstractNotifyListener.notify
validation
protected function notify($type, $resource) { // Create $notify = $this->builder->create($type, $resource); // Build if (!$this->builder->build($notify)) { return; } // Enqueue $this->queue->add($notify); }
php
{ "resource": "" }
q248169
InvoiceSynchronizer.persistInvoice
validation
private function persistInvoice(Invoice\InvoiceInterface $invoice) { $this->persistenceHelper->persistAndRecompute($invoice, true); foreach ($invoice->getLines() as $line) { $this->persistenceHelper->persistAndRecompute($line, true); } // Persist the shipment <-> invoice relation, without scheduling event. $this->persistenceHelper->persistAndRecompute($invoice->getShipment(), false); }
php
{ "resource": "" }
q248170
InvoiceSynchronizer.checkShipmentInvoice
validation
private function checkShipmentInvoice(Invoice\InvoiceInterface $invoice) { if (null === $shipment = $invoice->getShipment()) { throw new LogicException("Invoice's shipment must be set at this point."); } // Check sale integrity if ($shipment->getSale() !== $sale = $invoice->getSale()) { throw new LogicException("Shipment/Invoice sale miss match."); } // Sale must be a invoice subject if (!$sale instanceof Invoice\InvoiceSubjectInterface) { throw new LogicException("Expected instance of " . Invoice\InvoiceSubjectInterface::class); } // Check shipment/invoice types integrity. if ($shipment->isReturn() && !Invoice\InvoiceTypes::isCredit($invoice)) { throw new LogicException("Invoice should not be associated with Return."); } elseif (!$shipment->isReturn() && !Invoice\InvoiceTypes::isInvoice($invoice)) { throw new LogicException("Credit should not be associated with Shipment."); } }
php
{ "resource": "" }
q248171
InvoiceSynchronizer.purgeShipmentInvoice
validation
private function purgeShipmentInvoice(Invoice\InvoiceInterface $invoice) { $changed = false; $shipment = $invoice->getShipment(); // Remove unexpected good lines /** @var Invoice\InvoiceLineInterface $line */ foreach ($invoice->getLinesByType(Document\DocumentLineTypes::TYPE_GOOD) as $line) { foreach ($shipment->getItems() as $shipmentItem) { if ($line->getSaleItem() === $shipmentItem->getSaleItem()) { continue 2; // Shipment item found -> next invoice line } } // Shipment item not found -> remove line $invoice->removeLine($line); $this->persistenceHelper->remove($line, false); $changed = true; } $sale = $invoice->getSale(); // Remove unexpected discount lines foreach ($invoice->getLinesByType(Document\DocumentLineTypes::TYPE_DISCOUNT) as $line) { foreach ($sale->getAdjustments(Common\AdjustmentTypes::TYPE_DISCOUNT) as $saleAdjustment) { if ($line->getSaleAdjustment() === $saleAdjustment) { continue 2; // Sale adjustment found -> next invoice line } } // Sale adjustment not found -> remove line $invoice->removeLine($line); $this->persistenceHelper->remove($line, false); $changed = true; } // Remove unexpected shipment lines if (null === $sale->getShipmentMethod()) { foreach ($invoice->getLinesByType(Document\DocumentLineTypes::TYPE_SHIPMENT) as $line) { $invoice->removeLine($line); $this->persistenceHelper->remove($line, false); $changed = true; } } return $changed; }
php
{ "resource": "" }
q248172
InvoiceSynchronizer.feedShipmentInvoice
validation
private function feedShipmentInvoice(Invoice\InvoiceInterface $invoice) { $changed = false; $shipment = $invoice->getShipment(); $calculator = $this->invoiceBuilder->getInvoiceCalculator(); // Add expected good lines /** @var Invoice\InvoiceLineInterface $line */ foreach ($shipment->getItems() as $shipmentItem) { $saleItem = $shipmentItem->getSaleItem(); $max = $shipment->isReturn() ? $calculator->calculateCreditableQuantity($saleItem) : $calculator->calculateInvoiceableQuantity($saleItem); if (0 < $quantity = min($max, $shipmentItem->getQuantity())) { $line = $this->invoiceBuilder->findOrCreateGoodLine($invoice, $saleItem, $max); if ($line->getQuantity() !== $quantity) { $line->setQuantity($quantity); $changed = true; } } /*else { // TODO find and remove line ? $invoice->removeLine($line); $changed = true; }*/ } if ($invoice->hasLineByType(Document\DocumentLineTypes::TYPE_GOOD)) { // Add expected discount lines $sale = $invoice->getSale(); foreach ($sale->getAdjustments(Common\AdjustmentTypes::TYPE_DISCOUNT) as $saleAdjustment) { foreach ($invoice->getLinesByType(Document\DocumentLineTypes::TYPE_DISCOUNT) as $line) { if ($saleAdjustment === $line->getSaleAdjustment()) { continue 2; // Invoice line found -> next sale adjustment } } // Invoice line not found -> create it $this->invoiceBuilder->buildDiscountLine($saleAdjustment, $invoice); $changed = true; } // Add expected shipment line if (null !== $sale->getShipmentMethod() && !$this->isShipmentAmountInvoiced($invoice)) { $this->invoiceBuilder->buildShipmentLine($invoice); } } return $changed; }
php
{ "resource": "" }
q248173
InvoiceSynchronizer.isShipmentAmountInvoiced
validation
private function isShipmentAmountInvoiced(Invoice\InvoiceInterface $invoice) { /** @var Invoice\InvoiceSubjectInterface $sale */ $sale = $invoice->getSale(); // Abort if another invoice has a shipment line foreach ($sale->getInvoices() as $i) { if ($i === $invoice) { continue; } if ($i->hasLineByType(Document\DocumentLineTypes::TYPE_SHIPMENT)) { return true; } } return false; }
php
{ "resource": "" }
q248174
SaleTransformer.transform
validation
public function transform() { if (null === $this->source || null === $this->target) { throw new LogicException("Please call initialize first."); } $event = new SaleTransformEvent($this->source, $this->target); $this->eventDispatcher->dispatch(SaleTransformEvents::PRE_TRANSFORM, $event); if ($event->hasErrors() || $event->isPropagationStopped()) { return $event; } // Persist the target sale $targetEvent = $this->getOperator($this->target)->persist($this->target); if (!$targetEvent->isPropagationStopped() && !$targetEvent->hasErrors()) { // Disable the uploadable listener $this->uploadableListener->setEnabled(false); // Delete the source sale $sourceEvent = $this->getOperator($this->source)->delete($this->source, true); // Hard delete if (!$sourceEvent->isPropagationStopped() && !$sourceEvent->hasErrors()) { $targetEvent = null; } // Enable the uploadable listener $this->uploadableListener->setEnabled(true); } $this->eventDispatcher->dispatch(SaleTransformEvents::POST_TRANSFORM, $event); if ($event->hasErrors() || $event->isPropagationStopped()) { return $event; } // Unset source and target sales $this->source = null; $this->target = null; return $targetEvent; }
php
{ "resource": "" }
q248175
SaleTransformer.getOperator
validation
protected function getOperator(SaleInterface $sale) { if ($sale instanceof CartInterface) { return $this->cartOperator; } elseif ($sale instanceof QuoteInterface) { return $this->quoteOperator; } elseif ($sale instanceof OrderInterface) { return $this->orderOperator; } throw new InvalidArgumentException("Unexpected sale type."); }
php
{ "resource": "" }
q248176
ErrorHandler.formatMessage
validation
protected function formatMessage($message, $format = [Console::FG_RED, Console::BOLD]) { $stream = (PHP_SAPI === 'cli') ? \STDERR : \STDOUT; if (Console::stream_supports_ansi_colors($stream)) { $message = Console::ansi_format($message, $format); } return $message; }
php
{ "resource": "" }
q248177
StockUnitCache.findBySubjectAndStates
validation
private function findBySubjectAndStates(StockSubjectInterface $subject, array $states = []) { $units = []; // Find by subject oid $oid = spl_object_hash($subject); if (isset($this->addedUnits[$oid])) { $units = $this->addedUnits[$oid]; } // Filter by states if (!empty($units) && !empty($states)) { $units = array_filter($units, function (StockUnitInterface $unit) use ($states) { return in_array($unit->getState(), $states); }); } return $units; }
php
{ "resource": "" }
q248178
StockUnitCache.has
validation
private function has(array &$list, $oid, StockUnitInterface $unit) { if (!isset($list[$oid])) { return false; } return false !== $this->find($list, $oid, $unit); }
php
{ "resource": "" }
q248179
StockUnitCache.find
validation
private function find(array &$list, $oid, StockUnitInterface $unit) { if (!isset($list[$oid])) { return false; } // Non persisted search if (null === $unit->getId()) { return array_search($unit, $list[$oid], true); } // Persisted search /** @var StockUnitInterface $u */ foreach ($list[$oid] as $index => $u) { if ($u->getId() == $unit->getId()) { return $index; } } return false; }
php
{ "resource": "" }
q248180
StockUnitCache.push
validation
private function push(array &$list, $oid, StockUnitInterface $unit) { if (!$this->has($list, $oid, $unit)) { $list[$oid][] = $unit; } }
php
{ "resource": "" }
q248181
StockUnitCache.pop
validation
private function pop(array &$list, $oid, StockUnitInterface $unit) { if (false !== $index = $this->find($list, $oid, $unit)) { unset($list[$oid][$index]); if (empty($list[$oid])) { unset($list[$oid]); } } }
php
{ "resource": "" }
q248182
MarginCalculator.getPurchaseCost
validation
private function getPurchaseCost(Model\SaleItemInterface $item) { /** @var \Ekyna\Component\Commerce\Subject\Model\SubjectInterface $subject */ if (null === $subject = $this->subjectHelper->resolve($item)) { return null; } $currency = $item->getSale()->getCurrency()->getCode(); if (null !== $cost = $this->purchaseCostGuesser->guess($subject, $currency)) { return $cost; } return null; }
php
{ "resource": "" }
q248183
AbstractStockUnitListener.scheduleSubjectStockUnitChangeEvent
validation
protected function scheduleSubjectStockUnitChangeEvent(StockUnitInterface $stockUnit) { $this->persistenceHelper->scheduleEvent( $this->getSubjectStockUnitChangeEventName(), new SubjectStockUnitEvent($stockUnit) ); }
php
{ "resource": "" }
q248184
RelayPointNormalizer.localizedDayOfWeek
validation
protected function localizedDayOfWeek($dayOfWeek) { if (class_exists('\IntlDateFormatter')) { $date = new \DateTime('2017-01-01'); // Starts sunday $date->modify('+' . $dayOfWeek . ' days'); $formatter = \IntlDateFormatter::create( $this->localeProvider->getCurrentLocale(), \IntlDateFormatter::NONE, \IntlDateFormatter::NONE, $date->getTimezone(), null, 'eeee' ); return $formatter->format($date->getTimestamp()); } return [ 1 => 'Monday', 2 => 'Tuesday', 3 => 'Wednesday', 4 => 'Thursday', 5 => 'Friday', 6 => 'Saturday', 7 => 'Sunday', ][$dayOfWeek]; }
php
{ "resource": "" }
q248185
PeskyCmfServiceProvider.registerClassInstanceSingleton
validation
protected function registerClassInstanceSingleton($singletonName, $classNameOrInstance = null) { if (empty($classNameOrInstance)) { $classNameOrInstance = $singletonName; } $this->app->singleton($singletonName, function () use ($classNameOrInstance) { /** @var TableInterface|TableStructureInterface $classNameOrInstance */ return is_string($classNameOrInstance) ? $classNameOrInstance::getInstance() : $classNameOrInstance; }); }
php
{ "resource": "" }
q248186
PaymentNotifyListener.watch
validation
protected function watch(OrderPaymentInterface $payment) { $order = $payment->getOrder(); // Abort if notify disabled or sample order if (!$order->isAutoNotify() || $order->isSample()) { return; } // Abort if not manual/offline payment if (!$payment->getMethod()->isManual()) { return; } // Abort if payment state has not changed for 'CAPTURED' if (!$this->didStateChangeTo($payment, PaymentStates::STATE_CAPTURED)) { return; } // Abort if sale has notification of type 'PAYMENT_CAPTURED' with same payment number /** @var \Ekyna\Component\Commerce\Order\Model\OrderNotificationInterface $n */ foreach ($order->getNotifications() as $n) { if ($n->getType() !== NotificationTypes::PAYMENT_CAPTURED) { continue; } if ($n->hasData('payment') && $n->getData('payment') === $payment->getNumber()) { return; } } $this->notify(NotificationTypes::PAYMENT_CAPTURED, $payment); }
php
{ "resource": "" }
q248187
OrderRepository.getRegularDueQueryBuilder
validation
private function getRegularDueQueryBuilder() { $qb = $this->createQueryBuilder('o'); $ex = $qb->expr(); return $qb ->where($ex->andX( $ex->eq('o.sample', ':not_sample'), // Not sample $ex->lt('o.paidTotal', 'o.grandTotal'), // Paid total lower than grand total $ex->notIn('o.invoiceState', ':canceled_or_refunded'), // Not canceled/refunded $ex->eq('o.shipmentState', ':shipped'), // Shipped $ex->isNull('o.paymentTerm') // Without payment term )) ->addOrderBy('o.createdAt', 'ASC') ->setParameter('not_sample', false) ->setParameter('shipped', ShipmentStates::STATE_COMPLETED) ->setParameter('canceled_or_refunded', [InvoiceStates::STATE_CANCELED, InvoiceStates::STATE_CREDITED]); }
php
{ "resource": "" }
q248188
OrderRepository.getOutstandingExpiredDueQueryBuilder
validation
private function getOutstandingExpiredDueQueryBuilder() { $qb = $this->createQueryBuilder('o'); $ex = $qb->expr(); $qb ->join('o.paymentTerm', 't') ->where($ex->andX( $ex->eq('o.sample', ':not_sample'), // Not sample $ex->lt('o.paidTotal', 'o.grandTotal'), // Paid total lower than grand total $ex->notIn('o.invoiceState', ':canceled_or_refunded'), // Not canceled/refunded $qb->expr()->lte('o.outstandingDate', ':today'), // Payment limit date lower than today $this->getDueClauses() // Terms triggered )) ->addOrderBy('o.outstandingDate', 'ASC') ->setParameter('not_sample', false) ->setParameter('today', (new \DateTime())->setTime(23, 59, 59), Type::DATETIME) ->setParameter('canceled_or_refunded', [InvoiceStates::STATE_CANCELED, InvoiceStates::STATE_CREDITED]); $this->setDueParameters($qb); return $qb; }
php
{ "resource": "" }
q248189
OrderRepository.setDueParameters
validation
private function setDueParameters($query) { $query ->setParameter('trigger_invoiced', Trigger::TRIGGER_INVOICED) ->setParameter('state_invoiced', [InvoiceStates::STATE_PARTIAL, InvoiceStates::STATE_COMPLETED]) ->setParameter('trigger_fully_invoiced', Trigger::TRIGGER_FULLY_INVOICED) ->setParameter('state_fully_invoiced', InvoiceStates::STATE_COMPLETED) ->setParameter('trigger_shipped', Trigger::TRIGGER_SHIPPED) ->setParameter('state_shipped', [ShipmentStates::STATE_PARTIAL, ShipmentStates::STATE_COMPLETED]) ->setParameter('trigger_fully_shipped', Trigger::TRIGGER_FULLY_SHIPPED) ->setParameter('state_fully_shipped', ShipmentStates::STATE_COMPLETED); }
php
{ "resource": "" }
q248190
TaxRuleRepository.getByCountryAndCustomerQuery
validation
private function getByCountryAndCustomerQuery() { if (null === $this->byCountryAndCustomerQuery) { $qb = $this->getBaseQueryBuilder(); $this->byCountryAndCustomerQuery = $qb ->andWhere($qb->expr()->eq('r.customer', ':customer')) ->getQuery() ->setParameter('customer', true) ->setMaxResults(1); } return $this->byCountryAndCustomerQuery; }
php
{ "resource": "" }
q248191
TaxRuleRepository.getByCountryAndBusinessQuery
validation
private function getByCountryAndBusinessQuery() { if (null === $this->byCountryAndBusinessQuery) { $qb = $this->getBaseQueryBuilder(); $this->byCountryAndBusinessQuery = $qb ->andWhere($qb->expr()->eq('r.business', ':business')) ->getQuery() ->setParameter('business', true) ->setMaxResults(1); } return $this->byCountryAndBusinessQuery; }
php
{ "resource": "" }
q248192
TaxRuleRepository.getBaseQueryBuilder
validation
private function getBaseQueryBuilder() { $qb = $this->getQueryBuilder('r', 'r.id'); return $qb ->andWhere( $qb->expr()->orX( $qb->expr()->isMemberOf(':country', 'r.countries'), 'r.countries IS EMPTY' ) ) ->addOrderBy('r.priority', 'DESC'); }
php
{ "resource": "" }
q248193
AbstractShipment.isSaleItemCovered
validation
private function isSaleItemCovered(Common\SaleItemInterface $saleItem, array $coveredIds) { // Skip compound with only public children if ($saleItem->isCompound() && !$saleItem->hasPrivateChildren()) { return true; } if (!in_array($saleItem->getId(), $coveredIds, true)) { return false; } foreach ($saleItem->getChildren() as $child) { if (!$this->isSaleItemCovered($child, $coveredIds)) { return false; } } return true; }
php
{ "resource": "" }
q248194
ShipmentPriceResolver.resolvePrice
validation
private function resolvePrice(array $entry, $weight) { $price = $count = 0; if ($weight > $entry['max_weight']) { $count = floor($weight / $entry['max_weight']); $weight = round(fmod($weight, $count), 3); } if (0 < $count) { $max = end($entry['prices'])['price']; $price = $count * $max; } foreach ($entry['prices'] as $p) { // If sale weight is lower than price weight if (1 === bccomp($p['weight'], $weight, 3)) { $price += $p['price']; break; } } return $price; }
php
{ "resource": "" }
q248195
ShipmentPriceResolver.getGridForCountry
validation
private function getGridForCountry(CountryInterface $country) { if (isset($this->grids[$country->getId()])) { return $this->grids[$country->getId()]; } $grid = []; $prices = $this->priceRepository->findByCountry($country); foreach ($prices as $price) { $method = $price->getMethod(); // Create method if not exists if (!isset($grid[$method->getId()])) { $gateway = $this->gatewayRegistry->getGateway($method->getGatewayName()); $grid[$method->getId()] = [ 'method' => $method, 'max_weight' => $gateway->getMaxWeight(), 'prices' => [], ]; } // Add price $grid[$method->getId()]['prices'][] = [ 'weight' => $price->getWeight(), 'price' => $price->getNetPrice(), ]; } foreach ($grid as &$method) { // Sort prices by weight ASC usort($method['prices'], function ($a, $b) { if (0 === bccomp($a['weight'], $b['weight'], 3)) { return 0; } return $a['weight'] > $b['weight'] ? 1 : -1; }); // Fix max weight $max = end($method['prices'])['weight']; if (0 == $method['max_weight'] || $method['max_weight'] > $max) { $method['max_weight'] = $max; } unset($method); } return $this->grids[$country->getId()] = $grid; }
php
{ "resource": "" }
q248196
ShipmentPriceResolver.getTaxesRates
validation
private function getTaxesRates(ShipmentMethodInterface $method, CountryInterface $country) { return array_map(function (TaxInterface $tax) { return $tax->getRate(); }, $this->taxResolver->resolveTaxes($method, $country)); }
php
{ "resource": "" }
q248197
SupplierOrderCalculator.calculatePaymentBase
validation
private function calculatePaymentBase(SupplierOrderInterface $order) { $base = $this->calculateItemsTotal($order) + $order->getShippingCost() - $order->getDiscountTotal(); $currency = $order->getCurrency()->getCode(); return Money::round($base, $currency); }
php
{ "resource": "" }
q248198
Config._getRenderedToc
validation
private function _getRenderedToc($list, $depth=1) { if (!isset($list) || empty($list)) return (''); $html = "<ul class=\"toc-list\">\n"; foreach ($list as $entry) { $html .= "<li class=\"toc-entry\">\n"; $html .= '<a href="#' . $this->getParam('anchorsPrefix') . $this->titleToIdentifier($depth, $entry['value']) . '">'. $entry['value'] . "</a>\n"; if (isset($entry['sub'])) $html .= $this->_getRenderedToc($entry['sub'], ($depth + 1)); $html .= "</li>\n"; } $html .= "</ul>\n"; return ($html); }
php
{ "resource": "" }
q248199
CmfJsonResponse.setForcedRedirect
validation
public function setForcedRedirect($url) { $data = $this->getData(true); $data[static::$forcedRedirectKey] = $url; return $this->setData($data); }
php
{ "resource": "" }