CreateEntityRow.php 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. namespace Magento\Framework\Model\ResourceModel\Db;
  7. use Magento\Framework\EntityManager\EntityMetadata;
  8. use Magento\Framework\EntityManager\MetadataPool;
  9. /**
  10. * Class ReadEntityRow
  11. */
  12. class CreateEntityRow
  13. {
  14. /**
  15. * @var MetadataPool
  16. */
  17. protected $metadataPool;
  18. /**
  19. * @param MetadataPool $metadataPool
  20. */
  21. public function __construct(
  22. MetadataPool $metadataPool
  23. ) {
  24. $this->metadataPool = $metadataPool;
  25. }
  26. /**
  27. * @param EntityMetadata $metadata
  28. * @param array $data
  29. * @return array
  30. */
  31. protected function prepareData(EntityMetadata $metadata, $data)
  32. {
  33. $output = [];
  34. foreach ($metadata->getEntityConnection()->describeTable($metadata->getEntityTable()) as $column) {
  35. if ($column['DEFAULT'] == 'CURRENT_TIMESTAMP' /*|| $column['IDENTITY']*/) {
  36. continue;
  37. }
  38. if (isset($data[strtolower($column['COLUMN_NAME'])])) {
  39. $output[strtolower($column['COLUMN_NAME'])] = $data[strtolower($column['COLUMN_NAME'])];
  40. } elseif ($column['DEFAULT'] === null) {
  41. $output[strtolower($column['COLUMN_NAME'])] = null;
  42. }
  43. }
  44. if (empty($data[$metadata->getIdentifierField()])) {
  45. $output[$metadata->getIdentifierField()] = $metadata->generateIdentifier();
  46. }
  47. return $output;
  48. }
  49. /**
  50. * @param string $entityType
  51. * @param array $data
  52. * @return array
  53. */
  54. public function execute($entityType, $data)
  55. {
  56. $metadata = $this->metadataPool->getMetadata($entityType);
  57. $linkField = $metadata->getLinkField();
  58. $entityTable = $metadata->getEntityTable();
  59. $connection = $metadata->getEntityConnection();
  60. $connection->insert($entityTable, $this->prepareData($metadata, $data));
  61. $data[$linkField] = $connection->lastInsertId($entityTable);
  62. return $data;
  63. }
  64. }