Extracted logic to stringify ShortUrls to its own service

This commit is contained in:
Alejandro Celaya
2021-02-01 22:55:52 +01:00
parent 01aebd90d5
commit 9cddedcdba
28 changed files with 215 additions and 135 deletions

View File

@@ -0,0 +1,36 @@
<?php
declare(strict_types=1);
namespace Shlinkio\Shlink\Core\ShortUrl\Helper;
use Laminas\Diactoros\Uri;
use Shlinkio\Shlink\Core\Entity\ShortUrl;
class ShortUrlStringifier implements ShortUrlStringifierInterface
{
private array $domainConfig;
public function __construct(array $domainConfig)
{
$this->domainConfig = $domainConfig;
}
public function stringify(ShortUrl $shortUrl): string
{
return (new Uri())->withPath($shortUrl->getShortCode())
->withScheme($this->domainConfig['schema'] ?? 'http')
->withHost($this->resolveDomain($shortUrl))
->__toString();
}
private function resolveDomain(ShortUrl $shortUrl): string
{
$domain = $shortUrl->getDomain();
if ($domain === null) {
return $this->domainConfig['hostname'] ?? '';
}
return $domain->getAuthority();
}
}

View File

@@ -0,0 +1,12 @@
<?php
declare(strict_types=1);
namespace Shlinkio\Shlink\Core\ShortUrl\Helper;
use Shlinkio\Shlink\Core\Entity\ShortUrl;
interface ShortUrlStringifierInterface
{
public function stringify(ShortUrl $shortUrl): string;
}

View File

@@ -0,0 +1,52 @@
<?php
declare(strict_types=1);
namespace Shlinkio\Shlink\Core\ShortUrl\Transformer;
use Shlinkio\Shlink\Common\Rest\DataTransformerInterface;
use Shlinkio\Shlink\Core\Entity\ShortUrl;
use Shlinkio\Shlink\Core\ShortUrl\Helper\ShortUrlStringifierInterface;
use function Functional\invoke;
use function Functional\invoke_if;
class ShortUrlDataTransformer implements DataTransformerInterface
{
private ShortUrlStringifierInterface $stringifier;
public function __construct(ShortUrlStringifierInterface $stringifier)
{
$this->stringifier = $stringifier;
}
/**
* @param ShortUrl $shortUrl
*/
public function transform($shortUrl): array // phpcs:ignore
{
return [
'shortCode' => $shortUrl->getShortCode(),
'shortUrl' => $this->stringifier->stringify($shortUrl),
'longUrl' => $shortUrl->getLongUrl(),
'dateCreated' => $shortUrl->getDateCreated()->toAtomString(),
'visitsCount' => $shortUrl->getVisitsCount(),
'tags' => invoke($shortUrl->getTags(), '__toString'),
'meta' => $this->buildMeta($shortUrl),
'domain' => $shortUrl->getDomain(),
];
}
private function buildMeta(ShortUrl $shortUrl): array
{
$validSince = $shortUrl->getValidSince();
$validUntil = $shortUrl->getValidUntil();
$maxVisits = $shortUrl->getMaxVisits();
return [
'validSince' => invoke_if($validSince, 'toAtomString'),
'validUntil' => invoke_if($validUntil, 'toAtomString'),
'maxVisits' => $maxVisits,
];
}
}