Skip to content

Commit d0e677d

Browse files
committed
Add DataProviderConverter helper
1 parent eb5c4ea commit d0e677d

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed

src/DataProviderConverter.php

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
<?php
2+
namespace webtoolsnz\helpers;
3+
4+
use yii\data\ActiveDataProvider;
5+
use yii\db\ActiveRecord;
6+
use yii\helpers\ArrayHelper;
7+
8+
/**
9+
* Class DataProviderConverter
10+
* @package webtoolsnz\helpers
11+
*/
12+
class DataProviderConverter
13+
{
14+
15+
/**
16+
* Convert a DataProvider instance and given columns into an array,
17+
* ideal for a CSV export, can reuse GridView columns array
18+
* @param ActiveDataProvider $dataProvider
19+
* @param array $columns
20+
* @return array
21+
*/
22+
public static function convertProviderToArray(ActiveDataProvider $dataProvider, $columns)
23+
{
24+
$header = [];
25+
$data = [];
26+
foreach($dataProvider->getModels() as $model) {
27+
/* @var ActiveRecord $model */
28+
$row = [];
29+
foreach($columns as $column) {
30+
if (is_string($column)) {
31+
// its an attribute
32+
if ($header !== false) {
33+
$header[] = $model->getAttributeLabel($column);
34+
}
35+
$row[] = ArrayHelper::getValue($model, $column);
36+
} else if(is_array($column)) {
37+
if ($header !== false) {
38+
$header[] = isset($column['label']) ? $column['label'] : $model->getAttributeLabel($column['attribute']);
39+
}
40+
$row[] = isset($column['value'])
41+
? (
42+
is_callable($column['value'])
43+
? call_user_func($column['value'], $model)
44+
: ArrayHelper::getValue($model, $column['value'])
45+
)
46+
: ArrayHelper::getValue($model, $column['attribute']);
47+
}
48+
}
49+
50+
if (is_array($header)) {
51+
$data[] = $header;
52+
$header = false;
53+
}
54+
$data[] = $row;
55+
}
56+
return $data;
57+
}
58+
}

0 commit comments

Comments
 (0)