Creates the different versions of images that are configured

@param \Cake\ORM\Table $table
@param array $entity
@param array $operations
@throws \Burzum\FileStorage\Event\Exception
@throws \Exception
@return false|null
167919
protected function _createVersions(Table $table, $entity, array $operations) {
		$Storage = StorageManager::adapter($entity['adapter']);
		$path = $this->_buildPath($entity, true);
		$tmpFile = $this->_tmpFile($Storage, $path, TMP . 'image-processing');

		foreach ($operations as $version => $imageOperations) {
			$hash = StorageUtils::hashOperations($imageOperations);
			$string = $this->_buildPath($entity, true, $hash);

			if ($this->adapterClass === 'AmazonS3' || $this->adapterClass === 'AwsS3') {
				$string = str_replace('\\', '/', $string);
			}

			if ($Storage->has($string)) {
				return false;
			}

			try {
				$image = $table->processImage($tmpFile, null, ['format' => $entity['extension']], $imageOperations);
				$Storage->write($string, $image->get($entity['extension']), true);
			} catch (\Exception $e) {
				$this->log($e->getMessage());
				unlink($tmpFile);
				throw $e;
			}
		}

		unlink($tmpFile);
	}
1342762
private function toProcessFile($entity, $operation)
    {
        switch ($operation) {
            case self::ENCRYPT:
                return !$entity->isFileEncrypted();
            case self::DECRYPT:
                return $entity->isFileEncrypted();
            default:
                return false;
        }
    }
983454
public function createImageVersions(EntityInterface $entity, array $versions, array $options = []) {
		$this->_checkImageVersions($entity->get('model'), $versions);
		$options += $this->_defaultOutput + [
			'overwrite' => true
		];

		$result = [];
		$storage = $this->getStorageAdapter($entity->adapter);

		foreach ($this->_imageVersions[$entity->get('model')] as $version => $operations) {
			if (!in_array($version, $versions)) {
				continue;
			}

			$saveOptions = $options + ['format' => $entity->extension];
			$mimeTypeToFileType = [
				'image/jpg' => 'jpeg',
				'image/jpeg' => 'jpeg',
				'image/png' => 'png',
				'image/gif' => 'gif'
			];

			if (empty($saveOptions['format'])) {
				$mime = $entity->get('mime_type');
				if (isset($mimeTypeToFileType[$mime])) {
					$saveOptions['format'] = $mimeTypeToFileType[$mime];
				}
			}

			if (isset($operations['_output'])) {
				$saveOptions = $operations['_output'] + $saveOptions;
				unset($operations['_output']);
			}

			$path = $this->imageVersionPath($entity, $version, 'fullPath', $saveOptions);

			try {
				if ($options['overwrite'] || !$storage->has($path)) {
					unset($saveOptions['overwrite']);

					$output = StorageUtils::createTmpFile();
					$tmpFile = $this->_tmpFile($storage, $this->pathBuilder()->fullPath($entity));

					$this->imageProcessor()->open($tmpFile);
					$this->imageProcessor()->batchProcess($output, $operations, $saveOptions);

					$storage->write($path, file_get_contents($output), true);

					unlink($tmpFile);
					unlink($output);
				}

				$result[$version] = [
					'status' => 'success',
					'path' => $path,
					'hash' => $this->getImageVersionHash($entity->get('model'), $version)
				];
			} catch (\Exception $e) {
				$this->log($e->getMessage(), LogLevel::ERROR, [
					'fileStorage'
				]);

				$result[$version] = [
					'status' => 'error',
					'error' => $e->getMessage(),
					'line' => $e->getLine(),
					'file' => $e->getFile()
				];
			}
		}

		return $result;
	}
859835
public function beforeSave(Event $event, Entity $entity, ArrayObject $options)
    {
        $onUpdate = $this->getConfig('onUpdate');
        if (!$entity->isNew() && !$onUpdate) {
            return;
        }

        $onDirty = $this->getConfig('onDirty');
        $field = $this->getConfig('field');
        if (!$onDirty
            && $entity->isDirty($field)
            && (!$entity->isNew() || (!empty($entity->{$field})))
        ) {
            return;
        }

        $separator = $this->getConfig('separator');
        if ($entity->isDirty($field) && !empty($entity->{$field})) {
            $slug = $this->slug($entity, $entity->{$field}, $separator);
            $entity->set($field, $slug);

            return;
        }

        $parts = $this->_getPartsFromEntity($entity);
        if (empty($parts)) {
            return;
        }

        $slug = $this->slug($entity, implode($separator, $parts), $separator);
        $entity->set($field, $slug);
    }
460222
public function lock($entity, $lockMode, $lockVersion = null)
    {
        if ($entity === null) {
            throw new InvalidArgumentException('No entity passed to UnitOfWork#lock().');
        }

        if ($this->getEntityState($entity, self::STATE_DETACHED) !== self::STATE_MANAGED) {
            throw ORMInvalidArgumentException::entityNotManaged($entity);
        }

        $class = $this->em->getClassMetadata(get_class($entity));

        switch (true) {
            case $lockMode === LockMode::OPTIMISTIC:
                if (! $class->isVersioned()) {
                    throw OptimisticLockException::notVersioned($class->getClassName());
                }

                if ($lockVersion === null) {
                    return;
                }

                if ($entity instanceof GhostObjectInterface && ! $entity->isProxyInitialized()) {
                    $entity->initializeProxy();
                }

                $entityVersion = $class->versionProperty->getValue($entity);

                if ($entityVersion !== $lockVersion) {
                    throw OptimisticLockException::lockFailedVersionMismatch($entity, $lockVersion, $entityVersion);
                }

                break;

            case $lockMode === LockMode::NONE:
            case $lockMode === LockMode::PESSIMISTIC_READ:
            case $lockMode === LockMode::PESSIMISTIC_WRITE:
                if (! $this->em->getConnection()->isTransactionActive()) {
                    throw TransactionRequiredException::transactionRequired();
                }

                $oid = spl_object_id($entity);

                $this->getEntityPersister($class->getClassName())->lock(
                    array_combine($class->getIdentifierFieldNames(), $this->entityIdentifiers[$oid]),
                    $lockMode
                );
                break;

            default:
                // Do nothing
        }
    }
1332072
public function getStableVersion(DocumentationEntity $entity)
    {
        foreach ($this->getEntities() as $check) {
            if ($check->getKey() == $entity->getKey()) {
                if ($check->getLanguage() == $entity->getLanguage()) {
                    if ($check->getIsStable()) {
                        return $check;
                    }
                }
            }
        }

        return $entity;
    }
145710
@Override
	public void update(Object entity) {
		if (entity == null) {
			throw new IllegalArgumentException("'entity' must not be [" + entity + "]");
		}
		
		assertTransactional();
		List<Log> logs = transaction.get().logs();
		
		if (logs.isEmpty()) {
			throw new IllegalStateException("Log ["
					+ Log.Operation.UPDATE
					+ "] is not allowed: previous operation must be ["
					+ Log.Operation.GET + "]");
		}
		
		for (int i = logs.size() - 1; i >= 0; i--) {
			Log log = logs.get(i);
			
			if (keyValue(entity).equals(keyValue(log.entity()))) {
				if (log.operation() == Log.Operation.GET) {
					break;
				} else {
					throw new IllegalStateException("Log [" + log.operation() 
							+ "] -> [" + Log.Operation.UPDATE
							+ "] is not allowed: previous operation must be ["
							+ Log.Operation.GET + "]");
				}
			}
		}
		
		Transaction tx = transaction.get().transaction();
		datastore.put(tx, Translation.toEntities(entity));
		Log log = new Log(logs.size() + 1, Log.Operation.UPDATE, entity);
		log.state(State.UNCOMMITTED);
		logs.add(log);
	}
782183
@SuppressWarnings("unchecked")
	@Override
	public int update(final Object entity) {
		@SuppressWarnings("rawtypes")
		EntityHandler handler = this.getEntityHandler();
		if (!handler.getEntityType().isInstance(entity)) {
			throw new IllegalArgumentException("Entity type not supported");
		}

		try {
			Class<?> type = entity.getClass();
			TableMetadata metadata = handler.getMetadata(this.transactionManager, type);
			SqlContext context = handler.createUpdateContext(this, metadata, type, true);
			context.setSqlKind(SqlKind.UPDATE);
			handler.setUpdateParams(context, entity);
			int count = handler.doUpdate(this, context, entity);

			if (count == 0 && MappingUtils.getVersionMappingColumn(type).isPresent()) {
				throw new OptimisticLockException(context);
			}
			return count;
		} catch (SQLException e) {
			throw new EntitySqlRuntimeException(SqlKind.UPDATE, e);
		}
	}
1228204
protected static function exeRead(string $entity, $data = null)
    {
        if (!is_array($data) && !is_numeric($data))
            return null;

        if (is_array($data)) {
            $read = new TableCrud($entity);
            $read->loadArray($data);
            if ($read->exist())
                $data = (int)$read->getDados()['id'];

            if (empty($data) || !is_numeric($data))
                return null;
        }

        return self::readValues($entity, $data);
    }
824171
@Override
  protected void deleteEntity(DbEntityOperation operation) {

    final DbEntity dbEntity = operation.getEntity();

    // get statement
    String deleteStatement = dbSqlSessionFactory.getDeleteStatement(dbEntity.getClass());
    ensureNotNull("no delete statement for " + dbEntity.getClass() + " in the ibatis mapping files", "deleteStatement", deleteStatement);

    LOG.executeDatabaseOperation("DELETE", dbEntity);

    // execute the delete
    int nrOfRowsDeleted = executeDelete(deleteStatement, dbEntity);
    operation.setRowsAffected(nrOfRowsDeleted);

    // It only makes sense to check for optimistic locking exceptions for objects that actually have a revision
    if (dbEntity instanceof HasDbRevision && nrOfRowsDeleted == 0) {
      operation.setFailed(true);
      return;
    }

    // perform post delete action
    entityDeleted(dbEntity);
  }
649744
protected function generateAccessorsMethods(Entity $entity)
    {
        $methods    = [];
        $descriptor = $entity->getDescriptor();
        $fields     = $descriptor->getFieldList() ?: [];

        foreach ($fields as $field) {
            $methods[] = $this->generateHasMethod($entity, $field);
            $methods[] = $this->generateGetterMethod($entity, $field);
            $methods[] = $this->generateSetterMethod($entity, $field);

            if ($field->getLabel() === Label::LABEL_REPEATED()) {
                $methods[] = $this->generateAddMethod($entity, $field);
            }
        }

        $methods[] = $this->generateGetExtensionsMethod($entity);
        $methods[] = $this->generateGetUnknownFieldSetMethod($entity);

        return $methods;
    }
656644
private function attachThumbnails(FileStorage $entity) : FileStorage
    {
        $entity->set('thumbnails', $this->getThumbnails($entity));

        return $entity;
    }
1030949
@Override
  protected void updateEntity(DbEntityOperation operation) {

    final DbEntity dbEntity = operation.getEntity();

    String updateStatement = dbSqlSessionFactory.getUpdateStatement(dbEntity);
    ensureNotNull("no update statement for " + dbEntity.getClass() + " in the ibatis mapping files", "updateStatement", updateStatement);

    LOG.executeDatabaseOperation("UPDATE", dbEntity);

    if (Context.getProcessEngineConfiguration().isJdbcBatchProcessing()) {
      // execute update
      executeUpdate(updateStatement, dbEntity);
    } else {
      // execute update
      int numOfRowsUpdated = executeUpdate(updateStatement, dbEntity);

      if (dbEntity instanceof HasDbRevision) {
        if (numOfRowsUpdated != 1) {
          // failed with optimistic locking
          operation.setFailed(true);
          return;
        } else {
          // increment revision of our copy
          HasDbRevision versionedObject = (HasDbRevision) dbEntity;
          versionedObject.setRevision(versionedObject.getRevisionNext());
        }
      }
    }

    // perform post update action
    entityUpdated(dbEntity);
  }
642349
protected function getEntityTable($entity)
    {
        if (!$entity instanceof EntityInterface) {
            $entity = $this->getEntityClass($entity);
        }
        return $this->tablePrefix . $entity::getTable() . $this->tableSuffix;
    }
149121
public function execute(StorageInterface $storage, Operations $operations)
    {
        foreach ($operations->getOperations() as $operation) {
            if ($operation instanceof AddDocumentOperation) {
                $document = $operation->getDocument();
                $event = new DocumentEvent($document);
                if ($this->eventDispatcher->dispatch(IndexerEvents::BEFORE_STORAGE_ADD_DOCUMENT, $event)
                    ->isPropagationStopped()
                ) {
                    continue;
                }

                $storage->addDocument($document);

                $event = new DocumentEvent($document);
                $this->eventDispatcher->dispatch(IndexerEvents::STORAGE_ADD_DOCUMENT, $event);
            } elseif ($operation instanceof AddIdentityOperation) {
                throw new InvalidArgumentException('Add identity command not supported by run().');
            } elseif ($operation instanceof UpdateDocumentOperation) {
                $document = $operation->getDocument();
                $event = new DocumentEvent($document);
                if ($this->eventDispatcher->dispatch(IndexerEvents::BEFORE_STORAGE_UPDATE_DOCUMENT, $event)->isPropagationStopped()) {
                    continue;
                }

                $storage->updateDocument($document);

                $event = new DocumentEvent($document);
                $this->eventDispatcher->dispatch(IndexerEvents::STORAGE_UPDATE_DOCUMENT, $event);
            } elseif ($operation instanceof UpdateIdentityOperation) {
                throw new InvalidArgumentException('Update identity command not supported by run().');
            } elseif ($operation instanceof DeleteDocumentOperation) {
                $storage->deleteDocument($operation->getDocument());
            } elseif ($operation instanceof DeleteIdentityOperation) {
                $storage->delete($operation->getIdentity());
            } elseif ($operation instanceof DeleteTypeOperation) {
                $storage->deleteType($operation->getType());
            } elseif ($operation instanceof DeleteAllOperation) {
                $storage->deleteAll();
            } elseif ($operation instanceof FlushOperation) {
                if ($storage instanceof Flushable) {
                    $storage->flush();
                }
            } elseif ($operation instanceof OptimizeOperation) {
                if ($storage instanceof Optimizable) {
                    $storage->optimize();
                }
            } elseif ($operation instanceof CommitOperation) {
                if ($storage instanceof Commitable) {
                    $storage->commit();
                }
            } elseif ($operation instanceof RollbackOperation) {
                if ($storage instanceof Rollbackable) {
                    $storage->rollback();
                }
            }
        }

        return true;
    }
842506
public function createAllImageVersions(EntityInterface $entity, array $options = []) {
		return $this->createImageVersions(
			$entity,
			$this->getAllVersionsKeysForModel($entity->get('model')),
			$options
		);
	}
730331
private function createTable(Table &$table) {
        $annotations = $this->getClassSettings();
        $create = false;
        foreach ($annotations as $columnName => $descArray) {
            $create = true;
            $dbColumnName = Util::camelTo_($columnName);

            if (isset($descArray['attrs']['primary']) && $descArray['attrs']['primary']) {
                $table->setPrimaryKey($dbColumnName);
            }

            if (isset($descArray['attrs']['reference'])) { // Reference not ReferenceMany
                $onDelete = (isset($descArray['attrs']['reference']['onDelete'])) ?
                        $descArray['attrs']['reference']['onDelete'] : 'RESTRICT';
                $onUpdate = (isset($descArray['attrs']['reference']['onUpdate'])) ?
                        $descArray['attrs']['reference']['onUpdate'] : 'RESTRICT';
                $table->addReference($dbColumnName, $descArray['attrs']['reference']['table'], $descArray['attrs']['reference']['column'], $onDelete, $onUpdate);

                $refTable = new Table($descArray['attrs']['reference']['table'], $table->getConnection());
                $refColumns = $refTable->getColumns();
                if (!empty($refColumns[$descArray['attrs']['reference']['column']]['charset'])) {
                    $descArray['attrs']['charset'] = $refColumns[$descArray['attrs']['reference']['column']]['charset'];
                    $descArray['attrs']['collation'] = $refColumns[$descArray['attrs']['reference']['column']]['collation'];
                }

                unset($descArray['attrs']['reference']['table']);
                unset($descArray['attrs']['reference']['column']);
                unset($descArray['attrs']['reference']['model']);

                if (isset($descArray['attrs']['reference']['onUpdate']))
                    unset($descArray['attrs']['reference']['onUpdate']);
                if (isset($descArray['attrs']['reference']['onDelete']))
                    unset($descArray['attrs']['reference']['onDelete']);

                if (!empty($descArray['attrs']['reference'])) {
                    $descArray['attrs'] = array_merge($descArray['attrs'], $descArray['attrs']['reference']);
                    unset($descArray['attrs']['reference']);
                }
            }

            $table->addColumn($dbColumnName, $this->parseAttributes($columnName, $descArray));
            $this->checkIndexes($dbColumnName, $descArray, $table);
        }

        return ($create) ? $table->getConnection()->createTable($table, false) : false;
    }