Skip to content

Commit

Permalink
Added the PercentDiscount adjuster
Browse files Browse the repository at this point in the history
  • Loading branch information
fulopattila122 committed Aug 25, 2024
1 parent 33df4d6 commit 32adb48
Show file tree
Hide file tree
Showing 2 changed files with 74 additions and 0 deletions.
69 changes: 69 additions & 0 deletions Adjusters/PercentDiscount.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
<?php

declare(strict_types=1);

namespace Vanilo\Adjustments\Adjusters;

use Vanilo\Adjustments\Contracts\Adjustable;
use Vanilo\Adjustments\Contracts\Adjuster;
use Vanilo\Adjustments\Contracts\Adjustment;
use Vanilo\Adjustments\Models\AdjustmentProxy;
use Vanilo\Adjustments\Models\AdjustmentTypeProxy;
use Vanilo\Adjustments\Support\HasWriteableTitleAndDescription;
use Vanilo\Adjustments\Support\IsLockable;
use Vanilo\Adjustments\Support\IsNotIncluded;

final class PercentDiscount implements Adjuster
{
use HasWriteableTitleAndDescription;
use IsLockable;
use IsNotIncluded;

private ?float $threshold;

public function __construct(
private float|int $percent
) {
}

public static function reproduceFromAdjustment(Adjustment $adjustment): Adjuster
{
$data = $adjustment->getData();

return new self(floatval($data['percent'] ?? 0));
}

public function createAdjustment(Adjustable $adjustable): Adjustment
{
$adjustmentClass = AdjustmentProxy::modelClass();

return new $adjustmentClass($this->getModelAttributes($adjustable));
}

public function recalculate(Adjustment $adjustment, Adjustable $adjustable): Adjustment
{
$adjustment->setAmount($this->calculateAmount($adjustable));

return $adjustment;
}

private function calculateAmount(Adjustable $adjustable): float
{
return -1 * round($adjustable->preAdjustmentTotal() / 100 * $this->percent, 2);
}

private function getModelAttributes(Adjustable $adjustable): array
{
return [
'type' => AdjustmentTypeProxy::PROMOTION(),
'adjuster' => self::class,
'origin' => null,
'title' => $this->getTitle(),
'description' => $this->getDescription(),
'data' => ['percent' => $this->percent,],
'amount' => $this->calculateAmount($adjustable),
'is_locked' => $this->isLocked(),
'is_included' => $this->isIncluded(),
];
}
}
5 changes: 5 additions & 0 deletions Changelog.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,11 @@

## 4.x Series

## Unreleased
##### 2024-XX-YY

- Added the `PercentDiscount` adjuster class

## 4.1.0
##### 2024-07-11

Expand Down

0 comments on commit 32adb48

Please sign in to comment.