Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
CsvTemplate.php
Go to the documentation of this file.
1 <?php
7 
9 
14 {
20  private $config;
21 
27  private $csv;
28 
32  public function __construct(array $config)
33  {
34  $this->config = $config;
35  }
36 
40  public function render()
41  {
42  if (!isset($this->config['filename'], $this->config['count'])) {
43  throw new \InvalidArgumentException(
44  'Configuration for file is bad. You must specify "filename" and "count" in configuration.'
45  );
46  }
47 
48  $filename = MTF_TESTS_PATH . $this->config['filename'] . '.php';
49 
50  if (!file_exists($filename)) {
51  throw new \Exception('File "' . $filename . '" does not exist.');
52  }
53 
54  $fh = fopen('php://temp', 'rw');
55  $fh = $this->addEntitiesData($fh);
56  rewind($fh);
57  $this->csv = stream_get_contents($fh);
58  fclose($fh);
59 
60  return $this->csv;
61  }
62 
66  public function getName()
67  {
68  return sprintf(
69  '%x_%s.csv',
70  crc32(time()),
71  basename($this->config['filename'])
72  );
73  }
74 
81  private function addEntitiesData($stream)
82  {
83  $filename = MTF_TESTS_PATH . $this->config['filename'] . '.php';
84  $entitiesData = include $filename;
85 
86  $placeholders = [];
87  if (!empty($this->config['placeholders'])) {
88  $placeholders = $this->config['placeholders'];
89  }
90 
91  fputcsv($stream, array_keys($entitiesData['entity_0']['data_0']));
92  foreach ($placeholders as $entityKey => $entityData) {
93  foreach ($entityData as $dataKey => $dataValue) {
94  $row = array_map(
95  function ($value) use ($placeholders, $entityKey, $dataKey, $dataValue) {
96  if (is_string($value) && isset($placeholders[$entityKey][$dataKey])) {
97  return strtr($value, $dataValue);
98  }
99  return $value;
100  },
101  $entitiesData[$entityKey][$dataKey]
102  );
103  fputcsv($stream, $row);
104  }
105  }
106  return $stream;
107  }
108 
114  public function getCsv()
115  {
116  return $this->csv;
117  }
118 }
$config
Definition: fraud_order.php:17
$value
Definition: gender.phtml:16
const MTF_TESTS_PATH
Definition: bootstrap.php:11