Removed duplicated code by using a utils trait

This commit is contained in:
Alejandro Celaya 2018-09-12 20:40:32 +02:00
parent 038ba3b006
commit a33151248d
3 changed files with 25 additions and 13 deletions

View File

@ -6,6 +6,7 @@ namespace Shlinkio\Shlink\CLI\Command\Shortcode;
use Shlinkio\Shlink\Core\Exception\InvalidUrlException;
use Shlinkio\Shlink\Core\Exception\NonUniqueSlugException;
use Shlinkio\Shlink\Core\Service\UrlShortenerInterface;
use Shlinkio\Shlink\Core\Util\ShortUrlBuilderTrait;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
@ -17,7 +18,9 @@ use Zend\I18n\Translator\TranslatorInterface;
class GenerateShortcodeCommand extends Command
{
const NAME = 'shortcode:generate';
use ShortUrlBuilderTrait;
public const NAME = 'shortcode:generate';
/**
* @var UrlShortenerInterface
@ -116,9 +119,7 @@ class GenerateShortcodeCommand extends Command
$customSlug,
$maxVisits !== null ? (int) $maxVisits : null
)->getShortCode();
$shortUrl = (string) (new Uri())->withPath($shortCode)
->withScheme($this->domainConfig['schema'])
->withHost($this->domainConfig['hostname']);
$shortUrl = $this->buildShortUrl($this->domainConfig, $shortCode);
$io->writeln([
\sprintf('%s <info>%s</info>', $this->translator->translate('Processed long URL:'), $longUrl),

View File

@ -6,10 +6,12 @@ namespace Shlinkio\Shlink\Core\Transformer;
use Shlinkio\Shlink\Common\Rest\DataTransformerInterface;
use Shlinkio\Shlink\Core\Entity\ShortUrl;
use Shlinkio\Shlink\Core\Entity\Tag;
use Zend\Diactoros\Uri;
use Shlinkio\Shlink\Core\Util\ShortUrlBuilderTrait;
class ShortUrlDataTransformer implements DataTransformerInterface
{
use ShortUrlBuilderTrait;
/**
* @var array
*/
@ -32,7 +34,7 @@ class ShortUrlDataTransformer implements DataTransformerInterface
return [
'shortCode' => $shortCode,
'shortUrl' => $this->buildShortUrl($shortCode),
'shortUrl' => $this->buildShortUrl($this->domainConfig, $shortCode),
'longUrl' => $longUrl,
'dateCreated' => $dateCreated !== null ? $dateCreated->format(\DateTime::ATOM) : null,
'visitsCount' => $value->getVisitsCount(),
@ -43,13 +45,6 @@ class ShortUrlDataTransformer implements DataTransformerInterface
];
}
private function buildShortUrl(string $shortCode): string
{
return (string) (new Uri())->withPath($shortCode)
->withScheme($this->domainConfig['schema'] ?? 'http')
->withHost($this->domainConfig['hostname'] ?? '');
}
private function serializeTag(Tag $tag): string
{
return $tag->getName();

View File

@ -0,0 +1,16 @@
<?php
declare(strict_types=1);
namespace Shlinkio\Shlink\Core\Util;
use Zend\Diactoros\Uri;
trait ShortUrlBuilderTrait
{
private function buildShortUrl(array $domainConfig, string $shortCode): string
{
return (string) (new Uri())->withPath($shortCode)
->withScheme($domainConfig['schema'] ?? 'http')
->withHost($domainConfig['hostname'] ?? '');
}
}