refactor: address code quality - readonly props, const fields, void return, rss+xml content type

This commit is contained in:
Joel Male
2026-04-11 08:12:00 +10:00
parent 1c426d0d1b
commit db8871110a
+9 -9
View File
@@ -11,13 +11,13 @@
class LaravelGoogleShoppingFeed
{
public string $title = '';
public string $description = '';
public string $link = '';
public readonly string $title;
public readonly string $description;
public readonly string $link;
protected array $products = [];
protected array $requiredProductFields = [
protected const array REQUIRED_PRODUCT_FIELDS = [
'id',
'link',
'title',
@@ -35,17 +35,15 @@ public static function init(string $title = '', string $description = '', string
return $feed;
}
public function addItem(array $item): bool
public function addItem(array $item): void
{
foreach ($this->requiredProductFields as $field) {
foreach (self::REQUIRED_PRODUCT_FIELDS as $field) {
if (! isset($item[$field])) {
throw new MissingRequiredFieldException("Required field '{$field}' is missing");
}
}
$this->products[] = $item;
return true;
}
public function toXml(): string
@@ -70,6 +68,8 @@ public function toXml(): string
$xml = ArrayToXml::convert($data, '');
$xml = str_replace([' ', '<root>', '</root>', "\n", "\r", '<remove>remove</remove>'], '', $xml);
// spatie/array-to-xml does not support repeated keys, so products are keyed as
// item_0, item_1, etc. and renamed back to <item> tags here.
$xml = (string) preg_replace('/item_\d+/', 'item', $xml);
return $xml;
@@ -77,6 +77,6 @@ public function toXml(): string
public function generate(): Response
{
return ResponseFacade::make($this->toXml(), 200, ['Content-Type' => 'text/xml']);
return ResponseFacade::make($this->toXml(), headers: ['Content-Type' => 'application/rss+xml']);
}
}