Skip to content

Commit

Permalink
refactor: deprecate FeedItem constructor
Browse files Browse the repository at this point in the history
  • Loading branch information
dvikan committed Aug 8, 2024
1 parent 613b076 commit 9e95d4d
Show file tree
Hide file tree
Showing 10 changed files with 76 additions and 112 deletions.
27 changes: 10 additions & 17 deletions actions/DisplayAction.php
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,6 @@ public function __invoke(Request $request): Response
private function createResponse(Request $request, BridgeAbstract $bridge, string $format)
{
$items = [];
$feed = [];

try {
$bridge->loadConfiguration();
Expand All @@ -113,14 +112,6 @@ private function createResponse(Request $request, BridgeAbstract $bridge, string
$bridge->setInput($input);
$bridge->collectData();
$items = $bridge->getItems();
if (isset($items[0]) && is_array($items[0])) {
$feedItems = [];
foreach ($items as $item) {
$feedItems[] = FeedItem::fromArray($item);
}
$items = $feedItems;
}
$feed = $bridge->getFeed();
} catch (\Throwable $e) {
if ($e instanceof RateLimitException) {
// These are internally generated by bridges
Expand Down Expand Up @@ -162,7 +153,7 @@ private function createResponse(Request $request, BridgeAbstract $bridge, string
$format = $formatFactory->create($format);

$format->setItems($items);
$format->setFeed($feed);
$format->setFeed($bridge->getFeed());
$now = time();
$format->setLastModified($now);
$headers = [
Expand All @@ -172,27 +163,29 @@ private function createResponse(Request $request, BridgeAbstract $bridge, string
return new Response($format->stringify(), 200, $headers);
}

private function createFeedItemFromException($e, BridgeAbstract $bridge): FeedItem
private function createFeedItemFromException($e, BridgeAbstract $bridge): array
{
$item = new FeedItem();
$item = [];

// Create a unique identifier every 24 hours
$uniqueIdentifier = urlencode((int)(time() / 86400));
$title = sprintf('Bridge returned error %s! (%s)', $e->getCode(), $uniqueIdentifier);
$item->setTitle($title);
$item->setURI(get_current_url());
$item->setTimestamp(time());

$item['title'] = $title;
$item['uri'] = get_current_url();
$item['timestamp'] = time();

// Create an item identifier for feed readers e.g. "staysafetv twitch videos_19389"
$item->setUid($bridge->getName() . '_' . $uniqueIdentifier);
$item['uid'] = $bridge->getName() . '_' . $uniqueIdentifier;

$content = render_template(__DIR__ . '/../templates/bridge-error.html.php', [
'error' => render_template(__DIR__ . '/../templates/exception.html.php', ['e' => $e]),
'searchUrl' => self::createGithubSearchUrl($bridge),
'issueUrl' => self::createGithubIssueUrl($bridge, $e, create_sane_exception_message($e)),
'maintainer' => $bridge->getMaintainer(),
]);
$item->setContent($content);
$item['content'] = $content;

return $item;
}

Expand Down
16 changes: 8 additions & 8 deletions bridges/GULPProjekteBridge.php
Original file line number Diff line number Diff line change
Expand Up @@ -129,24 +129,24 @@ public function collectData()
while (true) {
$items = $this->getDriver()->findElements(WebDriverBy::tagName('app-project-view'));
foreach ($items as $item) {
$feedItem = new FeedItem();
$feedItem = [];

$heading = $item->findElement(WebDriverBy::xpath('.//app-heading-tag/h1/a'));
$feedItem->setTitle($heading->getText());
$feedItem->setURI('https://www.gulp.de' . $heading->getAttribute('href'));
$feedItem['title'] = $heading->getText();
$feedItem['uri'] = 'https://www.gulp.de' . $heading->getAttribute('href');
$info = $item->findElement(WebDriverBy::tagName('app-icon-info-list'));
if ($logo = $this->getLogo($item)) {
$feedItem->setEnclosures([$logo]);
$feedItem['enclosures'] = [$logo];
}
if (str_contains($info->getText(), 'Projektanbieter:')) {
$feedItem->setAuthor($info->findElement(WebDriverBy::xpath('.//li/span[2]/span'))->getText());
$feedItem['author'] = $info->findElement(WebDriverBy::xpath('.//li/span[2]/span'))->getText();
} else {
// mostly "Direkt vom Auftraggeber" or "GULP Agentur"
$feedItem->setAuthor($item->findElement(WebDriverBy::tagName('b'))->getText());
$feedItem['author'] = $item->findElement(WebDriverBy::tagName('b'))->getText();
}
$feedItem->setContent($item->findElement(WebDriverBy::xpath('.//p[@class="description"]'))->getText());
$feedItem['content'] = $item->findElement(WebDriverBy::xpath('.//p[@class="description"]'))->getText();
$timeAgo = $item->findElement(WebDriverBy::xpath('.//small[contains(@class, "time-ago")]'))->getText();
$feedItem->setTimestamp($this->getTimestamp($timeAgo));
$feedItem['timestamp'] = $this->getTimestamp($timeAgo);

$this->items[] = $feedItem;
}
Expand Down
2 changes: 1 addition & 1 deletion bridges/NintendoBridge.php
Original file line number Diff line number Diff line change
Expand Up @@ -477,7 +477,7 @@ protected function formatItemTimestamp($value)
return $date->getTimestamp();
}

protected function generateItemId(FeedItem $item)
protected function generateItemId(array $item)
{
return $this->getCurrentCategory() . '-' . $this->lastId;
}
Expand Down
15 changes: 8 additions & 7 deletions bridges/RutubeBridge.php
Original file line number Diff line number Diff line change
Expand Up @@ -107,10 +107,10 @@ public function collectData()
}

foreach ($videos as $video) {
$item = new FeedItem();
$item->setTitle($video->title);
$item->setURI($video->video_url);
$content = '<a href="' . $item->getURI() . '">';
$item = [];
$item['title'] = $video->title;
$item['uri'] = $video->video_url;
$content = '<a href="' . $video->video_url . '">';
$content .= '<img src="' . $video->thumbnail_url . '" />';
$content .= '</a><br/>';
$content .= nl2br(
Expand All @@ -122,9 +122,10 @@ public function collectData()
$video->description . ' '
)
);
$item->setTimestamp($video->created_ts);
$item->setAuthor($video->author->name);
$item->setContent($content);
$item['timestamp'] = $video->created_ts;
$item['author'] = $video->author->name;
$item['content'] = $content;

$this->items[] = $item;
}
}
Expand Down
18 changes: 11 additions & 7 deletions bridges/ScalableCapitalBlogBridge.php
Original file line number Diff line number Diff line change
Expand Up @@ -41,16 +41,20 @@ public function collectData()

$items = $this->getDriver()->findElements(WebDriverBy::xpath('//div[contains(@class, "articles")]//div[@class="items"]//div[contains(@class, "item")]'));
foreach ($items as $item) {
$feedItem = new FeedItem();
$feedItem = [];

$feedItem['enclosures'] = ['https://de.scalable.capital' . $item->findElement(WebDriverBy::tagName('img'))->getAttribute('src')];

$feedItem->setEnclosures(['https://de.scalable.capital' . $item->findElement(WebDriverBy::tagName('img'))->getAttribute('src')]);
$heading = $item->findElement(WebDriverBy::tagName('a'));
$feedItem->setTitle($heading->getText());
$feedItem->setURI('https://de.scalable.capital' . $heading->getAttribute('href'));
$feedItem->setContent($item->findElement(WebDriverBy::xpath('.//div[@class="summary"]'))->getText());
$feedItem['title'] = $heading->getText();

$feedItem['uri'] = 'https://de.scalable.capital' . $heading->getAttribute('href');
$feedItem['content'] = $item->findElement(WebDriverBy::xpath('.//div[@class="summary"]'))->getText();

$date = $item->findElement(WebDriverBy::xpath('.//div[@class="published-date"]'))->getText();
$feedItem->setTimestamp($this->formatItemTimestamp($date));
$feedItem->setAuthor($item->findElement(WebDriverBy::xpath('.//div[@class="author"]'))->getText());
$feedItem['timestamp'] = $this->formatItemTimestamp($date);

$feedItem['author'] = $item->findElement(WebDriverBy::xpath('.//div[@class="author"]'))->getText();

$this->items[] = $feedItem;
}
Expand Down
12 changes: 6 additions & 6 deletions bridges/Vk2Bridge.php
Original file line number Diff line number Diff line change
Expand Up @@ -255,7 +255,7 @@ protected function generateFeed($r)
if (!$ownerId) {
$ownerId = $post['owner_id'];
}
$item = new FeedItem();
$item = [];
$content = $this->generateContentFromPost($post);
if (isset($post['copy_history'])) {
if ($this->getInput('hide_reposts')) {
Expand All @@ -277,11 +277,11 @@ protected function generateFeed($r)
$content .= '):</p>';
$content .= $this->generateContentFromPost($originalPost);
}
$item->setContent($content);
$item->setTimestamp($post['date']);
$item->setAuthor($this->ownerNames[$post['from_id']]);
$item->setTitle($this->getTitle(strip_tags($content)));
$item->setURI($this->getPostURI($post));
$item['content'] = $content;
$item['timestamp'] = $post['date'];
$item['author'] = $this->ownerNames[$post['from_id']];
$item['title'] = $this->getTitle(strip_tags($content));
$item['uri'] = $this->getPostURI($post);

$this->items[] = $item;
}
Expand Down
20 changes: 4 additions & 16 deletions lib/FeedItem.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,6 @@ class FeedItem
protected ?string $uid = null;
protected array $misc = [];

public function __construct()
{
}

public static function fromArray(array $itemArray): self
{
$item = new self();
Expand All @@ -25,6 +21,10 @@ public static function fromArray(array $itemArray): self
return $item;
}

private function __construct()
{
}

public function __set($name, $value)
{
switch ($name) {
Expand Down Expand Up @@ -89,18 +89,6 @@ public function getURI(): ?string
return $this->uri;
}

/**
* Set URI to the full article.
*
* Use {@see FeedItem::getURI()} to get the URI.
*
* _Note_: Removes whitespace from the beginning and end of the URI.
*
* _Remarks_: Uses the attribute "href" or "src" if the provided URI is an
* object of simple_html_dom_node.
*
* @param simple_html_dom_node|object|string $uri URI to the full article.
*/
public function setURI($uri)
{
$this->uri = null; // Clear previous data
Expand Down
13 changes: 6 additions & 7 deletions lib/FormatAbstract.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,11 @@ abstract class FormatAbstract

const MIME_TYPE = 'text/plain';

protected string $charset = 'UTF-8';
protected array $feed = [];
protected array $items = [];
protected int $lastModified;
protected string $charset = 'UTF-8';

protected array $feed = [];
protected int $lastModified;

abstract public function stringify();

Expand All @@ -30,12 +30,11 @@ public function getFeed(): array
return $this->feed;
}

/**
* @param FeedItem[] $items
*/
public function setItems(array $items): void
{
$this->items = $items;
foreach ($items as $item) {
$this->items[] = FeedItem::fromArray($item);
}
}

/**
Expand Down
26 changes: 17 additions & 9 deletions lib/XPathAbstract.php
Original file line number Diff line number Diff line change
Expand Up @@ -422,9 +422,18 @@ public function collectData()
}

foreach ($entries as $entry) {
$item = new FeedItem();
foreach (['title', 'content', 'uri', 'author', 'timestamp', 'enclosures', 'categories'] as $param) {
$expression = $this->getParam($param);
$item = [];
$parameters = [
'title',
'content',
'uri',
'author',
'timestamp',
'enclosures',
'categories',
];
foreach ($parameters as $parameter) {
$expression = $this->getParam($parameter);
if ('' === $expression) {
continue;
}
Expand All @@ -438,21 +447,21 @@ public function collectData()
continue;
}

if ('categories' === $param && $typedResult instanceof \DOMNodeList) {
if ('categories' === $parameter && $typedResult instanceof \DOMNodeList) {
$value = [];
foreach ($typedResult as $domNode) {
$value[] = $this->getItemValueOrNodeValue($domNode, false);
}
} else {
$value = $this->getItemValueOrNodeValue($typedResult, 'content' === $param);
$value = $this->getItemValueOrNodeValue($typedResult, 'content' === $parameter);
}

$item->__set($param, $this->formatParamValue($param, $value));
$item[$parameter] = $this->formatParamValue($parameter, $value);
}

$itemId = $this->generateItemId($item);
if (null !== $itemId) {
$item->setUid($itemId);
$item['uid'] = $itemId;
}

$this->items[] = $item;
Expand Down Expand Up @@ -646,10 +655,9 @@ protected function fixEncoding($input)
/**
* Allows overriding default mechanism determining items Uid's
*
* @param FeedItem $item
* @return string|null
*/
protected function generateItemId(FeedItem $item)
protected function generateItemId(array $item)
{
return null;
}
Expand Down
39 changes: 5 additions & 34 deletions tests/FeedItemTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,45 +4,16 @@

namespace RssBridge\Tests;

use FeedItem;
use PHPUnit\Framework\TestCase;

class FeedItemTest extends TestCase
{
public function test()
{
$item = new FeedItem();
$item->setTitle('hello');
$this->assertSame('hello', $item->getTitle());

$item = FeedItem::fromArray(['title' => 'hello2']);
$this->assertSame('hello2', $item->getTitle());

$item = new FeedItem();
$item->setAuthor('123');
$this->assertSame('123', $item->getAuthor());

$item = new FeedItem();
$item->title = 'aa';
$this->assertSame('aa', $item->title);
$this->assertSame('aa', $item->getTitle());
}

public function testTimestamp()
{
$item = new FeedItem();
$item->setTimestamp(5);
$this->assertSame(5, $item->getTimestamp());

$item->setTimestamp('5');
$this->assertSame(5, $item->getTimestamp());

$item->setTimestamp('1970-01-01 18:00:00');
$this->assertSame(64800, $item->getTimestamp());

$item->setTimestamp('1st jan last year');

// This will fail at 2025-01-01 hehe
$this->assertSame(1672531200, $item->getTimestamp());
$item = [
'title' => 'kek',
];
$feedItem = \FeedItem::fromArray($item);
$this->assertSame('kek', $feedItem->getTitle());
}
}

0 comments on commit 9e95d4d

Please sign in to comment.