Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use enum instead of constants for SmartAlbumTypes #1793

Merged
merged 4 commits into from
Apr 15, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
60 changes: 60 additions & 0 deletions app/Enum/DecorateBackedEnum.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
<?php

/**
* The MIT License (MIT).
*
* Copyright (c) laracraft-tech [email protected]
*
* https://github.com/laracraft-tech/laravel-useful-additions#usefulenums3
*/

namespace App\Enum;

/**
* add a 3 utility functions to enum.
*
* enum PaymentType: int
* {
* use DecorateEnum;
*
* case Pending = 1;
* case Failed = 2;
* case Success = 3;
* }
*
* PaymentType::names(); // return ['Pending', 'Failed', 'Success']
* PaymentType::values(); // return [1, 2, 3]
* PaymentType::array(); // return ['Pending' => 1, 'Failed' => 2, 'Success' => 3]
*/
trait DecorateBackedEnum
{
/**
* Returns a list of name covered by the enum.
*
* @return array
*/
public static function names(): array
{
return array_column(self::cases(), 'name');
}

/**
* Returns a list of values covered by the enum.
*
* @return array
*/
public static function values(): array
{
return array_column(self::cases(), 'value');
}

/**
* Returns an associative array [name => value].
*
* @return array
*/
public static function array(): array
{
return array_combine(self::names(), self::values());
}
}
17 changes: 17 additions & 0 deletions app/Enum/SmartAlbumType.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
<?php

namespace App\Enum;

/**
* Enum SmartAlbumType.
*/
enum SmartAlbumType: string
{
use DecorateBackedEnum;

case UNSORTED = 'unsorted';
case STARRED = 'starred';
case RECENT = 'recent';
case PUBLIC = 'public';
case ON_THIS_DAY = 'on_this_day';
}
73 changes: 35 additions & 38 deletions app/Factories/AlbumFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
namespace App\Factories;

use App\Contracts\Models\AbstractAlbum;
use App\Enum\SmartAlbumType;
use App\Exceptions\Internal\InvalidSmartIdException;
use App\Exceptions\Internal\LycheeAssertionError;
use App\Models\Album;
Expand All @@ -20,12 +21,21 @@

class AlbumFactory
{
public const BUILTIN_SMARTS = [
UnsortedAlbum::ID => UnsortedAlbum::class,
StarredAlbum::ID => StarredAlbum::class,
PublicAlbum::ID => PublicAlbum::class,
RecentAlbum::ID => RecentAlbum::class,
OnThisDayAlbum::ID => OnThisDayAlbum::class,
// PHP 8.2
// public const BUILTIN_SMARTS_CLASS = [
// SmartAlbumType::UNSORTED->value => UnsortedAlbum::class,
// SmartAlbumType::STARRED->value => StarredAlbum::class,
// SmartAlbumType::PUBLIC->value => PublicAlbum::class,
// SmartAlbumType::RECENT->value => RecentAlbum::class,
// SmartAlbumType::ON_THIS_DAY->value => OnThisDayAlbum::class,
// ];

public const BUILTIN_SMARTS_CLASS = [
'unsorted' => UnsortedAlbum::class,
'starred' => StarredAlbum::class,
'public' => PublicAlbum::class,
'recent' => RecentAlbum::class,
'on_this_day' => OnThisDayAlbum::class,
];

/**
Expand All @@ -45,8 +55,9 @@ class AlbumFactory
*/
public function findAbstractAlbumOrFail(string $albumId, bool $withRelations = true): AbstractAlbum
{
if ($this->isBuiltInSmartAlbum($albumId)) {
return $this->createSmartAlbum($albumId, $withRelations);
$smartAlbumType = SmartAlbumType::tryFrom($albumId);
if ($smartAlbumType !== null) {
return $this->createSmartAlbum($smartAlbumType, $withRelations);
}

return $this->findBaseAlbumOrFail($albumId, $withRelations);
Expand Down Expand Up @@ -108,16 +119,17 @@ public function findAbstractAlbumsOrFail(array $albumIDs, bool $withRelations =
{
// Remove root (ID===`null`) and duplicates
$albumIDs = array_diff(array_unique($albumIDs), [null]);
$smartAlbumIDs = array_intersect($albumIDs, array_keys(self::BUILTIN_SMARTS));
$modelAlbumIDs = array_diff($albumIDs, array_keys(self::BUILTIN_SMARTS));
$smartAlbumIDs = array_intersect($albumIDs, SmartAlbumType::values());
$modelAlbumIDs = array_diff($albumIDs, SmartAlbumType::values());

$smartAlbums = [];
foreach ($smartAlbumIDs as $smartID) {
try {
$smartAlbums[] = $this->createSmartAlbum($smartID, $withRelations);
} catch (InvalidSmartIdException $e) {
// InvalidSmartIdException must not be thrown, as search has been limited to self::BUILTIN_SMARTS'
throw LycheeAssertionError::createFromUnexpectedException($e);
$smartAlbumType = SmartAlbumType::from($smartID);
$smartAlbums[] = $this->createSmartAlbum($smartAlbumType, $withRelations);
} catch (\ValueError $e) {
$e2 = new InvalidSmartIdException($smartID);
throw LycheeAssertionError::createFromUnexpectedException($e2);
}
}

Expand Down Expand Up @@ -183,45 +195,30 @@ public function findBaseAlbumsOrFail(array $albumIDs, bool $withRelations = true
public function getAllBuiltInSmartAlbums(bool $withRelations = true): Collection
{
$smartAlbums = new Collection();
foreach (self::BUILTIN_SMARTS as $smartAlbumId => $smartAlbumClass) {
$smartAlbums->put($smartAlbumId, $this->createSmartAlbum($smartAlbumId, $withRelations));
/** @var SmartAlbumType $smartAlbumId */
foreach (SmartAlbumType::cases() as $smartAlbumId) {
$smartAlbums->put($smartAlbumId->value, $this->createSmartAlbum($smartAlbumId, $withRelations));
}

return $smartAlbums;
}

/**
* Checks if the given album ID denotes one of the built-in smart albums.
*
* @param string $albumId
*
* @return bool true, if the album ID refers to a built-in smart album
*/
public function isBuiltInSmartAlbum(string $albumId): bool
{
return array_key_exists($albumId, self::BUILTIN_SMARTS);
}

/**
* Returns the instance of the built-in smart album with the designated ID.
*
* @param string $smartAlbumId the ID of the smart album
* @param bool $withRelations Eagerly loads the relation
* {@link BaseSmartAlbum::photos()}
* for the smart album
* @param SmartAlbumType $smartAlbumId the ID of the smart album
* @param bool $withRelations Eagerly loads the relation
* {@link BaseSmartAlbum::photos()}
* for the smart album
*
* @return BaseSmartAlbum
*
* @throws InvalidSmartIdException
*/
public function createSmartAlbum(string $smartAlbumId, bool $withRelations = true): BaseSmartAlbum
public function createSmartAlbum(SmartAlbumType $smartAlbumId, bool $withRelations = true): BaseSmartAlbum
{
if (!$this->isBuiltInSmartAlbum($smartAlbumId)) {
throw new InvalidSmartIdException($smartAlbumId);
}

/** @var BaseSmartAlbum $smartAlbum */
$smartAlbum = call_user_func(self::BUILTIN_SMARTS[$smartAlbumId] . '::getInstance');
$smartAlbum = call_user_func(self::BUILTIN_SMARTS_CLASS[$smartAlbumId->value] . '::getInstance');
if ($withRelations) {
// Just try to get the photos.
// This loads the relation from DB and caches it.
Expand Down
6 changes: 3 additions & 3 deletions app/Policies/AlbumPolicy.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,10 @@
namespace App\Policies;

use App\Contracts\Models\AbstractAlbum;
use App\Enum\SmartAlbumType;
use App\Exceptions\ConfigurationKeyMissingException;
use App\Exceptions\Internal\LycheeAssertionError;
use App\Exceptions\Internal\QueryBuilderException;
use App\Factories\AlbumFactory;
use App\Models\BaseAlbumImpl;
use App\Models\Configs;
use App\Models\Extensions\BaseAlbum;
Expand Down Expand Up @@ -232,7 +232,7 @@ public function canEditById(User $user, array $albumIDs): bool
// Make IDs unique as otherwise count will fail.
$albumIDs = array_diff(
array_unique($albumIDs),
array_keys(AlbumFactory::BUILTIN_SMARTS),
array_keys(SmartAlbumType::values()),
[null]
);

Expand Down Expand Up @@ -264,7 +264,7 @@ public function canShareWithUsers(?User $user, ?AbstractAlbum $abstractAlbum): b
return false;
}

if (in_array($abstractAlbum->id, AlbumFactory::BUILTIN_SMARTS, true)) {
if (SmartAlbumType::tryFrom($abstractAlbum->id) !== null) {
return false;
}

Expand Down
4 changes: 2 additions & 2 deletions app/Rules/AlbumIDListRule.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
namespace App\Rules;

use App\Constants\RandomID;
use App\Factories\AlbumFactory;
use App\Enum\SmartAlbumType;
use Illuminate\Contracts\Validation\ValidationRule;

class AlbumIDListRule implements ValidationRule
Expand Down Expand Up @@ -35,6 +35,6 @@ public function message(): string
{
return ':attribute must be a comma-separated string of strings with either ' .
RandomID::ID_LENGTH . ' characters each or one of the built-in IDs ' .
implode(', ', array_keys(AlbumFactory::BUILTIN_SMARTS));
implode(', ', SmartAlbumType::values());
}
}
6 changes: 3 additions & 3 deletions app/Rules/AlbumIDRule.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
namespace App\Rules;

use App\Constants\RandomID;
use App\Factories\AlbumFactory;
use App\Enum\SmartAlbumType;
use Illuminate\Contracts\Validation\ValidationRule;

class AlbumIDRule implements ValidationRule
Expand All @@ -25,7 +25,7 @@ public function passes(string $attribute, mixed $value): bool
return
($value === null && $this->isNullable) ||
strlen($value) === RandomID::ID_LENGTH ||
array_key_exists($value, AlbumFactory::BUILTIN_SMARTS);
SmartAlbumType::tryFrom($value) !== null;
}

/**
Expand All @@ -35,6 +35,6 @@ public function message(): string
{
return ':attribute ' .
' must either be null, a string with ' . RandomID::ID_LENGTH . ' characters or one of the built-in IDs ' .
implode(', ', array_keys(AlbumFactory::BUILTIN_SMARTS));
implode(', ', SmartAlbumType::values());
}
}
7 changes: 4 additions & 3 deletions app/SmartAlbums/BaseSmartAlbum.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
use App\Contracts\Exceptions\InternalLycheeException;
use App\Contracts\Models\AbstractAlbum;
use App\DTO\PhotoSortingCriterion;
use App\Enum\SmartAlbumType;
use App\Exceptions\ConfigurationKeyMissingException;
use App\Exceptions\Internal\FrameworkException;
use App\Exceptions\Internal\InvalidOrderDirectionException;
Expand Down Expand Up @@ -51,12 +52,12 @@ abstract class BaseSmartAlbum implements AbstractAlbum
* @throws ConfigurationKeyMissingException
* @throws FrameworkException
*/
protected function __construct(string $id, string $title, bool $is_public, \Closure $smartCondition)
protected function __construct(SmartAlbumType $id, bool $is_public, \Closure $smartCondition)
{
try {
$this->photoQueryPolicy = resolve(PhotoQueryPolicy::class);
$this->id = $id;
$this->title = $title;
$this->id = $id->value;
$this->title = __('lychee.' . $id->name) ?? $id->name;
$this->is_public = $is_public;
$this->grants_download = Configs::getValueAsBool('grants_download');
$this->grants_full_photo_access = Configs::getValueAsBool('grants_full_photo_access');
Expand Down
6 changes: 4 additions & 2 deletions app/SmartAlbums/OnThisDayAlbum.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace App\SmartAlbums;

use App\Enum\SmartAlbumType;
use App\Exceptions\ConfigurationKeyMissingException;
use App\Exceptions\Internal\FrameworkException;
use App\Models\Configs;
Expand All @@ -13,6 +14,8 @@
class OnThisDayAlbum extends BaseSmartAlbum
{
private static ?self $instance = null;
// PHP 8.2
// public const ID = SmartAlbumType::ON_THIS_DAY->value;
public const ID = 'on_this_day';

/**
Expand All @@ -26,8 +29,7 @@ protected function __construct()
$today = Carbon::today();

parent::__construct(
self::ID,
__('lychee.ON_THIS_DAY'),
SmartAlbumType::ON_THIS_DAY,
Configs::getValueAsBool('public_on_this_day'),
function (Builder $query) use ($today) {
$query->where(fn (Builder $q) => $q
Expand Down
6 changes: 4 additions & 2 deletions app/SmartAlbums/PublicAlbum.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace App\SmartAlbums;

use App\Enum\SmartAlbumType;
use App\Exceptions\ConfigurationKeyMissingException;
use App\Exceptions\Internal\FrameworkException;
use Illuminate\Database\Eloquent\Builder;
Expand All @@ -26,6 +27,8 @@
class PublicAlbum extends BaseSmartAlbum
{
private static ?self $instance = null;
// PHP 8.2
// public const ID = SmartAlbumType::PUBLIC->value;
public const ID = 'public';

/**
Expand All @@ -44,8 +47,7 @@ class PublicAlbum extends BaseSmartAlbum
protected function __construct()
{
parent::__construct(
self::ID,
__('lychee.PUBLIC'),
SmartAlbumType::PUBLIC,
false,
fn (Builder $q) => $q->where('photos.is_public', '=', true)
);
Expand Down
6 changes: 4 additions & 2 deletions app/SmartAlbums/RecentAlbum.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace App\SmartAlbums;

use App\Enum\SmartAlbumType;
use App\Exceptions\ConfigurationKeyMissingException;
use App\Exceptions\Internal\FrameworkException;
use App\Models\Configs;
Expand All @@ -13,6 +14,8 @@
class RecentAlbum extends BaseSmartAlbum
{
private static ?self $instance = null;
// PHP 8.2
// public const ID = SmartAlbumType::RECENT->value;
public const ID = 'recent';

/**
Expand All @@ -28,8 +31,7 @@ protected function __construct()
);

parent::__construct(
self::ID,
__('lychee.RECENT'),
SmartAlbumType::RECENT,
Configs::getValueAsBool('public_recent'),
function (Builder $query) use ($strRecent) {
$query->where('photos.created_at', '>=', $strRecent);
Expand Down
Loading