Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature/modernize entities #2068

Merged
merged 6 commits into from
Mar 18, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,23 @@ All notable changes to this project will be documented in this file.

The format is based on [Keep a Changelog](https://keepachangelog.com), and this project adheres to [Semantic Versioning](https://semver.org).

## [Unreleased]
### Added
* *Nothing*

### Changed
* [#2034](https://github.com/shlinkio/shlink/issues/2034) Modernize entities, using constructor property promotion and readonly wherever possible.

### Deprecated
* *Nothing*

### Removed
* *Nothing*

### Fixed
* *Nothing*


## [4.0.3] - 2024-03-15
### Added
* *Nothing*
Expand Down
4 changes: 2 additions & 2 deletions module/CLI/src/Command/Api/ListKeysCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -50,11 +50,11 @@ protected function execute(InputInterface $input, OutputInterface $output): int
$enabledOnly = $input->getOption('enabled-only');

$rows = array_map(function (ApiKey $apiKey) use ($enabledOnly) {
$expiration = $apiKey->getExpirationDate();
$expiration = $apiKey->expirationDate;
$messagePattern = $this->determineMessagePattern($apiKey);

// Set columns for this row
$rowData = [sprintf($messagePattern, $apiKey), sprintf($messagePattern, $apiKey->name() ?? '-')];
$rowData = [sprintf($messagePattern, $apiKey), sprintf($messagePattern, $apiKey->name ?? '-')];
if (! $enabledOnly) {
$rowData[] = sprintf($messagePattern, $this->getEnabledSymbol($apiKey));
}
Expand Down
2 changes: 1 addition & 1 deletion module/CLI/src/Command/Domain/GetDomainVisitsCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ protected function getVisitsPaginator(InputInterface $input, DateRange $dateRang
*/
protected function mapExtraFields(Visit $visit): array
{
$shortUrl = $visit->getShortUrl();
$shortUrl = $visit->shortUrl;
return $shortUrl === null ? [] : ['shortUrl' => $this->shortUrlStringifier->stringify($shortUrl)];
}
}
4 changes: 2 additions & 2 deletions module/CLI/src/Command/ShortUrl/ListShortUrlsCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -229,11 +229,11 @@ private function resolveColumnsMap(InputInterface $input): array
}
if ($input->getOption('show-api-key')) {
$columnsMap['API Key'] = static fn (array $_, ShortUrl $shortUrl): string =>
$shortUrl->authorApiKey()?->__toString() ?? '';
$shortUrl->authorApiKey?->__toString() ?? '';
}
if ($input->getOption('show-api-key-name')) {
$columnsMap['API Key Name'] = static fn (array $_, ShortUrl $shortUrl): ?string =>
$shortUrl->authorApiKey()?->name();
$shortUrl->authorApiKey?->name;
}

return $columnsMap;
Expand Down
2 changes: 1 addition & 1 deletion module/CLI/src/Command/Tag/GetTagVisitsCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ protected function getVisitsPaginator(InputInterface $input, DateRange $dateRang
*/
protected function mapExtraFields(Visit $visit): array
{
$shortUrl = $visit->getShortUrl();
$shortUrl = $visit->shortUrl;
return $shortUrl === null ? [] : ['shortUrl' => $this->shortUrlStringifier->stringify($shortUrl)];
}
}
4 changes: 2 additions & 2 deletions module/CLI/src/Command/Visit/AbstractVisitsListCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -55,8 +55,8 @@ private function resolveRowsAndHeaders(Paginator $paginator): array

$rowData = [
...$visit->jsonSerialize(),
'country' => $visit->getVisitLocation()?->getCountryName() ?? 'Unknown',
'city' => $visit->getVisitLocation()?->getCityName() ?? 'Unknown',
'country' => $visit->getVisitLocation()?->countryName ?? 'Unknown',
'city' => $visit->getVisitLocation()?->cityName ?? 'Unknown',
...$extraFields,
];

Expand Down
2 changes: 1 addition & 1 deletion module/CLI/src/Command/Visit/GetNonOrphanVisitsCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ protected function getVisitsPaginator(InputInterface $input, DateRange $dateRang
*/
protected function mapExtraFields(Visit $visit): array
{
$shortUrl = $visit->getShortUrl();
$shortUrl = $visit->shortUrl;
return $shortUrl === null ? [] : ['shortUrl' => $this->shortUrlStringifier->stringify($shortUrl)];
}
}
2 changes: 1 addition & 1 deletion module/CLI/src/Command/Visit/GetOrphanVisitsCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,6 @@ protected function getVisitsPaginator(InputInterface $input, DateRange $dateRang
*/
protected function mapExtraFields(Visit $visit): array
{
return ['type' => $visit->type()->value];
return ['type' => $visit->type->value];
}
}
8 changes: 4 additions & 4 deletions module/CLI/src/Command/Visit/LocateVisitsCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@
*/
public function geolocateVisit(Visit $visit): Location
{
$ipAddr = $visit->getRemoteAddr() ?? '?';
$ipAddr = $visit->remoteAddr ?? '?';
$this->io->write(sprintf('Processing IP <fg=blue>%s</>', $ipAddr));

try {
Expand All @@ -154,9 +154,9 @@

public function onVisitLocated(VisitLocation $visitLocation, Visit $visit): void
{
if (! $visitLocation->isEmpty()) {
$this->io->writeln(sprintf(' [<info>Address located in "%s"</info>]', $visitLocation->getCountryName()));
} elseif ($visit->hasRemoteAddr() && $visit->getRemoteAddr() !== IpAddress::LOCALHOST) {
if (! $visitLocation->isEmpty) {
$this->io->writeln(sprintf(' [<info>Address located in "%s"</info>]', $visitLocation->countryName));

Check warning on line 158 in module/CLI/src/Command/Visit/LocateVisitsCommand.php

View check run for this annotation

Codecov / codecov/patch

module/CLI/src/Command/Visit/LocateVisitsCommand.php#L158

Added line #L158 was not covered by tests
} elseif ($visit->hasRemoteAddr() && $visit->remoteAddr !== IpAddress::LOCALHOST) {
$this->io->writeln(' <comment>[Could not locate address]</comment>');
}
}
Expand Down
12 changes: 6 additions & 6 deletions module/Core/src/Domain/Entity/Domain.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,12 @@

class Domain extends AbstractEntity implements JsonSerializable, NotFoundRedirectConfigInterface
{
private ?string $baseUrlRedirect = null;
private ?string $regular404Redirect = null;
private ?string $invalidShortUrlRedirect = null;

private function __construct(public readonly string $authority)
{
private function __construct(
public readonly string $authority,
private ?string $baseUrlRedirect = null,
private ?string $regular404Redirect = null,
private ?string $invalidShortUrlRedirect = null,
) {
}

public static function withAuthority(string $authority): self
Expand Down
2 changes: 1 addition & 1 deletion module/Core/src/EventDispatcher/LocateVisit.php
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ private function locateVisit(string $visitId, ?string $originalIpAddress, Visit
}

$isLocatable = $originalIpAddress !== null || $visit->isLocatable();
$addr = $originalIpAddress ?? $visit->getRemoteAddr() ?? '';
$addr = $originalIpAddress ?? $visit->remoteAddr ?? '';

try {
$location = $isLocatable ? $this->ipLocationResolver->resolveIpLocation($addr) : Location::emptyInstance();
Expand Down
20 changes: 10 additions & 10 deletions module/Core/src/EventDispatcher/Matomo/SendVisitToMatomo.php
Original file line number Diff line number Diff line change
Expand Up @@ -46,21 +46,21 @@ public function __invoke(VisitLocated $visitLocated): void

$tracker
->setUrl($this->resolveUrlToTrack($visit))
->setCustomTrackingParameter('type', $visit->type()->value)
->setUserAgent($visit->userAgent())
->setUrlReferrer($visit->referer());
->setCustomTrackingParameter('type', $visit->type->value)
->setUserAgent($visit->userAgent)
->setUrlReferrer($visit->referer);

$location = $visit->getVisitLocation();
if ($location !== null) {
$tracker
->setCity($location->getCityName())
->setCountry($location->getCountryName())
->setLatitude($location->getLatitude())
->setLongitude($location->getLongitude());
->setCity($location->cityName)
->setCountry($location->countryName)
->setLatitude($location->latitude)
->setLongitude($location->longitude);
}

// Set not obfuscated IP if possible, as matomo handles obfuscation itself
$ip = $visitLocated->originalIpAddress ?? $visit->getRemoteAddr();
$ip = $visitLocated->originalIpAddress ?? $visit->remoteAddr;
if ($ip !== null) {
$tracker->setIp($ip);
}
Expand All @@ -79,9 +79,9 @@ public function __invoke(VisitLocated $visitLocated): void

public function resolveUrlToTrack(Visit $visit): string
{
$shortUrl = $visit->getShortUrl();
$shortUrl = $visit->shortUrl;
if ($shortUrl === null) {
return $visit->visitedUrl() ?? '';
return $visit->visitedUrl ?? '';
}

return $this->shortUrlStringifier->stringify($shortUrl);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ public function __construct(
public function newVisitUpdate(Visit $visit): Update
{
return Update::forTopicAndPayload(Topic::NEW_VISIT->value, [
'shortUrl' => $this->shortUrlTransformer->transform($visit->getShortUrl()),
'shortUrl' => $this->shortUrlTransformer->transform($visit->shortUrl),
'visit' => $visit->jsonSerialize(),
]);
}
Expand All @@ -34,7 +34,7 @@ public function newOrphanVisitUpdate(Visit $visit): Update

public function newShortUrlVisitUpdate(Visit $visit): Update
{
$shortUrl = $visit->getShortUrl();
$shortUrl = $visit->shortUrl;
$topic = Topic::newShortUrlVisit($shortUrl?->getShortCode());

return Update::forTopicAndPayload($topic, [
Expand Down
100 changes: 47 additions & 53 deletions module/Core/src/ShortUrl/Entity/ShortUrl.php
Original file line number Diff line number Diff line change
Expand Up @@ -32,29 +32,30 @@

class ShortUrl extends AbstractEntity
{
private string $longUrl;
private string $shortCode;
private Chronos $dateCreated;
/** @var Collection<int, Visit> & Selectable */
private Collection & Selectable $visits;
/** @var Collection<int, Tag> */
private Collection $tags;
private ?Chronos $validSince = null;
private ?Chronos $validUntil = null;
private ?int $maxVisits = null;
private ?Domain $domain = null;
private bool $customSlugWasProvided;
private int $shortCodeLength;
private ?string $importSource = null;
private ?string $importOriginalShortCode = null;
private ?ApiKey $authorApiKey = null;
private ?string $title = null;
private bool $titleWasAutoResolved = false;
private bool $crawlable = false;
private bool $forwardQuery = true;

private function __construct()
{
/**
* @param Collection<int, Tag> $tags
* @param Collection<int, Visit> & Selectable $visits
*/
private function __construct(
private string $longUrl,
private string $shortCode,
private Chronos $dateCreated = new Chronos(),
private Collection $tags = new ArrayCollection(),
private Collection & Selectable $visits = new ArrayCollection(),
private ?Chronos $validSince = null,
private ?Chronos $validUntil = null,
private ?int $maxVisits = null,
private ?Domain $domain = null,
private bool $customSlugWasProvided = false,
private int $shortCodeLength = 0,
public readonly ?ApiKey $authorApiKey = null,
private ?string $title = null,
private bool $titleWasAutoResolved = false,
private bool $crawlable = false,
private bool $forwardQuery = true,
private ?string $importSource = null,
private ?string $importOriginalShortCode = null,
) {
}

/**
Expand All @@ -78,31 +79,29 @@ public static function create(
ShortUrlCreation $creation,
?ShortUrlRelationResolverInterface $relationResolver = null,
): self {
$instance = new self();
$relationResolver = $relationResolver ?? new SimpleShortUrlRelationResolver();

$instance->longUrl = $creation->getLongUrl();
$instance->dateCreated = Chronos::now();
$instance->visits = new ArrayCollection();
$instance->tags = $relationResolver->resolveTags($creation->tags);
$instance->validSince = $creation->validSince;
$instance->validUntil = $creation->validUntil;
$instance->maxVisits = $creation->maxVisits;
$instance->customSlugWasProvided = $creation->hasCustomSlug();
$instance->shortCodeLength = $creation->shortCodeLength;
$instance->shortCode = sprintf(
'%s%s',
$creation->pathPrefix ?? '',
$creation->customSlug ?? generateRandomShortCode($instance->shortCodeLength, $creation->shortUrlMode),
$shortCodeLength = $creation->shortCodeLength;

return new self(
longUrl: $creation->getLongUrl(),
shortCode: sprintf(
'%s%s',
$creation->pathPrefix ?? '',
$creation->customSlug ?? generateRandomShortCode($shortCodeLength, $creation->shortUrlMode),
),
tags: $relationResolver->resolveTags($creation->tags),
validSince: $creation->validSince,
validUntil: $creation->validUntil,
maxVisits: $creation->maxVisits,
domain: $relationResolver->resolveDomain($creation->domain),
customSlugWasProvided: $creation->hasCustomSlug(),
shortCodeLength: $shortCodeLength,
authorApiKey: $creation->apiKey,
title: $creation->title,
titleWasAutoResolved: $creation->titleWasAutoResolved,
crawlable: $creation->crawlable,
forwardQuery: $creation->forwardQuery,
);
$instance->domain = $relationResolver->resolveDomain($creation->domain);
$instance->authorApiKey = $creation->apiKey;
$instance->title = $creation->title;
$instance->titleWasAutoResolved = $creation->titleWasAutoResolved;
$instance->crawlable = $creation->crawlable;
$instance->forwardQuery = $creation->forwardQuery;

return $instance;
}

public static function fromImport(
Expand All @@ -123,11 +122,11 @@ public static function fromImport(

$instance = self::create(ShortUrlCreation::fromRawData($meta), $relationResolver);

$instance->importSource = $url->source->value;
$instance->importOriginalShortCode = $url->shortCode;
$instance->validSince = normalizeOptionalDate($url->meta->validSince);
$instance->validUntil = normalizeOptionalDate($url->meta->validUntil);
$instance->dateCreated = normalizeDate($url->createdAt);
$instance->importSource = $url->source->value;
$instance->importOriginalShortCode = $url->shortCode;

return $instance;
}
Expand Down Expand Up @@ -196,11 +195,6 @@ public function getTags(): Collection
return $this->tags;
}

public function authorApiKey(): ?ApiKey
{
return $this->authorApiKey;
}

public function getValidSince(): ?Chronos
{
return $this->validSince;
Expand Down
Loading
Loading