_id
stringlengths 2
7
| title
stringlengths 3
151
| partition
stringclasses 3
values | text
stringlengths 83
13k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q248000 | GenericCompilerPass.process | validation | public function process(ContainerBuilder $container)
{
if (!$container->has($this->registry)) {
return;
}
$definition = $container->findDefinition($this->registry);
$taggedServices = $container->findTaggedServiceIds($this->tag);
foreach ($taggedServices as $id => $tags) {
$arguments = [new Reference($id)];
if ($this->withPriority) {
$arguments[] = $this->resolvePriority($tags);
}
$definition->addMethodCall($this->method, $arguments);
}
} | php | {
"resource": ""
} |
q248001 | CacheForDbSelects.buildCacheKey | validation | static public function buildCacheKey($columns = '*', array $conditionsAndOptions = []) {
foreach ($conditionsAndOptions as &$value) {
if ($value instanceof DbExpr) {
$value = $value->get();
} else if (is_object($value)) {
throw new \InvalidArgumentException(
'$conditionsAndOptions argument may contain only strings and objects of class \PeskyORM\Core\DbExpr.'
. ' Object of class ' . get_class($value) . ' detected'
);
}
}
unset($value);
if (is_array($columns)) {
foreach ($columns as &$value) {
if ($value instanceof DbExpr) {
$value = $value->get();
} else if (is_object($value)) {
throw new \InvalidArgumentException(
'$columns argument may contain only strings and objects of class \PeskyORM\Core\DbExpr.'
. ' Object of class ' . get_class($value) . ' detected'
);
}
}
unset($value);
} else if ($columns instanceof DbExpr) {
$columns = $columns->get();
}
return hash('sha256', json_encode(array($columns, $conditionsAndOptions)));
} | php | {
"resource": ""
} |
q248002 | Collection.find | validation | public function find($criteria)
{
if (!$criteria)
{
error_log("collection error: no criteria specified");
return null;
}
else if (is_callable($criteria))
{
foreach ($this->models as $model)
if ($criteria($model)) return $model;
}
else if (is_a($criteria, "SnooPHP\Model\Model"))
{
foreach ($this->models as $i => $model)
if ($model == $criteria) return $i;
}
return null;
} | php | {
"resource": ""
} |
q248003 | Collection.expand | validation | public function expand($edges = [], $force = false)
{
if ($force) foreach ($this->models as $i => $model) $this->models[$i]->expand($edges);
else foreach ($this->models as $i => $model) if (is_a($model, "SnooPHP\Model\Node")) $this->models[$i]->expand($edges);
return $this;
} | php | {
"resource": ""
} |
q248004 | Collection.append | validation | public function append(Collection $collection)
{
if (!$collection) return $this;
$this->models = array_merge($this->array(), $collection->array());
return $this;
} | php | {
"resource": ""
} |
q248005 | AbstractSaleListener.handleInsert | validation | protected function handleInsert(SaleInterface $sale)
{
$changed = false;
// Generate number and key
$changed |= $this->updateNumber($sale);
$changed |= $this->updateKey($sale);
// Handle customer information
$changed |= $this->updateInformation($sale, true);
// Update pricing
$changed |= $this->pricingUpdater->updateVatNumberSubject($sale);
// Update outstanding
$changed |= $this->saleUpdater->updatePaymentTerm($sale);
// Update discounts
$changed |= $this->saleUpdater->updateDiscounts($sale, true);
// Update taxation
$changed |= $this->saleUpdater->updateTaxation($sale, true);
// Update totals
$changed |= $this->saleUpdater->updateTotals($sale);
// Update state
$changed |= $this->updateState($sale);
return $changed;
} | php | {
"resource": ""
} |
q248006 | AbstractSaleListener.handleUpdate | validation | protected function handleUpdate(SaleInterface $sale)
{
$changed = false;
// Generate number and key
$changed |= $this->updateNumber($sale);
$changed |= $this->updateKey($sale);
// Handle customer information
$changed |= $this->updateInformation($sale, true);
// Update pricing
if ($this->persistenceHelper->isChanged($sale, 'vatNumber')) {
$changed |= $this->pricingUpdater->updateVatNumberSubject($sale);
}
// If customer has changed
if ($this->persistenceHelper->isChanged($sale, 'customer')) {
$changed |= $this->saleUpdater->updatePaymentTerm($sale);
// TODO Update customer's balances
// TODO For each payments
// If payment is paid or has changed from paid state
// TODO For each (credit)invoices
}
// Update shipment and amount
if ($this->persistenceHelper->isChanged($sale, ['shipmentMethod', 'customerGroup'])) {
$changed = $this->saleUpdater->updateShipmentMethodAndAmount($sale);
}
// Update discounts
if ($this->isDiscountUpdateNeeded($sale)) {
$changed |= $this->saleUpdater->updateDiscounts($sale, true);
}
// Update taxation
if ($this->isTaxationUpdateNeeded($sale)) {
$changed |= $this->saleUpdater->updateTaxation($sale, true);
} elseif ($this->isShipmentTaxationUpdateNeeded($sale)) {
$changed |= $this->saleUpdater->updateShipmentTaxation($sale, true);
}
return $changed;
} | php | {
"resource": ""
} |
q248007 | AbstractSaleListener.onAddressChange | validation | public function onAddressChange(ResourceEventInterface $event)
{
$sale = $this->getSaleFromEvent($event);
if ($this->persistenceHelper->isScheduledForRemove($sale)) {
$event->stopPropagation();
return;
}
if ($this->handleAddressChange($sale)) {
$this->persistenceHelper->persistAndRecompute($sale, false);
$this->scheduleContentChangeEvent($sale);
}
} | php | {
"resource": ""
} |
q248008 | AbstractSaleListener.handleAddressChange | validation | protected function handleAddressChange(SaleInterface $sale)
{
$changed = false;
// Update shipment method and amount
if ($this->didDeliveryCountryChanged($sale)) {
$changed |= $this->saleUpdater->updateShipmentMethodAndAmount($sale);
}
// Update discounts
if ($this->isDiscountUpdateNeeded($sale)) {
$changed |= $this->saleUpdater->updateDiscounts($sale, true);
}
// Update taxation
if ($this->isTaxationUpdateNeeded($sale)) {
$changed |= $this->saleUpdater->updateTaxation($sale, true);
} elseif ($this->isShipmentTaxationUpdateNeeded($sale)) {
$changed |= $this->saleUpdater->updateShipmentTaxation($sale, true);
}
return $changed;
} | php | {
"resource": ""
} |
q248009 | AbstractSaleListener.handleContentChange | validation | protected function handleContentChange(SaleInterface $sale)
{
// Shipment method and amount
$changed = $this->saleUpdater->updateShipmentMethodAndAmount($sale);
// Shipment taxation
if ($this->isShipmentTaxationUpdateNeeded($sale)) {
$changed = $this->saleUpdater->updateShipmentTaxation($sale, true);
}
// Update totals
$changed |= $this->saleUpdater->updateTotals($sale);
// Update state
$changed |= $this->updateState($sale);
// Update outstanding date
$changed |= $this->saleUpdater->updateOutstandingDate($sale);
return $changed;
} | php | {
"resource": ""
} |
q248010 | AbstractSaleListener.onStateChange | validation | public function onStateChange(ResourceEventInterface $event)
{
$sale = $this->getSaleFromEvent($event);
if ($this->persistenceHelper->isScheduledForRemove($sale)) {
$event->stopPropagation();
return;
}
$this->handleStateChange($sale);
} | php | {
"resource": ""
} |
q248011 | AbstractSaleListener.handleStateChange | validation | protected function handleStateChange(SaleInterface $sale)
{
if ($this->configureAcceptedSale($sale)) {
$this->persistenceHelper->persistAndRecompute($sale, false);
}
} | php | {
"resource": ""
} |
q248012 | AbstractSaleListener.isDiscountUpdateNeeded | validation | protected function isDiscountUpdateNeeded(SaleInterface $sale)
{
if ($this->persistenceHelper->isChanged($sale, ['autoDiscount'])) {
return true;
}
if ((0 == $sale->getPaidTotal()) && $this->persistenceHelper->isChanged($sale, ['customerGroup', 'customer'])) {
return true;
}
return $this->didInvoiceCountryChanged($sale);
} | php | {
"resource": ""
} |
q248013 | AbstractSaleListener.didInvoiceCountryChanged | validation | protected function didInvoiceCountryChanged(SaleInterface $sale)
{
$saleCs = $this->persistenceHelper->getChangeSet($sale);
// Watch for invoice country change
$oldCountry = $newCountry = null;
$oldAddress = isset($saleCs['invoiceAddress']) ? $saleCs['invoiceAddress'][0] : $sale->getInvoiceAddress();
if (null !== $oldAddress) {
$oldAddressCs = $this->persistenceHelper->getChangeSet($oldAddress);
$oldCountry = isset($oldAddressCs['country']) ? $oldAddressCs['country'][0] : $oldAddress->getCountry();
}
// Resolve the new tax resolution target country
if (null !== $newAddress = $sale->getInvoiceAddress()) {
$newCountry = $newAddress->getCountry();
}
if ($oldCountry !== $newCountry) {
return true;
}
return false;
} | php | {
"resource": ""
} |
q248014 | AbstractSaleListener.isTaxationUpdateNeeded | validation | protected function isTaxationUpdateNeeded(SaleInterface $sale)
{
// TODO (Order) Abort if "completed" and not "has changed for completed"
// TODO Get tax resolution mode. (by invoice/delivery/origin).
if ($this->persistenceHelper->isChanged($sale, ['taxExempt', 'customer', 'vatValid'])) {
return true;
}
return $this->didDeliveryCountryChanged($sale);
} | php | {
"resource": ""
} |
q248015 | AbstractSaleListener.didDeliveryCountryChanged | validation | protected function didDeliveryCountryChanged(SaleInterface $sale)
{
$saleCs = $this->persistenceHelper->getChangeSet($sale);
// Watch for delivery country change
$oldCountry = $newCountry = null;
// Resolve the old tax resolution target country
$oldSameAddress = isset($saleCs['sameAddress']) ? $saleCs['sameAddress'][0] : $sale->isSameAddress();
if ($oldSameAddress) {
$oldAddress = isset($saleCs['invoiceAddress']) ? $saleCs['invoiceAddress'][0] : $sale->getInvoiceAddress();
} else {
$oldAddress = isset($saleCs['deliveryAddress']) ? $saleCs['deliveryAddress'][0] : $sale->getDeliveryAddress();
}
if (null !== $oldAddress) {
$oldAddressCs = $this->persistenceHelper->getChangeSet($oldAddress);
$oldCountry = isset($oldAddressCs['country']) ? $oldAddressCs['country'][0] : $oldAddress->getCountry();
}
// Resolve the new tax resolution target country
$newAddress = $sale->isSameAddress() ? $sale->getInvoiceAddress() : $sale->getDeliveryAddress();
if (null !== $newAddress) {
$newCountry = $newAddress->getCountry();
}
if ($oldCountry !== $newCountry) {
return true;
}
return false;
} | php | {
"resource": ""
} |
q248016 | AbstractSaleListener.updateKey | validation | protected function updateKey(SaleInterface $sale)
{
if (0 == strlen($sale->getKey())) {
$this->keyGenerator->generate($sale);
return true;
}
return false;
} | php | {
"resource": ""
} |
q248017 | AbstractSaleListener.updateInformation | validation | protected function updateInformation(SaleInterface $sale, $persistence = false)
{
$changed = false;
if (null !== $customer = $sale->getCustomer()) {
// Customer group
if (null === $sale->getCustomerGroup()) {
$sale->setCustomerGroup($customer->getCustomerGroup());
$changed = true;
}
// Email
if (0 == strlen($sale->getEmail())) {
$sale->setEmail($customer->getEmail());
$changed = true;
}
// Identity
if (0 == strlen($sale->getGender())) {
$sale->setGender($customer->getGender());
$changed = true;
}
if (0 == strlen($sale->getFirstName())) {
$sale->setFirstName($customer->getFirstName());
$changed = true;
}
if (0 == strlen($sale->getLastName())) {
$sale->setLastName($customer->getLastName());
$changed = true;
}
// Company
if (0 == strlen($sale->getCompany()) && 0 < strlen($customer->getCompany())) {
$sale->setCompany($customer->getCompany());
$changed = true;
}
// Vat data
$changed |= $this->updateVatData($sale);
// Invoice address
if (null === $sale->getInvoiceAddress() && null !== $address = $customer->getDefaultInvoiceAddress(true)) {
$changed |= $this->saleUpdater->updateInvoiceAddressFromAddress($sale, $address, $persistence);
}
// Delivery address
if ($sale->isSameAddress()) {
// Remove unused address
if (null !== $address = $sale->getDeliveryAddress()) {
$sale->setDeliveryAddress(null);
if ($persistence) {
$this->persistenceHelper->remove($address, true);
}
}
} else if (null === $sale->getDeliveryAddress() && null !== $address = $customer->getDefaultDeliveryAddress()) {
$changed |= $this->saleUpdater->updateDeliveryAddressFromAddress($sale, $address, $persistence);
}
}
// Vat display mode
$changed |= $this->updateVatDisplayMode($sale);
return $changed;
} | php | {
"resource": ""
} |
q248018 | AbstractSaleListener.updateVatData | validation | protected function updateVatData(SaleInterface $sale)
{
$changed = false;
if (null !== $customer = $sale->getCustomer()) {
if (0 == strlen($sale->getVatNumber()) && 0 < strlen($customer->getVatNumber())) {
$sale->setVatNumber($customer->getVatNumber());
$changed = true;
}
if (empty($sale->getVatDetails()) && !empty($customer->getVatDetails())) {
$sale->setVatDetails($customer->getVatDetails());
$changed = true;
}
if (!$sale->isVatValid() && $customer->isVatValid()) {
$sale->setVatValid(true);
$changed = true;
}
}
return $changed;
} | php | {
"resource": ""
} |
q248019 | AbstractSaleListener.updateVatDisplayMode | validation | protected function updateVatDisplayMode(SaleInterface $sale)
{
// Vat display mode must not change if sale has payments
if ($sale->hasPayments()) {
return false;
}
$mode = null;
if (null !== $group = $sale->getCustomerGroup()) {
$mode = $group->getVatDisplayMode();
}
if (null === $mode) {
$mode = $this->defaultVatDisplayMode;
}
if ($mode !== $sale->getVatDisplayMode()) {
$sale->setVatDisplayMode($mode);
return true;
}
return false;
} | php | {
"resource": ""
} |
q248020 | AbstractSaleListener.configureAcceptedSale | validation | protected function configureAcceptedSale(SaleInterface $sale)
{
if (null === $date = $sale->getAcceptedAt()) {
return false;
}
$changed = $this->updateExchangeRate($sale);
$changed |= $this->updateLocale($sale);
return $changed;
} | php | {
"resource": ""
} |
q248021 | AbstractSaleListener.updateExchangeRate | validation | protected function updateExchangeRate(SaleInterface $sale)
{
if (null !== $sale->getExchangeRate()) {
return false;
}
$date = $sale->getExchangeDate() ?? new \DateTime();
$rate = $this->currencyConverter->getRate(
$this->currencyConverter->getDefaultCurrency(),
$sale->getCurrency()->getCode(),
$date
);
$sale
->setExchangeRate($rate)
->setExchangeDate($date);
return true;
} | php | {
"resource": ""
} |
q248022 | AbstractSaleListener.updateLocale | validation | protected function updateLocale(SaleInterface $sale)
{
if (null !== $sale->getLocale()) {
return false;
}
$sale->setLocale($this->localeProvider->getCurrentLocale());
return true;
} | php | {
"resource": ""
} |
q248023 | QueryParam.setFormParameters | validation | public function setFormParameters($optionNames)
{
foreach ((array) $optionNames as $option) {
$this->formParameters[$option] = true;
}
return $this;
} | php | {
"resource": ""
} |
q248024 | QueryParam.setHeaderParameters | validation | public function setHeaderParameters($optionNames)
{
foreach ((array) $optionNames as $option) {
$this->headerParameters[$option] = true;
}
return $this;
} | php | {
"resource": ""
} |
q248025 | QueryParam.buildQueryString | validation | public function buildQueryString($options)
{
$options = $this->resolve($options);
foreach ($this->formParameters as $key => $isFormParameter) {
if ($isFormParameter && isset($options[$key])) {
unset($options[$key]);
}
}
foreach ($this->headerParameters as $key => $isHeaderParameter) {
if ($isHeaderParameter && isset($options[$key])) {
unset($options[$key]);
}
}
return http_build_query($options);
} | php | {
"resource": ""
} |
q248026 | QueryParam.buildFormDataString | validation | public function buildFormDataString($options)
{
$options = $this->resolve($options);
$formOptions = [];
foreach ($this->formParameters as $key => $isFormParameter) {
if ($isFormParameter && isset($options[$key])) {
$formOptions[$key] = $options[$key];
}
}
return http_build_query($formOptions);
} | php | {
"resource": ""
} |
q248027 | QueryParam.buildHeaders | validation | public function buildHeaders($options)
{
$options = $this->resolve($options);
$headerOptions = [];
foreach ($this->headerParameters as $key => $isHeaderParameter) {
if ($isHeaderParameter && isset($options[$key])) {
$headerOptions[$key] = $options[$key];
}
}
return $headerOptions;
} | php | {
"resource": ""
} |
q248028 | CustomerGroupListener.fixDefault | validation | protected function fixDefault(CustomerGroupInterface $customerGroup)
{
if (!$this->persistenceHelper->isChanged($customerGroup, ['default'])) {
return;
}
if ($customerGroup->isDefault()) {
try {
$previousGroup = $this->customerGroupRepository->findDefault();
} catch (RuntimeException $e) {
return;
}
if ($previousGroup === $customerGroup) {
return;
}
$previousGroup->setDefault(false);
$this->persistenceHelper->persistAndRecompute($previousGroup, false);
}
} | php | {
"resource": ""
} |
q248029 | CustomerGroupListener.getCustomerGroupFromEvent | validation | protected function getCustomerGroupFromEvent(ResourceEventInterface $event)
{
$resource = $event->getResource();
if (!$resource instanceof CustomerGroupInterface) {
throw new InvalidArgumentException('Expected instance of ' . CustomerGroupInterface::class);
}
return $resource;
} | php | {
"resource": ""
} |
q248030 | AbstractPlatform.assertShipmentPlatform | validation | protected function assertShipmentPlatform(ShipmentInterface $shipment)
{
if ($shipment->getPlatformName() !== $this->getName()) {
throw new InvalidArgumentException(sprintf(
"Platform %s does not support shipment %s.",
$this->getName(), $shipment->getNumber()
));
}
} | php | {
"resource": ""
} |
q248031 | StockUnitResolver.merge | validation | protected function merge(array $cachedUnits, array $fetchedUnits)
{
$cachedIds = [];
foreach ($cachedUnits as $unit) {
if (null !== $id = $unit->getId()) {
$cachedIds[] = $unit->getId();
}
}
foreach ($fetchedUnits as $unit) {
if (in_array($unit->getId(), $cachedIds)) {
continue;
}
if ($this->unitCache->isRemoved($unit)) {
continue;
}
if ($this->persistenceHelper->isScheduledForRemove($unit)) {
continue;
}
$cachedUnits[] = $unit;
}
return $cachedUnits;
} | php | {
"resource": ""
} |
q248032 | NotifyBuilder.create | validation | public function create($type, $source = null)
{
$notify = new Notify();
$notify
->setType($type)
->setSource($source);
return $notify;
} | php | {
"resource": ""
} |
q248033 | NotifyBuilder.build | validation | public function build(Notify $notify)
{
$event = new NotifyEvent($notify);
$this->eventDispatcher->dispatch(NotifyEvents::BUILD, $event);
return !$event->isAbort();
} | php | {
"resource": ""
} |
q248034 | TranslatedTags.getTagSortSourceColumn | validation | protected function getTagSortSourceColumn($prefix = null)
{
$column = $this->get('tag_srcsorting');
if (!$column) {
return null;
}
if (null !== $prefix) {
return $prefix . '.' . $column;
}
return $column;
} | php | {
"resource": ""
} |
q248035 | TranslatedTags.getTagCount | validation | public function getTagCount($ids)
{
$tableName = $this->getTagSource();
$colNameId = $this->getIdColumn();
$return = [];
if ($tableName && $colNameId) {
$statement = $this->getConnection()->createQueryBuilder()
->select('item_id', 'count(*) as count')
->from('tl_metamodel_tag_relation')
->where('att_id=:att')
->andWhere('item_id IN (:items)')
->groupBy('item_id')
->setParameter('att', $this->get('id'))
->setParameter('items', $ids, Connection::PARAM_INT_ARRAY)
->execute();
while ($row = $statement->fetch(\PDO::FETCH_OBJ)) {
$itemId = $row->item_id;
$return[$itemId] = (int) $row->count;
}
}
return $return;
} | php | {
"resource": ""
} |
q248036 | TranslatedTags.convertValueIds | validation | protected function convertValueIds($valueResult, &$counter = null)
{
$result = [];
$aliases = [];
$idColumn = $this->getIdColumn();
$aliasColumn = $this->getAliasColumn();
while ($row = $valueResult->fetch(\PDO::FETCH_OBJ)) {
$valueId = $row->$idColumn;
$aliases[$valueId] = $row->$aliasColumn;
$result[] = $valueId;
}
if (($counter !== null) && !empty($result)) {
$statement = $this->getConnection()->createQueryBuilder()
->select('value_id', 'COUNT(value_id) as mm_count')
->from('tl_metamodel_tag_relation')
->where('att_id=:att')
->andWhere('value_id IN (:values)')
->groupBy('item_id')
->setParameter('att', $this->get('id'))
->setParameter('values', $result, Connection::PARAM_STR_ARRAY)
->execute()
->fetch(\PDO::FETCH_OBJ);
$amount = $statement->mm_count;
$valueId = $statement->value_id;
$alias = $aliases[$valueId];
$counter[$valueId] = $amount;
$counter[$alias] = $amount;
}
return $result;
} | php | {
"resource": ""
} |
q248037 | TranslatedTags.getValues | validation | protected function getValues($valueIds, $language)
{
$queryBuilder = $this->getConnection()->createQueryBuilder();
$where = $this->getWhereColumn()
? '(' . $this->getWhereColumn() . ')'
: null;
$statement = $this->getConnection()->createQueryBuilder()
->select('source.*')
->from($this->getTagSource(), 'source')
->where($queryBuilder->expr()->in('source.' . $this->getIdColumn(), $valueIds))
->andWhere(
$queryBuilder->expr()->andX()->add('source.' . $this->getTagLangColumn() . '=:lang')->add($where)
)
->setParameter('lang', $language)
->groupBy('source.' . $this->getIdColumn());
if ($this->getTagSortSourceTable()) {
$statement->addSelect($this->getTagSortSourceTable() . '.*');
$statement->join(
's',
$this->getTagSortSourceTable(),
'sort',
$queryBuilder->expr()->eq('source.' . $this->getIdColumn(), 'sort.id')
);
if ($this->getTagSortSourceColumn()) {
$statement->orderBy($this->getTagSortSourceColumn('sort'));
}
}
$statement->addOrderBy('source.' . $this->getSortingColumn());
return $statement->execute();
} | php | {
"resource": ""
} |
q248038 | TranslatedTags.convertRows | validation | private function convertRows(Statement $dbResult, $idColumn, $valueColumn)
{
$result = [];
while ($row = $dbResult->fetch(\PDO::FETCH_ASSOC)) {
if (!isset($result[$row[$idColumn]])) {
$result[$row[$idColumn]] = [];
}
$data = $row;
unset($data[$idColumn]);
$result[$row[$idColumn]][$row[$valueColumn]] = $data;
}
return $result;
} | php | {
"resource": ""
} |
q248039 | Installer.install | validation | public function install($country = 'US', $currency = 'USD')
{
$this->installCountries($country);
$this->installCurrencies($currency);
$this->installTaxes($country);
$this->installTaxGroups($country);
$this->installTaxRules($country);
$this->installCustomerGroups();
} | php | {
"resource": ""
} |
q248040 | Installer.installCountries | validation | public function installCountries($code = 'US')
{
$countryNames = Intl::getRegionBundle()->getCountryNames();
if (!isset($countryNames[$code])) {
throw new InvalidArgumentException("Invalid default country code '$code'.");
}
asort($countryNames);
$this->generate(Country::class, $countryNames, $code);
} | php | {
"resource": ""
} |
q248041 | Installer.installCurrencies | validation | public function installCurrencies($code = 'USD')
{
$currencyNames = Intl::getCurrencyBundle()->getCurrencyNames();
if (!isset($currencyNames[$code])) {
throw new InvalidArgumentException("Invalid default currency code '$code'.");
}
asort($currencyNames);
$this->generate(Currency::class, $currencyNames, $code);
} | php | {
"resource": ""
} |
q248042 | Installer.installTaxes | validation | public function installTaxes($codes = ['US'])
{
$codes = (array)$codes;
if (empty($codes)) {
return;
}
$taxRepository = $this->manager->getRepository(Tax::class);
foreach ($codes as $code) {
$path = __DIR__ . '/data/' . $code . '_taxes.yml';
if (!(file_exists($path) && is_readable($path))) {
call_user_func($this->log, 'Taxes data', 'not found');
continue;
}
$data = Yaml::parse(file_get_contents($path));
if (!is_array($data) || empty($data)) {
continue;
}
$country = $this
->manager
->getRepository(Country::class)
->findOneBy(['code' => $code]);
if (null === $country) {
continue;
}
foreach ($data as $datum) {
$name = $datum['name'];
$result = 'already exists';
if (null === $taxRepository->findOneBy(['name' => $name])) {
$tax = new Tax();
$tax
->setName($name)
->setRate($datum['rate'])
->setCountry($country);
$this->manager->persist($tax);
$result = 'done';
}
call_user_func($this->log, $name, $result);
}
}
$this->manager->flush();
} | php | {
"resource": ""
} |
q248043 | Installer.installTaxGroups | validation | public function installTaxGroups($codes = ['US'])
{
$codes = (array)$codes;
if (empty($codes)) {
return;
}
$taxGroupRepository = $this->manager->getRepository(TaxGroup::class);
$taxRepository = $this->manager->getRepository(Tax::class);
foreach ($codes as $code) {
$path = __DIR__ . '/data/' . $code . '_tax_groups.yml';
if (!(file_exists($path) && is_readable($path))) {
call_user_func($this->log, 'Tax groups data', 'not found');
continue;
}
$data = Yaml::parse(file_get_contents($path));
if (!is_array($data) || empty($data)) {
continue;
}
foreach ($data as $datum) {
$name = $datum['name'];
$result = 'already exists';
if ($datum['default']) {
$taxGroup = $this
->manager
->getRepository(TaxGroup::class)
->findOneBy(['default' => true]);
if (null !== $taxGroup) {
call_user_func($this->log, $name, 'skipped');
continue;
}
}
if (null === $taxGroupRepository->findOneBy(['name' => $name])) {
$taxGroup = new TaxGroup();
$taxGroup
->setName($name)
->setDefault($datum['default']);
if (!empty($taxNames = $datum['taxes'])) {
$taxGroup->setTaxes($taxRepository->findBy(['name' => $taxNames]));
}
$this->manager->persist($taxGroup);
$result = 'done';
}
call_user_func($this->log, $name, $result);
}
}
$this->manager->flush();
} | php | {
"resource": ""
} |
q248044 | Installer.installTaxRules | validation | public function installTaxRules($codes = ['US'])
{
$codes = (array)$codes;
if (empty($codes)) {
return;
}
$countryRepository = $this->manager->getRepository(Country::class);
$taxRepository = $this->manager->getRepository(Tax::class);
$taxRuleRepository = $this->manager->getRepository(TaxRule::class);
foreach ($codes as $code) {
$path = __DIR__ . '/data/' . $code . '_tax_rules.yml';
if (!(file_exists($path) && is_readable($path))) {
call_user_func($this->log, 'Tax rules data', 'not found');
continue;
}
$data = Yaml::parse(file_get_contents($path));
if (!is_array($data) || empty($data)) {
continue;
}
foreach ($data as $datum) {
$name = $datum['name'];
$result = 'already exists';
if (null === $taxRuleRepository->findOneBy(['name' => $name])) {
$taxRule = new TaxRule();
$taxRule
->setName($name)
->setPriority($datum['priority'])
->setCustomer($datum['customer'])
->setBusiness($datum['business'])
->setNotices($datum['notices']);
if (!empty($countryCodes = $datum['countries'])) {
$taxRule->setCountries($countryRepository->findBy(['code' => $countryCodes]));
}
if (!empty($taxNames = $datum['taxes'])) {
$taxRule->setTaxes($taxRepository->findBy(['name' => $taxNames]));
}
$this->manager->persist($taxRule);
$result = 'done';
}
call_user_func($this->log, $name, $result);
}
}
$this->manager->flush();
} | php | {
"resource": ""
} |
q248045 | Installer.installCustomerGroups | validation | public function installCustomerGroups()
{
$groups = (array) $this->customerGroupRepository->findBy([], [], 1)->getIterator();
if (!empty($groups)) {
call_user_func($this->log, 'All', 'skipped');
return;
}
$groups = [
'Particuliers' => [
'default' => true,
'business' => false,
'registration' => true,
],
'Entreprise' => [
'default' => false,
'business' => true,
'registration' => true,
],
];
foreach ($groups as $name => $config) {
$result = 'already exists';
if (null === $this->customerGroupRepository->findOneBy(['name' => $name])) {
/** @var \Ekyna\Component\Commerce\Customer\Model\CustomerGroupInterface $customerGroup */
$customerGroup = $this->customerGroupRepository->createNew();
$customerGroup
->setName($name)
->setDefault($config['default'])
->setBusiness($config['business'])
->setRegistration($config['registration'])
->translate()
->setTitle($name);
$this->manager->persist($customerGroup);
$result = 'done';
}
call_user_func($this->log, $name, $result);
}
$this->manager->flush();
} | php | {
"resource": ""
} |
q248046 | Installer.generate | validation | private function generate($class, array $names, $defaultCode)
{
/** @var \Ekyna\Component\Resource\Doctrine\ORM\ResourceRepositoryInterface $repository */
$repository = $this->manager->getRepository($class);
foreach ($names as $code => $name) {
$result = 'already exists';
if (null === $repository->findOneBy(['code' => $code])) {
/** @var CountryInterface|CurrencyInterface $entity */
$entity = $repository->createNew();
$entity
->setName($name)
->setCode($code)
->setEnabled($defaultCode === $code);
$this->manager->persist($entity);
$result = 'done';
}
call_user_func($this->log, $name, $result);
}
$this->manager->flush();
} | php | {
"resource": ""
} |
q248047 | FormatterFactory.create | validation | public function create(string $locale = null, string $currency = null)
{
$locale = $locale ?? $this->localeProvider->getCurrentLocale();
$currency = $currency ?? $this->currencyProvider->getCurrentCurrency();
if (isset($this->cache[$key = strtolower("$locale-$currency")])) {
return $this->cache[$key];
}
return $this->cache[$key] = new Formatter($locale, $currency);
} | php | {
"resource": ""
} |
q248048 | FormatterFactory.createFromContext | validation | public function createFromContext(ContextInterface $context)
{
return $this->create($context->getLocale(), $context->getCurrency()->getCode());
} | php | {
"resource": ""
} |
q248049 | Formatter.number | validation | public function number(float $number): string
{
return $this->getNumberFormatter()->format($number, NumberFormatter::TYPE_DEFAULT);
} | php | {
"resource": ""
} |
q248050 | Formatter.currency | validation | public function currency(float $number, string $currency = null): string
{
return $this->getCurrencyFormatter()->formatCurrency($number, $currency ? $currency : $this->currency);
} | php | {
"resource": ""
} |
q248051 | Formatter.rates | validation | public function rates(Adjustment ...$adjustments): string
{
return implode(', ', array_map(function (Adjustment $adjustment) {
return $this->percent($adjustment->getRate());
}, $adjustments));
} | php | {
"resource": ""
} |
q248052 | Formatter.getDateFormatter | validation | private function getDateFormatter()
{
if ($this->dateFormatter) {
return $this->dateFormatter;
}
return $this->dateFormatter = IntlDateFormatter::create(
$this->locale,
IntlDateFormatter::SHORT,
IntlDateFormatter::NONE,
ini_get('date.timezone'),
//PHP_VERSION_ID >= 50500 ? $date->getTimezone() : $date->getTimezone()->getName(),
IntlDateFormatter::GREGORIAN
);
} | php | {
"resource": ""
} |
q248053 | Formatter.getDateTimeFormatter | validation | private function getDateTimeFormatter()
{
if ($this->dateTimeFormatter) {
return $this->dateTimeFormatter;
}
return $this->dateTimeFormatter = IntlDateFormatter::create(
$this->locale,
IntlDateFormatter::SHORT,
IntlDateFormatter::SHORT,
ini_get('date.timezone'),
//PHP_VERSION_ID >= 50500 ? $date->getTimezone() : $date->getTimezone()->getName(),
IntlDateFormatter::GREGORIAN
);
} | php | {
"resource": ""
} |
q248054 | Formatter.getNumberFormatter | validation | private function getNumberFormatter()
{
if ($this->numberFormatter) {
return $this->numberFormatter;
}
return $this->numberFormatter = NumberFormatter::create($this->locale, NumberFormatter::DECIMAL);
} | php | {
"resource": ""
} |
q248055 | Formatter.getCurrencyFormatter | validation | private function getCurrencyFormatter()
{
if ($this->currencyFormatter) {
return $this->currencyFormatter;
}
return $this->currencyFormatter = NumberFormatter::create($this->locale, NumberFormatter::CURRENCY);
} | php | {
"resource": ""
} |
q248056 | SupplierOrderExporter.buildFile | validation | protected function buildFile(array $orders, string $name)
{
if (false === $path = tempnam(sys_get_temp_dir(), $name)) {
throw new RuntimeException("Failed to create temporary file.");
}
if (false === $handle = fopen($path, "w")) {
throw new RuntimeException("Failed to open '$path' for writing.");
}
if (!empty($headers = $this->buildHeaders())) {
fputcsv($handle, $headers, ';', '"');
}
$supplierTotal = 0;
$forwarderTotal = 0;
// Order rows
foreach ($orders as $order) {
if (!empty($row = $this->buildRow($order))) {
fputcsv($handle, $row, ';', '"');
$supplierTotal += $row['payment_total'];
$forwarderTotal += $row['forwarder_total'];
}
}
// Total row
fputcsv($handle, [
'id' => '',
'number' => '',
'state' => '',
'ordered_at' => '',
'completed_at' => '',
'supplier' => '',
'payment_total' => $supplierTotal,
'payment_date' => '',
'payment_due_date' => '',
'carrier' => '',
'forwarder_total' => $forwarderTotal,
'forwarder_date' => '',
'forwarder_due_date' => '',
], ';', '"');
fclose($handle);
return $path;
} | php | {
"resource": ""
} |
q248057 | Adjustment.isSameAs | validation | public function isSameAs(Adjustment $adjustment): bool
{
return $this->name === $adjustment->getName() && $this->rate === $adjustment->getRate();
} | php | {
"resource": ""
} |
q248058 | AdjustmentBuilder.buildAdjustments | validation | protected function buildAdjustments($type, Model\AdjustableInterface $adjustable, array $data, $persistence = false)
{
Model\AdjustmentTypes::isValidType($type);
$change = false;
// Generate adjustments
$newAdjustments = [];
foreach ($data as $d) {
$adjustment = $this->saleFactory->createAdjustmentFor($adjustable);
$adjustment
->setType($type)
->setMode($d->getMode())
->setDesignation($d->getDesignation())
->setAmount($d->getAmount())
->setImmutable($d->isImmutable());
$newAdjustments[] = $adjustment;
}
// Current adjustments
$oldAdjustments = $adjustable->getAdjustments($type);
// Remove current adjustments that do not match any generated adjustments
foreach ($oldAdjustments as $oldAdjustment) {
// Skip non-immutable adjustment as they have been defined by the user.
if (!$oldAdjustment->isImmutable()) {
continue;
}
// Look for a corresponding adjustment
foreach ($newAdjustments as $index => $newAdjustment) {
if ($oldAdjustment->equals($newAdjustment)) {
// Remove the generated adjustment
unset($newAdjustments[$index]);
continue 2;
}
}
// No matching generated adjustment found : remove the current.
$adjustable->removeAdjustment($oldAdjustment);
if ($persistence) {
$this->persistenceHelper->remove($oldAdjustment, true);
}
$change = true;
}
// Adds the remaining generated adjustments
foreach ($newAdjustments as $newAdjustment) {
$adjustable->addAdjustment($newAdjustment);
if ($persistence) {
$this->persistenceHelper->persistAndRecompute($newAdjustment, true);
}
$change = true;
}
return $change;
} | php | {
"resource": ""
} |
q248059 | AccountingExporter.writeInvoiceGoodsLines | validation | protected function writeInvoiceGoodsLines()
{
$sale = $this->invoice->getSale();
$date = $sale->getCreatedAt();
$taxRule = $this->taxResolver->resolveSaleTaxRule($sale);
/** @var \Ekyna\Component\Commerce\Common\Model\AdjustmentInterface[] $discounts */
$discounts = $sale->getAdjustments(AdjustmentTypes::TYPE_DISCOUNT)->toArray();
// Gather amounts by tax rates
$amounts = [];
foreach ($this->invoice->getLinesByType(DocumentLineTypes::TYPE_GOOD) as $line) {
// Skip private lines
if ($line->getSaleItem()->isPrivate()) {
continue;
}
$rates = $line->getTaxRates();
if (empty($rates)) {
$rate = 0;
} elseif (1 === count($rates)) {
$rate = current($rates);
} else {
throw new LogicException("Multiple tax rates on goods lines are not yet supported."); // TODO
}
$amount = $line->getBase();
// Apply sale's discounts
if (!empty($discounts)) {
$base = $amount;
foreach ($discounts as $adjustment) {
if ($adjustment->getMode() === AdjustmentModes::MODE_PERCENT) {
$amount -= $this->round($amount * $adjustment->getAmount() / 100);
} else {
$amount -= $this->round($base / $this->invoice->getGoodsBase() * $adjustment->getAmount());
}
}
}
if (!isset($amounts[(string)$rate])) {
$amounts[(string)$rate] = 0;
}
$amounts[(string)$rate] += $this->round($amount);
}
$credit = $this->invoice->getType() === InvoiceTypes::TYPE_CREDIT;
// Writes each tax rates's amount
foreach ($amounts as $rate => $amount) {
$amount = $this->round($amount);
if (0 === $this->compare($amount, 0)) {
continue; // next tax rate
}
$account = $this->getGoodAccountNumber($taxRule, (float)$rate, $this->invoice->getNumber());
if ($credit) {
$this->writer->credit($account, (string)$amount, $date);
$this->balance -= $amount;
} else {
$this->writer->debit($account, (string)$amount, $date);
$this->balance += $amount;
}
}
} | php | {
"resource": ""
} |
q248060 | AccountingExporter.writeInvoiceShipmentLine | validation | protected function writeInvoiceShipmentLine()
{
$amount = $this->invoice->getShipmentBase();
if (0 === $this->compare($amount, 0)) {
return;
}
$amount = $this->round($amount);
$sale = $this->invoice->getSale();
$date = $sale->getCreatedAt();
$taxRule = $this->taxResolver->resolveSaleTaxRule($sale);
$account = $this->getShipmentAccountNumber($taxRule, $this->invoice->getNumber());
if ($this->invoice->getType() === InvoiceTypes::TYPE_CREDIT) {
$this->writer->credit($account, (string)$amount, $date);
$this->balance -= $amount;
} else {
$this->writer->debit($account, (string)$amount, $date);
$this->balance += $amount;
}
} | php | {
"resource": ""
} |
q248061 | AccountingExporter.writeInvoiceTaxesLine | validation | protected function writeInvoiceTaxesLine()
{
$sale = $this->invoice->getSale();
$date = $sale->getCreatedAt();
$credit = $this->invoice->getType() === InvoiceTypes::TYPE_CREDIT;
foreach ($this->invoice->getTaxesDetails() as $detail) {
$amount = $this->round($detail['amount']);
if (0 === $this->compare($amount, 0)) {
continue; // next tax details
}
$account = $this->getTaxAccountNumber($detail['rate'], $this->invoice->getNumber());
if ($credit) {
$this->writer->credit($account, (string)$amount, $date);
$this->balance -= $amount;
} else {
$this->writer->debit($account, (string)$amount, $date);
$this->balance += $amount;
}
}
} | php | {
"resource": ""
} |
q248062 | AccountingExporter.compare | validation | protected function compare(float $a, float $b)
{
// TODO currency conversion ?
return Money::compare($a, $b, $this->currency);
} | php | {
"resource": ""
} |
q248063 | AccountingExporter.getGoodAccountNumber | validation | protected function getGoodAccountNumber(TaxRuleInterface $rule, float $rate, string $origin)
{
foreach ($this->accounts as $account) {
if ($account->getType() !== AccountingTypes::TYPE_GOOD) {
continue;
}
if ($account->getTaxRule() !== $rule) {
continue;
}
if (is_null($account->getTax())) {
if ($rate == 0) {
return $account->getNumber();
}
continue;
}
if (0 === bccomp($account->getTax()->getRate(), $rate, 5)) {
return $account->getNumber();
}
}
throw new LogicException(sprintf(
"No goods account number configured for tax rule '%s' and tax rate %s (%s)",
$rule->getName(),
$rate,
$origin
));
} | php | {
"resource": ""
} |
q248064 | AccountingExporter.getShipmentAccountNumber | validation | protected function getShipmentAccountNumber(TaxRuleInterface $rule, string $origin)
{
foreach ($this->accounts as $account) {
if ($account->getType() !== AccountingTypes::TYPE_SHIPPING) {
continue;
}
if ($account->getTaxRule() !== $rule) {
continue;
}
return $account->getNumber();
}
throw new LogicException(sprintf(
"No shipment account number configured for tax rule '%s' (%s)",
$rule->getName(),
$origin
));
} | php | {
"resource": ""
} |
q248065 | AccountingExporter.getTaxAccountNumber | validation | protected function getTaxAccountNumber(float $rate, string $origin)
{
foreach ($this->accounts as $account) {
if ($account->getType() !== AccountingTypes::TYPE_TAX) {
continue;
}
if (0 !== bccomp($account->getTax()->getRate(), $rate, 5)) {
continue;
}
return $account->getNumber();
}
throw new LogicException(sprintf(
"No tax account number configured for tax rate '%s' (%s)",
$rate,
$origin
));
} | php | {
"resource": ""
} |
q248066 | AccountingExporter.getPaymentAccountNumber | validation | protected function getPaymentAccountNumber(PaymentMethodInterface $method, string $origin)
{
foreach ($this->accounts as $account) {
if ($account->getType() !== AccountingTypes::TYPE_PAYMENT) {
continue;
}
if ($account->getPaymentMethod() !== $method) {
continue;
}
return $account->getNumber();
}
throw new LogicException(sprintf(
"No payment account number configured for payment method '%s' (%s)",
$method->getName(),
$origin
));
} | php | {
"resource": ""
} |
q248067 | AccountingExporter.getUnpaidAccountNumber | validation | protected function getUnpaidAccountNumber(CustomerGroupInterface $group, string $origin)
{
foreach ($this->accounts as $account) {
if ($account->getType() !== AccountingTypes::TYPE_UNPAID) {
continue;
}
foreach ($account->getCustomerGroups() as $g) {
if ($g->getId() === $group->getId()) {
return $account->getNumber();
}
}
}
// Fallback to 'all' (empty) customer groups
foreach ($this->accounts as $account) {
if ($account->getType() !== AccountingTypes::TYPE_UNPAID) {
continue;
}
if (0 < $account->getCustomerGroups()->count()) {
continue;
}
return $account->getNumber();
}
throw new LogicException(sprintf(
"No unpaid account number configured for customer group '%s' (%s)",
$group->getName(),
$origin
));
} | php | {
"resource": ""
} |
q248068 | GatewayActions.isValid | validation | public static function isValid($action, $throw = false)
{
if (in_array($action, static::getActions(), true)) {
return true;
}
if ($throw) {
throw new InvalidArgumentException("Unknown gateway action '$action'.");
}
return false;
} | php | {
"resource": ""
} |
q248069 | ShipmentAddressResolver.getSaleDeliveryAddress | validation | private function getSaleDeliveryAddress(ShipmentInterface $shipment)
{
if (null === $sale = $shipment->getSale()) {
throw new LogicException("Shipment's sale must be set at this point.");
}
return $sale->isSameAddress() ? $sale->getInvoiceAddress() : $sale->getDeliveryAddress();
} | php | {
"resource": ""
} |
q248070 | StockPrioritizer.prioritizeAssignment | validation | protected function prioritizeAssignment(Stock\StockAssignmentInterface $assignment)
{
if ($assignment->isFullyShipped() || $assignment->isFullyShippable()) {
return false;
}
// Get the non shippable quantity
if (0 >= $quantity = $assignment->getSoldQuantity() - $assignment->getShippableQuantity()) {
return false;
}
// Options are:
// - Splitting non shippable quantity to other stock unit(s)
// - Moving the whole assignment to other stock unit(s) (TODO)
// - Moving other assignment(s) to other stock unit(s) (TODO)
$changed = false;
$helper = new PrioritizeHelper($this->unitResolver);
$sourceUnit = $assignment->getStockUnit();
$candidates = $helper->getUnitCandidates($assignment, $quantity);
foreach ($candidates as $candidate) {
$targetUnit = $candidate->unit;
// If not enough reservable quantity
if ((0 < $quantity - $targetUnit->getReservableQuantity()) && ($combination = $candidate->combination)) {
// Use combination to release quantity
foreach ($combination->map as $id => $qty) {
if (null === $a = $candidate->getAssignmentById($id)) {
throw new StockLogicException("Assignment not found.");
}
// Move assignment to the source unit
$this->moveAssignment($a, $sourceUnit, min($qty, $quantity));
}
}
// Move assignment to the target unit.
$delta = min($quantity, $targetUnit->getReservableQuantity());
$quantity -= $this->moveAssignment($assignment, $targetUnit, $delta);
// TODO Validate units ?
$changed = true;
if (0 >= $quantity) {
break;
}
}
return $changed;
} | php | {
"resource": ""
} |
q248071 | StockPrioritizer.moveAssignment | validation | protected function moveAssignment(
Stock\StockAssignmentInterface $assignment,
Stock\StockUnitInterface $targetUnit,
$quantity
) {
/**
* TODO Refactor with:
* @see \Ekyna\Component\Commerce\Stock\Dispatcher\StockAssignmentDispatcher::moveAssignments()
*/
// Don't move shipped quantity
$quantity = min($quantity, $assignment->getSoldQuantity() - $assignment->getShippedQuantity());
if (0 >= $quantity) { // TODO Packaging format
return 0;
}
$sourceUnit = $assignment->getStockUnit();
$saleItem = $assignment->getSaleItem();
// Debit source unit's sold quantity
$this->logger->unitSold($sourceUnit, -$quantity);
$sourceUnit->setSoldQuantity($sourceUnit->getSoldQuantity() - $quantity);
$this->manager->persist($sourceUnit);
// Credit target unit
$this->logger->unitSold($targetUnit, $quantity);
$targetUnit->setSoldQuantity($targetUnit->getSoldQuantity() + $quantity);
$this->manager->persist($targetUnit);
// Merge assignment lookup
$merge = null;
foreach ($targetUnit->getStockAssignments() as $m) {
if ($m->getSaleItem() === $saleItem) {
$merge = $m;
break;
}
}
if ($quantity == $assignment->getSoldQuantity()) {
if (null !== $merge) {
// Credit quantity to mergeable assignment
$this->logger->assignmentSold($merge, $quantity);
$merge->setSoldQuantity($merge->getSoldQuantity() + $quantity);
$this->manager->persist($merge);
// Debit quantity from source assignment
$this->logger->assignmentSold($assignment, 0, false); // TODO log removal ?
$assignment
->setSoldQuantity(0)
->setSaleItem(null)
->setStockUnit(null);
$this->manager->remove($assignment);
} else {
// Move source assignment to target unit
$this->logger->assignmentUnit($assignment, $targetUnit);
$assignment->setStockUnit($targetUnit);
$this->manager->persist($assignment);
}
} else {
// Debit quantity from source assignment
$this->logger->assignmentSold($assignment, -$quantity);
$assignment->setSoldQuantity($assignment->getSoldQuantity() - $quantity);
$this->manager->persist($assignment);
if (null !== $merge) {
// Credit quantity to mergeable assignment
$this->logger->assignmentSold($merge, $quantity);
$merge->setSoldQuantity($merge->getSoldQuantity() + $quantity);
$this->manager->persist($merge);
} else {
// Credit quantity to new assignment
$create = $this->saleFactory->createStockAssignmentForItem($saleItem);
$this->logger->assignmentSold($create, $quantity, false);
$create
->setSoldQuantity($quantity)
->setSaleItem($saleItem)
->setStockUnit($targetUnit);
$this->manager->persist($create);
}
}
return $quantity;
} | php | {
"resource": ""
} |
q248072 | SupplierOrderItemListener.synchronizeWithProduct | validation | protected function synchronizeWithProduct(SupplierOrderItemInterface $item)
{
$changed = false;
// TODO What about stock management if subject change ???
if (null !== $product = $item->getProduct()) {
// TODO Create an utility class to do this
$productSID = $product->getSubjectIdentity();
if ($productSID->hasIdentity()) {
$itemSID = $item->getSubjectIdentity();
if ($itemSID->hasIdentity()) {
if (!$itemSID->equals($productSID)) {
throw new LogicException(
'Breaking synchronization between supplier order item and supplier product is not supported.'
);
}
$changed = false;
} else {
$itemSID->copy($productSID);
$changed = true;
}
} else {
throw new InvalidArgumentException(
'Supplier product subject identity is not set.'
);
}
if (0 == strlen($item->getDesignation())) {
$item->setDesignation($product->getDesignation());
}
if (0 == strlen($item->getReference())) {
$item->setReference($product->getReference());
}
if (0 == $item->getNetPrice()) {
$item->setNetPrice($product->getNetPrice());
}
} elseif ($item->hasSubjectIdentity()) {
throw new LogicException(
'Breaking synchronization between supplier order item and supplier product is not supported.'
);
}
return $changed;
} | php | {
"resource": ""
} |
q248073 | SupplierOrderItemListener.getSupplierOrderItemFromEvent | validation | protected function getSupplierOrderItemFromEvent(ResourceEventInterface $event)
{
$item = $event->getResource();
if (!$item instanceof SupplierOrderItemInterface) {
throw new InvalidArgumentException("Expected instance of SupplierOrderItemInterface.");
}
return $item;
} | php | {
"resource": ""
} |
q248074 | UserRights.userHasRight | validation | public function userHasRight(array $user, $right) {
$hasRight = false;
if (isset($user['role']) && !empty($right) && isset($this->_rightsConfig[$right])) {
if (in_array($user['role'], $this->_rightsConfig[$right])) {
$hasRight = true;
}
}
return $hasRight;
} | php | {
"resource": ""
} |
q248075 | SupplierOrderRepository.getFindNewBySupplierQuery | validation | private function getFindNewBySupplierQuery()
{
if (null !== $this->findNewBySupplierQuery) {
return $this->findNewBySupplierQuery;
}
$qb = $this->createQueryBuilder();
$as = $this->getAlias();
return $this->findNewBySupplierQuery = $qb
->andWhere($qb->expr()->eq($as . '.supplier', ':supplier'))
->andWhere($qb->expr()->eq($as . '.state', ':state'))
->getQuery()
->setParameter('state', Model\SupplierOrderStates::STATE_NEW);
} | php | {
"resource": ""
} |
q248076 | AbstractInvoiceLineListener.preventForbiddenChange | validation | protected function preventForbiddenChange(Model\InvoiceLineInterface $line)
{
if ($this->persistenceHelper->isChanged($line, 'type')) {
list($old, $new) = $this->persistenceHelper->getChangeSet($line, 'type');
if ($old !== $new) {
throw new Exception\RuntimeException("Changing the invoice line's type is not supported.");
}
}
} | php | {
"resource": ""
} |
q248077 | SaleShipmentStepValidator.isIdentityValid | validation | private function isIdentityValid(SaleInterface $cart)
{
return 0 < strlen($cart->getEmail())
&& 0 < strlen($cart->getGender())
&& 0 < strlen($cart->getFirstName())
&& 0 < strlen($cart->getLastName());
} | php | {
"resource": ""
} |
q248078 | Injector.map | validation | public function map($key,$obj = null,$need_cache = false){
$this->clearCache($key);
if (is_null($obj)) {
$obj = $key;
}
$this->objects[$key] = [$obj,$need_cache];
return $this;
} | php | {
"resource": ""
} |
q248079 | Injector.mapDatas | validation | public function mapDatas($kvs){
foreach ($kvs as $k => $v){
$this->mapData($k,$v);
}
} | php | {
"resource": ""
} |
q248080 | Injector.get | validation | public function get($key){
if(isset($this->objects[$key])){
return $this->objects[$key];
}
throw new InjectorException("obj $key not found");
} | php | {
"resource": ""
} |
q248081 | Injector.getData | validation | public function getData($key){
if(isset($this->data[$key])){
return $this->data[$key];
}
throw new InjectorException("data $key not found");
} | php | {
"resource": ""
} |
q248082 | Injector.getCache | validation | public function getCache($key){
return isset($this->caches[$key]) ? $this->caches[$key] : null;
} | php | {
"resource": ""
} |
q248083 | Injector.produce | validation | public function produce($key,$params = array(),$enable_reflect = true){
//if in data
if(isset($this->data[$key])) return $this->data[$key];
//if cached
if(isset($this->caches[$key])) return $this->caches[$key];
//if obj/closure
if(isset($this->objects[$key])){
$obj = $this->get($key);
$concrete = $obj[self::INDEX_CONCRETE];
}else{
if($this->MUST_REG || !$enable_reflect){
throw new InjectorException("$key not registered");
}else{
$concrete = $key;
$not_reg = true;
}
}
$result = $this->build($concrete,$params);
if($not_reg === true || $obj[self::INDEX_CACHED] === true){
$this->caches[$key] = $result;
}
return $result;
} | php | {
"resource": ""
} |
q248084 | Injector.call | validation | public function call(Closure $c,$params = array()){
$ref = new ReflectionFunction($c);
$params_need = $ref->getParameters();
$args = $this->apply($params_need,$params);
return call_user_func_array($c,$args);
//return $ref->invokeArgs($args);
} | php | {
"resource": ""
} |
q248085 | Injector.callInClass | validation | public function callInClass($class_name,$action,$params = array()){
$ref = new ReflectionMethod($class_name, $action);
if(!$ref->isPublic() && !$ref->isStatic()) throw new InjectorException("$class_name->$action is not public or static");
$params_need = $ref->getParameters();
$args = $this->apply($params_need,$params);
$obj = $this->produce($class_name,$params);
return call_user_func_array([$obj,$action],$args);
//return $ref->invokeArgs($obj,$args);
} | php | {
"resource": ""
} |
q248086 | Date.seconds | validation | public static function seconds($step = 1, $start = 0, $end = 60) {
// Always integer
$step = (int)$step;
$seconds = array();
for ($i = $start; $i < $end; $i += $step) {
$seconds[$i] = sprintf('%02d', $i);
}
return $seconds;
} | php | {
"resource": ""
} |
q248087 | Date.hours | validation | public static function hours($step = 1, $long = false, $start = null) {
// Set the default start if none was specified.
if (!$start) {
$start = $long ? 0 : 1;
}
// 24-hour time has 24 hours, instead of 12
$size = $long ? 23 : 12;
$step = (int)$step;
$hours = array();
for ($i = $start; $i <= $size; $i += $step) {
$hours[$i] = (string)$i;
}
return $hours;
} | php | {
"resource": ""
} |
q248088 | Date.adjust | validation | public static function adjust($hour, $ampm) {
$hour = (int)$hour;
$ampm = strtolower($ampm);
switch ($ampm) {
case 'am':
if ($hour == 12) {
$hour = 0;
}
break;
case 'pm':
if ($hour < 12) {
$hour += 12;
}
break;
}
return sprintf('%02d', $hour);
} | php | {
"resource": ""
} |
q248089 | Date.days | validation | public static function days($month, $year = null) {
static $months;
if (!isset($year)) {
// Use the current year by default
$year = date('Y');
}
// Always integers
$month = (int)$month;
$year = (int)$year;
// We use caching for months, because time functions are used
if (empty($months[$year][$month])) {
// Use date to find the number of days in the given month
$total = date('t', mktime(1, 0, 0, $month, 1, $year)) + 1;
$months[$year][$month] = array();
for ($i = 1; $i < $total; $i++) {
$months[$year][$month][$i] = (string)$i;
}
}
return $months[$year][$month];
} | php | {
"resource": ""
} |
q248090 | Date.months | validation | public static function months($format = null) {
$months = array();
if ($format === static::MONTHS_LONG || $format === static::MONTHS_SHORT) {
for ($i = 1; $i <= 12; ++$i) {
$months[$i] = strftime($format, mktime(0, 0, 0, $i, 1));
}
} else {
$months = static::hours();
}
return $months;
} | php | {
"resource": ""
} |
q248091 | Date.years | validation | public static function years($start = false, $end = false) {
// Default values
$start = ($start === false) ? (date('Y') - 5) : (int)$start;
$end = ($end === false) ? (date('Y') + 5) : (int)$end;
$years = array();
for ($i = $start; $i <= $end; $i++) {
$years[$i] = (string)$i;
}
return $years;
} | php | {
"resource": ""
} |
q248092 | Date.fuzzySpan | validation | public static function fuzzySpan($timestamp, $local_timestamp = null) {
$local_timestamp = ($local_timestamp === null) ? time() : (int)$local_timestamp;
// Determine the difference in seconds
$offset = abs($local_timestamp - $timestamp);
if ($offset <= static::MINUTE) {
$span = 'moments';
} elseif ($offset < (static::MINUTE * 20)) {
$span = 'a few minutes';
} elseif ($offset < static::HOUR) {
$span = 'less than an hour';
} elseif ($offset < (static::HOUR * 4)) {
$span = 'a couple of hours';
} elseif ($offset < static::DAY) {
$span = 'less than a day';
} elseif ($offset < (static::DAY * 2)) {
$span = 'about a day';
} elseif ($offset < (static::DAY * 4)) {
$span = 'a couple of days';
} elseif ($offset < static::WEEK) {
$span = 'less than a week';
} elseif ($offset < (static::WEEK * 2)) {
$span = 'about a week';
} elseif ($offset < static::MONTH) {
$span = 'less than a month';
} elseif ($offset < (static::MONTH * 2)) {
$span = 'about a month';
} elseif ($offset < (static::MONTH * 4)) {
$span = 'a couple of months';
} elseif ($offset < static::YEAR) {
$span = 'less than a year';
} elseif ($offset < (static::YEAR * 2)) {
$span = 'about a year';
} elseif ($offset < (static::YEAR * 4)) {
$span = 'a couple of years';
} elseif ($offset < (static::YEAR * 8)) {
$span = 'a few years';
} elseif ($offset < (static::YEAR * 12)) {
$span = 'about a decade';
} elseif ($offset < (static::YEAR * 24)) {
$span = 'a couple of decades';
} elseif ($offset < (static::YEAR * 64)) {
$span = 'several decades';
} else {
$span = 'a long time';
}
if ($timestamp <= $local_timestamp) {
// This is in the past
return $span . ' ago';
} else {
// This in the future
return 'in ' . $span;
}
} | php | {
"resource": ""
} |
q248093 | PaymentTermTriggers.isValidTrigger | validation | static public function isValidTrigger($trigger, $throwException = true)
{
if (in_array($trigger, static::getTriggers(), true)) {
return true;
}
if ($throwException) {
throw new InvalidArgumentException("Invalid payment term trigger '$trigger'.");
}
return false;
} | php | {
"resource": ""
} |
q248094 | PaymentDoneEventSubscriber.onStatus | validation | public function onStatus(PaymentEvent $event)
{
$payment = $event->getPayment();
$sale = $payment->getSale();
if ($sale instanceof OrderInterface) {
return;
}
if ($sale instanceof CartInterface && $sale->getState() !== CartStates::STATE_ACCEPTED) {
return;
}
if ($sale instanceof QuoteInterface && $sale->getState() !== QuoteStates::STATE_ACCEPTED) {
return;
}
// Store payment tokens
$tokens = $this->findPaymentTokens($payment);
// Transform sale to order
if (null === $order = $this->transform($sale)) {
return;
}
// Find order's transformed payment
$newPayment = null;
foreach ($order->getPayments() as $p) {
if ($p->getNumber() === $payment->getNumber()) {
$newPayment = $p;
break;
}
}
if (null === $newPayment) {
throw new RuntimeException("Failed to find the transformed payment.");
}
// Convert tokens
$this->convertTokens($this->getPaymentIdentity($newPayment), $tokens);
// Set event new payment
$event->setPayment($newPayment);
} | php | {
"resource": ""
} |
q248095 | PaymentDoneEventSubscriber.findPaymentTokens | validation | private function findPaymentTokens(PaymentInterface $payment)
{
$identity = $this->getPaymentIdentity($payment);
/** @var TokenInterface[] $tokens */
$tokens = $this->payum->getTokenStorage()->findBy([
'details' => $identity,
]);
return $tokens;
} | php | {
"resource": ""
} |
q248096 | PaymentDoneEventSubscriber.transform | validation | private function transform(SaleInterface $sale)
{
$order = $this->newOrder();
// Initialize transformation
$this->saleTransformer->initialize($sale, $order);
// Transform
if (null === $event = $this->saleTransformer->transform()) {
// Success
return $order;
}
return null;
} | php | {
"resource": ""
} |
q248097 | SolsticeEquinoxTrait.equinoxMarch | validation | protected static function equinoxMarch($year, $vsop = true) {
$month = 3;
if ($vsop)
return static::accurate($year, static::meanTerms($month, $year), $month);
else
return static::approx($year, static::meanTerms($month, $year));
} | php | {
"resource": ""
} |
q248098 | SolsticeEquinoxTrait.equinoxSeptember | validation | protected static function equinoxSeptember($year, $vsop = true) {
$month = 9;
if ($vsop)
return static::accurate($year, static::meanTerms($month, $year), $month);
else
return static::approx($year, static::meanTerms($month, $year));
} | php | {
"resource": ""
} |
q248099 | SolsticeEquinoxTrait.solsticeJune | validation | protected static function solsticeJune($year, $vsop = true) {
$month = 6;
if ($vsop)
return static::accurate($year, static::meanTerms($month, $year), $month);
else
return static::approx($year, static::meanTerms($month, $year));
} | php | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.