AdjustmentTransformer.php in Commerce Core 8.2
File
modules/order/src/AdjustmentTransformer.php
View source
<?php
namespace Drupal\commerce_order;
use Drupal\commerce_price\RounderInterface;
use Drupal\Component\Utility\SortArray;
class AdjustmentTransformer implements AdjustmentTransformerInterface {
protected $adjustmentTypeManager;
protected $rounder;
public function __construct(AdjustmentTypeManager $adjustment_type_manager, RounderInterface $rounder) {
$this->adjustmentTypeManager = $adjustment_type_manager;
$this->rounder = $rounder;
}
public function processAdjustments(array $adjustments) {
$adjustments = $this
->combineAdjustments($adjustments);
$adjustments = $this
->sortAdjustments($adjustments);
$adjustments = $this
->roundAdjustments($adjustments);
return $adjustments;
}
public function combineAdjustments(array $adjustments) {
$combined_adjustments = [];
foreach ($adjustments as $index => $adjustment) {
$type = $adjustment
->getType();
$source_id = $adjustment
->getSourceId();
if (empty($source_id)) {
$key = $index;
}
else {
$key = $type . '_' . $source_id;
}
if (empty($combined_adjustments[$key])) {
$combined_adjustments[$key] = $adjustment;
}
else {
$combined_adjustments[$key] = $combined_adjustments[$key]
->add($adjustment);
}
}
$combined_adjustments = array_values($combined_adjustments);
return $combined_adjustments;
}
public function sortAdjustments(array $adjustments) {
$types = $this->adjustmentTypeManager
->getDefinitions();
$data = [];
foreach ($adjustments as $adjustment) {
$data[] = [
'adjustment' => $adjustment,
'weight' => $types[$adjustment
->getType()]['weight'],
];
}
uasort($data, [
SortArray::class,
'sortByWeightElement',
]);
$adjustments = array_column($data, 'adjustment');
return $adjustments;
}
public function roundAdjustments(array $adjustments, $mode = PHP_ROUND_HALF_UP) {
foreach ($adjustments as $index => $adjustment) {
$adjustments[$index] = $this
->roundAdjustment($adjustment, $mode);
}
return $adjustments;
}
public function roundAdjustment(Adjustment $adjustment, $mode = PHP_ROUND_HALF_UP) {
$amount = $this->rounder
->round($adjustment
->getAmount(), $mode);
$adjustment = new Adjustment([
'amount' => $amount,
] + $adjustment
->toArray());
return $adjustment;
}
}