Standard::path()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 19
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 3
nc 1
nop 0
dl 0
loc 19
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), 2018-2025
6
 * @package Controller
7
 * @subpackage Jobs
8
 */
9
10
11
namespace Aimeos\Controller\Jobs\Subscription\Export\Csv;
12
13
14
/**
15
 * Job controller for CSV subscription 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/subscription/export/csv/name
25
	 * Class name of the used subscription 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\Subscription\Export\Csv\Standard
35
	 *
36
	 * and you want to replace it with your own version named
37
	 *
38
	 *  \Aimeos\Controller\Jobs\Subscription\Export\Csv\Mycsv
39
	 *
40
	 * then you have to set the this configuration option:
41
	 *
42
	 *  controller/jobs/subscription/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 2018.04
55
	 */
56
57
	/** controller/jobs/subscription/export/csv/decorators/excludes
58
	 * Excludes decorators added by the "common" option from the subscription 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/subscription/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 2018.04
77
	 * @see controller/jobs/common/decorators/default
78
	 * @see controller/jobs/subscription/export/csv/decorators/global
79
	 * @see controller/jobs/subscription/export/csv/decorators/local
80
	 */
81
82
	/** controller/jobs/subscription/export/csv/decorators/global
83
	 * Adds a list of globally available decorators only to the subscription 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/subscription/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 2018.04
100
	 * @see controller/jobs/common/decorators/default
101
	 * @see controller/jobs/subscription/export/csv/decorators/excludes
102
	 * @see controller/jobs/subscription/export/csv/decorators/local
103
	 */
104
105
	/** controller/jobs/subscription/export/csv/decorators/local
106
	 * Adds a list of local decorators only to the subscription 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\Subscription\Export\Csv\Decorator\*") around the job
115
	 * controller.
116
	 *
117
	 *  controller/jobs/subscription/export/csv/decorators/local = array( 'decorator2' )
118
	 *
119
	 * This would add the decorator named "decorator2" defined by
120
	 * "\Aimeos\Controller\Jobs\Subscription\Export\Csv\Decorator\Decorator2"
121
	 * only to the job controller.
122
	 *
123
	 * @param array List of decorator names
124
	 * @since 2018.04
125
	 * @see controller/jobs/common/decorators/default
126
	 * @see controller/jobs/subscription/export/csv/decorators/excludes
127
	 * @see controller/jobs/subscription/export/csv/decorators/global
128
	 */
129
130
	use \Aimeos\Macro\Macroable;
131
132
133
	/**
134
	 * Returns the localized name of the job.
135
	 *
136
	 * @return string Name of the job
137
	 */
138
	public function getName() : string
139
	{
140
		return $this->context()->translate( 'controller/jobs', 'Subscription export CSV' );
141
	}
142
143
144
	/**
145
	 * Returns the localized description of the job.
146
	 *
147
	 * @return string Description of the job
148
	 */
149
	public function getDescription() : string
150
	{
151
		return $this->context()->translate( 'controller/jobs', 'Exports subscriptions to CSV file' );
152
	}
153
154
155
	/**
156
	 * Executes the job.
157
	 *
158
	 * @throws \Aimeos\Controller\Jobs\Exception If an error occurs
159
	 */
160
	public function run()
161
	{
162
		$context = $this->context();
163
		$mq = $context->queue( 'mq-admin', 'subscription-export' );
164
165
		while( $msg = $mq->get() )
166
		{
167
			try
168
			{
169
				$body = $msg->getBody();
170
171
				if( ( $data = json_decode( $body, true ) ) === null ) {
172
					throw new \Aimeos\Controller\Jobs\Exception( sprintf( 'Invalid message: %1$s', $body ) );
173
				}
174
175
				$this->export( $data );
176
			}
177
			catch( \Exception $e )
178
			{
179
				$str = 'Subscription export error: ' . $e->getMessage() . "\n" . $e->getTraceAsString();
180
				$context->logger()->error( $str, 'subscription/export/csv' );
181
			}
182
183
			$mq->del( $msg );
184
		}
185
	}
186
187
188
	/**
189
	 * Initializes the search criteria
190
	 *
191
	 * @param \Aimeos\Base\Criteria\Iface $criteria New criteria object
192
	 * @param array $msg Message data
193
	 * @return \Aimeos\Base\Criteria\Iface Initialized criteria object
194
	 */
195
	protected function criteria( \Aimeos\Base\Criteria\Iface $criteria, array $msg ) : \Aimeos\Base\Criteria\Iface
196
	{
197
		/** controller/jobs/subscription/export/csv/max-size
198
		 * Maximum number of CSV rows to export at once
199
		 *
200
		 * It's more efficient to read and export more than one row at a time
201
		 * to speed up the export. Usually, the bigger the chunk that is exported
202
		 * at once, the less time the exporter will need. The downside is that
203
		 * the amount of memory required by the export process will increase as
204
		 * well. Therefore, it's a trade-off between memory consumption and
205
		 * export speed.
206
		 *
207
		 * @param integer Number of rows
208
		 * @since 2023.04
209
		 */
210
		$size = (int) $this->context()->config()->get( 'controller/jobs/subscription/export/csv/max-size', 1000 );
211
212
		return $criteria->add( $criteria->parse( $msg['filter'] ?? [] ) )->order( $msg['sort'] ?? [] )->slice( 0, $size );
213
	}
214
215
216
	/**
217
	 * Exports the orders
218
	 *
219
	 * @param array $msg Message data passed from the frontend
220
	 */
221
	protected function export( array $msg )
222
	{
223
		if( ( $fh = tmpfile() ) === false ) {
224
			throw new \Aimeos\Controller\Jobs\Exception( 'Unable to create temporary file' );
225
		}
226
227
		$path = $this->path();
228
		$lcontext = $this->getLocaleContext( $msg );
229
230
		$manager = \Aimeos\MShop::create( $lcontext, 'subscription' );
231
		$cursor = $manager->cursor( $this->criteria( $manager->filter( false, true ), $msg ) );
232
233
		while( $items = $manager->iterate( $cursor, ['order', 'order/address', 'order/product'] ) )
234
		{
235
			$items = $this->call( 'hydrate', $items );
236
237
			if( fwrite( $fh, $this->render( $items ) ) === false ) {
238
				throw new \Aimeos\Controller\Jobs\Exception( 'Unable to add data to temporary file' );
239
			}
240
		}
241
242
		rewind( $fh );
243
		$lcontext->fs( 'fs-admin' )->writes( $path, $fh );
244
		fclose( $fh );
245
246
		$manager = \Aimeos\MAdmin::create( $lcontext, 'job' );
247
		$manager->save( $manager->create()->setPath( $path )->setLabel( $path ), false );
248
	}
249
250
251
	/**
252
	 * Returns a new context including the locale from the message data
253
	 *
254
	 * @param array $msg Message data including a "sitecode" value
255
	 * @return \Aimeos\MShop\ContextIface New context item with updated locale
256
	 */
257
	protected function getLocaleContext( array $msg ) : \Aimeos\MShop\ContextIface
258
	{
259
		$lcontext = clone $this->context();
260
		$manager = \Aimeos\MShop::create( $lcontext, 'locale' );
261
262
		$sitecode = ( isset( $msg['sitecode'] ) ? $msg['sitecode'] : 'default' );
263
		$localeItem = $manager->bootstrap( $sitecode, '', '', false, \Aimeos\MShop\Locale\Manager\Base::SITE_ONE );
264
265
		return $lcontext->setLocale( $localeItem );
266
	}
267
268
269
	/**
270
	 * Hydrates the given list of items
271
	 *
272
	 * @param \Aimeos\Map $items List of items to hydrate
273
	 * @return \Aimeos\Map Hydrated list of items
274
	 */
275
	protected function hydrate( \Aimeos\Map $items ) : \Aimeos\Map
276
	{
277
		return $items;
278
	}
279
280
281
	/**
282
	 * Returns the relative path the subscriptions should be exported to
283
	 *
284
	 * @return string Relativ path to the export file
285
	 */
286
	protected function path() : string
287
	{
288
		/** controller/jobs/subscription/export/csv/path
289
		 * Relativ path to the export file
290
		 *
291
		 * It's more efficient to read and export more than one row at a time
292
		 * to speed up the export. Usually, the bigger the chunk that is exported
293
		 * at once, the less time the exporter will need. The downside is that
294
		 * the amount of memory required by the export process will increase as
295
		 * well. Therefore, it's a trade-off between memory consumption and
296
		 * export speed.
297
		 *
298
		 * @param string Relativ path with placeholders
299
		 * @since 2023.04
300
		 */
301
		$path = 'subscription-export_%Y-%m-%d_%H-%i-%s';
302
		$path = $this->context()->config()->get( 'controller/jobs/subscription/export/csv/path', $path );
303
304
		return \Aimeos\Base\Str::strtime( $path );
305
	}
306
307
308
	/**
309
	 * Creates the CSV file for the given subscriptions
310
	 *
311
	 * @param \Aimeos\MShop\Subscription\Item\Iface[] $items List of subscription items to export
312
	 * @return string Generated CSV
313
	 */
314
	protected function render( iterable $items ) : string
315
	{
316
		$context = $this->context();
317
318
		/** controller/jobs/subscription/export/csv/template
319
		 * Relative path to the template for generating the CSV subscription export.
320
		 *
321
		 * The template file contains the text and processing instructions
322
		 * to generate the result shown in the body of the frontend. The
323
		 * configuration string is the path to the template file relative
324
		 * to the templates directory (usually in templates/controller/jobs).
325
		 * You can overwrite the template file configuration in extensions and
326
		 * provide alternative templates.
327
		 *
328
		 * @param string Relative path to the template
329
		 * @since 2023.04
330
		 */
331
		$template = $context->config()->get( 'controller/jobs/subscription/export/csv/template', 'subscription/export/csv/body' );
332
333
		return $context->view()->assign( ['items' => $items] )->render( $template );
334
	}
335
}
336