Skip to content

Commit

Permalink
Queue export with dependencies (#1362)
Browse files Browse the repository at this point in the history
* Queue export with dependencies

* Add test

* Pint
  • Loading branch information
luanfreitasdev authored Feb 1, 2024
1 parent a6eaba9 commit 01151f6
Show file tree
Hide file tree
Showing 10 changed files with 140 additions and 21 deletions.
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@
"laravel/pint": "^1.13.8",
"laradumps/laradumps-core": "^1.1",
"larastan/larastan": "^2.8.1",
"pestphp/pest": "^2.30.0",
"pestphp/pest": "2.28.0",
"orchestra/testbench": "8.19|^9.0"
},
"suggest": {
Expand Down
2 changes: 1 addition & 1 deletion phpstan.neon
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ parameters:
- '~^Parameter #1 \$value of function intval expects array\|bool\|float\|int\|resource\|string\|null, mixed given\.$~'
- '#^Method .*::fromLivewire\(\) has no return type specified\.#'
- '#^Method .*::fromLivewire\(\) has parameter \$value with no type specified\.#'

- '#Call to an undefined method PowerComponents\\LivewirePowerGrid\\PowerGridComponent::datasource\(\).#'
paths:
- src

Expand Down
8 changes: 0 additions & 8 deletions src/Concerns/Base.php
Original file line number Diff line number Diff line change
Expand Up @@ -79,14 +79,6 @@ public function filters(): array
return [];
}

/**
* @return null
*/
public function datasource()
{
return null;
}

public function summarizeFormat(): array
{
return [];
Expand Down
8 changes: 6 additions & 2 deletions src/Jobs/ExportJob.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\{InteractsWithQueue, SerializesModels};
use Illuminate\Support\Facades\Crypt;
use PowerComponents\LivewirePowerGrid\PowerGridComponent;
use PowerComponents\LivewirePowerGrid\Traits\ExportableJob;

Expand All @@ -19,6 +20,8 @@ class ExportJob implements ShouldQueue
use SerializesModels;
use ExportableJob;

private array $properties;

/**
* @param string $componentTable
* @param array $columns
Expand All @@ -34,7 +37,8 @@ public function __construct(
$this->fileName = $params['fileName'];
$this->offset = $params['offset'];
$this->limit = $params['limit'];
$this->filters = $params['filters'];
$this->filters = (array) Crypt::decrypt($params['filters']);
$this->properties = (array) Crypt::decrypt($params['parameters']);

/** @var PowerGridComponent $componentTable */
$this->componentTable = new $componentTable();
Expand All @@ -56,7 +60,7 @@ public function handle(): void
/** @phpstan-ignore-next-line */
$exportable
->fileName($this->getFilename())
->setData($columnsWithHiddenState, $this->prepareToExport())
->setData($columnsWithHiddenState, $this->prepareToExport($this->properties))
->download([]);
}
}
10 changes: 10 additions & 0 deletions src/PowerGridComponent.php
Original file line number Diff line number Diff line change
Expand Up @@ -184,6 +184,16 @@ private function renderView(mixed $data): Application|Factory|View
]);
}

public function getPublicPropertiesDefinedInComponent(): array
{
return collect((new \ReflectionClass($this))->getProperties(\ReflectionProperty::IS_PUBLIC))
->where('class', get_class($this))
->pluck('name')
->intersect(array_keys($this->all()))
->mapWithKeys(fn ($property) => [$property => $this->$property])
->all();
}

/**
* @throws Exception|Throwable
*/
Expand Down
11 changes: 5 additions & 6 deletions src/ProcessDataSource.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,13 +21,14 @@ class ProcessDataSource
public bool $isCollection = false;

public function __construct(
public PowerGridComponent $component
public PowerGridComponent $component,
public array $properties = [],
) {
}

public static function fillData(PowerGridComponent $powerGridComponent): ProcessDataSource
public static function fillData(PowerGridComponent $powerGridComponent, array $properties = []): ProcessDataSource
{
return new self($powerGridComponent);
return new self($powerGridComponent, $properties);
}

/**
Expand Down Expand Up @@ -55,7 +56,7 @@ public function prepareDataSource(): EloquentBuilder|BaseCollection|Collection|Q
$datasource = $this->component->datasource ?? null;

if (empty($datasource)) {
$datasource = $this->component->datasource();
$datasource = $this->component->datasource($this->properties);
}

if (is_array($datasource)) {
Expand Down Expand Up @@ -108,15 +109,13 @@ private function processModel(EloquentBuilder|MorphToMany|QueryBuilder|BaseColle
);

if ($datasource instanceof EloquentBuilder || $datasource instanceof MorphToMany) {
/** @phpstan-ignore-next-line */
$results = $this->applySoftDeletes($results, $this->component->softDeletes);
}

$this->applySummaries($results);

$sortField = $this->makeSortField($this->component->sortField);

/** @phpstan-ignore-next-line */
$results = $this->component->multiSort ? $this->applyMultipleSort($results) : $this->applySingleSort($results, $sortField);

$results = $this->applyPerPage($results);
Expand Down
4 changes: 2 additions & 2 deletions src/Traits/ExportableJob.php
Original file line number Diff line number Diff line change
Expand Up @@ -31,10 +31,10 @@ private function getFilename(): Stringable
->replace('.csv', '');
}

private function prepareToExport(): Eloquent\Collection|Collection
private function prepareToExport(array $properties = []): Eloquent\Collection|Collection
{
/** @phpstan-ignore-next-line */
$processDataSource = tap(ProcessDataSource::fillData($this->componentTable), fn ($datasource) => $datasource->get());
$processDataSource = tap(ProcessDataSource::fillData($this->componentTable, $properties), fn ($datasource) => $datasource->get());

$inClause = $processDataSource->component->filtered ?? [];

Expand Down
3 changes: 2 additions & 1 deletion src/Traits/WithExport.php
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,8 @@ private function putQueuesToBus(string $exportableClass, string $fileExtension):
'fileName' => $fileName,
'offset' => $offset,
'limit' => $limit,
'filters' => $filters,
'filters' => Support\Facades\Crypt::encrypt($filters),
'parameters' => Support\Facades\Crypt::encrypt($processDataSource->component->getPublicPropertiesDefinedInComponent()),
];

$queues->push(new $this->exportableJobClass(
Expand Down
81 changes: 81 additions & 0 deletions tests/Concerns/Components/BatchExportTable.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
<?php

namespace PowerComponents\LivewirePowerGrid\Tests\Concerns\Components;

use Illuminate\Database\Eloquent\Builder;
use PowerComponents\LivewirePowerGrid\Tests\Concerns\Models\Dish;
use PowerComponents\LivewirePowerGrid\{
Column,
Exportable,
Footer,
Header,
PowerGrid,
PowerGridComponent,
PowerGridFields,
Traits\WithExport
};

class BatchExportTable extends PowerGridComponent
{
use WithExport;

public int $filterDataSourceId;

public ?int $idFromBatch = null;

public function setUp(): array
{
return [
Exportable::make('export')
->striped()
->type(Exportable::TYPE_XLS, Exportable::TYPE_CSV)
->queues(6),

Header::make()
->showSearchInput(),

Footer::make()
->showPerPage()
->showRecordCount(),
];
}

public function datasource(array $parameters): Builder
{
return Dish::with('category')->where('id', $parameters['filterDataSourceId'] ?? 1);
}

public function fields(): PowerGridFields
{
return PowerGrid::fields()
->add('id')
->add('name');
}

public function columns(): array
{
return [
Column::add()
->title(__('ID'))
->field('id')
->searchable()
->sortable(),

Column::add()
->title('Dish')
->field('name')
->searchable()
->sortable(),
];
}

public function bootstrap()
{
config(['livewire-powergrid.theme' => 'bootstrap']);
}

public function tailwind()
{
config(['livewire-powergrid.theme' => 'tailwind']);
}
}
32 changes: 32 additions & 0 deletions tests/Feature/BatchExportTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
<?php

use Illuminate\Bus\PendingBatch;
use Illuminate\Support\Facades\Bus;
use Livewire\Features\SupportTesting\Testable;

use function Livewire\invade;

use PowerComponents\LivewirePowerGrid\Tests\Concerns\Components\BatchExportTable;

use function PowerComponents\LivewirePowerGrid\Tests\Plugins\livewire;

it('can pass class parameters in batch export.', function () {
Bus::fake();

/** @var Testable $component */
$component = livewire(BatchExportTable::class, [
'filterDataSourceId' => 77,
])
->call('exportToXLS', false);

$getPublicPropertiesDefinedInComponent = $component->instance()->getPublicPropertiesDefinedInComponent();

Bus::assertBatched(function (PendingBatch $batch) use ($getPublicPropertiesDefinedInComponent) {
$jobs = $batch->jobs[0];

$properties = invade($jobs[0])->properties;

return $getPublicPropertiesDefinedInComponent['filterDataSourceId'] ===
$properties['filterDataSourceId'];
});
})->requiresOpenSpout();

0 comments on commit 01151f6

Please sign in to comment.