hyperf-view/builder/View/Grid/Exporter.php

146 lines
2.8 KiB
PHP

<?php
namespace Builder\View\Grid;
use Builder\View\Grid;
use Builder\View\Grid\Exporters\CsvExporter;
class Exporter
{
/**
* Export scope constants.
*/
const SCOPE_ALL = 'all';
const SCOPE_WHERE = 'where';
const SCOPE_CURRENT_PAGE = 'page';
const SCOPE_SELECTED_ROWS = 'selected';
/**
* @var Grid
*/
protected $grid;
/**
* Available exporter drivers.
*
* @var array
*/
protected $drivers = [];
/**
* Export query name.
*
* @var string
*/
public static $queryName = '_export_';
/**
* @var Table\Exporters\AbstractExporter
*/
protected $exporter;
/**
* Create a new Exporter instance.
*
* @param Table $grid
*/
public function __construct(Grid $grid)
{
$this->grid = $grid;
$this->grid->model()->usePaginate(false);
}
/**
* Set export query name.
*
* @param $name
*/
public static function setQueryName($name)
{
static::$queryName = $name;
}
/**
* Extends new exporter driver.
*
* @param $driver
* @param $extend
*/
public static function extend($driver, $extend)
{
static::$drivers[$driver] = $extend;
}
/**
* Resolve export driver.
*
* @param string $driver
*
* @return CsvExporter
*/
public function resolve($driver)
{
if ($driver instanceof Grid\Exporters\AbstractExporter) {
$driver->setGrid($this->grid);
return $driver;
}
return $this->getExporter($driver);
}
/**
* Get export driver.
*
* @param string $driver
*
* @return CsvExporter
*/
protected function getExporter($driver)
{
if ($this->exporter) {
return $this->exporter;
}
if (!array_key_exists($driver, $this->drivers)) {
return $this->exporter = $this->getDefaultExporter();
}
return $this->exporter = new $this->drivers[$driver]($this->grid);
}
/**
* Get default exporter.
*
* @return CsvExporter
*/
public function getDefaultExporter()
{
return new CsvExporter($this->grid);
}
/**
* Format query for export url.
*
* @param int $scope
* @param null $args
*
* @return array
*/
public static function formatExportQuery($scope = '', $args = null)
{
$query = '';
if ($scope == static::SCOPE_ALL) {
$query = 'all';
}
if ($scope == static::SCOPE_CURRENT_PAGE) {
$query = "page:$args";
}
if ($scope == static::SCOPE_SELECTED_ROWS) {
$query = "selected:$args";
}
return [static::$queryName => $query];
}
}