Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
DataProvider.php
Go to the documentation of this file.
1 <?php
7 
16 use Magento\Customer\Model\FileProcessorFactory;
19 use Magento\Customer\Model\ResourceModel\Customer\CollectionFactory as CustomerCollectionFactory;
30 
38 {
42  const MAX_FILE_SIZE = 2097152;
43 
47  protected $collection;
48 
52  protected $eavConfig;
53 
57  protected $filterPool;
58 
62  protected $loadedData;
63 
67  private $countryWithWebsiteSource;
68 
72  private $shareConfig;
73 
78  protected $metaProperties = [
79  'dataType' => 'frontend_input',
80  'visible' => 'is_visible',
81  'required' => 'is_required',
82  'label' => 'frontend_label',
83  'sortOrder' => 'sort_order',
84  'notice' => 'note',
85  'default' => 'default_value',
86  'size' => 'multiline_count',
87  ];
88 
94  protected $formElement = [
95  'text' => 'input',
96  'hidden' => 'input',
97  'boolean' => 'checkbox',
98  ];
99 
104 
109  protected $session;
110 
114  private $fileProcessorFactory;
115 
121  private $fileUploaderTypes = [
122  'image',
123  'file',
124  ];
125 
131  private $forbiddenCustomerFields = [
132  'password_hash',
133  'rp_token',
134  'confirmation',
135  ];
136 
137  /*
138  * @var ContextInterface
139  */
140  private $context;
141 
147  private $allowToShowHiddenAttributes;
148 
164  public function __construct(
165  $name,
169  CustomerCollectionFactory $customerCollectionFactory,
172  FileProcessorFactory $fileProcessorFactory = null,
173  array $meta = [],
174  array $data = [],
175  ContextInterface $context = null,
176  $allowToShowHiddenAttributes = true
177  ) {
178  parent::__construct($name, $primaryFieldName, $requestFieldName, $meta, $data);
179  $this->eavValidationRules = $eavValidationRules;
180  $this->collection = $customerCollectionFactory->create();
181  $this->collection->addAttributeToSelect('*');
182  $this->eavConfig = $eavConfig;
183  $this->filterPool = $filterPool;
184  $this->fileProcessorFactory = $fileProcessorFactory ?: $this->getFileProcessorFactory();
185  $this->context = $context ?: ObjectManager::getInstance()->get(ContextInterface::class);
186  $this->allowToShowHiddenAttributes = $allowToShowHiddenAttributes;
187  $this->meta['customer']['children'] = $this->getAttributesMeta(
188  $this->eavConfig->getEntityType('customer')
189  );
190  $this->meta['address']['children'] = $this->getAttributesMeta(
191  $this->eavConfig->getEntityType('customer_address')
192  );
193  }
194 
202  protected function getSession()
203  {
204  if ($this->session === null) {
205  $this->session = ObjectManager::getInstance()->get(
206  \Magento\Framework\Session\SessionManagerInterface::class
207  );
208  }
209  return $this->session;
210  }
211 
217  public function getData()
218  {
219  if (isset($this->loadedData)) {
220  return $this->loadedData;
221  }
222  $items = $this->collection->getItems();
224  foreach ($items as $customer) {
225  $result['customer'] = $customer->getData();
226 
227  $this->overrideFileUploaderData($customer, $result['customer']);
228 
229  $result['customer'] = array_diff_key(
230  $result['customer'],
231  array_flip($this->forbiddenCustomerFields)
232  );
233  unset($result['address']);
234 
236  foreach ($customer->getAddresses() as $address) {
237  $addressId = $address->getId();
238  $address->load($addressId);
239  $result['address'][$addressId] = $address->getData();
240  $this->prepareAddressData($addressId, $result['address'], $result['customer']);
241 
242  $this->overrideFileUploaderData($address, $result['address'][$addressId]);
243  }
244  $this->loadedData[$customer->getId()] = $result;
245  }
246 
247  $data = $this->getSession()->getCustomerFormData();
248  if (!empty($data)) {
249  $customerId = isset($data['customer']['entity_id']) ? $data['customer']['entity_id'] : null;
250  $this->loadedData[$customerId] = $data;
251  $this->getSession()->unsCustomerFormData();
252  }
253 
254  return $this->loadedData;
255  }
256 
266  private function overrideFileUploaderData($entity, array &$entityData)
267  {
268  $attributes = $entity->getAttributes();
269  foreach ($attributes as $attribute) {
271  if (in_array($attribute->getFrontendInput(), $this->fileUploaderTypes)) {
272  $entityData[$attribute->getAttributeCode()] = $this->getFileUploaderData(
273  $entity->getEntityType(),
274  $attribute,
275  $entityData
276  );
277  }
278  }
279  }
280 
290  private function getFileUploaderData(
291  Type $entityType,
292  Attribute $attribute,
293  array $customerData
294  ) {
295  $attributeCode = $attribute->getAttributeCode();
296 
297  $file = isset($customerData[$attributeCode])
299  : '';
300 
302  $fileProcessor = $this->getFileProcessorFactory()->create([
303  'entityTypeCode' => $entityType->getEntityTypeCode(),
304  ]);
305 
306  if (!empty($file)
307  && $fileProcessor->isExist($file)
308  ) {
309  $stat = $fileProcessor->getStat($file);
310  $viewUrl = $fileProcessor->getViewUrl($file, $attribute->getFrontendInput());
311 
312  return [
313  [
314  'file' => $file,
315  'size' => isset($stat) ? $stat['size'] : 0,
316  'url' => isset($viewUrl) ? $viewUrl : '',
317  'name' => basename($file),
318  'type' => $fileProcessor->getMimeType($file),
319  ],
320  ];
321  }
322 
323  return [];
324  }
325 
333  protected function getAttributesMeta(Type $entityType)
334  {
335  $meta = [];
336  $attributes = $entityType->getAttributeCollection();
337  /* @var AbstractAttribute $attribute */
338  foreach ($attributes as $attribute) {
339  $this->processFrontendInput($attribute, $meta);
340 
341  $code = $attribute->getAttributeCode();
342 
343  // use getDataUsingMethod, since some getters are defined and apply additional processing of returning value
344  foreach ($this->metaProperties as $metaName => $origName) {
345  $value = $attribute->getDataUsingMethod($origName);
346  $meta[$code]['arguments']['data']['config'][$metaName] = ($metaName === 'label') ? __($value) : $value;
347  if ('frontend_input' === $origName) {
348  $meta[$code]['arguments']['data']['config']['formElement'] = isset($this->formElement[$value])
349  ? $this->formElement[$value]
350  : $value;
351  }
352  }
353 
354  if ($attribute->usesSource()) {
356  $meta[$code]['arguments']['data']['config']['options'] = $this->getCountryWithWebsiteSource()
357  ->getAllOptions();
358  } else {
359  $meta[$code]['arguments']['data']['config']['options'] = $attribute->getSource()->getAllOptions();
360  }
361  }
362 
363  $rules = $this->eavValidationRules->build($attribute, $meta[$code]['arguments']['data']['config']);
364  if (!empty($rules)) {
365  $meta[$code]['arguments']['data']['config']['validation'] = $rules;
366  }
367 
368  $meta[$code]['arguments']['data']['config']['componentType'] = Field::NAME;
369  $meta[$code]['arguments']['data']['config']['visible'] = $this->canShowAttribute($attribute);
370 
371  $this->overrideFileUploaderMetadata($entityType, $attribute, $meta[$code]['arguments']['data']['config']);
372  }
373 
374  $this->processWebsiteMeta($meta);
375  return $meta;
376  }
377 
384  private function canShowAttributeInForm(AbstractAttribute $customerAttribute)
385  {
386  $isRegistration = $this->context->getRequestParam($this->getRequestFieldName()) === null;
387 
388  if ($customerAttribute->getEntityType()->getEntityTypeCode() === 'customer') {
389  return is_array($customerAttribute->getUsedInForms()) &&
390  (
391  (in_array('customer_account_create', $customerAttribute->getUsedInForms()) && $isRegistration) ||
392  (in_array('customer_account_edit', $customerAttribute->getUsedInForms()) && !$isRegistration)
393  );
394  } else {
395  return is_array($customerAttribute->getUsedInForms()) &&
396  in_array('customer_address_edit', $customerAttribute->getUsedInForms());
397  }
398  }
399 
406  private function canShowAttribute(AbstractAttribute $customerAttribute)
407  {
408  $userDefined = (bool) $customerAttribute->getIsUserDefined();
409  if (!$userDefined) {
410  return $customerAttribute->getIsVisible();
411  }
412 
413  $canShowOnForm = $this->canShowAttributeInForm($customerAttribute);
414 
415  return ($this->allowToShowHiddenAttributes && $canShowOnForm) ||
416  (!$this->allowToShowHiddenAttributes && $canShowOnForm && $customerAttribute->getIsVisible());
417  }
418 
425  private function getCountryWithWebsiteSource()
426  {
427  if (!$this->countryWithWebsiteSource) {
428  $this->countryWithWebsiteSource = ObjectManager::getInstance()->get(CountryWithWebsites::class);
429  }
430 
431  return $this->countryWithWebsiteSource;
432  }
433 
440  private function getShareConfig()
441  {
442  if (!$this->shareConfig) {
443  $this->shareConfig = ObjectManager::getInstance()->get(\Magento\Customer\Model\Config\Share::class);
444  }
445 
446  return $this->shareConfig;
447  }
448 
455  private function processWebsiteMeta(&$meta)
456  {
457  if (isset($meta[CustomerInterface::WEBSITE_ID]) && $this->getShareConfig()->isGlobalScope()) {
458  $meta[CustomerInterface::WEBSITE_ID]['arguments']['data']['config']['isGlobalScope'] = 1;
459  }
460 
461  if (isset($meta[AddressInterface::COUNTRY_ID]) && !$this->getShareConfig()->isGlobalScope()) {
462  $meta[AddressInterface::COUNTRY_ID]['arguments']['data']['config']['filterBy'] = [
463  'target' => '${ $.provider }:data.customer.website_id',
464  'field' => 'website_ids'
465  ];
466  }
467  }
468 
479  private function overrideFileUploaderMetadata(
480  Type $entityType,
481  AbstractAttribute $attribute,
482  array &$config
483  ) {
484  if (in_array($attribute->getFrontendInput(), $this->fileUploaderTypes)) {
485  $maxFileSize = self::MAX_FILE_SIZE;
486 
487  if (isset($config['validation']['max_file_size'])) {
488  $maxFileSize = (int)$config['validation']['max_file_size'];
489  }
490 
491  $allowedExtensions = [];
492 
493  if (isset($config['validation']['file_extensions'])) {
494  $allowedExtensions = explode(',', $config['validation']['file_extensions']);
495  array_walk($allowedExtensions, function (&$value) {
496  $value = strtolower(trim($value));
497  });
498  }
499 
500  $allowedExtensions = implode(' ', $allowedExtensions);
501 
502  $entityTypeCode = $entityType->getEntityTypeCode();
503  $url = $this->getFileUploadUrl($entityTypeCode);
504 
505  $config = [
506  'formElement' => 'fileUploader',
507  'componentType' => 'fileUploader',
508  'maxFileSize' => $maxFileSize,
509  'allowedExtensions' => $allowedExtensions,
510  'uploaderConfig' => [
511  'url' => $url,
512  ],
513  'label' => $this->getMetadataValue($config, 'label'),
514  'sortOrder' => $this->getMetadataValue($config, 'sortOrder'),
515  'required' => $this->getMetadataValue($config, 'required'),
516  'visible' => $this->getMetadataValue($config, 'visible'),
517  'validation' => $this->getMetadataValue($config, 'validation'),
518  ];
519  }
520  }
521 
530  private function getMetadataValue($config, $name, $default = null)
531  {
532  $value = isset($config[$name]) ? $config[$name] : $default;
533  return $value;
534  }
535 
542  private function getFileUploadUrl($entityTypeCode)
543  {
544  switch ($entityTypeCode) {
546  $url = 'customer/file/customer_upload';
547  break;
548 
550  $url = 'customer/file/address_upload';
551  break;
552 
553  default:
554  $url = '';
555  break;
556  }
557  return $url;
558  }
559 
567  private function processFrontendInput(AttributeInterface $attribute, array &$meta)
568  {
569  $code = $attribute->getAttributeCode();
570  if ($attribute->getFrontendInput() === 'boolean') {
571  $meta[$code]['arguments']['data']['config']['prefer'] = 'toggle';
572  $meta[$code]['arguments']['data']['config']['valueMap'] = [
573  'true' => '1',
574  'false' => '0',
575  ];
576  }
577  }
578 
587  protected function prepareAddressData($addressId, array &$addresses, array $customer)
588  {
589  if (isset($customer['default_billing'])
590  && $addressId == $customer['default_billing']
591  ) {
592  $addresses[$addressId]['default_billing'] = $customer['default_billing'];
593  }
594  if (isset($customer['default_shipping'])
595  && $addressId == $customer['default_shipping']
596  ) {
597  $addresses[$addressId]['default_shipping'] = $customer['default_shipping'];
598  }
599  if (isset($addresses[$addressId]['street']) && !is_array($addresses[$addressId]['street'])) {
600  $addresses[$addressId]['street'] = explode("\n", $addresses[$addressId]['street']);
601  }
602  }
603 
610  private function getFileProcessorFactory()
611  {
612  if ($this->fileProcessorFactory === null) {
613  $this->fileProcessorFactory = ObjectManager::getInstance()
614  ->get(\Magento\Customer\Model\FileProcessorFactory::class);
615  }
616  return $this->fileProcessorFactory;
617  }
618 }
$customerData
$customer
Definition: customers.php:11
$config
Definition: fraud_order.php:17
$addresses
Definition: address_list.php:7
__construct( $name, $primaryFieldName, $requestFieldName, EavValidationRules $eavValidationRules, CustomerCollectionFactory $customerCollectionFactory, Config $eavConfig, FilterPool $filterPool, FileProcessorFactory $fileProcessorFactory=null, array $meta=[], array $data=[], ContextInterface $context=null, $allowToShowHiddenAttributes=true)
__()
Definition: __.php:13
$allowedExtensions
Definition: uploader.phtml:12
$address
Definition: customer.php:38
$value
Definition: gender.phtml:16
$attributeCode
Definition: extend.phtml:12
prepareAddressData($addressId, array &$addresses, array $customer)
$entity
Definition: element.phtml:22
$attributes
Definition: matrix.phtml:13
$code
Definition: info.phtml:12
$items