| 1 |
<?php |
| 2 |
|
| 3 |
namespace FluentForm\App\Modules\Entries; |
| 4 |
|
| 5 |
use SplTempFileObject; |
| 6 |
use FluentForm\App\Services\FormParser; |
| 7 |
use FluentForm\Framework\Helpers\ArrayHelper; |
| 8 |
use FluentForm\App\Services\FormResponseParser; |
| 9 |
use FluentForm\Framework\Foundation\Application; |
| 10 |
|
| 11 |
class Export |
| 12 |
{ |
| 13 |
/** |
| 14 |
* @var \FluentForm\Framework\Request\Request |
| 15 |
*/ |
| 16 |
protected $request; |
| 17 |
|
| 18 |
/** |
| 19 |
* Export constructor. |
| 20 |
* |
| 21 |
* @param \FluentForm\Framework\Foundation\Application $application |
| 22 |
*/ |
| 23 |
public function __construct(Application $application) |
| 24 |
{ |
| 25 |
$this->request = $application->request; |
| 26 |
} |
| 27 |
|
| 28 |
/** |
| 29 |
* Exports form entries as CSV. |
| 30 |
* |
| 31 |
* @todo:: refactor. |
| 32 |
*/ |
| 33 |
public function index() |
| 34 |
{ |
| 35 |
$formId = intval($this->request->get('form_id')); |
| 36 |
|
| 37 |
$form = wpFluent()->table('fluentform_forms')->find($formId); |
| 38 |
|
| 39 |
$formParser = new FormParser($form); |
| 40 |
|
| 41 |
$formInputs = $formParser->getEntryInputs(); |
| 42 |
|
| 43 |
$inputLabels = $formParser->getAdminLabels($formInputs); |
| 44 |
|
| 45 |
$submissions = wpFluent()->table('fluentform_submissions')->where('form_id', $formId)->get(); |
| 46 |
|
| 47 |
$submissions = FormResponseParser::transformSubmissions($submissions, $formInputs, $formId); |
| 48 |
|
| 49 |
$exportData = []; |
| 50 |
|
| 51 |
foreach ($submissions as $submission) { |
| 52 |
$responses = json_decode($submission->response, true); |
| 53 |
|
| 54 |
$temp = []; |
| 55 |
|
| 56 |
foreach ($inputLabels as $field => $label) { |
| 57 |
$value = ArrayHelper::get($responses, $field); |
| 58 |
|
| 59 |
$temp[] = is_array($value) ? implode(', ', $value) : $value; |
| 60 |
} |
| 61 |
|
| 62 |
$exportData[] = $temp; |
| 63 |
} |
| 64 |
|
| 65 |
$fileName = 'export-data-'.date('d-m-Y'); |
| 66 |
|
| 67 |
$writer = \League\Csv\Writer::createFromFileObject(new SplTempFileObject()); |
| 68 |
$writer->setDelimiter(","); |
| 69 |
$writer->setNewline("\r\n"); |
| 70 |
$writer->insertOne($inputLabels); |
| 71 |
$writer->insertAll($exportData); |
| 72 |
$writer->output($fileName.'.csv'); |
| 73 |
die(); |
| 74 |
} |
| 75 |
} |