{@inheritdoc}
@throws RuntimeException if the upload was not successful.
334012
public function getStream()
    {
        $this->validateActive();

        if ($this->stream instanceof StreamInterface) {
            return $this->stream;
        }

        return new LazyOpenStream($this->file, 'r+');
    }
1013723
protected function checkUploadPostback()
    {
        if (!($uniqueId = Request::header('X-OCTOBER-FILEUPLOAD')) || $uniqueId != $this->getId()) {
            return;
        }

        try {
            if (!Input::hasFile('file_data')) {
                throw new ApplicationException('File missing from request');
            }

            $fileModel = $this->getRelationModel();
            $uploadedFile = Input::file('file_data');

            $validationRules = ['max:'.$fileModel::getMaxFilesize()];
            if ($fileTypes = $this->getAcceptedFileTypes()) {
                $validationRules[] = 'extensions:'.$fileTypes;
            }

            if ($this->mimeTypes) {
                $validationRules[] = 'mimes:'.$this->mimeTypes;
            }

            $validation = Validator::make(
                ['file_data' => $uploadedFile],
                ['file_data' => $validationRules]
            );

            if ($validation->fails()) {
                throw new ValidationException($validation);
            }

            if (!$uploadedFile->isValid()) {
                throw new ApplicationException('File is not valid');
            }

            $fileRelation = $this->getRelationObject();

            $file = $fileModel;
            $file->data = $uploadedFile;
            $file->is_public = $fileRelation->isPublic();
            $file->save();

            /**
             * Attach directly to the parent model if it exists and attachOnUpload has been set to true
             * else attach via deferred binding
             */
            $parent = $fileRelation->getParent();
            if ($this->attachOnUpload && $parent && $parent->exists) {
                $fileRelation->add($file);
            } else {
                $fileRelation->add($file, $this->sessionKey);
            }

            $file = $this->decorateFileAttributes($file);

            $result = [
                'id' => $file->id,
                'thumb' => $file->thumbUrl,
                'path' => $file->pathUrl
            ];

            Response::json($result, 200)->send();

        }
        catch (Exception $ex) {
            Response::json($ex->getMessage(), 400)->send();
        }

        exit;
    }
799455
protected function read()
	{
		if( !file_exists( $this->fileName ) )
			throw new RuntimeException( 'File "'.$this->fileName.'" is not existing.' );
		$this->data		= parse_ini_file( $this->fileName, true );
	}
651099
public function save(EventInterface $event) {
        $request = $event->getRequest();
        $database = $event->getDatabase();

        $user = $request->getUser();
        $imageIdentifier = $request->getImage()->getImageIdentifier();

        try {
            $database->updateMetadata(
                $user,
                $imageIdentifier,
                $this->properties
            );
        } catch (DatabaseException $e) {
            $database->deleteImage($user, $imageIdentifier);

            throw new RuntimeException('Could not store EXIF-metadata', 500);
        }
    }
899002
protected function execute(InputInterface $input, OutputInterface $output)
    {
        $batchSize = 100;
        $logs = [];

        $isDryRun = $input->getOption('dry-run');

        $uploadFileId = $input->getArgument('csv_file');
        $adminCode = $input->getArgument('admin_code');
        $encode = mb_strtolower($input->getArgument('encode'));
        $fileLoaderId = $input->getArgument('file_loader');

        $container = $this->getContainer();

        $doctrine = $container->get('doctrine');

        /** @var EntityManager $em */
        $em = $doctrine->getManager();

        $this->setEm($em);

        /** @var UploadFile $uploadFile */
        $uploadFile = $em->getRepository(UploadFile::class)->find($uploadFileId);

        if (null === $uploadFile) {
            throw new \RuntimeException('Upload file not found');
        }

        $fileLoaders = $container->getParameter('compo_import.class_loaders');

        $fileLoader = $fileLoaders[$fileLoaderId]['class'] ?? null;

        if (!class_exists($fileLoader)) {
            $uploadFile->setStatus(UploadFile::STATUS_ERROR);
            $uploadFile->setMessage('class_loader not found');

            $em->flush($uploadFile);

            return;
        }

        $fileLoader = new $fileLoader();

        if (!$fileLoader instanceof FileLoaderInterface) {
            $uploadFile->setStatus(UploadFile::STATUS_ERROR);
            $uploadFile->setMessage('class_loader must be instanceof "FileLoaderInterface"');

            $em->flush($uploadFile);

            return;
        }

        $fileLoader->setContainer($this->getContainer());

        try {
            $fileLoader->setFile(new File($uploadFile->getFile()));

            $pool = $container->get('sonata.admin.pool');

            /** @var \Compo\Sonata\AdminBundle\Admin\AbstractAdmin $instance */
            $instance = $pool->getInstance($adminCode);

            $entityClass = $instance->getClass();

            $meta = $em->getClassMetadata($entityClass);

            $identifier = $meta->getSingleIdentifierFieldName();

            $exportFields = $instance->getExportFields();

            $validator = $container->get('validator');

            $firstLine = [];

            $exportFieldsAsString = [];

            foreach ($exportFields as $exportFieldKey => $exportField) {
                if (false !== mb_strpos($exportField, 'ExportAsString')) {
                    $exportFieldsAsString[$exportFieldKey] = $exportFieldKey;
                    $exportFields[$exportFieldKey] = str_replace('ExportAsString', '', $exportField);
                }
            }

            /** @var array $iterator */
            $iterator = $fileLoader->getIteration();

            $headers = [];
            $methods = [];

            $associationMappings = $meta->associationMappings;

            $fieldsMappings = $meta->fieldMappings;

            foreach ($iterator as $line => $dataRaw) {
                $output->writeln($line);

                if (0 === $line) {
                    $firstLine = $dataRaw;
                    $output->writeln($firstLine);

                    foreach ($exportFields as $key => $name) {
                        $data_key = $key;

                        if (!\in_array($data_key, $firstLine)) {
                            $data_key = $instance->getExportTranslationLabel($data_key, $name);

                            if (!\in_array($data_key, $firstLine)) {
                                continue;
                            }
                        }

                        $headers[$key] = $data_key;

                        $methods[$name] = [
                            'set' => $this->getSetMethod($name),
                            'get' => $this->getSetMethod($name, 'get'),
                            'is' => $this->getSetMethod($name, 'is'),
                        ];
                    }

                    continue;
                }

                $data = [];

                foreach ($firstLine as $columnKey => $columnName) {
                    $data[$columnName] = $dataRaw[$columnKey];
                }

                $log = new ImportLog();

                $log->setLine($line);

                //$log->setUploadFile($uploadFile);

                $errors = [];

                $changes = [];

                $oldValueRawArray = [];
                $newValueRawArray = [];

                $identifier_data_key = $headers[$identifier];

                $identifier_value = $data[$identifier_data_key];

                if ($identifier_value) {
                    $entity = $instance->getObject($identifier_value);

                    if (!$entity) {
                        $errors[] = 'Not found';
                    }
                } else {
                    $entity = new $entityClass();
                }

                $valueRawArray = [];

                foreach ($exportFields as $key => $name) {
                    if (!\array_key_exists($key, $headers)) {
                        continue;
                    }

                    $data_key = $headers[$key];

                    $valueRaw = $data[$data_key];

                    $newValueRawArray[$name] = $valueRaw;

                    $value = $valueRaw;

                    if ($name === $identifier) {
                        continue;
                    }

                    /*
                     * Многие делают ошибки в стандартной кодировке,
                     * поэтому на всякий случай провверяем оба варианта написания
                     */
                    if ('utf8' !== $encode && 'utf-8' !== $encode) {
                        $value = iconv($encode, 'utf8//TRANSLIT', $value);
                    }

                    try {
                        $getMethod = $methods[$name]['get'];
                        $setMethod = $methods[$name]['set'];

                        if (!method_exists($entity, $getMethod)) {
                            $getMethod = $methods[$name]['is'];
                        }

                        if (!method_exists($entity, $getMethod)) {
                            continue;
                        }

                        $oldValue = $entity->$getMethod();

                        if (isset($exportFieldsAsString[$name])) {
                            $getMethodRaw = $getMethod . 'ExportAsString';
                            $oldValueRawArray[$name] = $entity->$getMethodRaw();
                        }

                        try {
                            $valueNew = null;

                            $type = '';

                            if (isset($fieldsMappings[$name])) {
                                $type = $fieldsMappings[$name]['type'];
                            }

                            if (isset($associationMappings[$name])) {
                                $associationMappingsItem = $associationMappings[$name];

                                if (ClassMetadataInfo::MANY_TO_MANY === $associationMappingsItem['type']) {
                                    $valueArray = explode(',', $value);

                                    foreach ($valueArray as $valueArrayKey => $valueArrayItem) {
                                        $valueArray[$valueArrayKey] = trim($valueArrayItem);
                                    }

                                    $type = 'many_to_many';

                                    $repo = $em->getRepository($associationMappingsItem['targetEntity']);

                                    $valueCollection = [];

                                    foreach ($valueArray as $valueItem) {
                                        $valueItemObject = $repo->findOneBy([
                                            'name' => $valueItem,
                                        ]);

                                        if ($valueItemObject) {
                                            $valueCollection[$valueItemObject->getId()] = $valueItemObject;
                                        }
                                    }

                                    $valueNew = $valueCollection;
                                }

                                if (ClassMetadataInfo::MANY_TO_ONE === $associationMappingsItem['type']) {
                                    $type = 'entity';

                                    if ('' === $value || null === $value) {
                                        $valueNew = null;
                                    } else {
                                        $repo = $em->getRepository($associationMappingsItem['targetEntity']);

                                        $qb = $repo->createQueryBuilder('entity');

                                        /* @var QueryBuilder $qb */
                                        if (method_exists($instance, 'importFieldHandler')) {
                                            $qb = $instance->importFieldHandler($qb, $entity, $name, $value);
                                        }

                                        $qb->getQuery()->setCacheable(true);
                                        $qb->getQuery()->setResultCacheLifetime(120);
                                        $qb->getQuery()->setQueryCacheLifetime(120);
                                        $result = $qb->getQuery()->getResult();

                                        if (1 === \count($result)) {
                                            $valueNew = $result[0];
                                        } else {
                                            $valueNew = null;

                                            throw new InvalidArgumentException(
                                                sprintf(
                                                    'Edit failed, object with id "%s" not found in association "%s".',
                                                    $value,
                                                    $name)
                                            );
                                        }
                                    }
                                }
                            }

                            if ('date' === $type || 'datetime' === $type) {
                                if ($value) {
                                    $valueNew = new \DateTime($value);

                                    $valueNewTimestamp = $valueNew->getTimestamp();

                                    /** @var \DateTime $oldValueDateTime */
                                    $oldValueDateTime = $oldValue;

                                    $oldValueTimestamp = $oldValueDateTime->getTimestamp();

                                    if ($valueNewTimestamp === $oldValueTimestamp) {
                                        $valueNew = $oldValue;
                                    }
                                } else {
                                    $valueNew = null;
                                }
                            }

                            if ('boolean' === $type) {
                                $valueNew = filter_var($value, FILTER_VALIDATE_BOOLEAN);
                            }

                            if ('integer' === $type) {
                                $valueNew = (int) $value;
                            }
                            if ('text' === $type) {
                                $valueNew = $value;
                            }
                            if ('string' === $type) {
                                $valueNew = $value;
                            }

                            if ('decimal' === $type) {
                                $valueNew = number_format($value, 2, '.', '');
                            }
                        } catch (\Exception $e) {
                            throw new InvalidArgumentException('Field name not found: ' . $e->getMessage());
                        }

                        $value = $valueNew;

                        if (\is_string($value) || null === $value) {
                            if ('setSlug' === $setMethod && '' === $value) {
                                $value = null;
                                $entity->$setMethod($value);
                            }

                            if (null === $oldValue) {
                                $oldValue = '';
                            }

                            if (null === $value) {
                                $value = '';
                            }

                            if ($value !== $oldValue) {
                                $entity->$setMethod($value);
                            }
                        } elseif (\is_bool($oldValue)) {
                            if ($value !== $oldValue) {
                                $entity->$setMethod($value);
                            }
                        } else {
                            $entity->$setMethod($value);
                        }

                        if (isset($exportFieldsAsString[$name])) {
                            $getMethodRaw = $getMethod . 'ExportAsString';
                            $valueRawArray[$name] = $entity->$getMethodRaw();
                        }
                    } catch (\Exception $e) {
                        $errors[] = $e->getMessage();
                        break;
                    }
                }

                $idMethod = $methods[$identifier]['get'];

                if ($entity->$idMethod()) {
                    $log->setForeignId($entity->$idMethod());
                }

                if (!\count($errors)) {
                    $errors = $validator->validate($entity);
                }

                if (!\count($errors)) {
                    /*
                     * Если у сещности нет ID, то она новая - добавляем ее
                     */
                    if (!$entity->$idMethod()) {
                        $log->setStatus(ImportLog::STATUS_SUCCESS);
                    } else {
                        $log->setStatus(ImportLog::STATUS_EXISTS);
                    }

                    $uow = $em->getUnitOfWork();

                    $uow->computeChangeSets();

                    $aChangeSet = $uow->getEntityChangeSet($entity);

                    $getScheduledCollectionUpdates = $uow->getScheduledCollectionUpdates();

                    $getScheduledCollectionDeletions = $uow->getScheduledCollectionDeletions();

                    if (!(\count($aChangeSet) || \count($getScheduledCollectionUpdates) || \count($getScheduledCollectionDeletions))) {
                        if (!$entity->$idMethod()) {
                            $log->setStatus(ImportLog::STATUS_SUCCESS);

                            foreach ($newValueRawArray as $newValueRawArrayKey => $newValueRawArrayValue) {
                                $changes[$newValueRawArrayKey] = [
                                    'old' => '',
                                    'new' => $newValueRawArrayValue,
                                ];
                            }

                            $log->setChanges($changes);

                            if (!$isDryRun) {
                                $em->persist($entity);
                                //$this->em->flush($entity);
                                $log->setForeignId($entity->$idMethod());
                            } //else {
                            //$em->detach($entity);
                            //}
                        } else {
                            //$em->detach($entity);

                            $log->setStatus(ImportLog::STATUS_NOCHANGE);
                        }
                    } //else {
                    //if (!$isDryRun) {
                    //$em->persist($entity);
                    //} else {
                    //$em->detach($entity);
                    //}
                    //}

                    foreach ($aChangeSet as $aChangeSetKey => $aChangeSetValue) {
                        if ($aChangeSetValue[0] instanceof \DateTimeInterface && $aChangeSetValue[1] instanceof \DateTimeInterface) {
                            [$old, $new] = $aChangeSetValue;

                            /* @var \DateTime $old */
                            /* @var \DateTime $new */

                            $changes[$aChangeSetKey] = [
                                'old' => (string) $old->format('d.m.Y H:i:s'),
                                'new' => (string) $new->format('d.m.Y H:i:s'),
                            ];
                        } else {
                            $changes[$aChangeSetKey] = [
                                'old' => (string) $aChangeSetValue[0],
                                'new' => (string) $aChangeSetValue[1],
                            ];
                        }
                    }

                    /** @var \Doctrine\ORM\PersistentCollection $getScheduledCollectionUpdates */
                    foreach ($getScheduledCollectionUpdates as $getScheduledCollectionUpdatesKey => $getScheduledCollectionUpdatesValue) {
                        $getScheduledCollectionUpdatesMapping = $getScheduledCollectionUpdatesValue->getMapping();

                        $changes[$getScheduledCollectionUpdatesMapping['fieldName']] = [
                            'old' => $oldValueRawArray[$getScheduledCollectionUpdatesMapping['fieldName']],
                            'new' => $valueRawArray[$getScheduledCollectionUpdatesMapping['fieldName']],
                        ];
                    }

                    $log->setChanges($changes);
                } else {
                    $log->setMessage(json_encode($errors));
                    $log->setStatus(ImportLog::STATUS_ERROR);
                }

                $logs[] = $log;

                //dump($changes);

                //$em->persist($log);

                //$em->flush($log);

                //$em->detach($log);

                if (!$isDryRun) {
                    if (method_exists($entity, 'setUpdatedBy')) {
                        $uploadFile = $em->getRepository(UploadFile::class)->find($uploadFileId);
                        $container->get('stof_doctrine_extensions.listener.blameable')
                            ->setUserValue($uploadFile->getCreatedBy());
                    }

                    $em->persist($entity);
                    $em->flush($entity);
                }

                $em->detach($entity);

                //$em->clear(get_class($entity));
                //$em->clear(get_class($log));

                $em->clear();

                if (0 === ($line % $batchSize)) {
                    $uploadFile = $em->getRepository(UploadFile::class)->find($uploadFileId);

                    /** @var ImportLog $logItem */
                    foreach ($logs as $logItem) {
                        $logItem->setUploadFile($uploadFile);
                        $em->persist($logItem);
                    }

                    $logs = [];

                    $em->flush();
                    $em->clear(); // Detaches all objects from Doctrine!
                }
            }

            $em->flush();

            $em->clear();

            $uploadFile = $em->getRepository(UploadFile::class)->find($uploadFileId);
            $container->get('stof_doctrine_extensions.listener.blameable')
                ->setUserValue($uploadFile->getCreatedBy());

            $em->refresh($uploadFile);

            $uploadFile->setStatus(UploadFile::STATUS_SUCCESS);

            /** @var ImportLog $logItem */
            foreach ($logs as $logItem) {
                $logItem->setUploadFile($uploadFile);
                $em->persist($logItem);
            }

            //$em->flush($uploadFile);

            //$uow = $em->getUnitOfWork();

            $em->flush();

            $em->clear();
        } catch (\Exception $e) {
            throw $e;
            /*
             * Данный хак нужен в случае бросания ORMException
             * В случае бросания ORMException entity manager останавливается
             * и его требуется перезагрузить
             */

            /*
            if (!$em->isOpen()) {
                    $newEm = $em->create(
                        $em->getConnection(),
                        $em->getConfiguration()
                    );

                $uploadFile = $em->getRepository(UploadFile::class)->find($uploadFileId);
            }

            $uploadFile->setStatus(UploadFile::STATUS_ERROR);
            $uploadFile->setMessage($e->getMessage());
            $em->flush($uploadFile);
             */
        }
    }
468408
public function load() : Persistable
    {
        if (!is_readable($this->path)) {
            throw new RuntimeException("File $this->path does not"
                . ' exist or is a folder, check path and permissions.');
        }
            
        $data = file_get_contents($this->path) ?: '';

        $persistable = $this->serializer->unserialize($data);

        if (!$persistable instanceof Persistable) {
            throw new RuntimeException('Model could not be reconstituted.');
        }

        return $persistable;
    }
1332119
public function addFile(string $filename, string $field, array $crop = null): bool
    {
        if (!file_exists($filename)) {
            throw new \RuntimeException("File not found: {$filename}");
        }

        // Prepare upload data for later save
        $data = [
            'name' => basename($filename),
            'type' => Utils::getMimeByLocalFile($filename),
            'size' => filesize($filename),
        ];

        $this->addFileInternal($field, $data['name'], $data, $crop);

        return true;
    }
1053090
public function upload()
    {
        if ($this->isValid() === false) {
            throw new \Upload\Exception('File validation failed');
        }

        foreach ($this->objects as $fileInfo) {
            $this->applyCallback('beforeUpload', $fileInfo);
            $this->storage->upload($fileInfo);
            $this->applyCallback('afterUpload', $fileInfo);
        }

        return true;
    }
1343642
protected function checkUploadPostback()
    {
        $fileName = null;

        try {
            $uploadedFile = Input::file('file_data');

            if (!is_object($uploadedFile)) {
                return;
            }

            $fileName = $uploadedFile->getClientOriginalName();

            /*
             * Check valid upload
             */
            if (!$uploadedFile->isValid()) {
                throw new ApplicationException(Lang::get('cms::lang.asset.file_not_valid'));
            }

            /*
             * Check file size
             */
            $maxSize = UploadedFile::getMaxFilesize();
            if ($uploadedFile->getSize() > $maxSize) {
                throw new ApplicationException(Lang::get(
                    'cms::lang.asset.too_large',
                    ['max_size' => File::sizeToString($maxSize)]
                ));
            }

            /*
             * Check for valid file extensions
             */
            if (!$this->validateFileType($fileName)) {
                throw new ApplicationException(Lang::get(
                    'cms::lang.asset.type_not_allowed',
                    ['allowed_types' => implode(', ', $this->assetExtensions)]
                ));
            }

            /*
             * Accept the uploaded file
             */
            $uploadedFile->move($this->getCurrentPath(), $uploadedFile->getClientOriginalName());

            die('success');
        }
        catch (Exception $ex) {
            $message = $fileName !== null
                ? Lang::get('cms::lang.asset.error_uploading_file', ['name' => $fileName, 'error' => $ex->getMessage()])
                : $ex->getMessage();

            die($message);
        }
    }
540503
public function connect()
    {
        if ($this->ssl) {
            $this->connection = ftp_ssl_connect($this->getHost(), $this->getPort(), $this->getTimeout());
        } else {
            $this->connection = ftp_connect($this->getHost(), $this->getPort(), $this->getTimeout());
        }

        if ( ! $this->connection) {
            throw new RuntimeException('Could not connect to host: ' . $this->getHost() . ', port:' . $this->getPort());
        }

        $this->login();
        $this->setUtf8Mode();
        $this->setConnectionPassiveMode();
        $this->setConnectionRoot();
        $this->isPureFtpd = $this->isPureFtpdServer();
    }
985595
public function fileDelete($file)
    {
        foreach ($this->files($file) as $f) {
            if (!unlink($f) && $this->fileExists($f)) {
                throw new RuntimeException(['delete `:file` failed: :last_error_message', 'file' => $f]);
            }
        }
    }
673588
protected function prepare()
    {
        parent::prepare();

        if (!$this->hasBodyStream()) {
            if (false === $stream = tmpfile()) {
                throw new RuntimeException("Can't create temporary file.");
            }
            fwrite($stream, $this->getBody());
            rewind($stream);
            $this->setBody($stream);
        }

        $this->addOption('url', $this->getUrl());
        $this->addOption('upload', true);
        $this->addOption('body', $this->getBody());
    }
1033962
private void checkFile() throws IORuntimeException {
		if (false == file.exists()) {
			throw new IORuntimeException("File not exist: " + file);
		}
		if (false == file.isFile()) {
			throw new IORuntimeException("Not a file:" + file);
		}
	}
371417
public function commit()
    {
        if (!$this->started) {
            throw new \RuntimeException('Cannot commit transaction before start');
        }
        if (!$this->pdo->commit()) {
            throw new \RuntimeException('Failed to commit transaction');
        }

        $this->started = false;
    }
917836
public function up($file)
    {
        if (false === ($contents = file_get_contents($file->getPathName()))) {
            throw new RuntimeException($file->getPathName() . ' is not found.');
        }
        $queries = explode(';', $contents);
        try {
            $dbh = $this->pdo->connection(true);
            $dbh->beginTransaction();
            foreach($queries as $query) {
                $cleanedQuery = trim($query);
                if ('' === $cleanedQuery) {
                    continue;
                }
                $stmt = $dbh->prepare($cleanedQuery);
                $stmt->execute();
            }
            $dbh->commit();
        } catch(\PDOException $e) {
            $dbh->rollBack();
            throw new RuntimeException($e->getMessage() . PHP_EOL . $query);
        }

        $this->copyToAppliedDir($file);
    }
692296
public function commit()
    {
        try {
            $this->persistenceHandler->commit();
        } catch (Exception $e) {
            throw new RuntimeException($e->getMessage(), 0, $e);
        }
    }
600982
public function execute()
    {
        foreach (array_unique($this->bootstrappers->all()) as $class) {
            $bootstrapper = $this->create($class);

            if (!method_exists($bootstrapper, 'run')) {
                throw new \RuntimeException("$class must have run() method");
            }

            $bootstrapper->run();
        }
    }