Passed
Push — master ( 5fde5f...44bc4c )
by Aimeos
03:11
created

Standard::render()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 3
nc 1
nop 1
dl 0
loc 6
rs 10
c 0
b 0
f 0
1
<?php
2
3
/**
4
 * @license LGPLv3, http://opensource.org/licenses/LGPL-3.0
5
 * @copyright Aimeos (aimeos.org), 2017-2022
6
 * @package Controller
7
 * @subpackage Jobs
8
 */
9
10
11
namespace Aimeos\Controller\Jobs\Order\Export\Csv;
12
13
14
/**
15
 * Job controller for CSV order exports.
16
 *
17
 * @package Controller
18
 * @subpackage Jobs
19
 */
20
class Standard
21
	extends \Aimeos\Controller\Jobs\Base
22
	implements \Aimeos\Controller\Jobs\Iface
23
{
24
	/** controller/jobs/order/export/csv/name
25
	 * Class name of the used order suggestions scheduler controller implementation
26
	 *
27
	 * Each default job controller can be replace by an alternative imlementation.
28
	 * To use this implementation, you have to set the last part of the class
29
	 * name as configuration value so the controller factory knows which class it
30
	 * has to instantiate.
31
	 *
32
	 * For example, if the name of the default class is
33
	 *
34
	 *  \Aimeos\Controller\Jobs\Order\Export\Csv\Standard
35
	 *
36
	 * and you want to replace it with your own version named
37
	 *
38
	 *  \Aimeos\Controller\Jobs\Order\Export\Csv\Mycsv
39
	 *
40
	 * then you have to set the this configuration option:
41
	 *
42
	 *  controller/jobs/order/export/csv/name = Mycsv
43
	 *
44
	 * The value is the last part of your own class name and it's case sensitive,
45
	 * so take care that the configuration value is exactly named like the last
46
	 * part of the class name.
47
	 *
48
	 * The allowed characters of the class name are A-Z, a-z and 0-9. No other
49
	 * characters are possible! You should always start the last part of the class
50
	 * name with an upper case character and continue only with lower case characters
51
	 * or numbers. Avoid chamel case names like "MyCsv"!
52
	 *
53
	 * @param string Last part of the class name
54
	 * @since 2015.01
55
	 */
56
57
	/** controller/jobs/order/export/csv/decorators/excludes
58
	 * Excludes decorators added by the "common" option from the order export CSV job controller
59
	 *
60
	 * Decorators extend the functionality of a class by adding new aspects
61
	 * (e.g. log what is currently done), executing the methods of the underlying
62
	 * class only in certain conditions (e.g. only for logged in users) or
63
	 * modify what is returned to the caller.
64
	 *
65
	 * This option allows you to remove a decorator added via
66
	 * "controller/jobs/common/decorators/default" before they are wrapped
67
	 * around the job controller.
68
	 *
69
	 *  controller/jobs/order/export/csv/decorators/excludes = array( 'decorator1' )
70
	 *
71
	 * This would remove the decorator named "decorator1" from the list of
72
	 * common decorators ("\Aimeos\Controller\Jobs\Common\Decorator\*") added via
73
	 * "controller/jobs/common/decorators/default" to the job controller.
74
	 *
75
	 * @param array List of decorator names
76
	 * @since 2015.01
77
	 * @see controller/jobs/common/decorators/default
78
	 * @see controller/jobs/order/export/csv/decorators/global
79
	 * @see controller/jobs/order/export/csv/decorators/local
80
	 */
81
82
	/** controller/jobs/order/export/csv/decorators/global
83
	 * Adds a list of globally available decorators only to the order export CSV job controller
84
	 *
85
	 * Decorators extend the functionality of a class by adding new aspects
86
	 * (e.g. log what is currently done), executing the methods of the underlying
87
	 * class only in certain conditions (e.g. only for logged in users) or
88
	 * modify what is returned to the caller.
89
	 *
90
	 * This option allows you to wrap global decorators
91
	 * ("\Aimeos\Controller\Jobs\Common\Decorator\*") around the job controller.
92
	 *
93
	 *  controller/jobs/order/export/csv/decorators/global = array( 'decorator1' )
94
	 *
95
	 * This would add the decorator named "decorator1" defined by
96
	 * "\Aimeos\Controller\Jobs\Common\Decorator\Decorator1" only to the job controller.
97
	 *
98
	 * @param array List of decorator names
99
	 * @since 2015.01
100
	 * @see controller/jobs/common/decorators/default
101
	 * @see controller/jobs/order/export/csv/decorators/excludes
102
	 * @see controller/jobs/order/export/csv/decorators/local
103
	 */
104
105
	/** controller/jobs/order/export/csv/decorators/local
106
	 * Adds a list of local decorators only to the order export CSV job controller
107
	 *
108
	 * Decorators extend the functionality of a class by adding new aspects
109
	 * (e.g. log what is currently done), executing the methods of the underlying
110
	 * class only in certain conditions (e.g. only for logged in users) or
111
	 * modify what is returned to the caller.
112
	 *
113
	 * This option allows you to wrap local decorators
114
	 * ("\Aimeos\Controller\Jobs\Order\Export\Csv\Decorator\*") around the job
115
	 * controller.
116
	 *
117
	 *  controller/jobs/order/export/csv/decorators/local = array( 'decorator2' )
118
	 *
119
	 * This would add the decorator named "decorator2" defined by
120
	 * "\Aimeos\Controller\Jobs\Order\Export\Csv\Decorator\Decorator2"
121
	 * only to the job controller.
122
	 *
123
	 * @param array List of decorator names
124
	 * @since 2015.01
125
	 * @see controller/jobs/common/decorators/default
126
	 * @see controller/jobs/order/export/csv/decorators/excludes
127
	 * @see controller/jobs/order/export/csv/decorators/global
128
	 */
129
130
131
	/**
132
	 * Returns the localized name of the job.
133
	 *
134
	 * @return string Name of the job
135
	 */
136
	public function getName() : string
137
	{
138
		return $this->context()->translate( 'controller/jobs', 'Order export CSV' );
139
	}
140
141
142
	/**
143
	 * Returns the localized description of the job.
144
	 *
145
	 * @return string Description of the job
146
	 */
147
	public function getDescription() : string
148
	{
149
		return $this->context()->translate( 'controller/jobs', 'Exports orders to CSV file' );
150
	}
151
152
153
	/**
154
	 * Executes the job.
155
	 *
156
	 * @throws \Aimeos\Controller\Jobs\Exception If an error occurs
157
	 */
158
	public function run()
159
	{
160
		$context = $this->context();
161
		$mq = $context->queue( 'mq-admin', 'order-export' );
162
163
		while( $msg = $mq->get() )
164
		{
165
			try
166
			{
167
				$body = $msg->getBody();
168
169
				if( ( $data = json_decode( $body, true ) ) === null ) {
170
					throw new \Aimeos\Controller\Jobs\Exception( sprintf( 'Invalid message: %1$s', $body ) );
171
				}
172
173
				$this->export( $data );
174
			}
175
			catch( \Exception $e )
176
			{
177
echo $e->getMessage() . "\n" . $e->getTraceAsString() . PHP_EOL;
178
				$str = 'Order export error: ' . $e->getMessage() . "\n" . $e->getTraceAsString();
179
				$context->logger()->error( $str, 'order/export/csv' );
180
			}
181
182
			$mq->del( $msg );
183
		}
184
	}
185
186
187
	/**
188
	 * Initializes the search criteria
189
	 *
190
	 * @param \Aimeos\Base\Criteria\Iface $criteria New criteria object
191
	 * @param array $msg Message data
192
	 * @return \Aimeos\Base\Criteria\Iface Initialized criteria object
193
	 */
194
	protected function criteria( \Aimeos\Base\Criteria\Iface $criteria, array $msg ) : \Aimeos\Base\Criteria\Iface
195
	{
196
		/** controller/jobs/order/export/csv/max-size
197
		 * Maximum number of CSV rows to export at once
198
		 *
199
		 * It's more efficient to read and export more than one row at a time
200
		 * to speed up the export. Usually, the bigger the chunk that is exported
201
		 * at once, the less time the exporter will need. The downside is that
202
		 * the amount of memory required by the export process will increase as
203
		 * well. Therefore, it's a trade-off between memory consumption and
204
		 * export speed.
205
		 *
206
		 * @param integer Number of rows
207
		 * @since 2023.04
208
		 */
209
		$size = (int) $this->context()->config()->get( 'controller/jobs/order/export/csv/max-size', 1000 );
210
211
		return $criteria->add( $criteria->parse( $msg['filter'] ?? [] ) )->order( $msg['sort'] ?? [] )->slice( 0, $size );
212
	}
213
214
215
	/**
216
	 * Exports the orders
217
	 *
218
	 * @param array $msg Message data passed from the frontend
219
	 */
220
	protected function export( array $msg )
221
	{
222
		if( ( $fh = tmpfile() ) === false ) {
223
			throw new \Aimeos\Controller\Jobs\Exception( 'Unable to create temporary file' );
224
		}
225
226
		$path = $this->path();
227
		$lcontext = $this->getLocaleContext( $msg );
228
		$manager = \Aimeos\MShop::create( $lcontext, 'order' );
229
230
		$cursor = $manager->cursor( $this->criteria( $manager->filter( false, true ), $msg ) );
231
		$ref = $lcontext->config()->get( 'mshop/order/manager/subdomains', [] );
232
233
		while( $items = $manager->iterate( $cursor, $ref ) )
234
		{
235
			if( fwrite( $fh, $this->render( $items ) ) === false ) {
236
				throw new \Aimeos\Controller\Jobs\Exception( 'Unable to add data to temporary file' );
237
			}
238
		}
239
240
		rewind( $fh );
241
		$lcontext->fs( 'fs-export' )->writes( $path, $fh );
242
		fclose( $fh );
243
244
		$manager = \Aimeos\MAdmin::create( $lcontext, 'job' );
245
		$manager->save( $manager->create()->setPath( $path )->setLabel( $path ), false );
246
	}
247
248
249
	/**
250
	 * Returns a new context including the locale from the message data
251
	 *
252
	 * @param array $msg Message data including a "sitecode" value
253
	 * @return \Aimeos\MShop\ContextIface New context item with updated locale
254
	 */
255
	protected function getLocaleContext( array $msg ) : \Aimeos\MShop\ContextIface
256
	{
257
		$lcontext = clone $this->context();
258
		$manager = \Aimeos\MShop::create( $lcontext, 'locale' );
259
260
		$sitecode = ( isset( $msg['sitecode'] ) ? $msg['sitecode'] : 'default' );
261
		$localeItem = $manager->bootstrap( $sitecode, '', '', false, \Aimeos\MShop\Locale\Manager\Base::SITE_PATH );
262
263
		return $lcontext->setLocale( $localeItem );
264
	}
265
266
267
	/**
268
	 * Returns the relative path the orders should be exported to
269
	 *
270
	 * @return string Relativ path to the export file
271
	 */
272
	protected function path() : string
273
	{
274
		/** controller/jobs/order/export/csv/path
275
		 * Relativ path to the export file
276
		 *
277
		 * It's more efficient to read and export more than one row at a time
278
		 * to speed up the export. Usually, the bigger the chunk that is exported
279
		 * at once, the less time the exporter will need. The downside is that
280
		 * the amount of memory required by the export process will increase as
281
		 * well. Therefore, it's a trade-off between memory consumption and
282
		 * export speed.
283
		 *
284
		 * @param string Relativ path with placeholders
285
		 * @since 2023.04
286
		 */
287
		$path = $this->context()->config()->get( 'controller/jobs/order/export/csv/path', 'order-export_%Y-%m-%d_%H-%i-%s' );
288
		return \Aimeos\Base\Str::strtime( $path );
289
	}
290
291
292
	/**
293
	 * Creates the CSV file for the given orders
294
	 *
295
	 * @param \Aimeos\MShop\Order\Item\Iface[] $orderItems List of order items to export
296
	 * @return string Generated CSV
297
	 */
298
	protected function render( iterable $orderItems ) : string
299
	{
300
		$context = $this->context();
301
		$template = $context->config()->get( 'controller/jobs/order/export/csv/template', 'order/export/csv/body' );
302
303
		return $context->view()->assign( ['orderItems' => $orderItems] )->render( $template );
304
	}
305
}
306