Passed
Push — master ( 44bc4c...88d223 )
by Aimeos
03:05
created

Standard::path()   A

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-2022
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
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', 'Subscription 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 subscriptions 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', 'subscription-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
				$str = 'Subscription export error: ' . $e->getMessage() . "\n" . $e->getTraceAsString();
178
				$context->logger()->error( $str, 'subscription/export/csv' );
179
			}
180
181
			$mq->del( $msg );
182
		}
183
	}
184
185
186
	/**
187
	 * Initializes the search criteria
188
	 *
189
	 * @param \Aimeos\Base\Criteria\Iface $criteria New criteria object
190
	 * @param array $msg Message data
191
	 * @return \Aimeos\Base\Criteria\Iface Initialized criteria object
192
	 */
193
	protected function criteria( \Aimeos\Base\Criteria\Iface $criteria, array $msg ) : \Aimeos\Base\Criteria\Iface
194
	{
195
		/** controller/jobs/subscription/export/csv/max-size
196
		 * Maximum number of CSV rows to export at once
197
		 *
198
		 * It's more efficient to read and export more than one row at a time
199
		 * to speed up the export. Usually, the bigger the chunk that is exported
200
		 * at once, the less time the exporter will need. The downside is that
201
		 * the amount of memory required by the export process will increase as
202
		 * well. Therefore, it's a trade-off between memory consumption and
203
		 * export speed.
204
		 *
205
		 * @param integer Number of rows
206
		 * @since 2023.04
207
		 */
208
		$size = (int) $this->context()->config()->get( 'controller/jobs/subscription/export/csv/max-size', 1000 );
209
210
		return $criteria->add( $criteria->parse( $msg['filter'] ?? [] ) )->order( $msg['sort'] ?? [] )->slice( 0, $size );
211
	}
212
213
214
	/**
215
	 * Exports the orders
216
	 *
217
	 * @param array $msg Message data passed from the frontend
218
	 */
219
	protected function export( array $msg )
220
	{
221
		if( ( $fh = tmpfile() ) === false ) {
222
			throw new \Aimeos\Controller\Jobs\Exception( 'Unable to create temporary file' );
223
		}
224
225
		$path = $this->path();
226
		$lcontext = $this->getLocaleContext( $msg );
227
228
		$manager = \Aimeos\MShop::create( $lcontext, 'subscription' );
229
		$cursor = $manager->cursor( $this->criteria( $manager->filter( false, true ), $msg ) );
230
231
		while( $items = $manager->iterate( $cursor, ['order', 'order/address', 'order/product'] ) )
232
		{
233
			if( fwrite( $fh, $this->render( $items ) ) === false ) {
234
				throw new \Aimeos\Controller\Jobs\Exception( 'Unable to add data to temporary file' );
235
			}
236
		}
237
238
		rewind( $fh );
239
		$lcontext->fs( 'fs-export' )->writes( $path, $fh );
240
		fclose( $fh );
241
242
		$manager = \Aimeos\MAdmin::create( $lcontext, 'job' );
243
		$manager->save( $manager->create()->setPath( $path )->setLabel( $path ), false );
244
	}
245
246
247
	/**
248
	 * Returns a new context including the locale from the message data
249
	 *
250
	 * @param array $msg Message data including a "sitecode" value
251
	 * @return \Aimeos\MShop\ContextIface New context item with updated locale
252
	 */
253
	protected function getLocaleContext( array $msg ) : \Aimeos\MShop\ContextIface
254
	{
255
		$lcontext = clone $this->context();
256
		$manager = \Aimeos\MShop::create( $lcontext, 'locale' );
257
258
		$sitecode = ( isset( $msg['sitecode'] ) ? $msg['sitecode'] : 'default' );
259
		$localeItem = $manager->bootstrap( $sitecode, '', '', false, \Aimeos\MShop\Locale\Manager\Base::SITE_ONE );
260
261
		return $lcontext->setLocale( $localeItem );
262
	}
263
264
265
	/**
266
	 * Returns the relative path the subscriptions should be exported to
267
	 *
268
	 * @return string Relativ path to the export file
269
	 */
270
	protected function path() : string
271
	{
272
		/** controller/jobs/subscription/export/csv/path
273
		 * Relativ path to the export file
274
		 *
275
		 * It's more efficient to read and export more than one row at a time
276
		 * to speed up the export. Usually, the bigger the chunk that is exported
277
		 * at once, the less time the exporter will need. The downside is that
278
		 * the amount of memory required by the export process will increase as
279
		 * well. Therefore, it's a trade-off between memory consumption and
280
		 * export speed.
281
		 *
282
		 * @param string Relativ path with placeholders
283
		 * @since 2023.04
284
		 */
285
		$path = 'subscription-export_%Y-%m-%d_%H-%i-%s';
286
		$path = $this->context()->config()->get( 'controller/jobs/subscription/export/csv/path', $path );
287
288
		return \Aimeos\Base\Str::strtime( $path );
289
	}
290
291
292
	/**
293
	 * Creates the CSV file for the given subscriptions
294
	 *
295
	 * @param \Aimeos\MShop\Subscription\Item\Iface[] $items List of subscription items to export
296
	 * @return string Generated CSV
297
	 */
298
	protected function render( iterable $items ) : string
299
	{
300
		$context = $this->context();
301
		$template = $context->config()->get( 'controller/jobs/subscription/export/csv/template', 'subscription/export/csv/body' );
302
303
		return $context->view()->assign( ['items' => $items] )->render( $template );
304
	}
305
}
306