Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[13.x] Allow normal and metered prices in builder #1336

Merged
merged 3 commits into from
Mar 15, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 16 additions & 4 deletions src/SubscriptionBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ class SubscriptionBuilder
*
* @var array
*/
protected $items;
protected $items = [];

/**
* The date and time the trial will expire.
Expand Down Expand Up @@ -99,6 +99,8 @@ public function price($price, $quantity = 1)
{
$options = is_array($price) ? $price : ['price' => $price];

$quantity = $price['quantity'] ?? $quantity;

if (! is_null($quantity)) {
$options['quantity'] = $quantity;
}
Expand All @@ -107,10 +109,10 @@ public function price($price, $quantity = 1)
$options['tax_rates'] = $taxRates;
}

if (is_array($price)) {
$this->items[] = $options;
if (isset($options['price'])) {
$this->items[$options['price']] = $options;
} else {
$this->items[$price] = $options;
$this->items[] = $options;
}

return $this;
Expand Down Expand Up @@ -452,4 +454,14 @@ protected function getPriceTaxRatesForPayload($price)
return $taxRates[$price] ?? null;
}
}

/**
* Get the items set on the subscription builder.
*
* @return array
*/
public function getItems()
{
return $this->items;
}
}
27 changes: 27 additions & 0 deletions tests/Unit/SubscriptionBuilderTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
<?php

namespace Laravel\Cashier\Tests\Unit;

use Laravel\Cashier\SubscriptionBuilder;
use Laravel\Cashier\Tests\Fixtures\User;
use PHPUnit\Framework\TestCase;

class SubscriptionBuilderTest extends TestCase
{
public function test_it_can_be_instantiated_with_both_normal_and_metered_prices()
{
$builder = new SubscriptionBuilder(new User, 'default', [
'price_foo',
['price' => 'price_bux'],
['price' => 'price_bar', 'quantity' => 1],
['price' => 'price_baz', 'quantity' => 0],
]);

$this->assertSame([
'price_foo' => ['price' => 'price_foo', 'quantity' => 1],
'price_bux' => ['price' => 'price_bux', 'quantity' => 1],
'price_bar' => ['price' => 'price_bar', 'quantity' => 1],
'price_baz' => ['price' => 'price_baz', 'quantity' => 0],
], $builder->getItems());
}
}