Projekt

Allgemein

Profil

GX-Bug #60708 » ManufacturerAjaxController.inc.php

Moritz Bunjes, 09.01.2019 19:20

 
1
<?php
2
/* --------------------------------------------------------------
3
  ManufacturerAjaxController.inc.php 2019-01-09
4
  Gambio GmbH
5
  http://www.gambio.de
6
  Copyright (c) 2019 Gambio GmbH
7
  Released under the GNU General Public License (Version 2)
8
  [http://www.gnu.org/licenses/gpl-2.0.html]
9
  --------------------------------------------------------------
10
*/
11

    
12
MainFactory::load_class('AdminHttpViewController');
13

    
14
/**
15
 * Class ManufacturerAjaxController
16
 *
17
 * @category   System
18
 * @package    AdminHttpViewControllers
19
 * @extends    AdminHttpViewController
20
 */
21
class ManufacturerAjaxController extends AdminHttpViewController
22
{
23
	/**
24
	 * @var \ManufacturerReadService
25
	 */
26
	protected $manufacturerReadService;
27
	
28
	/**
29
	 * @var \ManufacturerWriteService
30
	 */
31
	protected $manufacturerWriteService;
32
	
33
	/**
34
	 * @var \LanguageProvider
35
	 */
36
	protected $languageProvider;
37
	
38
	
39
	/**
40
	 * Initialization of Manufacturer controller
41
	 */
42
	public function init()
43
	{
44
		$this->languageProvider         = MainFactory::create('LanguageProvider',
45
		                                                      StaticGXCoreLoader::getDatabaseQueryBuilder());
46
		$this->manufacturerReadService  = StaticGXCoreLoader::getService('ManufacturerRead');
47
		$this->manufacturerWriteService = StaticGXCoreLoader::getService('ManufacturerWrite');
48
	}
49
	
50
	
51
	/**
52
	 * Creates an manufacturer entity in the database.
53
	 *
54
	 * @return bool
55
	 */
56
	public function actionSave()
57
	{
58
		$result = $this->_storeManufacturer($this->manufacturerWriteService->createManufacturer());
59
		
60
		return MainFactory::create('JsonHttpControllerResponse', $result);
61
	}
62
	
63
	
64
	/**
65
	 * Creates manufacturers data from post data.
66
	 * manufacturer_urls from $_POST parameter are set by this method.
67
	 *
68
	 * @param \ManufacturerInterface $manufacturer
69
	 *
70
	 * @return array
71
	 */
72
	protected function _storeManufacturer(ManufacturerInterface $manufacturer)
73
	{
74
		try
75
		{
76
			$manufacturer->setName(new NonEmptyStringType(strip_tags(stripslashes($this->_getPostData('manufacturer_name')))));
77
			
78
			$this->_storeManufacturerUrls($manufacturer);
79
			$this->_storeManufacturerImage($manufacturer);
80
			$this->_storeManufacturerImageName($manufacturer);
81
			$this->_deleteImageCheckbox($manufacturer);
82
			$this->manufacturerWriteService->save($manufacturer);
83
			
84
			$result = [
85
				'renamed' => $this->_isImageNameChanged($manufacturer),
86
				'success' => true
87
			];
88
		}
89
		catch(Exception $e)
90
		{
91
			$result = [
92
				'success' => false,
93
				'renamed' => false,
94
				'msg'     => $e->getMessage()
95
			];
96
		}
97
		
98
		return $result;
99
	}
100
	
101
	
102
	/**
103
	 * Stores all manufacturer urls with language id.
104
	 *
105
	 * @param \ManufacturerInterface $manufacturer
106
	 *
107
	 * @return $this
108
	 */
109
	protected function _storeManufacturerUrls(ManufacturerInterface $manufacturer)
110
	{
111
		$manufacturerUrls = $this->_getPostData('manufacturer_urls') ? : [];
112
		$languageIds = $this->languageProvider->getIds()->getIntArray();
113
		$defaultLanguageId = $this->languageProvider->getDefaultLanguageId();
114
		foreach($languageIds as $languageId)
115
		{
116
			$url = $manufacturerUrls[(string)$languageId] ?: $manufacturerUrls[(string)$defaultLanguageId];
117
			$manufacturer->setUrl(new StringType(strip_tags($url)),
118
			                      $this->languageProvider->getCodeById(new IdType($languageId)));
119
		}
120
		
121
		return $this;
122
	}
123
	
124
	
125
	/**
126
	 * Stores an manufacturer image or replace one.
127
	 *
128
	 * @param \ManufacturerInterface $manufacturer
129
	 *
130
	 * @return $this
131
	 */
132
	protected function _storeManufacturerImage(ManufacturerInterface $manufacturer)
133
	{
134
		$imageName    = $this->manufacturerWriteService->unifyFilename(new FilenameStringType(strip_tags($_FILES['manufacturer_logo']['name'])));
135
		$filesTmpName = strip_tags($_FILES['manufacturer_logo']['tmp_name']);
136
		
137
		if(array_key_exists('manufacturer_logo', $_FILES) && $filesTmpName !== '' && $imageName !== '')
138
		{
139
			$existingFilesTmpName = new ExistingFile(new NonEmptyStringType($filesTmpName));
140
			
141
			if($manufacturer->getId() === 0)
142
			{
143
				$this->_setImageToManufacturer($manufacturer, $existingFilesTmpName, $imageName);
144
			}
145
			else
146
			{
147
				$this->_deleteImageIfExists($manufacturer);
148
				
149
				$this->_setImageToManufacturer($manufacturer, $existingFilesTmpName, $imageName);
150
			}
151
		}
152
		
153
		return $this;
154
	}
155
	
156
	
157
	/**
158
	 * Stores manufacturer image name if set.
159
	 *
160
	 * @param \ManufacturerInterface $manufacturer
161
	 *
162
	 * @return $this
163
	 */
164
	protected function _storeManufacturerImageName(ManufacturerInterface $manufacturer)
165
	{
166
		$manufacturerLogoName = strip_tags($this->_getPostData('manufacturer_logo'));
167
		
168
		if($manufacturerLogoName !== null && $manufacturerLogoName !== ''
169
		   && !(strpos($manufacturerLogoName, 'manufacturers/') !== false))
170
		{
171
			$manufacturer->setImage(new StringType('manufacturers/' . $manufacturerLogoName));
172
		}
173
		
174
		return $this;
175
	}
176
	
177
	
178
	/**
179
	 * If checkbox are checked, delete the manufacturer image.
180
	 *
181
	 * @param \ManufacturerInterface $manufacturer
182
	 *
183
	 * @return $this
184
	 */
185
	protected function _deleteImageCheckbox(ManufacturerInterface $manufacturer)
186
	{
187
		$filesTmpName = strip_tags($_FILES['manufacturer_logo']['tmp_name']);
188
		$isPostFile   = strip_tags($this->_getPostData('manufacturer_file'));
189
		
190
		if($this->_getPostData('manufacturer_checkbox') === 'true'
191
		   && ($filesTmpName === ''
192
		       || $isPostFile === 'false'))
193
		{
194
			if($isPostFile === 'true')
195
			{
196
				$this->_removeImage();
197
				$manufacturer->setImage(new StringType(''));
198
			}
199
			
200
			if($isPostFile === 'false')
201
			{
202
				$manufacturer->setImage(new StringType(''));
203
			}
204
		}
205
		
206
		return $this;
207
	}
208
	
209
	
210
	/**
211
	 * Checks if the name of the image has changed.
212
	 *
213
	 * @param \ManufacturerInterface $manufacturer
214
	 *
215
	 * @return boolean
216
	 */
217
	protected function _isImageNameChanged(ManufacturerInterface $manufacturer)
218
	{
219
		
220
		if(array_key_exists('manufacturer_logo', $_FILES)
221
		   && strip_tags($_FILES['manufacturer_logo']['tmp_name']) !== '')
222
		{
223
			
224
			return basename($manufacturer->getImage())
225
			       === strip_tags($_FILES['manufacturer_logo']['name']) ? false : true;
226
		}
227
		
228
		return false;
229
	}
230
	
231
	
232
	/**
233
	 * Set an Image to an Manufacturer after saving it in the Filesystem.
234
	 *
235
	 * @param \ManufacturerInterface $manufacturer
236
	 * @param \ExistingFile          $existingFilesTmpName
237
	 * @param \FilenameStringType    $imageName
238
	 *
239
	 * @return $this
240
	 */
241
	protected function _setImageToManufacturer(ManufacturerInterface $manufacturer,
242
	                                           ExistingFile $existingFilesTmpName,
243
	                                           FilenameStringType $imageName)
244
	{
245
		$this->manufacturerWriteService->saveImage($existingFilesTmpName, $imageName);
246
		$manufacturer->setImage(new StringType('manufacturers/' . $imageName->asString()));
247
		
248
		return $this;
249
	}
250
	
251
	
252
	/**
253
	 * Deletes image from manufacturer if set.
254
	 *
255
	 * @param \ManufacturerInterface $manufacturer
256
	 *
257
	 * @return $this
258
	 */
259
	protected function _deleteImageIfExists(ManufacturerInterface $manufacturer)
260
	{
261
		if($manufacturer->getImage() !== '')
262
		{
263
			$this->manufacturerWriteService->deleteImage(new IdType($manufacturer->getId()));
264
		}
265
		
266
		return $this;
267
	}
268
	
269
	
270
	/**
271
	 * Removes an manufacturers image in the database and filesystem if image is set.
272
	 *
273
	 * @return $this
274
	 */
275
	public function _removeImage()
276
	{
277
		$manufacturer = $this->_manufacturerById('post');
278
		
279
		if($manufacturer->getImage() !== '')
280
		{
281
			$this->manufacturerWriteService->deleteImage(new IdType($manufacturer->getId()));
282
		}
283
		
284
		return $this;
285
	}
286
	
287
	
288
	/**
289
	 *
290
	 *
291
	 * @param string $type
292
	 *
293
	 * @return \ManufacturerInterface
294
	 */
295
	protected function _manufacturerById($type = 'get')
296
	{
297
		$id = ($type === 'post') ? $this->_getPostData('id') : $this->_getQueryParameter('id');
298
		
299
		return $this->manufacturerReadService->getById(new IdType($id));
300
	}
301
	
302
	
303
	/**
304
	 * Gets all manufacturers entity's from database.
305
	 *
306
	 * @return bool
307
	 */
308
	public function actionGetData()
309
	{
310
		return MainFactory::create('JsonHttpControllerResponse',
311
		                           $this->_serializeManufacturerCollection($this->manufacturerReadService->getAll()));
312
	}
313
	
314
	
315
	/**
316
	 * Serializes manufacturer collections.
317
	 *
318
	 * @param \ManufacturerCollection $manufacturerCollection Manufacturer collection to be serialized.
319
	 *
320
	 * @return array Serialized manufacturer collection array.
321
	 */
322
	protected function _serializeManufacturerCollection(ManufacturerCollection $manufacturerCollection)
323
	{
324
		$data = [];
325
		foreach($manufacturerCollection->getArray() as $manufacturer)
326
		{
327
			$data[] = $this->_serializeManufacturer($manufacturer);
328
		}
329
		
330
		return $data;
331
	}
332
	
333
	
334
	/**
335
	 * Serializes manufacturer entities.
336
	 *
337
	 * @param \ManufacturerInterface $manufacturer Manufacturer entity to be serialized.
338
	 *
339
	 * @return array Serialized manufacturer array.
340
	 */
341
	protected function _serializeManufacturer(ManufacturerInterface $manufacturer)
342
	{
343
		return [
344
			'id'           => $manufacturer->getId(),
345
			'name'         => $manufacturer->getName(),
346
			'imagePath'    => '../images/' . $manufacturer->getImage(),
347
			'image'        => $manufacturer->getImage(),
348
			'dateAdded'    => $manufacturer->getDateAdded()->format('d.m.Y H:i'),
349
			'lastModified' => $manufacturer->getLastModified()->format('d.m.Y H:i'),
350
			'urls'         => $manufacturer->getUrls(),
351
			'languageIds'  => $this->_langIdsByLangCode(array_keys($manufacturer->getUrls()))
352
		];
353
	}
354
	
355
	
356
	/**
357
	 * Converts an array with language codes to an array with codes as key and the language id as value.
358
	 *
359
	 * @param array $languageCodes Array that contains the language codes.
360
	 *
361
	 * @return array Format: [$languageCode => $languageId, (…)].
362
	 */
363
	protected function _langIdsByLangCode(array $languageCodes)
364
	{
365
		$data = [];
366
		
367
		foreach($languageCodes as $languageCode)
368
		{
369
			$data[$languageCode] = $this->languageProvider->getIdByCode(new LanguageCode(new StringType($languageCode)));
370
		}
371
		
372
		return $data;
373
	}
374
	
375
	
376
	/**
377
	 * Gets an manufacturers entity from database by id.
378
	 *
379
	 * @return bool
380
	 */
381
	public function actionGetById()
382
	{
383
		return MainFactory::create('JsonHttpControllerResponse',
384
		                           $this->_serializeManufacturer($this->_manufacturerById()));
385
	}
386
	
387
	
388
	/**
389
	 * Updates an manufacturers entity in the database.
390
	 *
391
	 * @return bool
392
	 */
393
	public function actionUpdate()
394
	{
395
		$result = $this->_storeManufacturer($this->manufacturerReadService->getById(new IdType($this->_getPostData('id'))));
396
		
397
		return MainFactory::create('JsonHttpControllerResponse', $result);
398
	}
399
	
400
	
401
	/**
402
	 * Removes an manufacturers entity in the database.
403
	 *
404
	 * @return bool
405
	 */
406
	public function actionRemove()
407
	{
408
		$this->_removeImage()->manufacturerWriteService->delete($this->_manufacturerById('post'));
409
		
410
		return MainFactory::create('JsonHttpControllerResponse', ['success' => true]);
411
	}
412
	
413
	
414
	/**
415
	 * Deserialize manufacturer entities.
416
	 *
417
	 * @param string $manufacturerJson Manufacturer entity as json string.
418
	 *
419
	 * @param null   $id
420
	 *
421
	 * @return \Manufacturer Deserialize manufacturer entity.
422
	 */
423
	protected function _deserializeManufacturer($manufacturerJson, $id = null)
424
	{
425
		$manufacturerData = json_decode($manufacturerJson, true);
426
		$manufacturer     = $id ? $this->manufacturerReadService->getById(new IdType($id)) : $this->manufacturerWriteService->createManufacturer();
427
		
428
		$manufacturer->setName(new StringType($manufacturerData['name']))->setImage(new StringType('manufacturers/'
429
		                                                                                           . $manufacturerData['image']));
430
		
431
		foreach($manufacturerData['urls'] as $languageCode => $url)
432
		{
433
			$manufacturer->setUrl(new StringType($url), new LanguageCode(new StringType($languageCode)));
434
		}
435
		
436
		return $manufacturer;
437
	}
438
}
    (1-1/1)