refactor: code style changes

Signed-off-by: miguel456 <me@nogueira.codes>
This commit is contained in:
2023-01-15 00:04:00 +00:00
parent 25155bff2e
commit 3727c84f3e
146 changed files with 1013 additions and 1341 deletions

View File

@@ -28,6 +28,7 @@ class ContextAwareValidator
{
/**
* The excludedNames array will make the validator ignore any of these names when including names into the rules.
*
* @var array
*/
private $excludedNames = [
@@ -39,7 +40,7 @@ class ContextAwareValidator
/**
* Utility wrapper for json_encode.
*
* @param array $value The array to be converted.
* @param array $value The array to be converted.
* @return string The JSON representation of $value
*/
private function encode(array $value): string
@@ -60,9 +61,9 @@ class ContextAwareValidator
*
* P.S This method automatically ignores the CSRF token for validation.
*
* @param array $fields The request form fields
* @param bool $generateStructure Whether to incldue a JSON-ready form structure for rendering
* @param bool $includeFormName Whether to include formName in the list of validation rules
* @param array $fields The request form fields
* @param bool $generateStructure Whether to incldue a JSON-ready form structure for rendering
* @param bool $includeFormName Whether to include formName in the list of validation rules
* @return Validator|Collection A validator instance you can use to check for validity, or a Collection with a validator and structure (validator, structure)
*/
public function getValidator(array $fields, bool $generateStructure = false, bool $includeFormName = false)
@@ -103,9 +104,9 @@ class ContextAwareValidator
*
* Also generates the storable response structure if you tell it to.
*
* @param array $fields The received fields
* @param array $formStructure The form structure - You must supply this if you want the response structure
* @param bool $generateResponseStructure Whether to generate the response structure
* @param array $fields The received fields
* @param array $formStructure The form structure - You must supply this if you want the response structure
* @param bool $generateResponseStructure Whether to generate the response structure
* @return Validator|Collection A collection or a validator, depending on the args. Will return validatior if only fields are supplied.
*/
public function getResponseValidator(array $fields, array $formStructure = [], bool $generateResponseStructure = true)

View File

@@ -1,5 +1,6 @@
<?php declare(strict_types=1);
<?php
declare(strict_types=1);
namespace App\Helpers;
@@ -10,31 +11,29 @@ namespace App\Helpers;
* It should be used whenever you need to display a file's size in a human readable way.
*
* It's framework agnostic, meaning you can take it out of context and it'll still work; However, you'll have to instantiate it first.
* @package App\Helpers
*/
class DigitalStorageHelper
{
/**
* The digital storage value to be manipulated.
* @var $value
*
* @var
*/
protected $value;
/**
* Sets the digital storage value for manipulation.
*
* @param int $value The digital storage value in bytes
* @param int $value The digital storage value in bytes
* @return $this The current instance
*/
public function setValue(int $value): DigitalStorageHelper
{
$this->value = $value;
return $this;
}
/**
* Converts the digital storage value to kilobytes.
*
@@ -45,7 +44,6 @@ class DigitalStorageHelper
return $this->value / 1000;
}
/**
* Converts the digital storage value to megabytes.
*
@@ -56,7 +54,6 @@ class DigitalStorageHelper
return $this->value / (1 * pow(10, 6)); // 1 times 10 to the power of 6
}
/**
* Convert the digital storage value to gigabytes. Might be an approximation
*
@@ -67,7 +64,6 @@ class DigitalStorageHelper
return $this->value / (1 * pow(10, 9));
}
/**
* Convert the digital storage value to terabytes.
*
@@ -78,22 +74,23 @@ class DigitalStorageHelper
return $this->value / (1 * pow(10, 12));
}
/**
* Format the digital storage value to one of the units: b, kb, mb, gb and tb.
* The method has been adapted to use both MiB and MB values.
*
* @param int $precision The rounding precision
* @param bool $si Use international system units. Defaults to false
* @param int $precision The rounding precision
* @param bool $si Use international system units. Defaults to false
* @return string The human readable digital storage value, in either, for instance, MB or MiB
*
* @see https://stackoverflow.com/a/2510459/11540218 StackOverflow question regarding unit conversion
* @since 7.3.23
*/
public function formatBytes($precision = 2, $si = false): string
{
$units = ['B', 'KiB', 'MiB', 'GiB', 'TiB'];
if ($si)
if ($si) {
$units = ['B', 'KB', 'MB', 'GB', 'TB'];
}
$bytes = max($this->value, 0);
$pow = floor(($bytes ? log($bytes) : 0) / log(($si) ? 1000 : 1024));
@@ -101,7 +98,6 @@ class DigitalStorageHelper
$bytes /= pow(($si) ? 1000 : 1024, $pow);
return round($bytes, $precision) . ' ' . $units[$pow];
return round($bytes, $precision).' '.$units[$pow];
}
}

View File

@@ -19,30 +19,25 @@
* along with Raspberry Staff Manager. If not, see <https://www.gnu.org/licenses/>.
*/
namespace App\Helpers;
use App\Exceptions\AccountNotLinkedException;
use App\User;
use Carbon\Carbon;
use Illuminate\Http\Client\RequestException;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\Http;
// Small wrapper for the necessary sections of the Discord API; A library is overkill here
class Discord
{
/**
* The current working guild. Default is Home guild from app config
*
* @var string
*/
protected string $workingGuild;
/**
* Current user.
*
@@ -50,42 +45,43 @@ class Discord
*/
protected User $user;
public function __construct() {
public function __construct()
{
if (isset($this->workingGuild)) {
$this->setWorkingGuild(config('services.discord.home_guild'));
}
}
/**
* Sets the working guild
*
* @param string $workingGuild
* @param string $workingGuild
* @return Discord
*/
public function setWorkingGuild(string $workingGuild): Discord
{
$this->workingGuild = $workingGuild;
return $this;
}
/**
* Sets the current user, upon validation
*
* @param User $user
* @param User $user
* @return Discord
*
* @throws AccountNotLinkedException
*/
public function setUser(User $user): Discord
{
if ($user->hasDiscordConnection()) {
$this->user = $user;
return $this;
}
if ($user->hasDiscordConnection()) {
$this->user = $user;
throw new AccountNotLinkedException('Specified website user has not linked their Discord account yet.');
return $this;
}
throw new AccountNotLinkedException('Specified website user has not linked their Discord account yet.');
}
/**
@@ -93,16 +89,16 @@ class Discord
* preventing unnecessary API requests.
*
* @return object Current user's authentication info (has no sensitive fields)
*
* @throws RequestException
*/
public function getAuthorizationInfo(): object {
public function getAuthorizationInfo(): object
{
if (Cache::has($this->user->discord_user_id)) {
return unserialize(Cache::get($this->user->discord_user_id));
}
else {
} else {
$authInfo = (object) Http::withToken($this->user->discord_token)
->get(config('services.discord.base_url') . '/oauth2/@me')
->get(config('services.discord.base_url').'/oauth2/@me')
->throw()
->json();
@@ -112,43 +108,42 @@ class Discord
}
}
/**
* Checks if the user's token is close to expiring.
* Tokens should be refreshed the day before they expire.
*
* @return bool Whether the user's token needs to be refreshed
*
* @throws RequestException
*/
public function needsRefresh(): bool {
public function needsRefresh(): bool
{
return Carbon::parse($this->getAuthorizationInfo()->expires)->diffInDays() == 1;
}
public function exchangeRefreshToken() {
public function exchangeRefreshToken()
{
}
/**
* Adds current working user to current working guild. Bot must be member of target guild, and account must be linked
*
* @return object|bool A GuildMember object; false if member is already in guild
*
* @throws RequestException Any client and server errors
*
* @see https://discord.com/developers/docs/resources/guild#guild-member-object
*/
public function addGuildMember(): object|bool
{
$params = [
'access_token' => $this->user->discord_token
'access_token' => $this->user->discord_token,
];
$member = Http::withBody(json_encode($params), 'application/json')
->withHeaders([
'Authorization' => 'Bot ' . config('services.discord.token')
])->put(config('services.discord.base_url') . "/guilds/{$this->workingGuild}/members/{$this->user->discord_user_id}")
'Authorization' => 'Bot '.config('services.discord.token'),
])->put(config('services.discord.base_url')."/guilds/{$this->workingGuild}/members/{$this->user->discord_user_id}")
->throw();
if ($member->successful() && $member->status() == 204) {
@@ -158,42 +153,45 @@ class Discord
}
}
/**
* Bans a specified user from the guild.
* May be called from the suspension service optionally by the banning user
*
* @param string $reason The reason to supply Discord with
* @param string $reason The reason to supply Discord with
* @return void Nothing on success
*
* @throws RequestException
* @throws AccountNotLinkedException
*/
public function addGuildBan(string $reason): void {
public function addGuildBan(string $reason): void
{
Http::withHeaders([
'Authorization' => 'Bot ' . config('services.discord.token'),
'X-Audit-Log-Reason' => $reason
])->put(config('services.discord.base_url') . "/guilds/{$this->workingGuild}/bans/{$this->user->discord_user_id}")
'Authorization' => 'Bot '.config('services.discord.token'),
'X-Audit-Log-Reason' => $reason,
])->put(config('services.discord.base_url')."/guilds/{$this->workingGuild}/bans/{$this->user->discord_user_id}")
->throw();
throw new AccountNotLinkedException('Specified website user has not linked their Discord account yet.');
}
/**
* @param string $reason The removal reason to provide Discord with (e.g. ban expired)
* @param string $reason The removal reason to provide Discord with (e.g. ban expired)
* @return null|bool Null on unnan, false if user is not banned
*
* @throws RequestException
*/
public function removeGuildBan(string $reason): null|bool {
public function removeGuildBan(string $reason): null|bool
{
if ($this->getGuildBan($this->user)) {
Http::withHeaders([
'Authorization' => 'Bot ' . config('services.discord.token'),
'X-Audit-Log-Reason' => $reason
])->delete(config('services.discord.base_url') . "/guilds/{$this->workingGuild}/bans/{$this->user->discord_user_id}")
'Authorization' => 'Bot '.config('services.discord.token'),
'X-Audit-Log-Reason' => $reason,
])->delete(config('services.discord.base_url')."/guilds/{$this->workingGuild}/bans/{$this->user->discord_user_id}")
->throw();
return null;
}
return false;
}
@@ -201,14 +199,16 @@ class Discord
* Gets (possible) ban for current user.
*
* @return object|bool Ban object if user is banned. Null
*
* @throws RequestException
*
* @see https://discord.com/developers/docs/resources/guild#ban-object
*/
public function getGuildBan(): object|bool
{
$ban = Http::withHeaders([
'Authorization' => 'Bot ' . config('services.discord.token')
])->get(config('services.discord.base_url') . "/guilds/{$this->workingGuild}/bans/{$this->user->discord_user_id}");
'Authorization' => 'Bot '.config('services.discord.token'),
])->get(config('services.discord.base_url')."/guilds/{$this->workingGuild}/bans/{$this->user->discord_user_id}");
if ($ban->status() == 404) {
return false;
@@ -217,20 +217,21 @@ class Discord
return ($ban->successful()) ? (object) $ban->json() : $ban->throwIf($ban->status() !== 404);
}
/**
* Retrieves list of Role objects
*
* @see https://discord.com/developers/docs/topics/permissions#role-object
*
* @return array List of role objects
*
* @throws RequestException
*/
public function getGuildRoles(): array {
public function getGuildRoles(): array
{
return Http::withHeaders([
'Authorization' => 'Bot ' . config('services.discord.token')
])->get(config('services.discord.base_url') . "/guilds/{$this->workingGuild}/roles")
'Authorization' => 'Bot '.config('services.discord.token'),
])->get(config('services.discord.base_url')."/guilds/{$this->workingGuild}/roles")
->throw()
->json();
}
}

View File

@@ -1,32 +1,41 @@
<?php
namespace App\Helpers;
/**
* Class JSON - Used for JSON responses.
* @package App\Helpers
*/
class JSON
{
protected $type;
protected $type, $status, $message, $code, $data, $additional;
protected $status;
protected $message;
protected $code;
protected $data;
protected $additional;
/**
* @param mixed $type
* @param mixed $type
*/
public function setResponseType($type): JSON
{
$this->type = $type;
return $this;
}
/**
* @param mixed $additional
* @param mixed $additional
*/
public function setAdditional($additional)
{
$this->additional = $additional;
return $this;
}
@@ -55,12 +64,13 @@ class JSON
}
/**
* @param mixed $status
* @param mixed $status
* @return JSON
*/
public function setStatus($status)
{
$this->status = $status;
return $this;
}
@@ -73,12 +83,13 @@ class JSON
}
/**
* @param mixed $message
* @param mixed $message
* @return JSON
*/
public function setMessage($message)
{
$this->message = $message;
return $this;
}
@@ -91,12 +102,13 @@ class JSON
}
/**
* @param mixed $code
* @param mixed $code
* @return JSON
*/
public function setCode($code)
{
$this->code = $code;
return $this;
}
@@ -109,12 +121,13 @@ class JSON
}
/**
* @param mixed $data
* @param mixed $data
* @return JSON
*/
public function setData($data)
{
$this->data = $data;
return $this;
}
@@ -126,17 +139,15 @@ class JSON
'meta' => [
'status' => $this->getStatus(),
'message' => $this->getMessage(),
]
],
];
if (!empty($this->additional))
{
foreach($this->additional as $additionalKeyName => $key)
{
if (! empty($this->additional)) {
foreach ($this->additional as $additionalKeyName => $key) {
$response[$additionalKeyName] = $key;
}
}
return response($response, $this->getCode(), $headers);
}
}

View File

@@ -33,30 +33,28 @@ use Illuminate\Support\Facades\Log;
*/
class Options
{
/**
* Returns an assortment of settings found in the mentioned category
*
* @param string $category The category
* @param string $category The category
* @return Collection The settings in this category
*
* @throws EmptyOptionsException
*/
public function getCategory(string $category): Collection
{
$options = Option::where('option_category', $category)->get();
if ($options->isEmpty())
{
throw new EmptyOptionsException('There are no options in category ' . $category);
if ($options->isEmpty()) {
throw new EmptyOptionsException('There are no options in category '.$category);
}
return $options;
}
public function getOption(string $option): string
{
$value = Cache::get($option);
if (is_null($value)) {
Log::debug('Option '.$option.'not found in cache, refreshing from database');
$value = Option::where('option_name', $option)->first();
@@ -79,7 +77,7 @@ class Options
'option_name' => $option,
'option_value' => $value,
'friendly_name' => $description,
'option_category' => $category
'option_category' => $category,
]);
Cache::put($option, $value, now()->addDay());
@@ -115,9 +113,9 @@ class Options
$dbOptionInstance->save();
Log::debug('New db configuration option saved',
[
'option' => $dbOptionInstance->option_value,
]);
[
'option' => $dbOptionInstance->option_value,
]);
Cache::put('option_name', $newValue, now()->addDay());
} else {