60 lines
1.9 KiB
PHP
60 lines
1.9 KiB
PHP
<?php
|
|
|
|
namespace IriksIT\Manager\Modules\Statistics;
|
|
|
|
use Closure;
|
|
use IriksIT\Manager\Facades\Manager;
|
|
use IriksIT\Manager\Models\Post;
|
|
|
|
/**
|
|
* Which addresses count as a page of the site. Only these are written to the statistics, so a
|
|
* visitor (or a script) cannot fill them with made-up addresses. The default list is the config
|
|
* (`manager.statistics.pages`, plus the posts under `manager.statistics.posts_path` when the
|
|
* posts module is on); a site with more kinds of pages adds a resolver of its own.
|
|
*/
|
|
final class CountedPages
|
|
{
|
|
/** @var list<Closure(string): (array{path: string, post_id: int|null}|null)> */
|
|
private array $resolvers = [];
|
|
|
|
/**
|
|
* @param Closure(string): (array{path: string, post_id: int|null}|null) $resolver gets a path like `/about`, returns the page or null
|
|
*/
|
|
public function register(Closure $resolver): void
|
|
{
|
|
$this->resolvers[] = $resolver;
|
|
}
|
|
|
|
/** @return array{path: string, post_id: int|null}|null */
|
|
public function resolve(string $path): ?array
|
|
{
|
|
$pages = array_map(fn (string $page) => '/'.trim($page, '/'), (array) config('manager.statistics.pages', ['/']));
|
|
|
|
if (in_array($path, $pages, true)) {
|
|
return ['path' => $path, 'post_id' => null];
|
|
}
|
|
|
|
$postsPath = config('manager.statistics.posts_path');
|
|
|
|
if (is_string($postsPath) && $postsPath !== '' && Manager::enabled('posts')) {
|
|
$prefix = '/'.trim($postsPath, '/').'/';
|
|
|
|
if (str_starts_with($path, $prefix)) {
|
|
$post = Post::query()->published()->where('slug', substr($path, strlen($prefix)))->first();
|
|
|
|
return $post instanceof Post ? ['path' => $path, 'post_id' => $post->id] : null;
|
|
}
|
|
}
|
|
|
|
foreach ($this->resolvers as $resolver) {
|
|
$page = $resolver($path);
|
|
|
|
if ($page !== null) {
|
|
return $page;
|
|
}
|
|
}
|
|
|
|
return null;
|
|
}
|
|
}
|