bump phpcs

phpcs clean
This commit is contained in:
Jérémy Munsch 2022-06-10 17:38:34 +02:00
parent de13de76b5
commit f2a8240c7c
No known key found for this signature in database
GPG key ID: 18361AF3BFEC0FEC
9 changed files with 275 additions and 176 deletions

171
phpcs.xml
View file

@ -1,74 +1,86 @@
<?xml version="1.0" encoding="UTF-8"?>
<ruleset name="RealWorld" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="vendor/squizlabs/php_codesniffer/phpcs.xsd">
<arg name="colors"/>
<arg name="extensions" value="php"/>
<ruleset name="LDC Laravel"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="vendor/squizlabs/php_codesniffer/phpcs.xsd">
<description>Created with the PHP Coding Standard Generator. http://edorian.github.com/php-coding-standard-generator/</description>
<arg name="colors" />
<arg name="extensions" value="php" />
<file>config/</file>
<file>src/</file>
<file>tests/</file>
<description>Created with the PHP Coding Standard Generator. http://edorian.github.com/php-coding-standard-generator/
</description>
<rule ref="Generic.CodeAnalysis.EmptyStatement" />
<rule ref="Generic.CodeAnalysis.ForLoopShouldBeWhileLoop" />
<rule ref="Generic.CodeAnalysis.ForLoopWithTestFunctionCall" />
<rule ref="Generic.CodeAnalysis.JumbledIncrementer" />
<rule ref="Generic.CodeAnalysis.UnconditionalIfStatement" />
<rule ref="Generic.CodeAnalysis.UnnecessaryFinalModifier" />
<rule ref="Generic.CodeAnalysis.UnusedFunctionParameter" />
<rule ref="Generic.CodeAnalysis.UselessOverridingMethod" />
<rule ref="Generic.Commenting.Todo" />
<rule ref="Generic.Commenting.Fixme" />
<rule ref="Generic.ControlStructures.InlineControlStructure" />
<rule ref="Generic.Files.ByteOrderMark" />
<rule ref="Generic.Files.LineEndings" />
<rule ref="Generic.Files.LineLength">
<properties>
<property name="lineLimit" value="120"/>
<property name="absoluteLineLimit" value="0"/>
</properties>
<rule ref="PSR1" />
<rule ref="PSR12" />
<rule ref="Generic.Classes.DuplicateClassName"/>
<rule ref="Generic.CodeAnalysis.EmptyStatement"/>
<rule ref="Generic.CodeAnalysis.ForLoopShouldBeWhileLoop"/>
<rule ref="Generic.CodeAnalysis.ForLoopWithTestFunctionCall"/>
<rule ref="Generic.CodeAnalysis.JumbledIncrementer"/>
<rule ref="Generic.CodeAnalysis.UnconditionalIfStatement"/>
<rule ref="Generic.CodeAnalysis.UnnecessaryFinalModifier"/>
<rule ref="Generic.CodeAnalysis.UnusedFunctionParameter"/>
<rule ref="Generic.CodeAnalysis.UselessOverridingMethod"/>
<rule ref="Generic.Commenting.Todo"/>
<rule ref="Generic.Commenting.Fixme"/>
<rule ref="Generic.ControlStructures.InlineControlStructure"/>
<rule ref="Generic.Files.ByteOrderMark"/>
<rule ref="Generic.Files.LineEndings"/>
<rule ref="Generic.Files.LineLength"/>
<rule ref="Generic.Formatting.DisallowMultipleStatements"/>
<rule ref="Generic.Formatting.MultipleStatementAlignment"/>
<rule ref="Generic.Formatting.NoSpaceAfterCast"/>
<rule ref="Generic.Functions.CallTimePassByReference"/>
<rule ref="Generic.Functions.FunctionCallArgumentSpacing"/>
<rule ref="Generic.Metrics.CyclomaticComplexity"/>
<rule ref="Generic.Metrics.NestingLevel"/>
<rule ref="Generic.NamingConventions.ConstructorName"/>
<rule ref="Generic.NamingConventions.UpperCaseConstantName"/>
<rule ref="Generic.NamingConventions.CamelCapsFunctionName"/>
<rule ref="Generic.PHP.DeprecatedFunctions"/>
<rule ref="Generic.PHP.DisallowShortOpenTag"/>
<rule ref="Generic.PHP.ForbiddenFunctions"/>
<rule ref="Generic.PHP.NoSilencedErrors"/>
<rule ref="Generic.Strings.UnnecessaryStringConcat"/>
<rule ref="Generic.WhiteSpace.DisallowTabIndent"/>
<rule ref="Generic.WhiteSpace.ScopeIndent"/>
<rule ref="MySource.PHP.EvalObjectFactory"/>
<rule ref="MySource.PHP.GetRequestData"/>
<rule ref="MySource.PHP.AjaxNullComparison"/>
<rule ref="PEAR.Classes.ClassDeclaration"/>
<rule ref="PEAR.Commenting.InlineComment"/>
<rule ref="PSR1.Classes.ClassDeclaration"/>
<rule ref="PSR1.Files.SideEffects"/>
<rule ref="PSR2.Classes.ClassDeclaration"/>
<rule ref="PSR2.Classes.PropertyDeclaration"/>
<rule ref="PSR2.ControlStructures.ElseIfDeclaration"/>
<rule ref="PSR2.ControlStructures.SwitchDeclaration"/>
<rule ref="PSR2.Files.EndFileNewline"/>
<rule ref="PSR2.Methods.MethodDeclaration"/>
<rule ref="PSR2.Namespaces.NamespaceDeclaration"/>
<rule ref="PSR2.Namespaces.UseDeclaration"/>
<rule ref="Squiz.PHP.CommentedOutCode"/>
<rule ref="Squiz.PHP.DisallowMultipleAssignments">
<exclude name="Squiz.PHP.DisallowMultipleAssignments.FoundInControlStructure" />
</rule>
<rule ref="Generic.Formatting.DisallowMultipleStatements" />
<rule ref="Generic.Formatting.NoSpaceAfterCast" />
<rule ref="Generic.Functions.CallTimePassByReference" />
<rule ref="Generic.Functions.FunctionCallArgumentSpacing" />
<rule ref="Generic.Metrics.CyclomaticComplexity" />
<rule ref="Generic.Metrics.NestingLevel" />
<rule ref="Generic.NamingConventions.ConstructorName" />
<rule ref="Generic.NamingConventions.UpperCaseConstantName" />
<rule ref="Generic.NamingConventions.CamelCapsFunctionName" />
<rule ref="Generic.PHP.DeprecatedFunctions" />
<rule ref="Generic.PHP.DisallowShortOpenTag" />
<rule ref="Generic.PHP.ForbiddenFunctions" />
<rule ref="Generic.PHP.LowerCaseConstant" />
<rule ref="Generic.PHP.NoSilencedErrors" />
<rule ref="Generic.Strings.UnnecessaryStringConcat" />
<rule ref="Generic.WhiteSpace.DisallowTabIndent" />
<rule ref="Generic.WhiteSpace.ScopeIndent" />
<rule ref="MySource.PHP.EvalObjectFactory" />
<rule ref="MySource.PHP.GetRequestData" />
<rule ref="MySource.PHP.AjaxNullComparison" />
<rule ref="PEAR.Classes.ClassDeclaration" />
<rule ref="PEAR.Commenting.InlineComment" />
<rule ref="PSR1.Classes.ClassDeclaration" />
<rule ref="PSR1.Files.SideEffects" />
<rule ref="Squiz.PHP.CommentedOutCode" />
<rule ref="Squiz.PHP.DisallowSizeFunctionsInLoops" />
<rule ref="Squiz.PHP.DisallowSizeFunctionsInLoops"/>
<rule ref="Squiz.PHP.DiscouragedFunctions">
<properties>
<property name="error" value="true" />
<property name="error" value="true"/>
</properties>
</rule>
<rule ref="Squiz.PHP.Eval" />
<rule ref="Squiz.PHP.GlobalKeyword" />
<rule ref="Squiz.PHP.Heredoc" />
<rule ref="Squiz.PHP.InnerFunctions" />
<rule ref="Squiz.PHP.LowercasePHPFunctions" />
<rule ref="Squiz.PHP.NonExecutableCode" />
<rule ref="Squiz.Scope.MemberVarScope" />
<rule ref="Squiz.Scope.MethodScope" />
<rule ref="Squiz.Scope.StaticThisUsage" />
<rule ref="Squiz.WhiteSpace.MemberVarSpacing" />
<rule ref="Squiz.WhiteSpace.ObjectOperatorSpacing">
<rule ref="Squiz.PHP.Eval"/>
<rule ref="Squiz.PHP.GlobalKeyword"/>
<rule ref="Squiz.PHP.Heredoc"/>
<rule ref="Squiz.PHP.InnerFunctions"/>
<rule ref="Squiz.PHP.LowercasePHPFunctions"/>
<rule ref="Squiz.PHP.NonExecutableCode"/>
<rule ref="Squiz.Scope.MemberVarScope"/>
<rule ref="Squiz.Scope.MethodScope"/>
<rule ref="Squiz.Scope.StaticThisUsage"/>
<rule ref="Squiz.WhiteSpace.LanguageConstructSpacing"/>
<rule ref="Squiz.WhiteSpace.LogicalOperatorSpacing"/>
<rule ref="Squiz.WhiteSpace.MemberVarSpacing">
<properties>
<property name="ignoreNewlines" value="true"/>
<property name="spacingBeforeFirst " value="false"/>
</properties>
</rule>
<rule ref="Squiz.WhiteSpace.OperatorSpacing">
@ -76,12 +88,39 @@
<property name="ignoreNewlines" value="true"/>
</properties>
</rule>
<rule ref="Squiz.WhiteSpace.ScopeKeywordSpacing" />
<rule ref="Squiz.WhiteSpace.SemicolonSpacing" />
<rule ref="Squiz.WhiteSpace.ObjectOperatorSpacing">
<properties>
<property name="ignoreNewlines" value="true"/>
</properties>
</rule>
<rule ref="Squiz.WhiteSpace.ScopeKeywordSpacing"/>
<rule ref="Squiz.WhiteSpace.SemicolonSpacing"/>
<rule ref="Squiz.Commenting.BlockComment">
<exclude name="Squiz.Commenting.BlockComment.WrongStart" />
</rule>
<rule ref="Squiz.Commenting.ClassComment">
<exclude name="Squiz.Commenting.ClassComment.Missing" />
<exclude name="Squiz.Commenting.ClassComment.TagNotAllowed" />
</rule>
<rule ref="Squiz.Commenting.DocCommentAlignment"/>
<rule ref="Squiz.Commenting.EmptyCatchComment"/>
<rule ref="Squiz.Commenting.FunctionComment">
<exclude name="Squiz.Commenting.FunctionComment.MissingParamComment" />
</rule>
<rule ref="Squiz.Commenting.FunctionCommentThrowTag"/>
<rule ref="Squiz.Commenting.InlineComment">
<exclude name="Squiz.Commenting.InlineComment.DocBlock" />
</rule>
<rule ref="Squiz.Commenting.LongConditionClosingComment">
<exclude name="Squiz.Commenting.LongConditionClosingComment.SpacingBefore" />
</rule>
<rule ref="Squiz.Commenting.PostStatementComment"/>
<rule ref="Squiz.Commenting.VariableComment"/>
<rule ref="SlevomatCodingStandard.Namespaces.UnusedUses.UnusedUse" />
<!-- For Laravel migrations -->
<rule ref="PSR1.Classes.ClassDeclaration.MissingNamespace">
<exclude-pattern>*/database/migrations/*</exclude-pattern>
</rule>
</ruleset>

View file

@ -4,13 +4,11 @@ namespace Kwaadpepper\RefreshSitemap\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Log;
use Kwaadpepper\RefreshSitemap\Exceptions\SitemapException;
use Kwaadpepper\RefreshSitemap\Lib\SitemapGenerator;
class RefreshSitemap extends Command
{
/**
* The name and signature of the console command.
*
@ -28,9 +26,9 @@ class RefreshSitemap extends Command
/**
* Execute the console command.
*
* @return void
* @return integer
*/
public function handle()
public function handle(): int
{
$sitemapGenerator = new SitemapGenerator();
@ -52,12 +50,14 @@ class RefreshSitemap extends Command
} catch (SitemapException $e) {
$this->error('An error occured while generating sitemap');
$this->error($e->getMessage());
Log::error($e->getMessage());
\report($e);
if (config('app.debug')) {
dump($e);
}
}
}//end try
$this->info('A new sitemap.xml was generated');
return 0;
}
}

View file

@ -2,11 +2,10 @@
namespace Kwaadpepper\RefreshSitemap\Exceptions;
use Exception;
/**
* Sitemap Excception for internal use
* @inheritDoc
*/
class SitemapException extends Exception
class SitemapException extends \Exception
{
}

View file

@ -19,7 +19,12 @@ class GenerateSitemap implements ShouldQueue
use Queueable;
use SerializesModels;
public function handle()
/**
* Execute the job.
*
* @return void
*/
public function handle(): void
{
$sitemapGenerator = new SitemapGenerator();
Log::debug('Generating Sitemap..');
@ -32,7 +37,7 @@ class GenerateSitemap implements ShouldQueue
} catch (SitemapException $e) {
Log::error('An error occured while generating sitemap');
Log::error($e->getMessage());
Log::debug($e);
\report($e);
}
Log::debug('A new sitemap.xml was generated');
}

View file

@ -11,13 +11,11 @@ use Kwaadpepper\RefreshSitemap\Exceptions\SitemapException;
use Kwaadpepper\RefreshSitemap\Traits\SitemapRouteBinder;
use Kwaadpepper\RefreshSitemap\Traits\SitemapRouteConditions;
use Kwaadpepper\RefreshSitemap\Traits\SitemapRouteInfos;
use ReflectionClass;
use Spatie\Sitemap\Sitemap;
use Spatie\Sitemap\Tags\Url;
final class SitemapGenerator
{
use SitemapRouteBinder;
use SitemapRouteConditions;
use SitemapRouteInfos;
@ -25,6 +23,9 @@ final class SitemapGenerator
/** @var \Spatie\Sitemap\Sitemap */
private $siteMap = null;
/**
* SitemapGenerator
*/
public function __construct()
{
$this->siteMap = Sitemap::create();
@ -34,7 +35,7 @@ final class SitemapGenerator
* Generate the sitemap Xml
*
* @return string An xml file
* @throws \Kwaadpepper\RefreshSitemap\Exceptions\SitemapException
* @throws \Kwaadpepper\RefreshSitemap\Exceptions\SitemapException If generating fails.
*/
public function generateSiteMap(): string
{
@ -47,8 +48,7 @@ final class SitemapGenerator
*
* @param string $path
* @return \Spatie\Sitemap\Sitemap
* @throws \Kwaadpepper\RefreshSitemap\Exceptions\SitemapException
* @throws \Illuminate\Contracts\Container\BindingResolutionException
* @throws \Kwaadpepper\RefreshSitemap\Exceptions\SitemapException If generating fails.
*/
public function writeToFile(string $path): Sitemap
{
@ -62,7 +62,7 @@ final class SitemapGenerator
* Actually generate the sitemap
*
* @return void
* @throws \Kwaadpepper\RefreshSitemap\Exceptions\SitemapException
* @throws \Kwaadpepper\RefreshSitemap\Exceptions\SitemapException If generating fails.
*/
private function generate(): void
{
@ -70,6 +70,10 @@ final class SitemapGenerator
$this->assertRouteBinderIsCorrect();
$routeCollection = Route::getRoutes();
/**
* @var array<array<int,string|float>>
*/
$generatedUris = [];
/** @var \Illuminate\Routing\Route $route */
@ -86,15 +90,17 @@ final class SitemapGenerator
}
foreach ($generatedUris as $smRules) {
$this->siteMap->add(Url::create($smRules[0])
$this->siteMap->add(Url::create(\strval($smRules[0]))
->setLastModificationDate(Carbon::yesterday())
->setChangeFrequency($smRules[1])
->setPriority($smRules[2]));
->setChangeFrequency(\strval($smRules[1]))
->setPriority(\floatval($smRules[2])));
}
}
/**
* Init variables from configuration
*
* @return void
*/
private static function initConfig(): void
{
@ -103,29 +109,37 @@ final class SitemapGenerator
self::initConfigInfo();
}
private function handleRoute(RoutingRoute $route, array &$generatedUris)
/**
* Undocumented function
*
* @param \Illuminate\Routing\Route $route
* @param array<array[string,string,float]> $generatedUris
* @return void
*/
private function handleRoute(\Illuminate\Routing\Route $route, array &$generatedUris): void
{
/** @var array to be populated with models from DB to generate a route */
$rParams = [];
/** @var \array [lluminate\Routing\Route::signatureParameters] parameters signature from the controller */
/** @var array<\ReflectionParameter> parameters signature from the controller */
$params = $route->signatureParameters();
/** @var \array [Illuminate\Routing\Route::parameterNames] parameters name from the registered route */
/** @var array<string> parameters name from the registered route */
$pNames = $route->parameterNames();
$hasModels = false;
$this->handleParams($params, $pNames, $route, $rParams, $hasModels);
// If the route has no dynamic models as parameters
// If the route has no dynamic models as parameters.
if (!count($params) or !$hasModels) {
$rName = $route->getName();
$rName = $route->getName();
$generatedUris[] = [
route($route->getName()),
self::getRouteFrequency($rName),
self::getRoutePriority($rName)
];
} else { // If the route has dynamic models as parameters
} else {
// If the route has dynamic models as parameters.
$this->genRoute($route, $generatedUris, $rParams);
}
}
@ -133,37 +147,34 @@ final class SitemapGenerator
/**
* Handle all route params
*
* @param array $params
* @param array|null $pNames
* @param \Illuminate\Routing\Route $route
* @param array $rParams
* @param bool $hasModels
* @param array<\ReflectionParameter> $params
* @param array<string>|null $pNames
* @param \Illuminate\Routing\Route $route
* @param array<string,\Illuminate\Database\Eloquent\Model,\Kwaadpepper\Enum\BaseEnumRoutable> $rParams
* @param boolean $hasModels
* @return void
* @throws \Illuminate\Contracts\Container\BindingResolutionException
* @throws \ReflectionException
* @throws \InvalidArgumentException
* @throws \Kwaadpepper\RefreshSitemap\Exceptions\SitemapException
* @throws SitemapException If a class on a route is not handled.
*/
private function handleParams(
array $params,
array $pNames = null,
RoutingRoute $route,
\Illuminate\Routing\Route $route,
array &$rParams,
bool &$hasModels
) {
foreach ($params as $param) {
/** @var ReflectionClass|null $name */
/** @var \ReflectionClass|null $name */
$name = $param->getType() && !$param->getType()->isBuiltin()
? new ReflectionClass($param->getType()->getName())
? new \ReflectionClass($param->getType()->getName())
: null;
/** @var string $pName $parameter name on route uri */
$pName = '';
// If the route has parameters and the controller accepts it
// If the route has parameters and the controller accepts it.
if (count($pNames) and \array_key_exists($param->getPosition(), $pNames)) {
// Get the controller parameter name for the route
// Get the controller parameter name for the route.
$pName = $pNames[$param->getPosition()];
}
@ -179,14 +190,14 @@ final class SitemapGenerator
));
}
// If We have a custom binder for this route
// If We have a custom binder for this route.
if ($this->hasRouteBinderParam($route, $pName)) {
$hasModels = true;
$this->processWithRouteBinderParam($rParams, $route, $pName);
continue;
}
// If This route takes a model as param
// If This route takes a model as param.
if ($name and $name->isSubclassOf(Model::class)) {
$hasModels = true;
/** @var \string */
@ -194,15 +205,17 @@ final class SitemapGenerator
$this->setParamsForModel($rParams, $modelClassName, $pName);
continue;
}
}
} //end foreach
}
/**
* Process route with binderParam
*
* @param array $rParams
* @param RoutingRoute $route
* @param string $pName
* @param string $pName
* @return void
* @throws SitemapException If a class on a route is not handled.
*/
private function processWithRouteBinderParam(array &$rParams, RoutingRoute $route, string $pName)
{
@ -212,7 +225,7 @@ final class SitemapGenerator
$modelClassName = $o[0];
/** @var \string */
$routeParamName = $o[1];
$rfLCls = (new ReflectionClass($modelClassName));
$rfLCls = (new \ReflectionClass($modelClassName));
switch (true) {
case $rfLCls->isSubclassOf(Model::class):
@ -231,7 +244,7 @@ final class SitemapGenerator
/**
* Set route param Array for Enums
*
* @param array $rParams
* @param array $rParams
* @param string $enumClassName
* @param string $pName
* @return void
@ -249,7 +262,7 @@ final class SitemapGenerator
/**
* Set route param Array for Models
*
* @param array $rParams
* @param array $rParams
* @param string $modelClassName
* @param string $pName
* @param string $routeParamName
@ -261,15 +274,15 @@ final class SitemapGenerator
string $pName,
string $routeParamName = null
) {
$i = 0;
$i = 0;
$limit = 10;
/** @var string $modelTable */
$modelTable = (new ReflectionClass($modelClassName))->newInstanceWithoutConstructor()->getTable();
$q = $modelClassName::query();
$modelTable = (new \ReflectionClass($modelClassName))->newInstanceWithoutConstructor()->getTable();
$q = $modelClassName::query();
self::queryConditions($q, $modelTable);
do {
$results = $q->offset($i * $limit)->limit($limit)->get();
$length = count($results);
$length = count($results);
$results->map(function (Model $model) use (&$rParams, $pName, $routeParamName) {
if (!array_key_exists($pName, $rParams)) {
$rParams[$pName] = [];
@ -283,9 +296,9 @@ final class SitemapGenerator
/**
* Recursively generate routes for all params
*
* @param RoutingRoute $route
* @param array $generatedUris
* @param array $params
* @param RoutingRoute $route
* @param array<array[string,string,float]> $generatedUris
* @param array $params
* @return void
*/
private function genRoute(RoutingRoute $route, array &$generatedUris, array $params)
@ -301,7 +314,7 @@ final class SitemapGenerator
$filtered = array_key_last($params) === $pName ? true : false;
}
if ($filtered) {
$routeName = $route->getName();
$routeName = $route->getName();
$generatedUris[] = [
route($routeName, $params),
self::getRouteFrequency($routeName),

View file

@ -4,21 +4,17 @@ namespace Kwaadpepper\RefreshSitemap;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Support\ServiceProvider;
use Kwaadpepper\RefreshSitemap\Console\Commands\RefreshSitemap;
use Kwaadpepper\RefreshSitemap\Jobs\GenerateSitemap;
class RefreshSitemapServiceProvider extends ServiceProvider
{
protected $commands = [
'Kwaadpepper\RefreshSitemap\Console\Commands\RefreshSitemap'
];
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
public function boot(): void
{
$this->publishes([
__DIR__ . '/../config' => \config_path(),
@ -34,12 +30,19 @@ class RefreshSitemapServiceProvider extends ServiceProvider
}
}
public function register()
/**
* Register any application services.
*
* @return void
*/
public function register(): void
{
$this->mergeConfigFrom(
\sprintf('%s/../config/refresh-sitemap.php', __DIR__),
'refresh-sitemap'
);
$this->commands($this->commands);
$this->commands([
RefreshSitemap::class
]);
}
}

View file

@ -3,7 +3,6 @@
namespace Kwaadpepper\RefreshSitemap\Traits;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Routing\Route as RoutingRoute;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\Schema;
use Kwaadpepper\Enum\BaseEnumRoutable;
@ -12,15 +11,18 @@ use ReflectionClass;
trait SitemapRouteBinder
{
/**
* List of route with its corresponding parameter
* arguments and models
*
* @var array<string,array<string,array<int,string>>>
*/
private static $routesBinder = [];
/**
* Init variables from configuration
*
* @return void
*/
private static function initConfigBinder(): void
{
@ -30,10 +32,10 @@ trait SitemapRouteBinder
/**
* Check if $route exists in routesBinder
*
* @param RoutingRoute $route
* @param \Illuminate\Routing\Route $route
* @return boolean
*/
private static function hasRouteBinder(RoutingRoute $route): bool
private static function hasRouteBinder(\Illuminate\Routing\Route $route): bool
{
return array_key_exists($route->getName(), self::$routesBinder);
}
@ -41,11 +43,11 @@ trait SitemapRouteBinder
/**
* Check if $route exists in routesBinder and has $param
*
* @param RoutingRoute $route
* @param string $param
* @param \Illuminate\Routing\Route $route
* @param string $param
* @return boolean
*/
private static function hasRouteBinderParam(RoutingRoute $route, string $param): bool
private static function hasRouteBinderParam(\Illuminate\Routing\Route $route, string $param): bool
{
if (self::hasRouteBinder($route)) {
return array_key_exists($param, self::getRouteBinder($route));
@ -56,10 +58,10 @@ trait SitemapRouteBinder
/**
* Get the routeBinder
*
* @param RoutingRoute $route
* @param \Illuminate\Routing\Route $route
* @return array
*/
private static function getRouteBinder(RoutingRoute $route): array
private static function getRouteBinder(\Illuminate\Routing\Route $route): array
{
return self::$routesBinder[$route->getName()] ?? [];
}
@ -67,11 +69,11 @@ trait SitemapRouteBinder
/**
* Get the routeBinder param
*
* @param RoutingRoute $route
* @param string $param
* @param \Illuminate\Routing\Route $route
* @param string $param
* @return array
*/
private static function getRouteBinderParam(RoutingRoute $route, string $param): array
private static function getRouteBinderParam(\Illuminate\Routing\Route $route, string $param): array
{
return self::$routesBinder[$route->getName()][$param];
}
@ -79,10 +81,10 @@ trait SitemapRouteBinder
/**
* Assert that routeBinder is correct
*
* @throws SitemapException
* @return void
* @throws SitemapException If a parameter bind is incorrect, or un handled.
*/
private static function assertRouteBinderIsCorrect()
private static function assertRouteBinderIsCorrect(): void
{
/** @var \Illuminate\Routing\RouteCollection */
$routeCollection = Route::getRoutes();
@ -103,11 +105,35 @@ trait SitemapRouteBinder
]
));
}
$rfCls = (new ReflectionClass($p[0]))->newInstanceWithoutConstructor();
if (is_subclass_of($rfCls, BaseEnumRoutable::class)) {
return;
}
if (!is_subclass_of($rfCls, Model::class)) {
try {
$rfCls = (new ReflectionClass($p[0]))->newInstanceWithoutConstructor();
if (is_subclass_of($rfCls, BaseEnumRoutable::class)) {
return;
}
if (!is_subclass_of($rfCls, Model::class)) {
throw new SitemapException(trans(
// phpcs:ignore Generic.Files.LineLength.TooLong
'Route ":routeName" parameter ":parameterName" first element must be a child of ":className"',
[
'routeName' => $routeName,
'parameterName' => $pName,
'className' => Model::class
]
));
}
if (!Schema::hasColumn($rfCls->getTable(), $p[1])) {
throw new SitemapException(\trans(
// phpcs:ignore Generic.Files.LineLength.TooLong
'":routeName" parameter ":parameterName" second element ":value" must refer to and existing database column of ":column"',
[
'routeName' => $routeName,
'parameterName' => $pName,
'value' => $p[1],
'column' => $p[0]
]
));
}
} catch (\ReflectionException $e) {
throw new SitemapException(trans(
'Route ":routeName" parameter ":parameterName" first element must be a child of ":className"',
[
@ -116,20 +142,8 @@ trait SitemapRouteBinder
'className' => Model::class
]
));
}
if (!Schema::hasColumn($rfCls->getTable(), $p[1])) {
throw new SitemapException(\trans(
// phpcs:ignore Generic.Files.LineLength.TooLong
'":routeName" parameter ":parameterName" second element ":value" must refer to and existing database column of ":column"',
[
'routeName' => $routeName,
'parameterName' => $pName,
'value' => $p[1],
'column' => $p[0]
]
));
}
}
}
}//end try
}//end foreach
}//end foreach
}
}

View file

@ -8,10 +8,11 @@ use Illuminate\Support\Facades\Schema;
trait SitemapRouteConditions
{
/**
* List eloquent condition to decide whether
* a route should appear in the sitemap or not
*
* @var array<string,string>
*/
private static $queryConditions = [];
@ -19,25 +20,26 @@ trait SitemapRouteConditions
* List of routes that should be ignored
* when generating sitemap
*
* @var array
* @var array<string>
*/
private static $ignoreRoutes = [];
/**
* Init variables from configuration
*
* @return void
*/
private static function initConfigConditions()
private static function initConfigConditions(): void
{
self::$ignoreRoutes = \config('refresh-sitemap.ignoreRoutes', self::$ignoreRoutes);
self::$ignoreRoutes = \config('refresh-sitemap.ignoreRoutes', self::$ignoreRoutes);
self::$queryConditions = \config('refresh-sitemap.queryConditions', self::$queryConditions);
}
/**
* Add query conditions using the config table
* @param \Illuminate\Database\Eloquent\Builder $query
* @param string $modelTable
* @param string $modelTable
* @return void
* @throws \InvalidArgumentException
*/
private static function queryConditions(Builder &$query, string $modelTable): void
{

View file

@ -6,15 +6,39 @@ use Spatie\Sitemap\Tags\Url;
trait SitemapRouteInfos
{
/**
* Route priority
*
* @var float
*/
private static $routeDefaultPriority = 0.5;
/**
* Route de fault frequency
*
* @var string
*/
private static $routeDefaultFrequency = Url::CHANGE_FREQUENCY_DAILY;
/**
* Route priorities
*
* @var array<string,float>
*/
private static $routePriorities = [];
/**
* Route frequencies
*
* @var array<string,string>
*/
private static $routeFrequencies = [];
/**
* Available route frequencies
*
* @var array<string>
*/
private static $existingRoutefreqencies = [
Url::CHANGE_FREQUENCY_ALWAYS,
Url::CHANGE_FREQUENCY_HOURLY,
@ -27,20 +51,21 @@ trait SitemapRouteInfos
/**
* Init variables from configuration
*
* @return void
*/
private static function initConfigInfo(): void
{
self::$routeDefaultPriority = \config('refresh-sitemap.routeDefaultPriority', self::$routeDefaultPriority);
self::$routeDefaultPriority = \config('refresh-sitemap.routeDefaultPriority', self::$routeDefaultPriority);
self::$routeDefaultFrequency = \config('refresh-sitemap.routeDefaultFrequency', self::$routeDefaultFrequency);
self::$routePriorities = \config('refresh-sitemap.routePriorities', self::$routePriorities);
self::$routeFrequencies = \config('refresh-sitemap.routeFrequencies', self::$routeFrequencies);
self::$routePriorities = \config('refresh-sitemap.routePriorities', self::$routePriorities);
self::$routeFrequencies = \config('refresh-sitemap.routeFrequencies', self::$routeFrequencies);
}
/**
* Get a route priority
* @param string $routeName
* @return string
* @throws \Illuminate\Contracts\Container\BindingResolutionException
*/
private static function getRouteFrequency(string $routeName): string
{
@ -57,13 +82,12 @@ trait SitemapRouteInfos
* Get a route priority
* @param string $routeName
* @return float
* @throws \Illuminate\Contracts\Container\BindingResolutionException
*/
private static function getRoutePriority(string $routeName): float
{
foreach (self::$routePriorities as $rName => $rPriority) {
if (\strpos($routeName, $rName) === 0) {
// Is a float between 0 and 1 ? $rPriority : $routeDefaultPriority
// Is a float between 0 and 1 ? $rPriority : $routeDefaultPriority .
$rPrio = \is_numeric($rPriority) ? \floatval($rPriority) : self::$routeDefaultPriority;
return (($rPrio <=> 0) === 1 and ($rPrio <=> 1) === -1) ? $rPrio : self::$routeDefaultPriority;
}