nextcloud/apps/workflowengine/lib/Check/FileSize.php

88 lines
2 KiB
PHP
Raw Normal View History

2016-07-27 09:57:00 -04:00
<?php
2016-07-27 09:57:00 -04:00
/**
* SPDX-FileCopyrightText: 2016 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
2016-07-27 09:57:00 -04:00
*/
namespace OCA\WorkflowEngine\Check;
use OCA\WorkflowEngine\Entity\File;
2016-08-01 11:56:33 -04:00
use OCP\IL10N;
2016-07-27 09:57:00 -04:00
use OCP\IRequest;
use OCP\Util;
use OCP\WorkflowEngine\ICheck;
class FileSize implements ICheck {
protected int|float|null $size = null;
2016-07-27 09:57:00 -04:00
public function __construct(
protected readonly IL10N $l,
protected readonly IRequest $request,
) {
2016-07-27 09:57:00 -04:00
}
/**
* @param string $operator
* @param string $value
*/
public function executeCheck($operator, $value): bool {
2016-07-27 09:57:00 -04:00
$size = $this->getFileSizeFromHeader();
if ($size === false) {
return false;
}
2016-07-27 09:57:00 -04:00
$value = Util::computerFileSize($value);
return match ($operator) {
'less' => $size < $value,
'!less' => $size >= $value,
'greater' => $size > $value,
'!greater' => $size <= $value,
default => false,
};
2016-07-27 09:57:00 -04:00
}
/**
* @param string $operator
* @param string $value
* @throws \UnexpectedValueException
*/
public function validateCheck($operator, $value): void {
2016-07-27 09:57:00 -04:00
if (!in_array($operator, ['less', '!less', 'greater', '!greater'])) {
2016-08-01 11:56:33 -04:00
throw new \UnexpectedValueException($this->l->t('The given operator is invalid'), 1);
2016-07-27 09:57:00 -04:00
}
if (!preg_match('/^[0-9]+[ ]?[kmgt]?b$/i', $value)) {
2016-08-01 11:56:33 -04:00
throw new \UnexpectedValueException($this->l->t('The given file size is invalid'), 2);
2016-07-27 09:57:00 -04:00
}
}
protected function getFileSizeFromHeader(): int|float|false {
2016-07-27 09:57:00 -04:00
if ($this->size !== null) {
return $this->size;
}
$size = $this->request->getHeader('OC-Total-Length');
if ($size === '') {
2016-07-27 09:57:00 -04:00
if (in_array($this->request->getMethod(), ['POST', 'PUT'])) {
$size = $this->request->getHeader('Content-Length');
}
}
if ($size === '' || !is_numeric($size)) {
2016-07-27 09:57:00 -04:00
$size = false;
}
$this->size = Util::numericToNumber($size);
2016-07-27 09:57:00 -04:00
return $this->size;
}
public function supportedEntities(): array {
return [ File::class ];
}
public function isAvailableForScope(int $scope): bool {
return true;
}
2016-07-27 09:57:00 -04:00
}