Refactored tracking actions

This commit is contained in:
Alejandro Celaya
2021-07-15 13:28:31 +02:00
parent fe5460e0c5
commit 265e8cdeaf
8 changed files with 34 additions and 37 deletions

View File

@@ -7,33 +7,27 @@ namespace Shlinkio\Shlink\Core\Action;
use Fig\Http\Message\RequestMethodInterface;
use Mezzio\Router\Middleware\ImplicitHeadMiddleware;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Psr\Log\LoggerInterface;
use Psr\Log\NullLogger;
use Shlinkio\Shlink\Core\Entity\ShortUrl;
use Shlinkio\Shlink\Core\Exception\ShortUrlNotFoundException;
use Shlinkio\Shlink\Core\Model\ShortUrlIdentifier;
use Shlinkio\Shlink\Core\Model\Visitor;
use Shlinkio\Shlink\Core\Options\TrackingOptions;
use Shlinkio\Shlink\Core\Service\ShortUrl\ShortUrlResolverInterface;
use Shlinkio\Shlink\Core\ShortUrl\Helper\ShortUrlRedirectionBuilderInterface;
use Shlinkio\Shlink\Core\Visit\VisitsTrackerInterface;
use function array_key_exists;
abstract class AbstractTrackingAction implements MiddlewareInterface, RequestMethodInterface
{
private LoggerInterface $logger;
public function __construct(
private ShortUrlResolverInterface $urlResolver,
private VisitsTrackerInterface $visitTracker,
private ShortUrlRedirectionBuilderInterface $redirectionBuilder,
private TrackingOptions $trackingOptions,
?LoggerInterface $logger = null
) {
$this->logger = $logger ?? new NullLogger();
}
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
@@ -48,9 +42,8 @@ abstract class AbstractTrackingAction implements MiddlewareInterface, RequestMet
$this->visitTracker->track($shortUrl, Visitor::fromRequest($request));
}
return $this->createSuccessResp($this->redirectionBuilder->buildShortUrlRedirect($shortUrl, $query));
return $this->createSuccessResp($shortUrl, $request);
} catch (ShortUrlNotFoundException $e) {
$this->logger->warning('An error occurred while tracking short code. {e}', ['e' => $e]);
return $this->createErrorResp($request, $handler);
}
}
@@ -66,10 +59,13 @@ abstract class AbstractTrackingAction implements MiddlewareInterface, RequestMet
return $disableTrackParam === null || ! array_key_exists($disableTrackParam, $query);
}
abstract protected function createSuccessResp(string $longUrl): ResponseInterface;
abstract protected function createErrorResp(
abstract protected function createSuccessResp(
ShortUrl $shortUrl,
ServerRequestInterface $request,
RequestHandlerInterface $handler,
): ResponseInterface;
protected function createErrorResp(ServerRequestInterface $request, RequestHandlerInterface $handler): Response
{
return $handler->handle($request);
}
}