mirror of
https://github.com/wearepixel/laravel-google-shopping-feed.git
synced 2026-11-14 13:21:46 +00:00
refactor: address code quality - readonly props, const fields, void return, rss+xml content type
This commit is contained in:
@@ -11,13 +11,13 @@
|
|||||||
|
|
||||||
class LaravelGoogleShoppingFeed
|
class LaravelGoogleShoppingFeed
|
||||||
{
|
{
|
||||||
public string $title = '';
|
public readonly string $title;
|
||||||
public string $description = '';
|
public readonly string $description;
|
||||||
public string $link = '';
|
public readonly string $link;
|
||||||
|
|
||||||
protected array $products = [];
|
protected array $products = [];
|
||||||
|
|
||||||
protected array $requiredProductFields = [
|
protected const array REQUIRED_PRODUCT_FIELDS = [
|
||||||
'id',
|
'id',
|
||||||
'link',
|
'link',
|
||||||
'title',
|
'title',
|
||||||
@@ -35,17 +35,15 @@ public static function init(string $title = '', string $description = '', string
|
|||||||
return $feed;
|
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])) {
|
if (! isset($item[$field])) {
|
||||||
throw new MissingRequiredFieldException("Required field '{$field}' is missing");
|
throw new MissingRequiredFieldException("Required field '{$field}' is missing");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
$this->products[] = $item;
|
$this->products[] = $item;
|
||||||
|
|
||||||
return true;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public function toXml(): string
|
public function toXml(): string
|
||||||
@@ -70,6 +68,8 @@ public function toXml(): string
|
|||||||
|
|
||||||
$xml = ArrayToXml::convert($data, '');
|
$xml = ArrayToXml::convert($data, '');
|
||||||
$xml = str_replace([' ', '<root>', '</root>', "\n", "\r", '<remove>remove</remove>'], '', $xml);
|
$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);
|
$xml = (string) preg_replace('/item_\d+/', 'item', $xml);
|
||||||
|
|
||||||
return $xml;
|
return $xml;
|
||||||
@@ -77,6 +77,6 @@ public function toXml(): string
|
|||||||
|
|
||||||
public function generate(): Response
|
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']);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user