ldc-refresh-sitemap/src/Lib/SitemapGenerator.php

326 lines
11 KiB
PHP
Raw Normal View History

2021-08-31 22:28:29 +02:00
<?php
namespace Kwaadpepper\RefreshSitemap\Lib;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Routing\Route as RoutingRoute;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Route;
use Kwaadpepper\Enum\BaseEnumRoutable;
use Kwaadpepper\RefreshSitemap\Exceptions\SitemapException;
use Kwaadpepper\RefreshSitemap\Traits\SitemapRouteBinder;
use Kwaadpepper\RefreshSitemap\Traits\SitemapRouteConditions;
use Kwaadpepper\RefreshSitemap\Traits\SitemapRouteInfos;
use Spatie\Sitemap\Sitemap;
use Spatie\Sitemap\Tags\Url;
final class SitemapGenerator
{
use SitemapRouteBinder;
use SitemapRouteConditions;
use SitemapRouteInfos;
/** @var \Spatie\Sitemap\Sitemap */
private $siteMap = null;
2022-06-10 17:38:34 +02:00
/**
* SitemapGenerator
*/
2021-08-31 22:28:29 +02:00
public function __construct()
{
$this->siteMap = Sitemap::create();
}
/**
* Generate the sitemap Xml
*
* @return string An xml file
2022-06-10 17:38:34 +02:00
* @throws \Kwaadpepper\RefreshSitemap\Exceptions\SitemapException If generating fails.
2021-08-31 22:28:29 +02:00
*/
public function generateSiteMap(): string
{
$this->generate();
return $this->siteMap->render();
}
/**
* Write sitemap into a file
*
* @param string $path
* @return \Spatie\Sitemap\Sitemap
2022-06-10 17:38:34 +02:00
* @throws \Kwaadpepper\RefreshSitemap\Exceptions\SitemapException If generating fails.
2021-08-31 22:28:29 +02:00
*/
public function writeToFile(string $path): Sitemap
{
$this->generate();
return $this->siteMap->writeToFile($path);
}
// --- PRIVATE METHODS ---
/**
* Actually generate the sitemap
*
* @return void
2022-06-10 17:38:34 +02:00
* @throws \Kwaadpepper\RefreshSitemap\Exceptions\SitemapException If generating fails.
2021-08-31 22:28:29 +02:00
*/
private function generate(): void
{
self::initConfig();
$this->assertRouteBinderIsCorrect();
$routeCollection = Route::getRoutes();
2022-06-10 17:38:34 +02:00
/**
* @var array<array<int,string|float>>
*/
2021-08-31 22:28:29 +02:00
$generatedUris = [];
/** @var \Illuminate\Routing\Route $route */
foreach ($routeCollection as $route) {
if (self::routeShouldBeIgnored($route)) {
continue;
}
if (!self::routeHandlesGetMethod($route)) {
continue;
}
$this->handleRoute($route, $generatedUris);
}
foreach ($generatedUris as $smRules) {
2022-06-10 17:38:34 +02:00
$this->siteMap->add(Url::create(\strval($smRules[0]))
2021-08-31 22:28:29 +02:00
->setLastModificationDate(Carbon::yesterday())
2022-06-10 17:38:34 +02:00
->setChangeFrequency(\strval($smRules[1]))
->setPriority(\floatval($smRules[2])));
2021-08-31 22:28:29 +02:00
}
}
/**
* Init variables from configuration
2022-06-10 17:38:34 +02:00
*
* @return void
2021-08-31 22:28:29 +02:00
*/
private static function initConfig(): void
{
self::initConfigBinder();
self::initConfigConditions();
self::initConfigInfo();
}
2022-06-10 17:38:34 +02:00
/**
* 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
2021-08-31 22:28:29 +02:00
{
/** @var array to be populated with models from DB to generate a route */
$rParams = [];
2022-06-10 17:38:34 +02:00
/** @var array<\ReflectionParameter> parameters signature from the controller */
2021-08-31 22:28:29 +02:00
$params = $route->signatureParameters();
2022-06-10 17:38:34 +02:00
/** @var array<string> parameters name from the registered route */
2021-08-31 22:28:29 +02:00
$pNames = $route->parameterNames();
$hasModels = false;
$this->handleParams($params, $pNames, $route, $rParams, $hasModels);
2022-06-10 17:38:34 +02:00
// If the route has no dynamic models as parameters.
2021-08-31 22:28:29 +02:00
if (!count($params) or !$hasModels) {
2022-06-10 17:38:34 +02:00
$rName = $route->getName();
2021-08-31 22:28:29 +02:00
$generatedUris[] = [
route($route->getName()),
self::getRouteFrequency($rName),
self::getRoutePriority($rName)
];
2022-06-10 17:38:34 +02:00
} else {
// If the route has dynamic models as parameters.
2021-08-31 22:28:29 +02:00
$this->genRoute($route, $generatedUris, $rParams);
}
}
/**
* Handle all route params
*
2022-06-10 17:38:34 +02:00
* @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
2021-08-31 22:28:29 +02:00
* @return void
2022-06-10 17:38:34 +02:00
* @throws SitemapException If a class on a route is not handled.
2021-08-31 22:28:29 +02:00
*/
private function handleParams(
array $params,
array $pNames = null,
2022-06-10 17:38:34 +02:00
\Illuminate\Routing\Route $route,
2021-08-31 22:28:29 +02:00
array &$rParams,
bool &$hasModels
) {
foreach ($params as $param) {
2022-06-10 17:38:34 +02:00
/** @var \ReflectionClass|null $name */
2021-08-31 22:28:29 +02:00
$name = $param->getType() && !$param->getType()->isBuiltin()
2022-06-10 17:38:34 +02:00
? new \ReflectionClass($param->getType()->getName())
2021-08-31 22:28:29 +02:00
: null;
/** @var string $pName $parameter name on route uri */
$pName = '';
2022-06-10 17:38:34 +02:00
// If the route has parameters and the controller accepts it.
2021-08-31 22:28:29 +02:00
if (count($pNames) and \array_key_exists($param->getPosition(), $pNames)) {
2022-06-10 17:38:34 +02:00
// Get the controller parameter name for the route.
2021-08-31 22:28:29 +02:00
$pName = $pNames[$param->getPosition()];
}
if (config('app.debug')) {
dump(\trans(
'Route name : :routeName, Param [type: :typeName, name: :paramName, binder: :hasBinder]',
[
'routeName' => $route->getName(),
'typeName' => $name ? $name->getName() : '',
'paramName' => $pName,
'hasBinder' => $this->hasRouteBinderParam($route, $pName) ? 'true' : 'false'
]
));
}
2022-06-10 17:38:34 +02:00
// If We have a custom binder for this route.
2021-08-31 22:28:29 +02:00
if ($this->hasRouteBinderParam($route, $pName)) {
$hasModels = true;
$this->processWithRouteBinderParam($rParams, $route, $pName);
continue;
}
2022-06-10 17:38:34 +02:00
// If This route takes a model as param.
2021-08-31 22:28:29 +02:00
if ($name and $name->isSubclassOf(Model::class)) {
$hasModels = true;
/** @var \string */
$modelClassName = $name->getName();
$this->setParamsForModel($rParams, $modelClassName, $pName);
continue;
}
2022-06-10 17:38:34 +02:00
} //end foreach
2021-08-31 22:28:29 +02:00
}
/**
* Process route with binderParam
*
2022-06-10 17:38:34 +02:00
* @param array $rParams
2021-08-31 22:28:29 +02:00
* @param RoutingRoute $route
2022-06-10 17:38:34 +02:00
* @param string $pName
2021-08-31 22:28:29 +02:00
* @return void
2022-06-10 17:38:34 +02:00
* @throws SitemapException If a class on a route is not handled.
2021-08-31 22:28:29 +02:00
*/
private function processWithRouteBinderParam(array &$rParams, RoutingRoute $route, string $pName)
{
$o = $this->getRouteBinderParam($route, $pName);
/** @var \string */
$modelClassName = $o[0];
/** @var \string */
$routeParamName = $o[1];
2022-06-10 17:38:34 +02:00
$rfLCls = (new \ReflectionClass($modelClassName));
2021-08-31 22:28:29 +02:00
switch (true) {
case $rfLCls->isSubclassOf(Model::class):
$this->setParamsForModel($rParams, $modelClassName, $pName, $routeParamName);
break;
case $rfLCls->isSubclassOf(BaseEnumRoutable::class):
$this->setParamForEnum($rParams, $rfLCls->getName(), $pName);
break;
default:
throw new SitemapException(trans('Unhandled class type :className', [
'className' => $rfLCls->getName()
]));
}
}
/**
* Set route param Array for Enums
*
2022-06-10 17:38:34 +02:00
* @param array $rParams
2021-08-31 22:28:29 +02:00
* @param string $enumClassName
* @param string $pName
* @return void
*/
private function setParamForEnum(array &$rParams, string $enumClassName, string $pName)
{
foreach (forward_static_call(sprintf('%s::toArray', $enumClassName)) as $enum) {
if (!array_key_exists($pName, $rParams)) {
$rParams[$pName] = [];
}
$rParams[$pName][] = $enum->value;
}
}
/**
* Set route param Array for Models
*
2022-06-10 17:38:34 +02:00
* @param array $rParams
2021-08-31 22:28:29 +02:00
* @param string $modelClassName
* @param string $pName
* @param string $routeParamName
* @return void
*/
private function setParamsForModel(
array &$rParams,
string $modelClassName,
string $pName,
string $routeParamName = null
) {
2022-06-10 17:38:34 +02:00
$i = 0;
2021-08-31 22:28:29 +02:00
$limit = 10;
/** @var string $modelTable */
2022-06-10 17:38:34 +02:00
$modelTable = (new \ReflectionClass($modelClassName))->newInstanceWithoutConstructor()->getTable();
$q = $modelClassName::query();
2021-08-31 22:28:29 +02:00
self::queryConditions($q, $modelTable);
do {
$results = $q->offset($i * $limit)->limit($limit)->get();
2022-06-10 17:38:34 +02:00
$length = count($results);
2021-08-31 22:28:29 +02:00
$results->map(function (Model $model) use (&$rParams, $pName, $routeParamName) {
if (!array_key_exists($pName, $rParams)) {
$rParams[$pName] = [];
}
$rParams[$pName][] = $routeParamName ? $model[$routeParamName] : $model;
});
$i++;
} while ($length);
}
/**
* Recursively generate routes for all params
*
2022-06-10 17:38:34 +02:00
* @param RoutingRoute $route
* @param array<array[string,string,float]> $generatedUris
* @param array $params
2021-08-31 22:28:29 +02:00
* @return void
*/
private function genRoute(RoutingRoute $route, array &$generatedUris, array $params)
{
$filtered = false;
foreach ($params as $pName => $param) {
if (is_array($param)) {
collect($param)->map(function ($p) use ($route, &$generatedUris, $params, $pName) {
$this->genRoute($route, $generatedUris, array_merge($params, [$pName => $p]));
});
return;
}
$filtered = array_key_last($params) === $pName ? true : false;
}
if ($filtered) {
2022-06-10 17:38:34 +02:00
$routeName = $route->getName();
2021-08-31 22:28:29 +02:00
$generatedUris[] = [
route($routeName, $params),
self::getRouteFrequency($routeName),
self::getRoutePriority($routeName)
];
}
}
}