$env */
private array $env;
/** @var string[] $infos */
@@ -75,7 +75,7 @@ public function __construct(
/**
* Returns number of new comments between two dates.
*/
- public function nb_new_comments(DateTimeInterface $start = null, DateTimeInterface $end = null): int
+ public function nb_new_comments(?DateTimeInterface $start = null, ?DateTimeInterface $end = null): int
{
return $this->commentRepository->getNewComments($this->userMapper->getUser()->getUserInfos()->getForbiddenAlbums(), $start, $end, $count_only = true);
}
@@ -85,7 +85,7 @@ public function nb_new_comments(DateTimeInterface $start = null, DateTimeInterfa
*
* @return Comment[]
*/
- public function new_comments(DateTimeInterface $start = null, DateTimeInterface $end = null): array
+ public function new_comments(?DateTimeInterface $start = null, ?DateTimeInterface $end = null): array
{
return $this->commentRepository->getNewComments($this->userMapper->getUser()->getUserInfos()->getForbiddenAlbums(), $start, $end);
}
@@ -93,7 +93,7 @@ public function new_comments(DateTimeInterface $start = null, DateTimeInterface
/**
* Returns number of unvalidated comments between two dates.
*/
- public function nb_unvalidated_comments(DateTimeInterface $start = null, DateTimeInterface $end = null): int
+ public function nb_unvalidated_comments(?DateTimeInterface $start = null, ?DateTimeInterface $end = null): int
{
return $this->commentRepository->getUnvalidatedComments($count_only = true, $start, $end);
}
@@ -101,7 +101,7 @@ public function nb_unvalidated_comments(DateTimeInterface $start = null, DateTim
/**
* Returns number of new photos between two dates.
*/
- public function nb_new_elements(DateTimeInterface $start = null, DateTimeInterface $end = null): int
+ public function nb_new_elements(?DateTimeInterface $start = null, ?DateTimeInterface $end = null): int
{
return $this->imageMapper->getRepository()->getNewElements($this->userMapper->getUser()->getUserInfos()->getForbiddenAlbums(), $start, $end, $count_only = true);
}
@@ -111,7 +111,7 @@ public function nb_new_elements(DateTimeInterface $start = null, DateTimeInterfa
*
* @return Image[]
*/
- public function new_elements(DateTimeInterface $start = null, DateTimeInterface $end = null): array
+ public function new_elements(?DateTimeInterface $start = null, ?DateTimeInterface $end = null): array
{
return $this->imageMapper->getRepository()->getNewElements($this->userMapper->getUser()->getUserInfos()->getForbiddenAlbums(), $start, $end);
}
@@ -119,7 +119,7 @@ public function new_elements(DateTimeInterface $start = null, DateTimeInterface
/**
* Returns number of updated albums between two dates.
*/
- public function nb_updated_albums(DateTimeInterface $start = null, DateTimeInterface $end = null): int
+ public function nb_updated_albums(?DateTimeInterface $start = null, ?DateTimeInterface $end = null): int
{
return $this->imageMapper->getRepository()->getUpdatedAlbums($this->userMapper->getUser()->getUserInfos()->getForbiddenAlbums(), $start, $end, $count_only = true);
}
@@ -129,7 +129,7 @@ public function nb_updated_albums(DateTimeInterface $start = null, DateTimeInter
*
* @return Album[]|int
*/
- public function updated_albums(DateTimeInterface $start = null, DateTimeInterface $end = null): array|int
+ public function updated_albums(?DateTimeInterface $start = null, ?DateTimeInterface $end = null): array|int
{
return $this->imageMapper->getRepository()->getUpdatedAlbums($this->userMapper->getUser()->getUserInfos()->getForbiddenAlbums(), $start, $end);
}
@@ -137,7 +137,7 @@ public function updated_albums(DateTimeInterface $start = null, DateTimeInterfac
/**
* Returns number of new users between two dates.
*/
- public function nb_new_users(DateTimeInterface $start = null, DateTimeInterface $end = null): int
+ public function nb_new_users(?DateTimeInterface $start = null, ?DateTimeInterface $end = null): int
{
return $this->userInfosRepository->countNewUsers($start, $end);
}
@@ -147,7 +147,7 @@ public function nb_new_users(DateTimeInterface $start = null, DateTimeInterface
*
* @return UserInfos[]
*/
- public function new_users(DateTimeInterface $start = null, DateTimeInterface $end = null)
+ public function new_users(?DateTimeInterface $start = null, ?DateTimeInterface $end = null)
{
return $this->userInfosRepository->getNewUsers($start, $end);
}
@@ -160,7 +160,7 @@ public function new_users(DateTimeInterface $start = null, DateTimeInterface $en
* unvalidated comments, number of new users.
* @todo number of unvalidated elements
*/
- public function news_exists(DateTimeInterface $start = null, DateTimeInterface $end = null): bool
+ public function news_exists(?DateTimeInterface $start = null, ?DateTimeInterface $end = null): bool
{
return (($this->nb_new_comments($start, $end) > 0) || ($this->nb_new_elements($start, $end) > 0)
|| ($this->nb_updated_albums($start, $end) > 0) || (($this->userMapper->isAdmin())
@@ -177,7 +177,7 @@ public function add_news_line(array $news, int $count, string $lang_key, string
{
if ($count > 0) {
$line = $this->translator->trans($lang_key, ['count' => $count]);
- if ($add_url and !empty($url)) {
+ if ($add_url && ($url !== '' && $url !== '0')) {
$line = '' . $line . '';
}
$news[] = $line;
@@ -198,7 +198,7 @@ public function add_news_line(array $news, int $count, string $lang_key, string
* @param bool $add_url add html link around news
* @return string[]
*/
- public function news(DateTimeInterface $start = null, DateTimeInterface $end = null, bool $exclude_img_cats = false, bool $add_url = false): array
+ public function news(?DateTimeInterface $start = null, ?DateTimeInterface $end = null, bool $exclude_img_cats = false, bool $add_url = false): array
{
$news = [];
@@ -261,8 +261,9 @@ public function news(DateTimeInterface $start = null, DateTimeInterface $end = n
public function get_recent_post_dates(int $max_dates, int $max_elements, int $max_cats): array
{
$dates = $this->imageMapper->getRepository()->getRecentPostedImages($max_dates, $this->userMapper->getUser()->getUserInfos()->getForbiddenAlbums());
+ $counter = count($dates);
- for ($i = 0; $i < count($dates); $i++) {
+ for ($i = 0; $i < $counter; $i++) {
if ($max_elements > 0) { // get some thumbnails ...
$ids = [];
foreach ($this->imageMapper->getRepository()->findRandomImages($max_elements, $this->userMapper->getUser()->getUserInfos()->getForbiddenAlbums()) as $id) {
@@ -388,12 +389,7 @@ public function check_sendmail_timeout(): bool
public function get_user_notifications(string $action, array $check_key_list = [], ?bool $enabled_filter_value = null): array
{
if (in_array($action, ['subscribe', 'send'])) {
- if ($action == 'send') {
- $orders = ['n.last_send', 'u.username'];
- } else {
- $orders = ['u.username'];
- }
-
+ $orders = $action === 'send' ? ['n.last_send', 'u.username'] : ['u.username'];
return $this->userMailNotificationRepository->findInfosForUsers(($action === 'send'), $enabled_filter_value, $check_key_list, $orders);
} else {
return [];
@@ -417,12 +413,10 @@ public function begin_users_env_nbm(bool $is_to_send_mail = false): void
// Init mail configuration
if (!empty($this->conf['nbm_send_mail_as'])) {
$this->env['send_as_name'] = $this->conf['nbm_send_mail_as'];
+ } elseif (!empty($this->conf['mail_sender_name'])) {
+ $this->env['send_as_name'] = $this->conf['mail_sender_name'];
} else {
- if (!empty($this->conf['mail_sender_name'])) {
- $this->env['send_as_name'] = $this->conf['mail_sender_name'];
- } else {
- $this->env['send_as_name'] = $this->conf['gallery_title'];
- }
+ $this->env['send_as_name'] = $this->conf['gallery_title'];
}
$this->env['send_as_mail_address'] = $this->userMapper->getWebmaster()->getMailAddress();
@@ -451,18 +445,18 @@ public function inc_mail_sent_failed($nbm_user): void
public function display_counter_info(): void
{
+ /** @phpstan-ignore-next-line */
if ($this->env['error_on_mail_count'] != 0) {
$this->errors[] = $this->translator->trans('number_of_mails_not_sent', ['count' => $this->env['error_on_mail_count']]);
-
+ /** @phpstan-ignore-next-line */
if ($this->env['sent_mail_count'] != 0) {
$this->infos[] = $this->translator->trans('number_of_mails_sent', ['count' => $this->env['sent_mail_count']]);
}
+ /** @phpstan-ignore-next-line */
+ } elseif ($this->env['sent_mail_count'] == 0) {
+ $this->infos[] = $this->translator->trans('No mail to send.');
} else {
- if ($this->env['sent_mail_count'] == 0) {
- $this->infos[] = $this->translator->trans('No mail to send.');
- } else {
- $this->infos[] = $this->translator->trans('number_of_mails_sent', ['count' => $this->env['sent_mail_count']]);
- }
+ $this->infos[] = $this->translator->trans('number_of_mails_sent', ['count' => $this->env['sent_mail_count']]);
}
}
@@ -608,19 +602,16 @@ public function subscribe_notification_by_mail($is_admin_request, $check_key_lis
*/
public function do_timeout_treatment($post_keyname, $check_key_treated = []): void
{
- if ($this->env['is_sendmail_timeout']) {
- if (isset($_POST[$post_keyname])) {
- $post_count = is_countable($_POST[$post_keyname]) ? count($_POST[$post_keyname]) : 0;
- $treated_count = is_countable($check_key_treated) ? count($check_key_treated) : 0;
- if ($treated_count != 0) {
- $time_refresh = ceil((microtime(true) - $this->env['start_time']) * $post_count / $treated_count);
- } else {
- $time_refresh = 0;
- }
- $_POST[$post_keyname] = array_diff($_POST[$post_keyname], $check_key_treated);
-
- $this->errors[] = $this->translator->trans('execution_timeout_in_seconds', ['count' => $time_refresh]);
+ if ($this->env['is_sendmail_timeout'] && isset($_POST[$post_keyname])) {
+ $post_count = is_countable($_POST[$post_keyname]) ? count($_POST[$post_keyname]) : 0;
+ $treated_count = is_countable($check_key_treated) ? count($check_key_treated) : 0;
+ if ($treated_count != 0) {
+ $time_refresh = ceil((microtime(true) - $this->env['start_time']) * $post_count / $treated_count);
+ } else {
+ $time_refresh = 0;
}
+ $_POST[$post_keyname] = array_diff($_POST[$post_keyname], $check_key_treated);
+ $this->errors[] = $this->translator->trans('execution_timeout_in_seconds', ['count' => $time_refresh]);
}
}
@@ -651,7 +642,7 @@ public function insert_new_data_user_mail_notification(): void
// On timeout simulate like tabsheet send
if ($this->env['is_sendmail_timeout']) {
$check_key_list = array_diff($check_key_list, $check_key_treated);
- if (count($check_key_list) > 0) {
+ if ($check_key_list !== []) {
$this->userMailNotificationRepository->deleteByCheckKeys($check_key_list);
}
}
@@ -683,21 +674,18 @@ public function do_action_send_mail_notification($action = 'list_to_send', $chec
// Check if exist news to list user or send mails
if ((!$is_list_all_without_test) || ($is_action_send)) {
- if (count($data_users) > 0) {
+ if ($data_users !== []) {
if (!isset($customize_mail_content)) {
$customize_mail_content = $this->conf['nbm_complementary_mail_content'];
}
-
// Prepare message after change language
if ($is_action_send) {
$msg_break_timeout = $this->translator->trans('Time to send mail is limited. Others mails are skipped.');
} else {
$msg_break_timeout = $this->translator->trans('Prepared time for list of users to send mail is limited. Others users are not listed.');
}
-
// Begin nbm users environment
$this->begin_users_env_nbm($is_action_send);
-
foreach ($data_users as $nbm_user) {
if ((!$is_action_send) && $this->check_sendmail_timeout()) {
// Stop fill list on 'list_to_send', if the quota is override
@@ -712,18 +700,15 @@ public function do_action_send_mail_notification($action = 'list_to_send', $chec
if ($is_action_send) {
$tpl_params = [];
-
// Fill return list of "treated" check_key for 'send'
$return_list[] = $nbm_user->getCheckKey();
-
$news = '';
if ($this->conf['nbm_send_detailed_content']) {
$news = $this->news($nbm_user->getLastSend(), $now, false, $this->conf['nbm_send_html_mail']);
- $exist_data = count($news) > 0;
+ $exist_data = $news !== [];
} else {
$exist_data = $this->news_exists($nbm_user->getLastSend(), $now);
}
-
if ($exist_data) {
$subject = $this->translator->trans('New photos added');
@@ -784,21 +769,16 @@ public function do_action_send_mail_notification($action = 'list_to_send', $chec
$this->inc_mail_sent_failed($nbm_user);
}
}
- } else {
- if ($this->news_exists($nbm_user->getLastSend(), $now)) {
- // Fill return list of "selected" users for 'list_to_send'
- $return_list[] = $nbm_user;
- }
+ } elseif ($this->news_exists($nbm_user->getLastSend(), $now)) {
+ // Fill return list of "selected" users for 'list_to_send'
+ $return_list[] = $nbm_user;
}
}
-
if ($is_action_send) {
$this->display_counter_info();
}
- } else {
- if ($is_action_send) {
- $this->errors[] = $this->translator->trans('No user to send notifications by mail.');
- }
+ } elseif ($is_action_send) {
+ $this->errors[] = $this->translator->trans('No user to send notifications by mail.');
}
} else {
// Quick List, don't check news
diff --git a/src/Phyxo/Block/BlockManager.php b/src/Phyxo/Block/BlockManager.php
index 21d778922..25df6c5aa 100644
--- a/src/Phyxo/Block/BlockManager.php
+++ b/src/Phyxo/Block/BlockManager.php
@@ -42,7 +42,7 @@ public function loadDefaultBlocks(): void
/**
* Triggers a notice that allows plugins of menu blocks to register the blocks.
*/
- public function loadRegisteredBlocks(EventDispatcherInterface $eventDispatcher = null): void
+ public function loadRegisteredBlocks(?EventDispatcherInterface $eventDispatcher = null): void
{
if (!is_null($eventDispatcher)) {
$eventDispatcher->dispatch(new BlockEvent($this));
diff --git a/src/Phyxo/Block/DisplayBlock.php b/src/Phyxo/Block/DisplayBlock.php
index f137a74eb..834d0519d 100644
--- a/src/Phyxo/Block/DisplayBlock.php
+++ b/src/Phyxo/Block/DisplayBlock.php
@@ -42,7 +42,7 @@ public function setPosition(int $position): void
public function getTitle(): string
{
- if (isset($this->title)) {
+ if ($this->title !== null) {
return $this->title;
} else {
return $this->registeredBlock->getName();
diff --git a/src/Phyxo/Block/RegisteredBlock.php b/src/Phyxo/Block/RegisteredBlock.php
index 4c1d14967..d2cf0bec4 100644
--- a/src/Phyxo/Block/RegisteredBlock.php
+++ b/src/Phyxo/Block/RegisteredBlock.php
@@ -18,7 +18,7 @@ class RegisteredBlock
{
private $dataCallback;
- public function __construct(private readonly string $id, private readonly string $name, private readonly string $owner, callable $dataCallback = null)
+ public function __construct(private readonly string $id, private readonly string $name, private readonly string $owner, ?callable $dataCallback = null)
{
$this->dataCallback = $dataCallback;
}
diff --git a/src/Phyxo/Conf.php b/src/Phyxo/Conf.php
index bee790b8a..1a3d2a676 100644
--- a/src/Phyxo/Conf.php
+++ b/src/Phyxo/Conf.php
@@ -35,7 +35,7 @@ public function __construct(private readonly ConfigRepository $configRepository)
public function init(string $default_config_file, string $user_config_file = ''): void
{
$this->loadFromFile($default_config_file);
- if (!empty($user_config_file)) {
+ if ($user_config_file !== '' && $user_config_file !== '0') {
$this->loadFromFile($user_config_file);
}
$this->loadFromDB();
@@ -54,7 +54,7 @@ public function loadFromFile($conf_file): void
ob_end_clean();
/** @phpstan-ignore-next-line */
- if (count($conf) > 0) {
+ if ($conf !== []) {
foreach ($conf as $key => $value) {
$this->keys[self::FILE_PREFIX . $key] = ['value' => $value, 'type' => null];
}
@@ -178,7 +178,7 @@ protected function deleteParam(string|array $params): void
$params = [$params];
}
- if (empty($params)) {
+ if ($params === []) {
return;
}
diff --git a/src/Phyxo/Extension/Extensions.php b/src/Phyxo/Extension/Extensions.php
index 48ff30397..afe4374f7 100644
--- a/src/Phyxo/Extension/Extensions.php
+++ b/src/Phyxo/Extension/Extensions.php
@@ -32,7 +32,7 @@ public function getJsonFromServer($url, $params = [])
throw new Exception("Response is not readable");
}
} catch (Exception $e) {
- throw new Exception($e->getMessage());
+ throw new Exception($e->getMessage(), $e->getCode(), $e);
}
}
@@ -63,7 +63,7 @@ public function download($filename, $params = [])
throw new Exception("Response is not readable");
}
} catch (Exception $e) {
- throw new Exception($e->getMessage());
+ throw new Exception($e->getMessage(), $e->getCode(), $e);
}
}
@@ -84,16 +84,14 @@ protected function extractZipFiles($zip_file, $main_file, $extract_path = ''): s
$root = basename(dirname((string) $main_filepath)); // dirname($main_filepath) cannot be null throw Exception if needed
$extract_path .= '/' . $root;
- if (!empty($this->directory_pattern)) {
- if (!preg_match($this->directory_pattern, $root)) {
- throw new Exception(sprintf('Root directory (%s) of archive does not follow expected pattern %s', $root, $this->directory_pattern));
- }
+ if ($this->directory_pattern !== '' && $this->directory_pattern !== '0' && !preg_match($this->directory_pattern, $root)) {
+ throw new Exception(sprintf('Root directory (%s) of archive does not follow expected pattern %s', $root, $this->directory_pattern));
}
// @TODO: use native zip library ; use arobase before
if ($results = @$zip->extract(PCLZIP_OPT_PATH, $extract_path, PCLZIP_OPT_REMOVE_PATH, $root, PCLZIP_OPT_REPLACE_NEWER)) {
$errors = array_filter($results, fn ($f) => ($f['status'] !== 'ok' && $f['status'] !== 'filtered') && $f['status'] !== 'already_a_directory');
- if (count($errors) > 0) {
+ if ($errors !== []) {
throw new Exception("Error while extracting some files from archive");
}
} else {
diff --git a/src/Phyxo/Functions/Language.php b/src/Phyxo/Functions/Language.php
index 3414b6841..c42cdf27a 100644
--- a/src/Phyxo/Functions/Language.php
+++ b/src/Phyxo/Functions/Language.php
@@ -20,7 +20,7 @@ public static function loadLanguageFile(string $filename, string $dirname = ''):
{
$content = '';
- if (!empty($dirname)) {
+ if ($dirname !== '' && $dirname !== '0') {
$filename = $dirname . '/' . $filename;
}
@@ -64,7 +64,7 @@ public static function qualify_utf8(string $Str): int
return -1;
} // Does not match any model
for ($j = 0; $j < $n; $j++) { // n bytes matching 10bbbbbb follow ?
- if ((++$i == strlen($Str)) || ((ord($Str[$i]) & 0xC0) != 0x80)) {
+ if ((++$i === strlen($Str)) || ((ord($Str[$i]) & 0xC0) != 0x80)) {
return -1;
}
}
diff --git a/src/Phyxo/Functions/Upload.php b/src/Phyxo/Functions/Upload.php
index 2c166c8f1..6e0968450 100644
--- a/src/Phyxo/Functions/Upload.php
+++ b/src/Phyxo/Functions/Upload.php
@@ -63,17 +63,12 @@ public static function save_upload_form_config(array $data, array &$errors = [],
continue;
}
if (is_bool($upload_form_config[$field]['default'])) {
- if (isset($value)) {
- $value = true;
- } else {
- $value = false;
- }
-
+ $value = isset($value);
$updates[] = [
'param' => $field,
'value' => true
];
- } elseif ($upload_form_config[$field]['can_be_null'] and empty($value)) {
+ } elseif ($upload_form_config[$field]['can_be_null'] && empty($value)) {
$updates[] = [
'param' => $field,
'value' => null,
@@ -83,7 +78,7 @@ public static function save_upload_form_config(array $data, array &$errors = [],
$max = $upload_form_config[$field]['max'];
$pattern = $upload_form_config[$field]['pattern'];
- if (preg_match($pattern, (string) $value) and $value >= $min and $value <= $max) {
+ if (preg_match($pattern, (string) $value) && $value >= $min && $value <= $max) {
$updates[] = [
'param' => $field,
'value' => $value
diff --git a/src/Phyxo/Functions/Utils.php b/src/Phyxo/Functions/Utils.php
index 3a387c908..0eaa8733f 100644
--- a/src/Phyxo/Functions/Utils.php
+++ b/src/Phyxo/Functions/Utils.php
@@ -105,10 +105,10 @@ public static function convert_charset($str, $source_charset, $dest_charset)
if ($source_charset == $dest_charset) {
return $str;
}
- if ($source_charset == 'iso-8859-1' and $dest_charset == 'utf-8') {
+ if ($source_charset == 'iso-8859-1' && $dest_charset == 'utf-8') {
return mb_convert_encoding($str, 'UTF-8', 'ISO-8859-1');
}
- if ($source_charset == 'utf-8' and $dest_charset == 'iso-8859-1') {
+ if ($source_charset == 'utf-8' && $dest_charset == 'iso-8859-1') {
return mb_convert_encoding($str, 'ISO-8859-1');
}
if (function_exists('iconv')) {
@@ -172,7 +172,7 @@ public static function getPrivacyLevelOptions(TranslatorInterface $translator, a
if (0 == $level) {
$label = $translator->trans('Everybody', [], $domain);
} else {
- if (strlen($label)) {
+ if (strlen($label) !== 0) {
$label .= ', ';
}
$label .= $translator->trans('Level ' . $level, [], $domain);
@@ -394,11 +394,7 @@ public static function getAdminClientCacheKeys(ManagerRegistry $managerRegistry,
'tags' => Tag::class,
];
- if (empty($requested)) {
- $returned = array_keys($tables);
- } else {
- $returned = array_intersect($requested, array_keys($tables));
- }
+ $returned = $requested === [] ? array_keys($tables) : array_intersect($requested, array_keys($tables));
$keys = [
'_hash' => md5($base_url),
@@ -421,12 +417,7 @@ public static function need_resize($image_filepath, $max_width, $max_height)
// rotation must be applied to the resized photo, then we should test
// invert width and height.
$file_infos = self::image_infos($image_filepath);
-
- if ($file_infos['width'] > $max_width || $file_infos['height'] > $max_height) {
- return true;
- }
-
- return false;
+ return $file_infos['width'] > $max_width || $file_infos['height'] > $max_height;
}
public static function image_infos($path): array
@@ -467,7 +458,7 @@ public static function convert_shorthand_notation_to_bytes($value)
if (!is_null($multiply_by)) {
$value = (int) substr((string) $value, 0, -1);
- $value = $value * $multiply_by;
+ $value *= $multiply_by;
}
return $value;
diff --git a/src/Phyxo/Functions/Ws/Category.php b/src/Phyxo/Functions/Ws/Category.php
index 6b827190a..151fa99ab 100644
--- a/src/Phyxo/Functions/Ws/Category.php
+++ b/src/Phyxo/Functions/Ws/Category.php
@@ -55,7 +55,7 @@ public static function getImages($params, Server $service)
}
//-------------------------------------------------------- get the images
- if (count($album_ids) > 0) {
+ if ($album_ids !== []) {
foreach ($service->getImageMapper()->getRepository()->getImagesFromAlbums($album_ids, $params['per_page'], $params['per_page'] * $params['page']) as $image) {
$images[] = $image->toArray();
}
@@ -303,6 +303,7 @@ public static function setInfo($params, Server $service)
if ($perform_update) {
$service->getAlbumMapper()->getRepository()->addOrUpdateAlbum($album);
}
+ return null;
}
/**
@@ -331,6 +332,7 @@ public static function setRepresentative($params, Server $service)
$service->getAlbumMapper()->getRepository()->addOrUpdateAlbum($album);
$service->getManagerRegistry()->getRepository(UserCacheAlbum::class)->unsetUserRepresentativePictureForAlbum($params['category_id']);
+ return null;
}
/**
@@ -370,7 +372,7 @@ public static function delete($params, Server $service)
}
if (count($album_ids) == 0) {
- return;
+ return null;
}
foreach ($service->getAlbumMapper()->getRepository()->findBy(['id' => $album_ids]) as $album) {
@@ -381,7 +383,7 @@ public static function delete($params, Server $service)
$image_ids_to_delete[] = $image_album->getImage()->getId();
}
$album->getImageAlbums()->clear();
- if (count($image_ids_to_delete) > 0) {
+ if ($image_ids_to_delete !== []) {
$service->getImageMapper()->deleteElements($image_ids_to_delete, true);
}
}
@@ -391,13 +393,14 @@ public static function delete($params, Server $service)
foreach ($service->getImageMapper()->getRepository()->findBy(['storage_category_id' => $album_ids]) as $image) {
$image_ids[] = $image->getId();
}
- if (count($image_ids) > 0) {
+ if ($image_ids !== []) {
$service->getImageMapper()->deleteElements($image_ids);
}
}
$service->getAlbumMapper()->deleteAlbums($album_ids);
$service->getAlbumMapper()->updateGlobalRank();
+ return null;
}
/**
@@ -460,9 +463,10 @@ public static function move($params, Server $service)
$service->getAlbumMapper()->moveAlbums($category_ids, $params['parent'] === 0 ? null : $params['parent']);
$service->getUserMapper()->invalidateUserCache();
- if (count($page['errors']) != 0) {
+ if ($page['errors'] !== []) {
return new Error(403, implode('; ', $page['errors']));
}
+ return null;
}
/**
diff --git a/src/Phyxo/Functions/Ws/Extension.php b/src/Phyxo/Functions/Ws/Extension.php
index 7144c7a63..1af855a82 100644
--- a/src/Phyxo/Functions/Ws/Extension.php
+++ b/src/Phyxo/Functions/Ws/Extension.php
@@ -65,7 +65,7 @@ public static function update($params, Server $service)
if (isset($extension->getDbPlugins()[$extension_id]) && $extension->getDbPlugins()[$extension_id]->getState() === Plugin::ACTIVE) {
$extension->performAction('deactivate', $extension_id);
- return;
+ return null;
}
$extension->performAction('update', $extension_id, $revision);
@@ -155,11 +155,7 @@ public static function checkupdates($params, Server $service)
$result['phyxo_need_update'] = $update->isCoreNeedUpdate();
- if (!empty($service->getConf()['updates_ignored'])) {
- $updates_ignored = $service->getConf()['updates_ignored'];
- } else {
- $updates_ignored = [];
- }
+ $updates_ignored = empty($service->getConf()['updates_ignored']) ? [] : $service->getConf()['updates_ignored'];
if (!$update->isExtensionsNeedUpdate()) {
$service->getConf()->addOrUpdateParam('updates_ignored', $update->checkExtensions($updates_ignored));
diff --git a/src/Phyxo/Functions/Ws/Image.php b/src/Phyxo/Functions/Ws/Image.php
index d247acab5..85e57fcf3 100644
--- a/src/Phyxo/Functions/Ws/Image.php
+++ b/src/Phyxo/Functions/Ws/Image.php
@@ -105,7 +105,7 @@ public static function getInfo($params, Server $service)
}
usort($related_categories, '\Phyxo\Functions\Utils::global_rank_compare');
- if (count($related_categories) === 0) {
+ if ($related_categories === []) {
return new Error(401, 'Access denied');
}
@@ -230,7 +230,7 @@ public static function search($params, Server $service)
$params['per_page']
);
- if (count($image_ids)) {
+ if ($image_ids !== []) {
$image_ids = array_flip($image_ids);
foreach ($service->getImageMapper()->getRepository()->findBy(['id' => $image_ids]) as $image) {
$image_infos = $image->toArray();
@@ -267,6 +267,7 @@ public static function setPrivacyLevel($params, Server $service)
$service->getImageMapper()->getRepository()->updateFieldForImages($params['image_id'], 'level', (int) $params['level']);
$service->getUserMapper()->invalidateUserCache();
+ return null;
}
/**
@@ -357,6 +358,7 @@ public static function addChunk($params, Server $service)
'an error has occured while writting chunk ' . $params['position'] . ' for ' . $params['type']
);
}
+ return null;
}
/**
@@ -419,6 +421,7 @@ public static function addFile($params, Server $service)
$image->getMd5sum() // we force the md5sum to remain the same
);
$service->getTagMapper()->sync_metadata([$image_id]);
+ return null;
}
/**
@@ -550,10 +553,8 @@ public static function addSimple($params, Server $service)
return new Error(405, 'The image (file) is missing');
}
- if ($params['image_id'] > 0) {
- if (is_null($service->getImageMapper()->getRepository()->find($params['image_id']))) {
- return new Error(404, 'image_id not found');
- }
+ if ($params['image_id'] > 0 && is_null($service->getImageMapper()->getRepository()->find($params['image_id']))) {
+ return new Error(404, 'image_id not found');
}
$image_id = self::addUploadedFile(
@@ -644,7 +645,7 @@ public static function upload($params, Server $service)
// Get a file name
if (isset($_REQUEST["name"])) {
$fileName = $_REQUEST["name"];
- } elseif (!empty($_FILES)) {
+ } elseif ($_FILES !== []) {
$fileName = $_FILES["file"]["name"];
} else {
$fileName = uniqid("file_");
@@ -657,23 +658,20 @@ public static function upload($params, Server $service)
$chunks = isset($_REQUEST["chunks"]) ? intval($_REQUEST["chunks"]) : 0;
// Open temp file
- if (!$out = @fopen("{$filePath}.part", $chunks ? "ab" : "wb")) {
+ if (!$out = @fopen("{$filePath}.part", $chunks !== 0 ? "ab" : "wb")) {
die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}');
}
- if (!empty($_FILES)) {
+ if ($_FILES !== []) {
if ($_FILES["file"]["error"] || !is_uploaded_file($_FILES["file"]["tmp_name"])) {
die('{"jsonrpc" : "2.0", "error" : {"code": 103, "message": "Failed to move uploaded file."}, "id" : "id"}');
}
-
// Read binary input stream and append it to temp file
if (!$in = @fopen($_FILES["file"]["tmp_name"], "rb")) {
die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');
}
- } else {
- if (!$in = @fopen("php://input", "rb")) {
- die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');
- }
+ } elseif (!$in = @fopen("php://input", "rb")) {
+ die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');
}
while ($buff = fread($in, 4096)) {
@@ -719,6 +717,7 @@ public static function upload($params, Server $service)
]
];
}
+ return null;
}
/**
@@ -817,11 +816,7 @@ public static function checkFiles($params, Server $service)
}
if (isset($compare_type)) {
- if (md5_file($image->getPath()) != $params[$compare_type . '_sum']) {
- $ret[$compare_type] = 'differs';
- } else {
- $ret[$compare_type] = 'equals';
- }
+ $ret[$compare_type] = md5_file($image->getPath()) != $params[$compare_type . '_sum'] ? 'differs' : 'equals';
}
return $ret;
@@ -856,15 +851,11 @@ public static function setRelatedTags($params, Server $service)
$removed_tags = array_diff($current_tags, $params['tags']);
$new_tags = array_diff($params['tags'], $current_tags);
- if (count($removed_tags) > 0) {
- if ($service->getSecurity()->isGranted(TagVoter::DELETE, $image) == false) {
- return new Error(403, 'You are not allowed to delete tags');
- }
+ if (count($removed_tags) > 0 && $service->getSecurity()->isGranted(TagVoter::DELETE, $image) == false) {
+ return new Error(403, 'You are not allowed to delete tags');
}
- if (count($new_tags) > 0) {
- if ($service->getSecurity()->isGranted(TagVoter::ADD, $image) == false) {
- return new Error(403, 'You are not allowed to add tags');
- }
+ if (count($new_tags) > 0 && $service->getSecurity()->isGranted(TagVoter::ADD, $image) == false) {
+ return new Error(403, 'You are not allowed to add tags');
}
try {
@@ -876,7 +867,7 @@ public static function setRelatedTags($params, Server $service)
}
} else {
// if publish_tags_immediately (or delete_tags_immediately) is not set we consider its value is 1
- if (count($removed_tags) > 0) {
+ if ($removed_tags !== []) {
$removed_tags_ids = $service->getTagMapper()->getTagsIds($removed_tags);
if (isset($service->getConf()['delete_tags_immediately']) && $service->getConf()['delete_tags_immediately'] == 0) {
$service->getTagMapper()->toBeValidatedTags($image, $removed_tags_ids, $service->getUserMapper()->getUser(), ImageTag::STATUS_TO_DELETE);
@@ -885,7 +876,7 @@ public static function setRelatedTags($params, Server $service)
}
}
- if (count($new_tags) > 0) {
+ if ($new_tags !== []) {
$new_tags_ids = $service->getTagMapper()->getTagsIds($new_tags);
if (isset($service->getConf()['publish_tags_immediately']) && $service->getConf()['publish_tags_immediately'] == 0) {
$service->getTagMapper()->toBeValidatedTags($image, $new_tags_ids, $service->getUserMapper()->getUser(), ImageTag::STATUS_TO_ADD);
@@ -897,6 +888,7 @@ public static function setRelatedTags($params, Server $service)
} catch (Exception) {
return new Error(500, '[ws_images_setRelatedTags] Something went wrong when updating tags');
}
+ return null;
}
/**
@@ -961,7 +953,7 @@ public static function setInfo($params, Server $service)
$service,
$params['image_id'],
$params['categories'],
- ('replace' == $params['multiple_value_mode'] ? true : false)
+ ('replace' == $params['multiple_value_mode'])
);
}
@@ -992,6 +984,7 @@ public static function setInfo($params, Server $service)
}
$service->getUserMapper()->invalidateUserCache();
+ return null;
}
/**
@@ -1038,10 +1031,8 @@ public static function checkUpload($params, Server $service)
if (!is_writable(dirname((string) $service->getUploadDir()))) {
$message = sprintf('Create the "%s" directory at the root of your Phyxo installation', basename((string) $service->getUploadDir()));
}
- } else {
- if (!is_writable($service->getUploadDir())) {
- $message = sprintf('Give write access (chmod 777) to "%s" directory at the root of your Phyxo installation', basename((string) $service->getUploadDir()));
- }
+ } elseif (!is_writable($service->getUploadDir())) {
+ $message = sprintf('Give write access (chmod 777) to "%s" directory at the root of your Phyxo installation', basename((string) $service->getUploadDir()));
}
return ['message' => $message, 'ready_for_upload' => $message === ''];
@@ -1085,7 +1076,7 @@ protected static function addImageAlbumRelations(Server $service, int $image_id,
$album_ids = array_unique($album_ids);
- if (count($album_ids) === 0) {
+ if ($album_ids === []) {
return new Error(
500,
'[\Phyxo\Functions\Ws\Images::addImageAlbumRelations] there is no category defined in "' . $categories_string . '"'
@@ -1118,6 +1109,7 @@ protected static function addImageAlbumRelations(Server $service, int $image_id,
}
$service->getAlbumMapper()->updateAlbums($album_ids);
+ return null;
}
/**
@@ -1157,6 +1149,7 @@ protected static function merge_chunks(string $output_filepath, string $original
unlink($chunk);
}
+ return null;
}
/**
@@ -1200,11 +1193,7 @@ protected static function addUploadedFile(Server $service, string $source_filepa
// TODO
// * check md5sum (already exists?)
- if (isset($original_md5sum)) {
- $md5sum = $original_md5sum;
- } else {
- $md5sum = md5_file($source_filepath);
- }
+ $md5sum = $original_md5sum ?? md5_file($source_filepath);
$fs = new Filesystem();
$file_path = null;
@@ -1283,7 +1272,7 @@ protected static function addUploadedFile(Server $service, string $source_filepa
if (isset($image_id)) {
$image = $service->getImageMapper()->getRepository()->find($image_id);
- $image->setFile(!empty($original_filename) ? $original_filename : basename((string) $file_path));
+ $image->setFile($original_filename === '' || $original_filename === '0' ? basename((string) $file_path) : $original_filename);
$image->setFilesize($filesize);
$image->setWidth($width);
$image->setHeight($height);
@@ -1297,7 +1286,7 @@ protected static function addUploadedFile(Server $service, string $source_filepa
$service->getImageMapper()->getRepository()->addOrUpdateImage($image);
} else {
$image = new EntityImage();
- $image->setFile(!empty($original_filename) ? $original_filename : basename((string) $file_path));
+ $image->setFile($original_filename === '' || $original_filename === '0' ? basename((string) $file_path) : $original_filename);
$image->setName(Utils::get_name_from_file($image->getFile()));
$image->setDateAvailable($now);
$image->setPath(preg_replace('#^' . preg_quote(dirname((string) $upload_dir)) . '#', '.', realpath($file_path)));
@@ -1319,7 +1308,7 @@ protected static function addUploadedFile(Server $service, string $source_filepa
$image_id = $service->getImageMapper()->getRepository()->addOrUpdateImage($image);
}
- if (count($categories) > 0) {
+ if ($categories !== []) {
$service->getAlbumMapper()->associateImagesToAlbums([$image_id], $categories);
}
diff --git a/src/Phyxo/Functions/Ws/Main.php b/src/Phyxo/Functions/Ws/Main.php
index a23e2b5cf..adcebfdcf 100644
--- a/src/Phyxo/Functions/Ws/Main.php
+++ b/src/Phyxo/Functions/Ws/Main.php
@@ -201,7 +201,9 @@ public static function stdGetUrls(Image $image, Server $service)
$derivatives_arr = [];
foreach ($derivatives as $type => $derivative) {
$size = $derivative->getSize();
- $size != null or $size = [null, null];
+ if ($size == null) {
+ $size = [null, null];
+ }
$derivatives_arr[$type] = [
'url' => $service->getRouter()->generate('admin_media', ['path' => $image->getPathBasename(), 'derivative' => $derivative->getUrlType(), 'image_extension' => $image->getExtension()]),
'width' => $size[0],
diff --git a/src/Phyxo/Functions/Ws/Permission.php b/src/Phyxo/Functions/Ws/Permission.php
index 06bed25a5..81819f0c7 100644
--- a/src/Phyxo/Functions/Ws/Permission.php
+++ b/src/Phyxo/Functions/Ws/Permission.php
@@ -64,11 +64,7 @@ public static function getList($params, Server $service)
// indirect users
$album_ids = [];
if (!empty($params['cat_id'])) {
- if (is_array($params['cat_id'])) {
- $album_ids = $params['cat_id'];
- } else {
- $album_ids = [$params['cat_id']];
- }
+ $album_ids = is_array($params['cat_id']) ? $params['cat_id'] : [$params['cat_id']];
}
foreach ($service->getUserMapper()->getRepository()->findWithAlbumsAccess($album_ids) as $user) {
$permissions[$album->getId()]['users_indirect'][] = $user->getId();
@@ -82,23 +78,18 @@ public static function getList($params, Server $service)
// filter by group and user
foreach ($permissions as $album_id => &$album) {
- if (!empty($params['group_id'])) {
- if (empty($album['groups']) || count(array_intersect($album['groups'], $params['group_id'])) === 0) {
- unset($permissions[$album_id]);
- continue;
- }
+ if (!empty($params['group_id']) && (empty($album['groups']) || count(array_intersect($album['groups'], $params['group_id'])) === 0)) {
+ unset($permissions[$album_id]);
+ continue;
}
- if (!empty($params['user_id'])) {
- if ((empty($album['users_indirect']) || count(array_intersect($album['users_indirect'], $params['user_id'])) === 0)
- && (empty($album['users']) || count(array_intersect($album['users'], $params['user_id'])) === 0)) {
- unset($permissions[$album_id]);
- continue;
- }
+ if (!empty($params['user_id']) && ((empty($album['users_indirect']) || count(array_intersect($album['users_indirect'], $params['user_id'])) === 0) && (empty($album['users']) || count(array_intersect($album['users'], $params['user_id'])) === 0))) {
+ unset($permissions[$album_id]);
+ continue;
}
- $album['groups'] = !empty($album['groups']) ? array_values(array_unique($album['groups'])) : [];
- $album['users'] = !empty($album['users']) ? array_values(array_unique($album['users'])) : [];
- $album['users_indirect'] = !empty($album['users_indirect']) ? array_values(array_unique($album['users_indirect'])) : [];
+ $album['groups'] = empty($album['groups']) ? [] : array_values(array_unique($album['groups']));
+ $album['users'] = empty($album['users']) ? [] : array_values(array_unique($album['users']));
+ $album['users_indirect'] = empty($album['users_indirect']) ? [] : array_values(array_unique($album['users_indirect']));
}
return ['categories' => array_values($permissions)];
@@ -133,14 +124,14 @@ public static function add($params, Server $service)
foreach ($service->getAlbumMapper()->findByIdsAndStatus($album_ids, Album::STATUS_PRIVATE) as $album) {
$need_update = false;
- if (count($groups) > 0) {
+ if ($groups !== []) {
$need_update = true;
foreach ($groups as $group) {
$album->addGroupAccess($group);
}
}
- if (count($users) > 0) {
+ if ($users !== []) {
$need_update = true;
foreach ($users as $user) {
$album->addUserAcccess($user);
diff --git a/src/Phyxo/Functions/Ws/Plugin.php b/src/Phyxo/Functions/Ws/Plugin.php
index db10605d1..d6b5dca26 100644
--- a/src/Phyxo/Functions/Ws/Plugin.php
+++ b/src/Phyxo/Functions/Ws/Plugin.php
@@ -31,11 +31,7 @@ public static function getList($params, Server $service)
$plugin_list = [];
foreach ($plugins->getFsPlugins() as $plugin_id => $fs_plugin) {
- if (isset($plugins->getDbPlugins()[$plugin_id])) {
- $state = $plugins->getDbPlugins()[$plugin_id]['state'];
- } else {
- $state = 'uninstalled';
- }
+ $state = isset($plugins->getDbPlugins()[$plugin_id]) ? $plugins->getDbPlugins()[$plugin_id]['state'] : 'uninstalled';
$plugin_list[] = [
'id' => $plugin_id,
@@ -62,8 +58,9 @@ public static function performAction($params, Server $service)
$plugins->setRootPath($service->getParams()->get('plugins_dir'));
$error = $plugins->performAction($params['action'], $params['plugin']);
- if (!empty($error)) {
+ if ($error !== '' && $error !== '0') {
return new Error(500, $error);
}
+ return null;
}
}
diff --git a/src/Phyxo/Functions/Ws/Rate.php b/src/Phyxo/Functions/Ws/Rate.php
index 3f8b9e68e..d14ca6594 100644
--- a/src/Phyxo/Functions/Ws/Rate.php
+++ b/src/Phyxo/Functions/Ws/Rate.php
@@ -27,8 +27,8 @@ public function delete($params, Server $service)
{
$changes = $service->getManagerRegistry()->getRepository(EntityRate::class)->deleteWithConditions(
$params['user_id'],
- !empty($params['anonymous_id']) ? $params['anonymous_id'] : null,
- !empty($params['image_id']) ? $params['image_id'] : null
+ empty($params['anonymous_id']) ? null : $params['anonymous_id'],
+ empty($params['image_id']) ? null : $params['image_id']
);
if ($changes) {
diff --git a/src/Phyxo/Functions/Ws/Session.php b/src/Phyxo/Functions/Ws/Session.php
index 1bc42596c..bb2f6dc20 100644
--- a/src/Phyxo/Functions/Ws/Session.php
+++ b/src/Phyxo/Functions/Ws/Session.php
@@ -27,7 +27,7 @@ class Session
*/
public static function login($params, Server $service)
{
- if ($service->getAppUserService()->getUser() !== null) {
+ if ($service->getAppUserService()->getUser() instanceof User) {
return true;
} else {
return new Error(999, 'Invalid username/password');
diff --git a/src/Phyxo/Functions/Ws/Tag.php b/src/Phyxo/Functions/Ws/Tag.php
index 59cc8511e..f3cb53c99 100644
--- a/src/Phyxo/Functions/Ws/Tag.php
+++ b/src/Phyxo/Functions/Ws/Tag.php
@@ -96,7 +96,7 @@ public static function getImages($params, Server $service)
$image_tag_map = [];
// build list of image ids with associated tags per image
- if (count($image_ids) > 0 && !$params['tag_mode_and']) {
+ if ($image_ids !== [] && !$params['tag_mode_and']) {
$image_tag_map = [];
foreach ($service->getTagMapper()->getRepository()->findImageTags($tag_ids, $image_ids) as $tag) {
$image_tag_map[$tag->getImage()->getId()][] = $tag->getId();
@@ -104,7 +104,7 @@ public static function getImages($params, Server $service)
}
$images = [];
- if (!empty($image_ids)) {
+ if ($image_ids !== []) {
$rank_of = array_flip($image_ids);
foreach ($service->getImageMapper()->getRepository()->findBy(['id' => $image_ids]) as $image) {
@@ -180,8 +180,9 @@ public static function tagsList(array $tags, $params, Server $service)
} else {
usort($tags, [$service->getTagMapper(), 'alphaCompare']);
}
+ $counter = count($tags);
- for ($i = 0; $i < count($tags); $i++) {
+ for ($i = 0; $i < $counter; $i++) {
if (!empty($params['sort_by_counter'])) {
$tags[$i]['counter'] = (int) $tags[$i]['counter'];
}
diff --git a/src/Phyxo/Functions/Ws/Theme.php b/src/Phyxo/Functions/Ws/Theme.php
index 5ea98a752..9323da7ea 100644
--- a/src/Phyxo/Functions/Ws/Theme.php
+++ b/src/Phyxo/Functions/Ws/Theme.php
@@ -30,7 +30,7 @@ public static function performAction(array $params, Server $service)
$themes = new Themes($service->getManagerRegistry()->getRepository(EntityTheme::class), $service->getUserMapper());
$errors = $themes->performAction($params['action'], $params['theme']);
- if (!empty($errors)) {
+ if ($errors !== '' && $errors !== '0') {
return new Error(500, $errors);
}
diff --git a/src/Phyxo/Functions/Ws/User.php b/src/Phyxo/Functions/Ws/User.php
index a4ba63c9c..3ffe4ea81 100644
--- a/src/Phyxo/Functions/Ws/User.php
+++ b/src/Phyxo/Functions/Ws/User.php
@@ -119,7 +119,7 @@ public static function getList($params, Server $service)
$users[$user['id']] = $user;
}
- if (count($users) > 0) {
+ if ($users !== []) {
foreach ($users as $cur_user) {
$fmt = new IntlDateFormatter($service->getUserMapper()->getUser()->getLocale(), IntlDateFormatter::FULL, IntlDateFormatter::NONE);
@@ -141,7 +141,7 @@ public static function getList($params, Server $service)
$history_ids[] = $history->getId();
}
- if (count($history_ids) > 0) {
+ if ($history_ids !== []) {
foreach ($service->getManagerRegistry()->getRepository(History::class)->findBy(['id' => $history_ids]) as $history) {
$last_visit = $history->getDate();
$last_visit->setTime(...explode(':', $history->getTime()->format('h:i:s')));
@@ -171,10 +171,8 @@ public static function getList($params, Server $service)
*/
public static function add($params, Server $service)
{
- if ($service->getConf()['double_password_type_in_admin']) {
- if ($params['password'] != $params['password_confirm']) {
- return new Error(Server::WS_ERR_INVALID_PARAM, 'The passwords do not match');
- }
+ if ($service->getConf()['double_password_type_in_admin'] && $params['password'] != $params['password_confirm']) {
+ return new Error(Server::WS_ERR_INVALID_PARAM, 'The passwords do not match');
}
try {
@@ -368,7 +366,7 @@ public static function setInfo($params, Server $service)
$service->getManagerRegistry()->getRepository(UserInfos::class)->updateFieldForUsers('status', $update_status, $params['user_id_for_status']);
}
- if (count($updates_infos) > 0) {
+ if ($updates_infos !== []) {
$service->getManagerRegistry()->getRepository(UserInfos::class)->updateFieldsForUsers($updates_infos, $params['user_id']);
}
diff --git a/src/Phyxo/Image/DerivativeImage.php b/src/Phyxo/Image/DerivativeImage.php
index 308bd5024..52187770c 100644
--- a/src/Phyxo/Image/DerivativeImage.php
+++ b/src/Phyxo/Image/DerivativeImage.php
@@ -65,7 +65,7 @@ public function getSize(): array
$rotation = intval($this->image->getRotation()) % 4;
// 1 or 5 => 90 clockwise
// 3 or 7 => 270 clockwise
- if ($rotation % 2) {
+ if ($rotation % 2 !== 0) {
$width = $this->image->getHeight();
$height = $this->image->getWidth();
}
@@ -85,7 +85,7 @@ public function getUrlSize(): string
$this->params->add_url_tokens($tokens);
}
- return sprintf('%s', implode('', $tokens));
+ return implode('', $tokens);
}
/**
@@ -94,7 +94,7 @@ public function getUrlSize(): string
public function getLiteralSize(): string
{
$size = $this->getSize();
- if (!$size) {
+ if ($size === []) {
return '';
}
@@ -111,7 +111,7 @@ public function relativeThumbInfos(): array
private function buildInfos(): array
{
- if (count($this->getSize()) > 0 && $this->params->is_identity($this->getSize())) {
+ if ($this->getSize() !== [] && $this->params->is_identity($this->getSize())) {
// the source image is smaller than what we should do - we do not upsample
if (!$this->params->will_watermark($this->getSize(), $this->image_std_params) && !$this->image->getRotation()) {
// no watermark, no rotation required -> we will use the source image
@@ -124,7 +124,8 @@ private function buildInfos(): array
}
$defined_types = array_keys($this->image_std_params->getDefinedTypeMap());
- for ($i = 0; $i < count($defined_types); $i++) {
+ $counter = count($defined_types);
+ for ($i = 0; $i < $counter; $i++) {
if ($defined_types[$i] == $this->params->type) {
for ($i--; $i >= 0; $i--) {
$smaller = $this->image_std_params->getByType($defined_types[$i]);
diff --git a/src/Phyxo/Image/DerivativeParams.php b/src/Phyxo/Image/DerivativeParams.php
index 23d0ecce9..70132a89a 100644
--- a/src/Phyxo/Image/DerivativeParams.php
+++ b/src/Phyxo/Image/DerivativeParams.php
@@ -66,7 +66,7 @@ public function max_height(): int
*/
public function is_identity(array $in_size): bool
{
- return !($in_size[0] > $this->sizing->ideal_size[0] || $in_size[1] > $this->sizing->ideal_size[1]);
+ return $in_size[0] <= $this->sizing->ideal_size[0] && $in_size[1] <= $this->sizing->ideal_size[1];
}
public function will_watermark($out_size, ImageStandardParams $image_std_params): bool
diff --git a/src/Phyxo/Image/ImageOptimizer.php b/src/Phyxo/Image/ImageOptimizer.php
index 08970244c..5ef210e71 100644
--- a/src/Phyxo/Image/ImageOptimizer.php
+++ b/src/Phyxo/Image/ImageOptimizer.php
@@ -185,7 +185,7 @@ public function mainResize(
$this->resize($resizeDimensions['width'], $resizeDimensions['height']);
- if (!empty($rotation)) {
+ if ($rotation !== null && $rotation !== 0) {
$this->rotate($rotation);
}
diff --git a/src/Phyxo/Image/ImageStandardParams.php b/src/Phyxo/Image/ImageStandardParams.php
index a6b599f5b..21c5fde2d 100644
--- a/src/Phyxo/Image/ImageStandardParams.php
+++ b/src/Phyxo/Image/ImageStandardParams.php
@@ -235,8 +235,9 @@ protected function buildMaps()
}
$this->all_type_map = $this->type_map;
+ $counter = count($this->all_types);
- for ($i = 0; $i < count($this->all_types); $i++) {
+ for ($i = 0; $i < $counter; $i++) {
$tocheck = $this->all_types[$i];
if (!isset($this->type_map[$tocheck])) {
for ($j = $i - 1; $j >= 0; $j--) {
diff --git a/src/Phyxo/Language/Languages.php b/src/Phyxo/Language/Languages.php
index 24457d760..b3311f99a 100644
--- a/src/Phyxo/Language/Languages.php
+++ b/src/Phyxo/Language/Languages.php
@@ -41,7 +41,7 @@ public function setRootPath(string $languages_root_path)
/**
* Perform requested actions
*/
- public function performAction(string $action, string $language_id, string $revision_id = null)
+ public function performAction(string $action, string $language_id, ?string $revision_id = null)
{
if (!$this->db_languages_retrieved) {
$this->getDbLanguages();
@@ -159,7 +159,8 @@ public function getFsLanguages(): array
if (preg_match("|Author URI:\\s*(https?:\\/\\/.+)|", $language_data, $val)) {
$language['author uri'] = trim($val[1]);
}
- if (!empty($language['uri']) and strpos($language['uri'], 'extension_view.php?eid=')) {
+ /** @phpstan-ignore-next-line */
+ if (isset($language['uri']) && ($language['uri'] !== '' && $language['uri'] !== '0') && strpos($language['uri'], 'extension_view.php?eid=')) {
[, $extension] = explode('extension_view.php?eid=', $language['uri']);
if (is_numeric($extension)) {
$language['extension'] = $extension;
@@ -216,10 +217,10 @@ public function getServerLanguages(string $pem_category, string $phyxo_version,
}
}
} catch (Exception $e) {
- throw new Exception($e->getMessage());
+ throw new Exception($e->getMessage(), $e->getCode(), $e);
}
- if (empty($versions_to_check)) {
+ if ($versions_to_check === []) {
return [];
}
@@ -239,7 +240,7 @@ public function getServerLanguages(string $pem_category, string $phyxo_version,
'lang' => 'en_GB', // @TODO: inject user language
'get_nb_downloads' => 'true',
]);
- if (!empty($languages_to_check)) {
+ if ($languages_to_check !== []) {
if ($new) {
$get_data['extension_exclude'] = implode(',', $languages_to_check);
} else {
@@ -260,7 +261,7 @@ public function getServerLanguages(string $pem_category, string $phyxo_version,
}
uasort($this->server_languages, $this->extensionNameCompare(...));
} catch (Exception $e) {
- throw new Exception($e->getMessage());
+ throw new Exception($e->getMessage(), $e->getCode(), $e);
}
$this->server_languages_retrieved = true;
@@ -283,7 +284,7 @@ public function extractLanguageFiles(string $action, int $revision)
try {
$this->download($archive, $get_data);
} catch (Exception $e) {
- throw new Exception("Cannot download language archive");
+ throw new Exception("Cannot download language archive", $e->getCode(), $e);
}
try {
@@ -295,7 +296,7 @@ public function extractLanguageFiles(string $action, int $revision)
$this->performAction('update', $language_id);
}
} catch (Exception $e) {
- throw new Exception($e->getMessage());
+ throw new Exception($e->getMessage(), $e->getCode(), $e);
} finally {
unlink($archive);
}
@@ -320,7 +321,7 @@ protected function extractLanguageZipFiles(string $zip_file, string $extract_pat
// @TODO: use native zip library ; use arobase before
if ($results = @$zip->extract(PCLZIP_OPT_PATH, $extract_path, PCLZIP_OPT_REMOVE_PATH, $extract_path, PCLZIP_OPT_REPLACE_NEWER)) {
$errors = array_filter($results, fn ($f) => ($f['status'] !== 'ok' && $f['status'] !== 'filtered') && $f['status'] !== 'already_a_directory');
- if (count($errors) > 0) {
+ if ($errors !== []) {
throw new Exception("Error while extracting some files from archive");
}
} else {
diff --git a/src/Phyxo/MenuBar.php b/src/Phyxo/MenuBar.php
index 8befab2b6..b6094bc92 100644
--- a/src/Phyxo/MenuBar.php
+++ b/src/Phyxo/MenuBar.php
@@ -101,7 +101,7 @@ protected function linksBlock()
$block->data[] = $tpl_var;
}
- if (!empty($block->data)) {
+ if ($block->data !== []) {
$block->template = 'menubar_links';
}
}
diff --git a/src/Phyxo/Plugin/Plugins.php b/src/Phyxo/Plugin/Plugins.php
index e118de0f4..32b6ac050 100644
--- a/src/Phyxo/Plugin/Plugins.php
+++ b/src/Phyxo/Plugin/Plugins.php
@@ -70,7 +70,7 @@ private function buildMaintainClass($plugin_id)
/**
* Perform requested actions
*/
- public function performAction(string $action, string $plugin_id, int $revision = null): string
+ public function performAction(string $action, string $plugin_id, ?int $revision = null): string
{
if (!$this->db_plugins_retrieved) {
$this->getDbPlugins();
@@ -232,7 +232,7 @@ public function getDbPlugins(string $state = '', string $id = ''): array
$this->db_plugins_retrieved = true;
}
- if (!empty($id)) {
+ if ($id !== '' && $id !== '0') {
return $this->db_plugins[$id] ?? [];
} else {
return $this->db_plugins;
@@ -315,7 +315,7 @@ public function getServerPlugins(string $pem_category, string $core_version, $ne
'get_nb_downloads' => 'true',
];
- if (!empty($plugins_to_check)) {
+ if ($plugins_to_check !== []) {
if ($new) {
$get_data['extension_exclude'] = implode(',', $plugins_to_check);
} else {
@@ -333,7 +333,7 @@ public function getServerPlugins(string $pem_category, string $core_version, $ne
$this->server_plugins[$plugin['extension_id']] = $plugin;
}
} catch (Exception $e) {
- throw new Exception($e->getMessage());
+ throw new Exception($e->getMessage(), $e->getCode(), $e);
}
$this->server_plugins_retrieved = true;
@@ -391,7 +391,7 @@ public function getIncompatiblePlugins(string $pem_category, string $core_versio
return $incompatible_plugins;
} catch (Exception $e) {
- throw new Exception($e->getMessage());
+ throw new Exception($e->getMessage(), $e->getCode(), $e);
}
}
@@ -433,14 +433,14 @@ public function extractPluginFiles(string $action, int $revision)
try {
$this->download($archive, $get_data);
} catch (Exception $e) {
- throw new Exception("Cannot download plugin file");
+ throw new Exception("Cannot download plugin file", $e->getCode(), $e);
}
$extract_path = $this->plugins_root_path;
try {
$this->extractZipFiles($archive, self::CONFIG_FILE, $extract_path);
} catch (Exception $e) {
- throw new Exception($e->getMessage());
+ throw new Exception($e->getMessage(), $e->getCode(), $e);
} finally {
unlink($archive);
}
diff --git a/src/Phyxo/Theme/Themes.php b/src/Phyxo/Theme/Themes.php
index f996b0040..00d87caae 100644
--- a/src/Phyxo/Theme/Themes.php
+++ b/src/Phyxo/Theme/Themes.php
@@ -185,7 +185,7 @@ public function getChildrenThemes($theme_id)
$children = [];
foreach ($this->getFsThemes() as $test_child) {
- if (isset($test_child['parent']) and $test_child['parent'] == $theme_id) {
+ if (isset($test_child['parent']) && $test_child['parent'] == $theme_id) {
$children[] = $test_child['name'];
}
}
@@ -321,10 +321,10 @@ public function getServerThemes(string $pem_category, string $phyxo_version, $ne
}
}
} catch (Exception $e) {
- throw new Exception($e->getMessage());
+ throw new Exception($e->getMessage(), $e->getCode(), $e);
}
- if (empty($versions_to_check)) {
+ if ($versions_to_check === []) {
return [];
}
@@ -348,7 +348,7 @@ public function getServerThemes(string $pem_category, string $phyxo_version, $ne
]
);
- if (!empty($themes_to_check)) {
+ if ($themes_to_check !== []) {
if ($new) {
$get_data['extension_exclude'] = implode(',', $themes_to_check);
} else {
@@ -365,7 +365,7 @@ public function getServerThemes(string $pem_category, string $phyxo_version, $ne
$this->server_themes[$theme['extension_id']] = $theme;
}
} catch (Exception $e) {
- throw new Exception($e->getMessage());
+ throw new Exception($e->getMessage(), $e->getCode(), $e);
}
$this->server_themes_retrieved = true;
}
@@ -410,14 +410,14 @@ public function extractThemeFiles(string $action, int $revision)
try {
$this->download($archive, $get_data);
} catch (Exception $e) {
- throw new Exception("Cannot download theme archive");
+ throw new Exception("Cannot download theme archive", $e->getCode(), $e);
}
$extract_path = $this->themes_root_path;
try {
$this->extractZipFiles($archive, self::CONFIG_FILE, $extract_path);
} catch (Exception $e) {
- throw new Exception($e->getMessage());
+ throw new Exception($e->getMessage(), $e->getCode(), $e);
} finally {
unlink($archive);
}
diff --git a/src/Phyxo/Update/Updates.php b/src/Phyxo/Update/Updates.php
index 363308ab7..5f3e60850 100644
--- a/src/Phyxo/Update/Updates.php
+++ b/src/Phyxo/Update/Updates.php
@@ -74,7 +74,7 @@ public function getAllVersions()
return false;
}
} catch (Exception $e) {
- throw new Exception($e->getMessage());
+ throw new Exception($e->getMessage(), $e->getCode(), $e);
}
}
@@ -121,7 +121,7 @@ public function download($zip_file)
file_put_contents($zip_file, $response->getContent());
}
} catch (Exception $e) {
- throw new Exception($e->getMessage());
+ throw new Exception($e->getMessage(), $e->getCode(), $e);
}
}
@@ -145,7 +145,7 @@ public function upgrade($zip_file)
continue;
}
}
- if (count($not_writable) > 0) {
+ if ($not_writable !== []) {
$message = 'Some files or directories are not writable';
$message .= '' . implode("\n", $not_writable) . '
';
throw new Exception($message);
@@ -193,10 +193,10 @@ public function getServerExtensions()
}
}
} catch (Exception $e) {
- throw new Exception($e->getMessage());
+ throw new Exception($e->getMessage(), $e->getCode(), $e);
}
- if (empty($versions_to_check)) {
+ if ($versions_to_check === []) {
return false;
}
@@ -222,7 +222,7 @@ public function getServerExtensions()
$url .= '?' . http_build_query($get_data, '', '&');
$post_data = [];
- if (!empty($ext_to_check)) {
+ if ($ext_to_check !== []) {
$post_data['extension_include'] = implode(',', array_keys($ext_to_check));
}
@@ -256,7 +256,7 @@ public function getServerExtensions()
$this->checkMissingExtensions($ext_to_check);
return [];
} catch (Exception $e) {
- throw new Exception($e->getMessage());
+ throw new Exception($e->getMessage(), $e->getCode(), $e);
}
}
@@ -270,7 +270,7 @@ public function checkCoreUpgrade()
$all_versions = json_decode($response->getContent(), true, 512, JSON_THROW_ON_ERROR);
}
} catch (Exception $e) {
- throw new Exception($e->getMessage());
+ throw new Exception($e->getMessage(), $e->getCode(), $e);
}
if (!empty($all_versions)) {
$new_version = trim((string) $all_versions[0]['version']);
@@ -322,6 +322,7 @@ public function checkUpdatedExtensions(array $updates_ignored = [])
}
}
}
+ return null;
}
protected function checkMissingExtensions($missing)
@@ -329,8 +330,7 @@ protected function checkMissingExtensions($missing)
foreach ($missing as $id => $type) {
$default = 'default_' . $type;
foreach ($this->getType($type)->getFsExtensions() as $ext_id => $ext) {
- if (isset($ext['extension']) and $id == $ext['extension']
- and !in_array($ext_id, $this->$default)) {
+ if (isset($ext['extension']) && $id == $ext['extension'] && !in_array($ext_id, $this->$default)) {
$this->missing[$type][] = $ext;
break;
}
diff --git a/src/Phyxo/Upgrade.php b/src/Phyxo/Upgrade.php
index 0e0727632..e06b9fe77 100644
--- a/src/Phyxo/Upgrade.php
+++ b/src/Phyxo/Upgrade.php
@@ -21,7 +21,7 @@ public static function getAvailableUpgradeIds(string $root_dir): array
if ($contents = opendir($upgrades_path)) {
while (($node = readdir($contents)) !== false) {
- if (is_file($upgrades_path . '/' . $node) and preg_match('/^(.*?)-database\.php$/', $node, $match)) {
+ if (is_file($upgrades_path . '/' . $node) && preg_match('/^(.*?)-database\.php$/', $node, $match)) {
$available_upgrade_ids[] = $match[1];
}
}
diff --git a/src/Phyxo/Ws/Server.php b/src/Phyxo/Ws/Server.php
index ec0aff505..2d4f4aba9 100644
--- a/src/Phyxo/Ws/Server.php
+++ b/src/Phyxo/Ws/Server.php
@@ -315,16 +315,13 @@ public function run(Request $request)
if ($request->getContentTypeFormat() === 'json') {
$request_params = json_decode($request->getContent(), true);
-
if (json_last_error() !== JSON_ERROR_NONE) {
throw new BadRequestHttpException('invalid json body: ' . json_last_error_msg());
}
+ } elseif ($request->isMethod('POST')) {
+ $request_params = $request->request->all();
} else {
- if ($request->isMethod('POST')) {
- $request_params = $request->request->all();
- } else {
- $request_params = $request->query->all();
- }
+ $request_params = $request->query->all();
}
foreach ($request_params as $name => $value) {
@@ -370,10 +367,6 @@ public function run(Request $request)
*/
public function addMethod(string $methodName, $callback, array $params = [], string $description = '', array $options = [])
{
- if (!is_array($params)) {
- $params = [];
- }
-
if (range(0, count($params) - 1) === array_keys($params)) {
$params = array_flip($params);
}
@@ -433,9 +426,9 @@ public static function isPost()
//Receive the RAW post data.
$content = trim(file_get_contents("php://input"));
- return !empty($content);
+ return $content !== '' && $content !== '0';
} else {
- return !empty($_POST);
+ return $_POST !== [];
}
}
@@ -443,10 +436,8 @@ public static function makeArrayParam(&$param)
{
if ($param == null) {
$param = [];
- } else {
- if (!is_array($param)) {
- $param = [$param];
- }
+ } elseif (!is_array($param)) {
+ $param = [$param];
}
}
@@ -479,8 +470,7 @@ public static function checkType(&$param, $type, $name)
unset($value);
} elseif (self::hasFlag($type, self::WS_TYPE_FLOAT)) {
foreach ($param as &$value) {
- if (($value = filter_var($value, FILTER_VALIDATE_FLOAT)) === false
- or (isset($opts['options']['min_range']) and $value < $opts['options']['min_range'])) {
+ if ($value = filter_var($value, FILTER_VALIDATE_FLOAT) === false || isset($opts['options']['min_range']) && $value < $opts['options']['min_range']) {
return new Error(self::WS_ERR_INVALID_PARAM, $name . ' must only contain' . $msg . ' floats');
}
}
@@ -496,8 +486,7 @@ public static function checkType(&$param, $type, $name)
return new Error(self::WS_ERR_INVALID_PARAM, $name . ' must be an' . $msg . ' integer');
}
} elseif (self::hasFlag($type, self::WS_TYPE_FLOAT)) {
- if (($param = filter_var($param, FILTER_VALIDATE_FLOAT)) === false
- or (isset($opts['options']['min_range']) and $param < $opts['options']['min_range'])) {
+ if ($param = filter_var($param, FILTER_VALIDATE_FLOAT) === false || isset($opts['options']['min_range']) && $param < $opts['options']['min_range']) {
return new Error(self::WS_ERR_INVALID_PARAM, $name . ' must be a' . $msg . ' float');
}
}
@@ -548,11 +537,11 @@ public function invoke(string $methodName, array $params)
self::makeArrayParam($params[$name]);
}
}
- } elseif ($params[$name] === '' and !self::hasFlag($flags, self::WS_PARAM_OPTIONAL)) { // parameter provided but empty
+ } elseif ($params[$name] === '' && !self::hasFlag($flags, self::WS_PARAM_OPTIONAL)) { // parameter provided but empty
$missing_params[] = $name;
} else { // parameter provided - do some basic checks
$the_param = $params[$name];
- if (is_array($the_param) and !self::hasFlag($flags, self::WS_PARAM_ACCEPT_ARRAY)) {
+ if (is_array($the_param) && !self::hasFlag($flags, self::WS_PARAM_ACCEPT_ARRAY)) {
return new Error(self::WS_ERR_INVALID_PARAM, $name . ' must be scalar');
}
@@ -560,13 +549,11 @@ public function invoke(string $methodName, array $params)
self::makeArrayParam($the_param);
}
- if ($options['type'] > 0) {
- if (($ret = self::checkType($the_param, $options['type'], $name)) !== null) {
- return $ret;
- }
+ if ($options['type'] > 0 && $ret = self::checkType($the_param, $options['type'], $name) !== null) {
+ return $ret;
}
- if (isset($options['maxValue']) and $the_param > $options['maxValue']) {
+ if (isset($options['maxValue']) && $the_param > $options['maxValue']) {
$the_param = $options['maxValue'];
}
@@ -574,7 +561,7 @@ public function invoke(string $methodName, array $params)
}
}
- if (count($missing_params)) {
+ if ($missing_params !== []) {
return new Error(self::WS_ERR_MISSING_PARAM, 'Missing parameters: ' . implode(',', $missing_params));
}
diff --git a/src/Repository/AlbumRepository.php b/src/Repository/AlbumRepository.php
index fc84b8d2a..de0aa4b1b 100644
--- a/src/Repository/AlbumRepository.php
+++ b/src/Repository/AlbumRepository.php
@@ -181,7 +181,7 @@ public function findAlbumsForImage(int $image_id)
/**
* @param int[] $forbidden_albums
*/
- public function getQueryBuilderForFindAllowedAlbums(array $forbidden_albums = [], QueryBuilder $qb = null): QueryBuilder
+ public function getQueryBuilderForFindAllowedAlbums(array $forbidden_albums = [], ? QueryBuilder $qb = null): QueryBuilder
{
$method = 'andWhere';
@@ -190,7 +190,7 @@ public function getQueryBuilderForFindAllowedAlbums(array $forbidden_albums = []
$method = 'where';
}
- if (count($forbidden_albums) > 0) {
+ if ($forbidden_albums !== []) {
$qb->$method($qb->expr()->notIn('a.id', $forbidden_albums));
}
@@ -239,7 +239,7 @@ public function findUnauthorized(array $album_ids = [])
$qb->where('a.status = :status');
$qb->setParameter('status', Album::STATUS_PRIVATE);
- if (count($album_ids) > 0) {
+ if ($album_ids !== []) {
$qb->andWhere($qb->expr()->notIn('a.id', $album_ids));
}
@@ -321,7 +321,7 @@ public function findPrivateWithUserAccessAndNotExclude(int $user_id, array $excl
$qb->andWhere('a.status = :status');
$qb->setParameter('status', Album::STATUS_PRIVATE);
- if (count($exclude_album_ids) > 0) {
+ if ($exclude_album_ids !== []) {
$qb->andWhere($qb->expr()->notIn('a.id', $exclude_album_ids));
}
@@ -582,7 +582,7 @@ public function findWrongRepresentant(array $album_ids = [])
$qb->leftJoin('a.imageAlbums', 'ia');
$qb->leftJoin('ia.image', 'i', Join::WITH, 'a.representative_picture_id = i.id');
$qb->where($qb->expr()->isNotNull('a.representative_picture_id'));
- if (count($album_ids) > 0) {
+ if ($album_ids !== []) {
$qb->andWhere($qb->expr()->in('a.id', $album_ids));
}
$qb->andWhere($qb->expr()->isNotNull('i.id'));
@@ -606,7 +606,7 @@ public function findNeedeedRandomRepresentant(array $album_ids = [])
$qb->select('DISTINCT(a.id)');
$qb->leftJoin('a.imageAlbums', 'ia');
$qb->where($qb->expr()->isNull('a.representative_picture_id'));
- if (count($album_ids) > 0) {
+ if ($album_ids !== []) {
$qb->andWhere($qb->expr()->in('a.id', $album_ids));
}
$qb->andWhere($qb->expr()->isNotNull('ia.image'));
diff --git a/src/Repository/CaddieRepository.php b/src/Repository/CaddieRepository.php
index 5100ff494..a1140fbdb 100644
--- a/src/Repository/CaddieRepository.php
+++ b/src/Repository/CaddieRepository.php
@@ -44,7 +44,7 @@ public function emptyCaddies(int $user_id): void
/**
* @param int[] $image_ids
*/
- public function deleteElements(array $image_ids, int $user_id = null): void
+ public function deleteElements(array $image_ids, ?int $user_id = null): void
{
$qb = $this->createQueryBuilder('c');
$qb->delete();
diff --git a/src/Repository/CommentRepository.php b/src/Repository/CommentRepository.php
index d91bc5576..2940e4d56 100644
--- a/src/Repository/CommentRepository.php
+++ b/src/Repository/CommentRepository.php
@@ -267,7 +267,7 @@ public function getCommentsOnImage(int $image_id, string $order, int $limit, int
*
* @return Comment[]|int
*/
- public function getNewComments(array $forbidden_albums = [], DateTimeInterface $start = null, DateTimeInterface $end = null, bool $count_only = false): array|int
+ public function getNewComments(array $forbidden_albums = [], ?DateTimeInterface $start = null, ?DateTimeInterface $end = null, bool $count_only = false): array|int
{
$qb = $this->createQueryBuilder('c');
@@ -278,7 +278,7 @@ public function getNewComments(array $forbidden_albums = [], DateTimeInterface $
$qb->leftJoin('c.image', 'i');
$qb->leftJoin('i.imageAlbums', 'ia');
- if (count($forbidden_albums)) {
+ if ($forbidden_albums !== []) {
$qb->where($qb->expr()->notIn('ia.album', $forbidden_albums));
}
@@ -302,7 +302,7 @@ public function getNewComments(array $forbidden_albums = [], DateTimeInterface $
/**
* @return Comment[]|int
*/
- public function getUnvalidatedComments(bool $count_only, DateTimeInterface $start = null, DateTimeInterface $end = null): array|int
+ public function getUnvalidatedComments(bool $count_only, ?DateTimeInterface $start = null, ?DateTimeInterface $end = null): array|int
{
$qb = $this->createQueryBuilder('c');
@@ -340,7 +340,7 @@ public function countAvailableComments(array $forbidden_albums = [], bool $isAdm
$qb->leftJoin('c.image', 'i');
$qb->leftJoin('i.imageAlbums', 'ia');
- if (count($forbidden_albums) > 0) {
+ if ($forbidden_albums !== []) {
$qb->where($qb->expr()->notIn('ia.album', $forbidden_albums));
}
diff --git a/src/Repository/FavoriteRepository.php b/src/Repository/FavoriteRepository.php
index 899e8f17f..685c55ade 100644
--- a/src/Repository/FavoriteRepository.php
+++ b/src/Repository/FavoriteRepository.php
@@ -42,7 +42,7 @@ public function findUserFavorites(int $user_id, array $forbidden_albums = [])
$qb->where('f.user = :user_id');
$qb->setParameter('user_id', $user_id);
- if (count($forbidden_albums) > 0) {
+ if ($forbidden_albums !== []) {
$qb->leftJoin('f.image', 'i');
$qb->leftJoin('i.imageAlbums', 'ia');
$qb->andWhere($qb->expr()->notIn('ia.album', $forbidden_albums));
diff --git a/src/Repository/GroupRepository.php b/src/Repository/GroupRepository.php
index decc960d9..0f0fb58be 100644
--- a/src/Repository/GroupRepository.php
+++ b/src/Repository/GroupRepository.php
@@ -115,7 +115,7 @@ public function findByNameOrGroupIds(?string $name = null, array $group_ids = []
$qb->setParameter('name', $name);
}
- if (count($group_ids) > 0) {
+ if ($group_ids !== []) {
$qb->andWhere($qb->expr()->in('g.id', $group_ids));
}
@@ -145,7 +145,7 @@ public function findWithAlbumsAccess(array $album_ids = [])
$qb = $this->createQueryBuilder('g');
$qb->leftJoin('g.group_access', 'ga');
- if (count($album_ids) > 0) {
+ if ($album_ids !== []) {
$qb->where($qb->expr()->in('ga.cat_id', $album_ids));
}
diff --git a/src/Repository/HistoryRepository.php b/src/Repository/HistoryRepository.php
index 3c0a58705..b67718518 100644
--- a/src/Repository/HistoryRepository.php
+++ b/src/Repository/HistoryRepository.php
@@ -11,6 +11,8 @@
namespace App\Repository;
+use DateTime;
+use App\Entity\User;
use App\Entity\History;
use App\Form\Model\SearchRulesModel;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
@@ -43,12 +45,12 @@ public function getHistory(SearchRulesModel $rules, array $types, int $limit, in
{
$qb = $this->createQueryBuilder('h');
- if ($rules->getStart()) {
+ if ($rules->getStart() instanceof DateTime) {
$qb->where('h.date >= :start');
$qb->setParameter('start', $rules->getStart());
}
- if ($rules->getEnd()) {
+ if ($rules->getEnd() instanceof DateTime) {
$qb->andWhere('h.date <= :end');
$qb->setParameter('end', $rules->getEnd());
}
@@ -65,12 +67,12 @@ public function getHistory(SearchRulesModel $rules, array $types, int $limit, in
}
}
}
- if (count($orXExpressions) > 0) {
+ if ($orXExpressions !== []) {
$qb->andWhere($qb->expr()->orX(...$orXExpressions));
}
}
- if ($rules->getUser()) {
+ if ($rules->getUser() instanceof User) {
$qb->andWhere('h.user = :user');
$qb->setParameter('user', $rules->getUser());
}
@@ -80,7 +82,7 @@ public function getHistory(SearchRulesModel $rules, array $types, int $limit, in
$qb->setParameter('image_id', $rules->getImageId());
}
- if (count($rules->getImageIds()) > 0) {
+ if ($rules->getImageIds() !== []) {
$qb->andWhere($qb->expr()->in('h.image', $rules->getImageIds()));
}
diff --git a/src/Repository/ImageAlbumRepository.php b/src/Repository/ImageAlbumRepository.php
index e9f4b6e95..ad6045b00 100644
--- a/src/Repository/ImageAlbumRepository.php
+++ b/src/Repository/ImageAlbumRepository.php
@@ -41,11 +41,11 @@ public function countTotalImages(string $access_type, array $forbidden_albums =
$qb = $this->createQueryBuilder('ia');
$qb->select('count(distinct(ia.image))');
- if (count($forbidden_albums) > 0) {
+ if ($forbidden_albums !== []) {
$qb->where($qb->expr()->notIn('ia.album', $forbidden_albums));
}
- if (count($image_ids) > 0) {
+ if ($image_ids !== []) {
if ($access_type === 'NOT IN') {
$qb->andWhere($qb->expr()->notIn('ia.image', $image_ids));
} else {
@@ -190,18 +190,18 @@ public function updateRankForImage(int $rank, int $image_id, int $album_id): voi
*/
public function deleteByAlbum(array $ids = [], array $image_ids = []): void
{
- if (count($ids) === 0 && count($image_ids) === 0) {
+ if ($ids === [] && $image_ids === []) {
return;
}
$qb = $this->createQueryBuilder('ia');
$qb->delete();
- if (count($ids) > 0) {
+ if ($ids !== []) {
$qb->where($qb->expr()->in('ia.album', $ids));
}
- if (count($image_ids) > 0) {
+ if ($image_ids !== []) {
$qb->andWhere($qb->expr()->in('ia.image', $image_ids));
}
@@ -216,7 +216,7 @@ public function deleteByImages(array $ids = []): void
$qb = $this->createQueryBuilder('ia');
$qb->delete();
- if (count($ids) > 0) {
+ if ($ids !== []) {
$qb->where($qb->expr()->in('ia.image', $ids));
}
@@ -243,7 +243,7 @@ public function getRelatedAlbum(int $image_id, array $forbidden_albums = [])
$qb->where('ia.image = :image_id');
$qb->setParameter('image_id', $image_id);
- if (count($forbidden_albums) > 0) {
+ if ($forbidden_albums !== []) {
$qb->andWhere($qb->expr()->notIn('ia.album', $forbidden_albums));
}
diff --git a/src/Repository/ImageRepository.php b/src/Repository/ImageRepository.php
index d49c66bd0..92cb703b0 100644
--- a/src/Repository/ImageRepository.php
+++ b/src/Repository/ImageRepository.php
@@ -100,7 +100,7 @@ public function findWithNoStorageOrStorageForAlbums(array $album_ids = [])
$qb = $this->createQueryBuilder('i');
$qb->where($qb->expr()->isNull('i.storage_category_id'));
- if (count($album_ids) > 0) {
+ if ($album_ids !== []) {
$qb->orWhere($qb->expr()->notIn('i.storage_category_id', $album_ids));
}
@@ -121,7 +121,7 @@ public function getForbiddenImages(array $forbidden_albums = [], int $level = 0)
$qb->where('i.level > :level');
$qb->setParameter('level', $level);
- if (count($forbidden_albums) > 0) {
+ if ($forbidden_albums !== []) {
$qb->andWhere($qb->expr()->notIn('ia.album', $forbidden_albums));
}
@@ -140,7 +140,7 @@ public function findMostVisited(array $forbidden_albums = [], array $sorts = [],
$qb->leftJoin('i.imageAlbums', 'ia');
$qb->where('i.hit > 0');
- if (count($forbidden_albums) > 0) {
+ if ($forbidden_albums !== []) {
$qb->andWhere($qb->expr()->notIn('ia.album', $forbidden_albums));
}
@@ -169,7 +169,7 @@ public function findRecentImages(DateTimeInterface $recent_date, array $forbidde
$qb->where('i.date_available >= :recent_date');
$qb->setParameter('recent_date', $recent_date);
- if (count($forbidden_albums) > 0) {
+ if ($forbidden_albums !== []) {
$qb->andWhere($qb->expr()->notIn('ia.album', $forbidden_albums));
}
@@ -204,7 +204,7 @@ public function findBestRated(int $limit, array $forbidden_albums = [], array $s
$qb->leftJoin('i.imageAlbums', 'ia');
$qb->where($qb->expr()->isNotNull('i.rating_score'));
- if (count($forbidden_albums) > 0) {
+ if ($forbidden_albums !== []) {
$qb->andWhere($qb->expr()->notIn('ia.album', $forbidden_albums));
}
@@ -227,7 +227,7 @@ public function findRandomImages(int $max, array $forbidden_albums = [])
$qb = $this->createQueryBuilder('i');
$qb->leftJoin('i.imageAlbums', 'ia');
- if (count($forbidden_albums) > 0) {
+ if ($forbidden_albums !== []) {
$qb->andWhere($qb->expr()->notIn('ia.album', $forbidden_albums));
}
@@ -268,7 +268,7 @@ public function getRandomImageInAlbum(int $album_id, string $uppercats = '', arr
$qb->setParameter('uppercats', $uppercats . ',%');
}
- if (count($forbidden_albums) > 0) {
+ if ($forbidden_albums !== []) {
$qb->andWhere($qb->expr()->notIn('a.id', $forbidden_albums));
}
$nb_images = $qb->getQuery()->getSingleScalarResult();
@@ -285,7 +285,7 @@ public function getRandomImageInAlbum(int $album_id, string $uppercats = '', arr
$qb->setParameter('uppercats', $uppercats . ',%');
}
- if (count($forbidden_albums) > 0) {
+ if ($forbidden_albums !== []) {
$qb->andWhere($qb->expr()->notIn('a.id', $forbidden_albums));
}
$qb->setFirstResult(random_int(0, $nb_images - 1));
@@ -309,7 +309,7 @@ public function getList(array $ids, array $forbidden_albums = [])
$qb->leftJoin('i.imageAlbums', 'ia');
$qb->where($qb->expr()->in('i.id', $ids));
- if (count($forbidden_albums) > 0) {
+ if ($forbidden_albums !== []) {
$qb->andWhere($qb->expr()->notIn('ia.album', $forbidden_albums));
}
@@ -321,7 +321,7 @@ public function getList(array $ids, array $forbidden_albums = [])
*
* @return Image[]|int
*/
- public function getNewElements(array $forbidden_albums = [], DateTimeInterface $start = null, DateTimeInterface $end = null, bool $count_only = false): array|int
+ public function getNewElements(array $forbidden_albums = [], ?DateTimeInterface $start = null, ?DateTimeInterface $end = null, bool $count_only = false): array|int
{
$qb = $this->createQueryBuilder('i');
if ($count_only) {
@@ -339,7 +339,7 @@ public function getNewElements(array $forbidden_albums = [], DateTimeInterface $
$qb->setParameter('end', $end);
}
- if (count($forbidden_albums) > 0) {
+ if ($forbidden_albums !== []) {
$qb->andWhere($qb->expr()->notIn('ia.album', $forbidden_albums));
}
@@ -355,7 +355,7 @@ public function getNewElements(array $forbidden_albums = [], DateTimeInterface $
*
* @return Album[]|int
*/
- public function getUpdatedAlbums(array $forbidden_albums = [], DateTimeInterface $start = null, DateTimeInterface $end = null, bool $count_only = false): array|int
+ public function getUpdatedAlbums(array $forbidden_albums = [], ?DateTimeInterface $start = null, ?DateTimeInterface $end = null, bool $count_only = false): array|int
{
return $this->getNewElements($forbidden_albums, $start, $end, $count_only);
}
@@ -365,7 +365,7 @@ public function getUpdatedAlbums(array $forbidden_albums = [], DateTimeInterface
*
* @return array
*/
- public function getRecentImages(int $limit, DateTimeInterface $date_available = null, array $forbidden_albums = [])
+ public function getRecentImages(int $limit, ?DateTimeInterface $date_available = null, array $forbidden_albums = [])
{
$qb = $this->createQueryBuilder('i');
$qb->select('DISTINCT(a.uppercats) AS upp, COUNT(i.id) AS img_count');
@@ -374,7 +374,7 @@ public function getRecentImages(int $limit, DateTimeInterface $date_available =
$qb->where('i.date_available = :date_avaiable');
$qb->setParameter('date_avaiable', $date_available);
- if (count($forbidden_albums) > 0) {
+ if ($forbidden_albums !== []) {
$qb->andWhere($qb->expr()->notIn('ia.album', $forbidden_albums));
}
@@ -401,7 +401,7 @@ public function getRecentPostedImages(int $limit, array $forbidden_albums = [])
$qb->select('i.date_available, COUNT(DISTINCT(i.id)) AS nb_elements');
$qb->leftJoin('i.imageAlbums', 'ia');
- if (count($forbidden_albums) > 0) {
+ if ($forbidden_albums !== []) {
$qb->andWhere($qb->expr()->notIn('ia.album', $forbidden_albums));
}
@@ -429,7 +429,7 @@ public function searchDistinctId(array $forbidden_albums = [], array $order_by =
// $qb->select('DISTINCT(i.id) AS id');
$qb->leftJoin('i.imageAlbums', 'ia');
- if (count($forbidden_albums) > 0) {
+ if ($forbidden_albums !== []) {
$qb->andWhere($qb->expr()->notIn('ia.album', $forbidden_albums));
}
@@ -457,7 +457,7 @@ public function searchDistinctIdInAlbum(int $album_id, array $forbidden_albums =
$qb->where('ia.album = :album_id');
$qb->setParameter('album_id', $album_id);
- if (count($forbidden_albums) > 0) {
+ if ($forbidden_albums !== []) {
$qb->andWhere($qb->expr()->notIn('ia.album', $forbidden_albums));
}
@@ -493,12 +493,12 @@ public function countImagesByYear(string $date_type = 'posted', array $forbidden
$andXExpression = [];
- if (count($forbidden_albums) > 0) {
+ if ($forbidden_albums !== []) {
$andXExpression[] = $qb->expr()->notIn('ia.album', ':ids');
$qb->setParameter('ids', $forbidden_albums);
}
- if (count($andXExpression) > 0) {
+ if ($andXExpression !== []) {
$qb->having($qb->expr()->andX(...$andXExpression));
}
@@ -515,7 +515,7 @@ public function countImagesByYear(string $date_type = 'posted', array $forbidden
*/
public function findOneImagePerYear(array $years = [], string $date_type = 'posted', array $forbidden_albums = [])
{
- if (count($years) === 0) {
+ if ($years === []) {
return [];
}
@@ -523,14 +523,14 @@ public function findOneImagePerYear(array $years = [], string $date_type = 'post
$fmt .= ' LEFT JOIN phyxo_image_category ic ON i.id = ic.image_id';
$fmt .= ' WHERE';
- if (count($forbidden_albums) > 0) {
+ if ($forbidden_albums !== []) {
$fmt .= ' ic.category_id NOT IN(%s) AND';
}
$fmt .= ' EXTRACT(YEAR FROM %s) = ?';
$fmt .= ' LIMIT 1)';
- if (count($forbidden_albums) > 0) {
+ if ($forbidden_albums !== []) {
$sql_select = sprintf($fmt, implode(', ', $forbidden_albums), $this->getFieldFromDateType($date_type));
} else {
/** @phpstan-ignore-next-line */
@@ -566,7 +566,7 @@ public function countImagesByMonth(int $year, string $date_type = 'posted', arra
$qb->groupBy('month');
$qb->orderBy('month', 'ASC');
- if (count($forbidden_albums) > 0) {
+ if ($forbidden_albums !== []) {
$qb->andWhere($qb->expr()->notIn('ia.album', $forbidden_albums));
}
@@ -581,7 +581,7 @@ public function countImagesByMonth(int $year, string $date_type = 'posted', arra
*/
public function findOneImagePerMonth(int $year, array $months = [], string $date_type = 'posted', array $forbidden_albums = [])
{
- if (count($months) === 0) {
+ if ($months === []) {
return [];
}
@@ -589,7 +589,7 @@ public function findOneImagePerMonth(int $year, array $months = [], string $date
$fmt .= ' LEFT JOIN phyxo_image_category ic ON i.id = ic.image_id';
$fmt .= ' WHERE';
- if (count($forbidden_albums) > 0) {
+ if ($forbidden_albums !== []) {
$fmt .= ' ic.category_id NOT IN(%s) AND';
}
@@ -597,7 +597,7 @@ public function findOneImagePerMonth(int $year, array $months = [], string $date
$fmt .= ' AND EXTRACT(YEAR FROM %s) = :year';
$fmt .= ' LIMIT 1)';
- if (count($forbidden_albums) > 0) {
+ if ($forbidden_albums !== []) {
$sql_select = sprintf($fmt, implode(', ', $forbidden_albums), $this->getFieldFromDateType($date_type), $this->getFieldFromDateType($date_type));
} else {
/** @phpstan-ignore-next-line */
@@ -636,7 +636,7 @@ public function countImagesByDay(int $year, int $month, string $date_type = 'pos
$qb->setParameter('month', $month);
$qb->orderBy('day', 'ASC');
- if (count($forbidden_albums) > 0) {
+ if ($forbidden_albums !== []) {
$qb->andWhere($qb->expr()->notIn('ia.album', $forbidden_albums));
}
@@ -651,7 +651,7 @@ public function countImagesByDay(int $year, int $month, string $date_type = 'pos
*/
public function findOneImagePerDay(int $year, int $month, array $days = [], string $date_type = 'posted', array $forbidden_albums = [])
{
- if (count($days) === 0) {
+ if ($days === []) {
return [];
}
@@ -659,7 +659,7 @@ public function findOneImagePerDay(int $year, int $month, array $days = [], stri
$fmt .= ' LEFT JOIN phyxo_image_category ic ON i.id = ic.image_id';
$fmt .= ' WHERE';
- if (count($forbidden_albums) > 0) {
+ if ($forbidden_albums !== []) {
$fmt .= ' ic.category_id NOT IN(%s) AND';
}
@@ -668,7 +668,7 @@ public function findOneImagePerDay(int $year, int $month, array $days = [], stri
$fmt .= ' AND EXTRACT(YEAR FROM %s) = :year';
$fmt .= ' LIMIT 1)';
- if (count($forbidden_albums) > 0) {
+ if ($forbidden_albums !== []) {
$sql_select = sprintf(
$fmt,
implode(', ', $forbidden_albums),
@@ -708,7 +708,7 @@ public function findImagesPerDate(DateTimeInterface $date, string $date_type = '
$qb->leftJoin('i.imageAlbums', 'ia');
$qb->where('DATE(i.' . $this->getFieldFromDateType($date_type) . ') = :date');
$qb->setParameter('date', $date);
- if (count($forbidden_albums) > 0) {
+ if ($forbidden_albums !== []) {
$qb->andWhere($qb->expr()->notIn('ia.album', $forbidden_albums));
}
@@ -991,7 +991,7 @@ public function findGroupByAuthor(array $forbidden_albums = [])
$qb = $this->createQueryBuilder('i');
$qb->leftJoin('i.imageAlbums', 'ia');
- if (count($forbidden_albums) > 0) {
+ if ($forbidden_albums !== []) {
$qb->where($qb->expr()->notIn('ia.album', $forbidden_albums));
}
$qb->andWhere($qb->expr()->isNotNull('i.author'));
@@ -1028,7 +1028,7 @@ public function qSearchImages(string $words, array $forbidden_albums = [])
$search_value = '%' . str_replace(' ', '%', trim(strtolower($words))) . '%';
$qb = $this->createQueryBuilder('i');
- if (count($forbidden_albums) > 0) {
+ if ($forbidden_albums !== []) {
$qb->leftJoin('i.imageAlbums', 'ia');
$qb->where($qb->expr()->notIn('ia.album', $forbidden_albums));
}
@@ -1054,7 +1054,7 @@ public function searchImages(array $rules, array $forbidden_albums = [])
$whereMethod = $rules['mode'] == 'AND' ? 'andWhere' : 'orWhere';
$qb = $this->createQueryBuilder('i');
- if (count($forbidden_albums) > 0 || isset($rules['fields']['cat'])) {
+ if ($forbidden_albums !== [] || isset($rules['fields']['cat'])) {
$qb->leftJoin('i.imageAlbums', 'ia');
}
@@ -1072,7 +1072,7 @@ public function searchImages(array $rules, array $forbidden_albums = [])
}
}
}
- if (count($clauses) > 0) {
+ if ($clauses !== []) {
$qb->$whereMethod(...$clauses);
}
@@ -1099,7 +1099,7 @@ public function searchImages(array $rules, array $forbidden_albums = [])
$qb->$whereMethod(...$clauses);
}
- if (count($forbidden_albums) > 0) {
+ if ($forbidden_albums !== []) {
$qb->andWhere($qb->expr()->notIn('ia.album', $forbidden_albums));
}
@@ -1151,7 +1151,7 @@ public function isAuthorizedToUser(int $image_id, array $forbidden_albums = []):
$qb->where('i.id = :image_id');
$qb->setParameter('image_id', $image_id);
- if (count($forbidden_albums) > 0) {
+ if ($forbidden_albums !== []) {
$qb->andWhere($qb->expr()->notIn('ia.album', $forbidden_albums));
}
@@ -1166,7 +1166,7 @@ public function isAuthorizedToUser(int $image_id, array $forbidden_albums = []):
*/
public function getImageIdsForTags(array $forbidden_albums = [], array $tag_ids = [], string $mode = 'AND')
{
- if (empty($tag_ids)) {
+ if ($tag_ids === []) {
return [];
}
@@ -1174,7 +1174,7 @@ public function getImageIdsForTags(array $forbidden_albums = [], array $tag_ids
$qb->leftJoin('i.imageTags', 'it');
$qb->where($qb->expr()->in('it.tag', $tag_ids));
- if (count($forbidden_albums) > 0) {
+ if ($forbidden_albums !== []) {
$qb->leftJoin('i.imageAlbums', 'ia');
$qb->andWhere($qb->expr()->notIn('ia.album', $forbidden_albums));
}
diff --git a/src/Repository/ImageTagRepository.php b/src/Repository/ImageTagRepository.php
index 94dd95dc1..722163135 100644
--- a/src/Repository/ImageTagRepository.php
+++ b/src/Repository/ImageTagRepository.php
@@ -82,7 +82,7 @@ public function getAvailableTags(int $user_id, array $forbidden_albums = [], boo
$this->addValidatedCondition($qb, $user_id, $show_pending_added_tags, $show_pending_deleted_tags);
- if (count($forbidden_albums) > 0) {
+ if ($forbidden_albums !== []) {
$qb->leftJoin('it.image', 'i');
$qb->leftJoin('i.imageAlbums', 'ia');
$qb->andWhere($qb->expr()->notIn('ia.album', $forbidden_albums));
diff --git a/src/Repository/RateRepository.php b/src/Repository/RateRepository.php
index 16d548983..be30bb1d8 100644
--- a/src/Repository/RateRepository.php
+++ b/src/Repository/RateRepository.php
@@ -46,7 +46,7 @@ public function calculateRateSummary(int $image_id)
return $qb->getQuery()->getOneOrNullResult(AbstractQuery::HYDRATE_SCALAR);
}
- public function countImagesRatedForUser(int $user_id, string $operator = null) : int
+ public function countImagesRatedForUser(int $user_id, ?string $operator = null) : int
{
$qb = $this->createQueryBuilder('r');
$qb->select('COUNT(DISTINCT(r.image))');
@@ -59,7 +59,7 @@ public function countImagesRatedForUser(int $user_id, string $operator = null) :
return $qb->getQuery()->getSingleScalarResult();
}
- public function getRatePerImage(int $user_id, string $order, int $limit, string $operator = null, int $offset = 0)
+ public function getRatePerImage(int $user_id, string $order, int $limit, ?string $operator = null, int $offset = 0)
{
$qb = $this->createQueryBuilder('r');
$qb->leftJoin('r.image', 'i');
diff --git a/src/Repository/TagRepository.php b/src/Repository/TagRepository.php
index 58f25f727..a4c531f96 100644
--- a/src/Repository/TagRepository.php
+++ b/src/Repository/TagRepository.php
@@ -42,7 +42,7 @@ public function addOrUpdateTag(Tag $tag): int
public function searchAll(string $q = '')
{
$qb = $this->createQueryBuilder('t');
- if (!empty($q)) {
+ if ($q !== '' && $q !== '0') {
$qb->where($qb->expr()->like("lower('t.name')", ':q'));
$qb->setParameter('q', '%' . strtolower($q) . '%');
}
@@ -72,15 +72,15 @@ public function findByIdsOrNamesOrUrlNames(array $ids = [], array $names = [], a
{
$qb = $this->createQueryBuilder('t');
- if (count($ids) > 0) {
+ if ($ids !== []) {
$qb->where($qb->expr()->in('t.id', $ids));
}
- if (count($names) > 0) {
+ if ($names !== []) {
$qb->orWhere($qb->expr()->in('t.name', $names));
}
- if (count($url_names) > 0) {
+ if ($url_names !== []) {
$qb->orWhere($qb->expr()->in('t.url_name', $url_names));
}
@@ -99,13 +99,13 @@ public function getCommonTags(int $user_id, array $items, int $max_tags, array $
$qb->leftJoin('t.imageTags', 'it');
$qb->addSelect('COUNT(1) AS counter');
- if (count($items) > 0) {
+ if ($items !== []) {
$qb->where($qb->expr()->in('it.image', $items));
}
$this->addValidatedCondition($qb, $user_id);
- if (count($excluded_tag_ids) > 0) {
+ if ($excluded_tag_ids !== []) {
$qb->andWhere($qb->expr()->notIn('t.id', $excluded_tag_ids));
}
diff --git a/src/Repository/UserCacheAlbumRepository.php b/src/Repository/UserCacheAlbumRepository.php
index e4ad98263..a3c5a1eac 100644
--- a/src/Repository/UserCacheAlbumRepository.php
+++ b/src/Repository/UserCacheAlbumRepository.php
@@ -57,7 +57,7 @@ public function deleteForAlbums(array $album_ids): void
$qb = $this->createQueryBuilder('ucc');
$qb->delete();
- if (count($album_ids) > 0) {
+ if ($album_ids !== []) {
$qb->where($qb->expr()->in('ucc.album', $album_ids));
}
diff --git a/src/Repository/UserInfosRepository.php b/src/Repository/UserInfosRepository.php
index f1984ddcb..546e8df75 100644
--- a/src/Repository/UserInfosRepository.php
+++ b/src/Repository/UserInfosRepository.php
@@ -58,7 +58,7 @@ public function updateFieldsForUsers(array $fields, array $user_ids = []): void
$qb->set('u.' . $field, ':' . $field);
$qb->setParameter($field, $value);
}
- if (count($user_ids) > 0) {
+ if ($user_ids !== []) {
$qb->where($qb->expr()->in('u.user', $user_ids));
}
@@ -83,7 +83,7 @@ public function updateLanguageForLanguages(string $language, array $languages):
/**
* @return UserInfos[]
*/
- public function getNewUsers(DateTimeInterface $start = null, DateTimeInterface $end = null)
+ public function getNewUsers(?DateTimeInterface $start = null, ?DateTimeInterface $end = null)
{
$qb = $this->createQueryBuilder('u');
$this->addBetweenDateCondition($qb, $start, $end);
@@ -91,7 +91,7 @@ public function getNewUsers(DateTimeInterface $start = null, DateTimeInterface $
return $qb->getQuery()->getResult();
}
- public function countNewUsers(DateTimeInterface $start = null, DateTimeInterface $end = null): int
+ public function countNewUsers(?DateTimeInterface $start = null, ?DateTimeInterface $end = null): int
{
$qb = $this->createQueryBuilder('u');
$qb->select('count(1)');
@@ -100,7 +100,7 @@ public function countNewUsers(DateTimeInterface $start = null, DateTimeInterface
return $qb->getQuery()->getSingleScalarResult();
}
- private function addBetweenDateCondition(QueryBuilder $qb, DateTimeInterface $start = null, DateTimeInterface $end = null): QueryBuilder
+ private function addBetweenDateCondition(QueryBuilder $qb, ?DateTimeInterface $start = null, ?DateTimeInterface $end = null): QueryBuilder
{
if (!is_null($start)) {
$qb->andWhere('u.registration_date > :start');
diff --git a/src/Repository/UserMailNotificationRepository.php b/src/Repository/UserMailNotificationRepository.php
index de7e591e4..09572e196 100644
--- a/src/Repository/UserMailNotificationRepository.php
+++ b/src/Repository/UserMailNotificationRepository.php
@@ -53,7 +53,7 @@ public function findInfosForUsers(bool $send, ?bool $enabled_filter_value, array
$qb->setParameter('enabled', $enabled_filter_value);
}
- if (count($check_keys) > 0) {
+ if ($check_keys !== []) {
$qb->andWhere($qb->expr()->in('n.check_key', $check_keys));
}
diff --git a/src/Repository/UserRepository.php b/src/Repository/UserRepository.php
index 29ecc5121..2a614bd46 100644
--- a/src/Repository/UserRepository.php
+++ b/src/Repository/UserRepository.php
@@ -127,7 +127,7 @@ public function findWithAlbumsAccess(array $album_ids = [])
$qb = $this->createQueryBuilder('u');
$qb->leftJoin('u.user_access', 'ua');
- if (count($album_ids) > 0) {
+ if ($album_ids !== []) {
$qb->where($qb->expr()->in('ua.cat_id', $album_ids));
}
diff --git a/src/Security/AppUserService.php b/src/Security/AppUserService.php
index c5cda6613..c70bbd579 100644
--- a/src/Security/AppUserService.php
+++ b/src/Security/AppUserService.php
@@ -95,11 +95,6 @@ public function canManageComment(string $action, int $comment_author_id): bool
if (($action === 'edit' && $this->conf['user_can_edit_comment']) && ($comment_author_id === $this->getUser()->getId())) {
return true;
}
-
- if (($action === 'delete' && $this->conf['user_can_delete_comment']) && ($comment_author_id == $this->getUser()->getId())) {
- return true;
- }
-
- return false;
+ return $action === 'delete' && $this->conf['user_can_delete_comment'] && $comment_author_id == $this->getUser()->getId();
}
}
diff --git a/src/Security/LoginFormAuthenticator.php b/src/Security/LoginFormAuthenticator.php
index ab48c53dc..8a2a30acf 100644
--- a/src/Security/LoginFormAuthenticator.php
+++ b/src/Security/LoginFormAuthenticator.php
@@ -38,9 +38,9 @@ public function supports(Request $request): bool
return $request->isMethod('POST') && $request->attributes->get('_route') === 'login';
}
- public function start(Request $request, AuthenticationException $authException = null): Response
+ public function start(Request $request, ?AuthenticationException $authException = null): Response
{
- if ($authException !== null) {
+ if ($authException instanceof AuthenticationException) {
$request->getSession()->set('_redirect', true);
}
diff --git a/src/Security/TagVoter.php b/src/Security/TagVoter.php
index ef7d3fb42..1a3608468 100644
--- a/src/Security/TagVoter.php
+++ b/src/Security/TagVoter.php
@@ -37,12 +37,7 @@ protected function supports(string $attribute, mixed $subject): bool
if (!in_array($attribute, [self::ADD, self::DELETE])) {
return false;
}
-
- if (!$subject instanceof Image) {
- return false;
- }
-
- return true;
+ return $subject instanceof Image;
}
protected function voteOnAttribute(string $attribute, mixed $subject, TokenInterface $token): bool
diff --git a/src/Security/UserProvider.php b/src/Security/UserProvider.php
index 14233a689..e03f5d4e0 100644
--- a/src/Security/UserProvider.php
+++ b/src/Security/UserProvider.php
@@ -52,7 +52,7 @@ public function loadUserByIdentifier(string $identifier): User
public function loadByActivationKey(string $key): User
{
- if (($user = $this->fetchUserByActivationKey($key)) === null) {
+ if (!($user = $this->fetchUserByActivationKey($key)) instanceof User) {
throw new TokenNotFoundException(sprintf('Activation key "%s" does not exist.', $key));
}
@@ -137,7 +137,7 @@ private function getUserCacheInfos(User $user): UserCache
$this->albumMapper->removeComputedAlbum($user_cache_albums, $album_infos);
}
}
- if (count($forbidden_ids) > 0) {
+ if ($forbidden_ids !== []) {
$forbidden_albums = array_merge($forbidden_albums, $forbidden_ids);
}
}
diff --git a/src/Services/DerivativeService.php b/src/Services/DerivativeService.php
index c0b6dceed..a469dfc9b 100644
--- a/src/Services/DerivativeService.php
+++ b/src/Services/DerivativeService.php
@@ -28,7 +28,8 @@ public function __construct(private readonly string $mediaCacheDir, private read
*/
public function clearCache(array $types, array $all_types)
{
- for ($i = 0; $i < count($types); $i++) {
+ $counter = count($types);
+ for ($i = 0; $i < $counter; $i++) {
$type = $types[$i];
if ($type === ImageStandardParams::IMG_CUSTOM) {
$pattern = DerivativeParams::derivative_to_url($type) . '[a-zA-Z0-9]+';
@@ -77,11 +78,7 @@ public function deleteForElement(array $infos, $type = 'all')
}
$dot = strrpos($relative_path, '.');
- if ($type == 'all') {
- $pattern = '-.*';
- } else {
- $pattern = '-' . DerivativeParams::derivative_to_url($type) . '.*';
- }
+ $pattern = $type == 'all' ? '-.*' : '-' . DerivativeParams::derivative_to_url($type) . '.*';
$pattern = '#' . substr_replace($relative_path, $pattern, $dot, 0) . '#';
$finder = new Finder();
diff --git a/src/Twig/DerivativeExtension.php b/src/Twig/DerivativeExtension.php
index 1d54b0178..949a69727 100644
--- a/src/Twig/DerivativeExtension.php
+++ b/src/Twig/DerivativeExtension.php
@@ -67,7 +67,7 @@ public function defineDerivative(array $params): DerivativeParams
$crop = (int) round($params['crop'] / 100, 2);
}
- if ($crop) {
+ if ($crop !== 0) {
$minw = empty($params['min_width']) ? $w : intval($params['min_width']);
if ($minw > $w) {
throw new Exception('define_derivative invalid min_width');
diff --git a/src/Twig/PhyxoAssetExtension.php b/src/Twig/PhyxoAssetExtension.php
index aad6e4b31..e876d568e 100644
--- a/src/Twig/PhyxoAssetExtension.php
+++ b/src/Twig/PhyxoAssetExtension.php
@@ -30,7 +30,7 @@ public function getFunctions(): array
public function getAssetPath(string $path, string $manifestRelativeFile = ''): string
{
- if (empty($manifestRelativeFile)) {
+ if ($manifestRelativeFile === '' || $manifestRelativeFile === '0') {
return $path;
}
diff --git a/src/Utils/RuntimeTranslator.php b/src/Utils/RuntimeTranslator.php
index 2b06f9e8d..42ad9ed3b 100644
--- a/src/Utils/RuntimeTranslator.php
+++ b/src/Utils/RuntimeTranslator.php
@@ -41,7 +41,7 @@ public function __call(string $method, mixed $args): mixed
return $this->translator->{$method}(...$args);
}
- public function getCatalogue($locale = null): MessageCatalogueInterface
+ public function getCatalogue(?string $locale = null): MessageCatalogueInterface
{
return $this->translator->getCatalogue($locale);
}
@@ -67,7 +67,7 @@ public function getLocale(): string
/**
* @param array $parameters
*/
- public function trans(string $id, array $parameters = [], string $domain = null, string $locale = null): string
+ public function trans(string $id, array $parameters = [], ?string $domain = null, ?string $locale = null): string
{
if ($locale === null) {
$locale = $this->getLocale();
@@ -85,7 +85,7 @@ public function trans(string $id, array $parameters = [], string $domain = null,
return $this->formatter->format($runtimeCatalogue->get($id, $domain), $locale, $parameters);
}
- public function addRuntimeResource(string $format, string $resource, string $locale, string $domain = null): void
+ public function addRuntimeResource(string $format, string $resource, string $locale, ?string $domain = null): void
{
if ($format !== 'php') {
return;
diff --git a/symfony.lock b/symfony.lock
index 66a34d5e8..d451c5b1a 100644
--- a/symfony.lock
+++ b/symfony.lock
@@ -366,15 +366,16 @@
"version": "v5.4.3"
},
"symfony/flex": {
- "version": "1.19",
+ "version": "2.4",
"recipe": {
"repo": "github.com/symfony/recipes",
"branch": "main",
- "version": "1.0",
- "ref": "146251ae39e06a95be0fe3d13c807bcf3938b172"
+ "version": "2.4",
+ "ref": "52e9754527a15e2b79d9a610f98185a1fe46622a"
},
"files": [
- ".env"
+ ".env",
+ ".env.dev"
]
},
"symfony/form": {
diff --git a/tests/Behat/ApiContext.php b/tests/Behat/ApiContext.php
index 1d37b86f9..4614be5a7 100644
--- a/tests/Behat/ApiContext.php
+++ b/tests/Behat/ApiContext.php
@@ -68,11 +68,11 @@ public function iAmAuthenticatedForApiAs(string $username, string $password)
public function iSendARequestWithValues(string $http_method, string $method, ?TableNode $values = null)
{
$requestOptions = [];
- if ($http_method == 'GET') {
+ if ($http_method === 'GET') {
$requestOptions['query']['method'] = $method;
- } elseif ($http_method == 'POST') {
+ } elseif ($http_method === 'POST') {
$requestOptions['form_params'] = [];
- if ($values !== null) {
+ if ($values instanceof TableNode) {
foreach ($values->getColumnsHash() as $columHash) {
$requestOptions['form_params'] = $columHash;
}
@@ -156,7 +156,7 @@ private function getProperty($data, $property)
$parts = explode('/', (string) $property);
$n = 0;
while ($n < count($parts)) {
- if (is_null($data[$parts[$n]]) && ($n + 1) == count($parts)) {
+ if (is_null($data[$parts[$n]]) && $n + 1 === count($parts)) {
$data = '';
} else {
if (!isset($data[$parts[$n]])) {
diff --git a/tests/Behat/BaseContext.php b/tests/Behat/BaseContext.php
index e9606f030..2a8614f39 100644
--- a/tests/Behat/BaseContext.php
+++ b/tests/Behat/BaseContext.php
@@ -62,7 +62,7 @@ public function spins(Closure $closure, int $tries = 3): void
return;
} catch (Exception $e) {
- if ($i == $tries) {
+ if ($i === $tries) {
throw $e;
}
}
@@ -73,7 +73,7 @@ public function spins(Closure $closure, int $tries = 3): void
public function findByDataTestid(string $data_id, NodeElement $parent = null): NodeElement
{
- if ($parent === null) {
+ if (!$parent instanceof NodeElement) {
$parent = $this->getSession()->getPage();
}
$element = $parent->find('css', sprintf('*[data-testid="%s"]', $data_id));
diff --git a/tests/Behat/DBContext.php b/tests/Behat/DBContext.php
index 84453f67d..761d16364 100644
--- a/tests/Behat/DBContext.php
+++ b/tests/Behat/DBContext.php
@@ -72,7 +72,7 @@ public function givenUsers(TableNode $table): void
$user = new User();
$user->setUsername($userRow['username']);
$user->setPassword($this->getContainer()->get('security.password_hasher')->hashPassword($user, $userRow['password']));
- $user->addRole(User::getRoleFromStatus(!empty($userRow['status']) ? $userRow['status'] : User::STATUS_NORMAL));
+ $user->addRole(User::getRoleFromStatus(empty($userRow['status']) ? User::STATUS_NORMAL : $userRow['status']));
if (!empty($userRow['mail_address'])) {
$user->setMailAddress($userRow['mail_address']);
}
@@ -385,11 +385,7 @@ protected function addTagsToImage(array $tags, int $image_id, int $user_id = nul
}
$image = $this->imageMapper->getRepository()->find($image_id);
- if (!is_null($user_id)) {
- $user = $this->userRepository->find($user_id);
- } else {
- $user = $this->userMapper->getDefaultUser();
- }
+ $user = is_null($user_id) ? $this->userMapper->getDefaultUser() : $this->userRepository->find($user_id);
$this->tagMapper->toBeValidatedTags($image, $tag_ids, $user, ImageTag::STATUS_TO_ADD, $validated);
}
@@ -411,11 +407,7 @@ protected function removeTagsFromImage(array $tags, int $image_id, int $user_id
$conf = $this->conf;
$image = $this->imageMapper->getRepository()->find($image_id);
- if (!is_null($user_id)) {
- $user = $this->userRepository->find($user_id);
- } else {
- $user = $this->userMapper->getDefaultUser();
- }
+ $user = is_null($user_id) ? $this->userMapper->getDefaultUser() : $this->userRepository->find($user_id);
// if publish_tags_immediately (or delete_tags_immediately) is not set we consider its value is true
if (isset($conf['publish_tags_immediately']) && $conf['publish_tags_immediately'] === false) {
diff --git a/tests/Behat/FeatureContext.php b/tests/Behat/FeatureContext.php
index 1f29dcfe7..2be3aeffe 100644
--- a/tests/Behat/FeatureContext.php
+++ b/tests/Behat/FeatureContext.php
@@ -165,11 +165,7 @@ public function iShouldNotSeeTag(string $tag_name): void
*/
public function iShouldSeeLink(string $link_label, string $parent = ''): void
{
- if (!empty($parent)) {
- $parentNode = $this->getSession()->getPage()->find('css', $parent);
- } else {
- $parentNode = $this->getSession()->getPage();
- }
+ $parentNode = $parent === '' || $parent === '0' ? $this->getSession()->getPage() : $this->getSession()->getPage()->find('css', $parent);
$link = $parentNode->findLink($link_label);
if ($link === null) {