Get upload file column headers (first row).

@param \CsvMigrations\Model\Entity\Import $entity Import entity
@return string[]
194278
public static function getUploadHeaders(ImportEntity $entity) : array
    {
        $reader = Reader::createFromPath($entity->filename, 'r');

        return $reader->fetchOne();
    }
292253
protected function prepareInsertData($entity) : array
    {
        $data = parent::prepareInsertData($entity);

        // Populate the discriminator column
        $discColumn = $this->class->discriminatorColumn;
        $tableName  = $discColumn->getTableName();
        $columnName = $discColumn->getColumnName();

        $this->columns[$columnName] = $discColumn;

        $data[$tableName][$columnName] = $this->class->discriminatorValue;

        return $data;
    }
812741
public function getColumnListing($table, $filed = '')
    {
        $columns =  \Schema::connection($this->databaseName)->getColumnListing($table);
        if($filed) {
        	return in_array(
	            strtolower($filed), array_map('strtolower', $columns)
	        );
        }
        return $columns;
    }
665517
public function getBlockVariables($field, $entity)
    {
        $defaults = parent::getBlockVariables($field, $entity);

        return [
            'value' => $defaults['value'],
            'truncate' => $field->getOption('truncate', 80),
            'escape' => $field->getOption('escape', true),
        ] + $defaults;
    }
813107
public function getOriginalEntityData($entity)
    {
        $oid = spl_object_hash($entity);

        if (isset($this->originalEntityData[$oid])) {
            return $this->originalEntityData[$oid];
        }

        return array();
    }
1041479
protected function getDimensions(UploadedFileInterface $upload)
    {
        $dimension = getimagesize($upload->getStream()->getMetadata('uri'));

        return [
            'width'  => $dimension[ 0 ],
            'height' => $dimension[ 1 ]
        ];
    }
869734
protected function generateFields(Entity $entity)
    {
        $fields     = [];
        $descriptor = $entity->getDescriptor();
        $extensions = $descriptor->getExtensionList() ?: [];

        foreach ($extensions as $field) {
            $fields[] = $this->generateExtensionField($entity, $field);
        }

        return $fields;
    }
237285
protected function getCellContent($entity)
    {
        $content = $this->getValue($entity);
        if ($content && isset($this->options['translate_content']) && $this->options['translate_content']) {
            $translator = isset($this->options['translator']) ? $this->options['translator'] : null;
            if ($translator) {
                $content = isset($this->options['translation_content_prefix'])
                    ? $this->options['translation_content_prefix'].$content
                    : $content;

                $translationOptions = isset($this->options['translation_options'])
                    ? $this->options['translation_options']
                    : array();

                $translationDomain = isset($this->options['translation_domain'])
                    ? $this->options['translation_domain']
                    : null;

                $content = $translator->trans($content, $translationOptions, $translationDomain);
            }
        }
        return $content;
    }
476761
private static function getFields($entity, $type = 1): array
    {
        $changeFields = [];

        // 实体表结构信息
        list($table, $id, $idColumn, $fields) = self::getClassMetaData($entity);

        // 实体映射字段、值处理以及验证处理
        $idValue = null;
        foreach ($fields as $proName => $proAry) {
            $column  = $proAry['column'];
            $default = $proAry['default'];

            // 实体属性对应值
            $proValue = self::getEntityProValue($entity, $proName);

            self::validate($proAry, $proValue);

            if($type === 1 && $proValue === null){
                continue;
            }

            // insert逻辑
            if ($type === 1 && $id === $proName && $default === $proValue) {
                continue;
            }

            // update逻辑
            if ($type === 2 && null === $proValue) {
                continue;
            }

            // delete和find逻辑
            if ($type === 3 && $default === $proValue) {
                continue;
            }

            // id值赋值
            if ($idColumn === $column) {
                $idValue = $proValue;
            }

            $changeFields[$column] = $proValue;
        }

        // 如果是更新找到变化的字段
        if ($type === 2) {
            $oldFields    = $entity->getAttrs();
            $oldFields    = self::getDbOldFields(get_class($entity), $oldFields);
            $changeFields = self::getUpdateFields($oldFields, $changeFields);
        }
        return [$table, $idColumn, $idValue, $changeFields];
    }
1095555
public function processEntity(string $entity, callable $callback = null): array
    {
        $this->dbUtils->assertTableExists($entity);

        $this->priKey = $this->dbUtils->getPrimaryKey($entity);
        $this->entityCols = $this->dbUtils->getTableCols($entity);
        $this->entity = $entity;

        $actionsOnThatEntity = $this->whatToDoWithEntity();
        $this->queries = [];

        // Prepare CSV
        if ($this->mode === 'batch') {
            $this->csv = new CSVWriter();
            $this->csv->setCsvControl('|', $this->dbHelper->getEnclosureForCSV());
        }

        // Wrap everything in a transaction
        $conn = $this->dbUtils->getConn();
        try {
            $conn->beginTransaction();

            if ($actionsOnThatEntity & self::UPDATE_TABLE) {
                $this->updateData($callback);
            }

            if ($actionsOnThatEntity & self::INSERT_TABLE) {
                $this->insertData($callback);
            }

            $conn->commit();
        } catch (\Exception $e) {
            $conn->rollBack();
            $conn->close(); // To avoid locks

            throw $e;
        }

        return $this->queries;
    }
1280702
protected function parseImports($content, $file)
    {
        if (!isset($content['imports'])) {
            return $content;
        }

        foreach ($content['imports'] as $import) {
            $this->setCurrentDir(dirname($file));
            $content = ArrayUtils::merge($this->import($import['resource'], null, isset($import['ignore_errors'])
                ? (Boolean) $import['ignore_errors'] : false, $file), $content);
        }

        unset($content['imports']);

        return $content;
    }
188212
public function getFieldsChoices($entity = null)
    {
        $entityChoices = $this->getEntityChoices();

        $fieldsChoices = [];

        $translator = $this->getContainer()->get('translator');

        $adminPool = $this->getContainer()->get('sonata.admin.pool');

        $em = $this->getContainer()->get('doctrine')->getManager();

        foreach ($entityChoices as $entityChoiceKey => $entityChoice) {
            if ($entity && $entityChoice !== $entity) {
                continue;
            }

            $admin = $adminPool->getAdminByClass($entityChoice);

            if (!$admin) {
                throw new \RuntimeException('Not found admin by class: ' . $entityChoice);
            }

            $translation_domain = $admin->getTranslationDomain();

            $classMetadata = $em->getClassMetadata($entityChoice);

            /** @var array $associationMappings */
            $associationMappings = $classMetadata->associationMappings;

            /** @var array $fieldsMappings */
            $fieldsMappings = $classMetadata->fieldMappings;

            foreach ($fieldsMappings as $fieldsMapping) {
                $fieldsChoices[$fieldsMapping['fieldName']] =
                    $entityChoiceKey . ' / ' . $translator->trans('form.label_' . $fieldsMapping['columnName'], [], $translation_domain);
            }

            foreach ($associationMappings as $associationMapping) {
                $mappingFieldName = $associationMapping['fieldName'];
                $mappingAdmin = $adminPool->getAdminByClass($associationMapping['targetEntity']);

                if (!$mappingAdmin) {
                    continue;
                }

                $mappingTranslationDomain = $mappingAdmin->getTranslationDomain();

                $classMetadataMapping = $em->getClassMetadata($associationMapping['targetEntity']);

                /** @var array $fieldsMappingsMapping */
                $fieldsMappingsMapping = $classMetadataMapping->fieldMappings;

                foreach ($fieldsMappingsMapping as $fieldsMappingAssoc) {
                    $fieldsChoices[$mappingFieldName . '.' . $fieldsMappingAssoc['fieldName']] =
                        $entityChoiceKey . ' / '
                        . $translator->trans('form.label_' . $this->camelCaseToUnderscore($mappingFieldName), [], $translation_domain) . ' / '
                        . $translator->trans('form.label_' . $this->camelCaseToUnderscore($fieldsMappingAssoc['fieldName']), [], $mappingTranslationDomain);
                }
            }
        }

        return $fieldsChoices;
    }
958549
protected function upload(UploadedFile $file): array
    {
        $media = new Media();
        $media->bucket = Yii::$app->request->get('bucket');
        $media->setDynamicFileRules($this->rules);
        $result = $media->linkMedia($file, $this->model::className(), $this->model->getPrimaryKey());
        if (is_object($result)) {
            return [
                'status' => 'success',
                'name' => $file->name,
                'mediaId' => $result->id,
                'media' => $result,
            ];
        } else {
            return [
                'status' => 'error',
                'message' => $result,
            ];
        }
    }
454758
protected function validateUploadImages($entity)
    {
        $files = $this->request->file('files');

        if (empty($files['name'][0])) {
            return null;
        }

        $directory = $this->config->get("{$entity}_image_dirname", $entity);
        $results = $this->file_transfer->uploadMultiple($files, 'image', "image/upload/$directory");

        foreach ($results['transferred'] as $key => $path) {
            $this->setSubmitted("images.$key.path", $path);
        }

        if (!empty($results['errors'])) {
            $this->setError('images', implode('<br>', (array) $results['errors']));
            return false;
        }

        return true;
    }
849295
public function import(string $id = '')
    {
        $table = TableRegistry::get('CsvMigrations.Imports');
        Assert::isInstanceOf($table, ImportsTable::class);

        $entity = '' === $id ? $table->newEntity() : $table->get($id);

        // AJAX logic
        if ($this->request->accepts('application/json')) { // Import/progress.ctp
            $this->viewBuilder()->setClassName('Json');
            $utility = new ImportUtility($this->{$this->name}, $this->request, $this->Flash);
            $columns = ['row_number', 'status', 'status_message'];
            $query = $utility->getImportResults($entity, $columns);
            Assert::isInstanceOf($query, Query::class);

            $pagination = [
                'count' => $query->count()
            ];

            $data = ImportUtility::toDatatables($this->paginate($query), $columns);
            $data = ImportUtility::actionButtons($this->paginate($query), $this->{$this->name}, $data);
            $data = ImportUtility::setStatusLabels($data, 1);

            $this->set([
                'success' => true,
                'data' => $data,
                'pagination' => $pagination,
                '_serialize' => ['success', 'data', 'pagination']
            ]);

            return;
        }

        // POST logic
        if ($this->request->is('post')) { // Import/upload.ctp
            $utility = new ImportUtility($this->{$this->name}, $this->request, $this->Flash);
            $filename = $utility->upload();
            if (!empty($filename) && $utility->create($table, $entity, $filename)) {
                return $this->redirect([$entity->id]);
            }
        }

        // PUT logic
        if ($this->request->is('put')) { // Import/mapping.ctp
            $options = ImportUtility::prepareOptions((array)$this->request->getData('options'));
            $entity = $table->patchEntity($entity, ['options' => $options]);
            if ($table->save($entity)) {
                return $this->redirect($this->request->getAttribute('here'));
            } else {
                $this->Flash->error('Unable to set import options.');
            }
        }

        // GET logic
        if (!$entity->isNew()) {
            $utility = new ImportUtility($this->{$this->name}, $this->request, $this->Flash);
            if (!$entity->get('options')) { // Import/mapping.ctp
                $this->set('headers', ImportUtility::getUploadHeaders($entity));
                $this->set('columns', $utility->getTableColumns());
            } else { // Import/progress.ctp
                $resultsTable = TableRegistry::get('CsvMigrations.ImportResults');
                $this->set('importCount', $resultsTable->find('imported', ['import' => $entity])->count());
                $this->set('pendingCount', $resultsTable->find('pending', ['import' => $entity])->count());
                $this->set('failCount', $resultsTable->find('failed', ['import' => $entity])->count());
            }
        } else { // Import/upload.ctp
            $query = $table->find('all')
                ->where(['model_name' => $this->{$this->name}->getRegistryAlias()])
                ->order(['created' => 'desc']);

            $this->set('existingImports', $query->all());
        }

        $this->set('import', $entity);

        if ($entity->isNew()) {
            $this->render('CsvMigrations.Import/upload');
        } else {
            if (!$entity->get('options')) {
                $this->render('CsvMigrations.Import/mapping');
            } else {
                $this->render('CsvMigrations.Import/progress');
            }
        }
    }
772836
private function getEntityDataArray($entity, $strict = true, $only = array())
    {
        $data = array();

        $structure = $this->getEntityStructure($entity);
        $columns = $structure->columns;

        foreach ($columns as $column) {
            if (count($only) > 0 && ! in_array($column->name, $only)) continue; // Ignore, we don't want this column!

            if (isset($entity->{$column->propertyName}) && $entity->{$column->propertyName} !== null) {
                $data[$column->name] = $entity->{$column->propertyName};
            } elseif (! isset($entity->{$column->propertyName}) && $entity->{$column->propertyName} === null) {
                // Throw exception if null not allowed and in strict mode.
                if ($strict && ! $column->null && ! $column->autoIncrement && $column->default === null) {
                    throw new ConstraintViolationException("Column '".$column->propertyName."' can't be empty! Null not allowed!");
                }

                // Fill in default value if allowed
                if (! $column->null && ! $column->autoIncrement && $column->default !== null) {
                    $data[$column->name] = $column->defaultValue();
                } else {
                    $data[$column->name] = null;
                }
            } else {
                $data[$column->name] = null;
            }
        }
        return $data;
    }
965895
public function serialize($entity)
    {
        return array($this->getName().'.'.$this->_target_parent_key => $entity->get($this->_target_parent_key));
    }