WIP with option and result types

This commit is contained in:
Daniel J. Summers 2024-06-25 18:37:00 -04:00
parent dfd9a873f8
commit 1d5a3c1c7a
16 changed files with 302 additions and 136 deletions

View File

@ -1,6 +1,6 @@
{ {
"name": "bit-badger/feed-reader-central", "name": "bit-badger/feed-reader-central",
"minimum-stability": "dev", "minimum-stability": "beta",
"require": { "require": {
"php": ">=8.2", "php": ">=8.2",
"bit-badger/pdo-document": "^1", "bit-badger/pdo-document": "^1",
@ -8,7 +8,8 @@
"ext-dom": "*", "ext-dom": "*",
"ext-pdo": "*", "ext-pdo": "*",
"ext-readline": "*", "ext-readline": "*",
"ext-sqlite3": "*" "ext-sqlite3": "*",
"graham-campbell/result-type": "^1.1"
}, },
"autoload": { "autoload": {
"psr-4": { "psr-4": {

153
src/composer.lock generated
View File

@ -4,20 +4,21 @@
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
"This file is @generated automatically" "This file is @generated automatically"
], ],
"content-hash": "4f0add59e384feb6787acf3685c9e031", "content-hash": "d5b7f01ef79cdce09364eed3dca3281d",
"packages": [ "packages": [
{ {
"name": "bit-badger/pdo-document", "name": "bit-badger/pdo-document",
"version": "v1.0.0-alpha2", "version": "v1.0.0-beta2",
"source": { "source": {
"type": "git", "type": "git",
"url": "https://git.bitbadger.solutions/bit-badger/pdo-document", "url": "https://git.bitbadger.solutions/bit-badger/pdo-document",
"reference": "330e27218756df8b93081a17dead8aaec789b071" "reference": "50854275a8b39074966cf00370f30b3e68edc6e7"
}, },
"require": { "require": {
"ext-pdo": "*", "ext-pdo": "*",
"netresearch/jsonmapper": "^4", "netresearch/jsonmapper": "^4",
"php": ">=8.2" "php": ">=8.2",
"phpoption/phpoption": "^1.9"
}, },
"require-dev": { "require-dev": {
"phpunit/phpunit": "^11" "phpunit/phpunit": "^11"
@ -42,11 +43,12 @@
"role": "Developer" "role": "Developer"
} }
], ],
"description": "Treat SQLite (and soon PostgreSQL) as a document store", "description": "Treat SQLite and PostgreSQL as document stores",
"keywords": [ "keywords": [
"database", "database",
"document", "document",
"pdo", "pdo",
"postgresql",
"sqlite" "sqlite"
], ],
"support": { "support": {
@ -54,7 +56,69 @@
"rss": "https://git.bitbadger.solutions/bit-badger/pdo-document.rss", "rss": "https://git.bitbadger.solutions/bit-badger/pdo-document.rss",
"source": "https://git.bitbadger.solutions/bit-badger/pdo-document" "source": "https://git.bitbadger.solutions/bit-badger/pdo-document"
}, },
"time": "2024-06-11T11:07:56+00:00" "time": "2024-06-25T14:42:26+00:00"
},
{
"name": "graham-campbell/result-type",
"version": "v1.1.2",
"source": {
"type": "git",
"url": "https://github.com/GrahamCampbell/Result-Type.git",
"reference": "fbd48bce38f73f8a4ec8583362e732e4095e5862"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/GrahamCampbell/Result-Type/zipball/fbd48bce38f73f8a4ec8583362e732e4095e5862",
"reference": "fbd48bce38f73f8a4ec8583362e732e4095e5862",
"shasum": ""
},
"require": {
"php": "^7.2.5 || ^8.0",
"phpoption/phpoption": "^1.9.2"
},
"require-dev": {
"phpunit/phpunit": "^8.5.34 || ^9.6.13 || ^10.4.2"
},
"type": "library",
"autoload": {
"psr-4": {
"GrahamCampbell\\ResultType\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Graham Campbell",
"email": "hello@gjcampbell.co.uk",
"homepage": "https://github.com/GrahamCampbell"
}
],
"description": "An Implementation Of The Result Type",
"keywords": [
"Graham Campbell",
"GrahamCampbell",
"Result Type",
"Result-Type",
"result"
],
"support": {
"issues": "https://github.com/GrahamCampbell/Result-Type/issues",
"source": "https://github.com/GrahamCampbell/Result-Type/tree/v1.1.2"
},
"funding": [
{
"url": "https://github.com/GrahamCampbell",
"type": "github"
},
{
"url": "https://tidelift.com/funding/github/packagist/graham-campbell/result-type",
"type": "tidelift"
}
],
"time": "2023-11-12T22:16:48+00:00"
}, },
{ {
"name": "netresearch/jsonmapper", "name": "netresearch/jsonmapper",
@ -106,11 +170,86 @@
"source": "https://github.com/cweiske/jsonmapper/tree/v4.4.1" "source": "https://github.com/cweiske/jsonmapper/tree/v4.4.1"
}, },
"time": "2024-01-31T06:18:54+00:00" "time": "2024-01-31T06:18:54+00:00"
},
{
"name": "phpoption/phpoption",
"version": "1.9.2",
"source": {
"type": "git",
"url": "https://github.com/schmittjoh/php-option.git",
"reference": "80735db690fe4fc5c76dfa7f9b770634285fa820"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/schmittjoh/php-option/zipball/80735db690fe4fc5c76dfa7f9b770634285fa820",
"reference": "80735db690fe4fc5c76dfa7f9b770634285fa820",
"shasum": ""
},
"require": {
"php": "^7.2.5 || ^8.0"
},
"require-dev": {
"bamarni/composer-bin-plugin": "^1.8.2",
"phpunit/phpunit": "^8.5.34 || ^9.6.13 || ^10.4.2"
},
"type": "library",
"extra": {
"bamarni-bin": {
"bin-links": true,
"forward-command": true
},
"branch-alias": {
"dev-master": "1.9-dev"
}
},
"autoload": {
"psr-4": {
"PhpOption\\": "src/PhpOption/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"Apache-2.0"
],
"authors": [
{
"name": "Johannes M. Schmitt",
"email": "schmittjoh@gmail.com",
"homepage": "https://github.com/schmittjoh"
},
{
"name": "Graham Campbell",
"email": "hello@gjcampbell.co.uk",
"homepage": "https://github.com/GrahamCampbell"
}
],
"description": "Option Type for PHP",
"keywords": [
"language",
"option",
"php",
"type"
],
"support": {
"issues": "https://github.com/schmittjoh/php-option/issues",
"source": "https://github.com/schmittjoh/php-option/tree/1.9.2"
},
"funding": [
{
"url": "https://github.com/GrahamCampbell",
"type": "github"
},
{
"url": "https://tidelift.com/funding/github/packagist/phpoption/phpoption",
"type": "tidelift"
}
],
"time": "2023-11-12T21:59:55+00:00"
} }
], ],
"packages-dev": [], "packages-dev": [],
"aliases": [], "aliases": [],
"minimum-stability": "dev", "minimum-stability": "beta",
"stability-flags": [], "stability-flags": [],
"prefer-stable": false, "prefer-stable": false,
"prefer-lowest": false, "prefer-lowest": false,

View File

@ -6,6 +6,10 @@ use BitBadger\PDODocument\{
Configuration, Custom, Document, DocumentException, DocumentList, Exists, Field, Find, Parameters, Patch, Query Configuration, Custom, Document, DocumentException, DocumentList, Exists, Field, Find, Parameters, Patch, Query
}; };
use DateTimeInterface; use DateTimeInterface;
use GrahamCampbell\ResultType\Error;
use GrahamCampbell\ResultType\Result;
use GrahamCampbell\ResultType\Success;
use PhpOption\Option;
/** /**
* An RSS or Atom feed * An RSS or Atom feed
@ -64,16 +68,17 @@ class Feed
* @param int $feedId The ID of the feed to which these items belong * @param int $feedId The ID of the feed to which these items belong
* @param ParsedFeed $parsed The extracted Atom or RSS feed items * @param ParsedFeed $parsed The extracted Atom or RSS feed items
* @param DateTimeInterface $lastChecked When this feed was last checked (only new items will be added) * @param DateTimeInterface $lastChecked When this feed was last checked (only new items will be added)
* @return array ['ok' => true] if successful, ['error' => message] if not * @return Result<true, string> True if successful, an error message if not
*/ */
public static function updateItems(int $feedId, ParsedFeed $parsed, DateTimeInterface $lastChecked): array public static function updateItems(int $feedId, ParsedFeed $parsed, DateTimeInterface $lastChecked): Result
{ {
$results = $results =
array_map(function ($item) use ($feedId) { array_map(function ($item) use ($feedId) {
try { try {
$existing = Find::firstByFields(Table::ITEM, $tryExisting = Find::firstByFields(Table::ITEM,
[Field::EQ('feed_id', $feedId), Field::EQ('item_guid', $item->guid)], Item::class); [Field::EQ('feed_id', $feedId), Field::EQ('item_guid', $item->guid)], Item::class);
if ($existing) { if ($tryExisting->isDefined()) {
$existing = $tryExisting->get();
if ($existing->published_on != $item->publishedOn if ($existing->published_on != $item->publishedOn
|| ($existing->updated_on != ($item->updatedOn ?? ''))) { || ($existing->updated_on != ($item->updatedOn ?? ''))) {
Item::update($existing->id, $item); Item::update($existing->id, $item);
@ -81,26 +86,28 @@ class Feed
} else { } else {
Item::add($feedId, $item); Item::add($feedId, $item);
} }
return ['ok' => true]; return Success::create(true);
} catch (DocumentException $ex) { } catch (DocumentException $ex) {
return ['error' => "$ex"]; return Error::create("$ex");
} }
}, array_filter($parsed->items, }, array_filter($parsed->items,
fn($it) => date_create_immutable($it->updatedOn ?? $it->publishedOn) >= $lastChecked)); fn(ParsedItem $it) => date_create_immutable($it->updatedOn ?? $it->publishedOn) >= $lastChecked));
$errors = array_map(fn($it) => $it['error'], array_filter($results, fn($it) => array_key_exists('error', $it))); $errors = array_map(fn(Result $it) => $it->error()->get(),
return sizeof($errors) > 0 ? ['error' => implode("\n", $errors)] : ['ok' => true]; array_filter($results, fn(Result $it) => $it->error()->isDefined()));
return sizeof($errors) > 0 ? Error::create(implode("\n", $errors)) : Success::create(true);
} }
/** /**
* Purge items for a feed * Purge items for a feed
* *
* @param int $feedId The ID of the feed to be purged * @param int $feedId The ID of the feed to be purged
* @return array|string[]|true[] ['ok' => true] if purging was successful, ['error' => message] if not * @return Result<true, string> True if purging was successful, an error message if not
* @throws DocumentException If any is encountered
*/ */
private static function purgeItems(int $feedId): array private static function purgeItems(int $feedId): Result
{ {
if (!array_search(PURGE_TYPE, [self::PURGE_READ, self::PURGE_BY_DAYS, self::PURGE_BY_COUNT])) { if (!array_search(PURGE_TYPE, [self::PURGE_READ, self::PURGE_BY_DAYS, self::PURGE_BY_COUNT])) {
return ['error' => 'Unrecognized purge type ' . PURGE_TYPE]; return Error::create('Unrecognized purge type ' . PURGE_TYPE);
} }
$fields = [Field::EQ('feed_id', $feedId, ':feed'), Data::bookmarkField(false)]; $fields = [Field::EQ('feed_id', $feedId, ':feed'), Data::bookmarkField(false)];
@ -127,9 +134,9 @@ class Feed
} }
try { try {
Custom::nonQuery($sql, Parameters::addFields($fields, [])); Custom::nonQuery($sql, Parameters::addFields($fields, []));
return ['ok' => true]; return Success::create(true);
} catch (DocumentException $ex) { } catch (DocumentException $ex) {
return ['error' => "$ex"]; return Error::create("$ex");
} }
} }
@ -138,21 +145,22 @@ class Feed
* *
* @param int $feedId The ID of the feed to be refreshed * @param int $feedId The ID of the feed to be refreshed
* @param string $url The URL of the feed to be refreshed * @param string $url The URL of the feed to be refreshed
* @return array|string[]|true[] ['ok' => true] if successful, ['error' => message] if not * @return Result<true, string> True if successful, an error message if not
* @throws DocumentException If any is encountered
*/ */
public static function refreshFeed(int $feedId, string $url): array public static function refreshFeed(int $feedId, string $url): Result
{ {
$feedRetrieval = ParsedFeed::retrieve($url); $tryRetrieve = ParsedFeed::retrieve($url);
if (key_exists('error', $feedRetrieval)) return $feedRetrieval; if ($tryRetrieve->error()->isDefined()) return $tryRetrieve->error()->get();
$feed = $feedRetrieval['ok']; $feed = $tryRetrieve->success()->get();
try { try {
$feedDoc = Find::byId(Table::FEED, $feedId, self::class); $feedDoc = Find::byId(Table::FEED, $feedId, self::class);
if (!$feedDoc) return ['error' => 'Could not derive date last checked for feed']; if ($feedDoc->isEmpty()) return Error::create('Could not derive date last checked for feed');
$lastChecked = date_create_immutable($feedDoc->checked_on ?? WWW_EPOCH); $lastChecked = date_create_immutable($feedDoc->get()->checked_on ?? WWW_EPOCH);
$itemUpdate = self::updateItems($feedId, $feed, $lastChecked); $itemUpdate = self::updateItems($feedId, $feed, $lastChecked);
if (key_exists('error', $itemUpdate)) return $itemUpdate; if ($itemUpdate->error()->isDefined()) return $itemUpdate->error()->get();
$patch = [ $patch = [
'title' => $feed->title, 'title' => $feed->title,
@ -162,42 +170,40 @@ class Feed
if ($url == $feed->url) $patch['url'] = $feed->url; if ($url == $feed->url) $patch['url'] = $feed->url;
Patch::byId(Table::FEED, $feedId, $patch); Patch::byId(Table::FEED, $feedId, $patch);
} catch (DocumentException $ex) { } catch (DocumentException $ex) {
return ['error' => "$ex"]; return Error::create("$ex");
} }
return PURGE_TYPE == self::PURGE_NONE ? ['ok' => true] : self::purgeItems($feedId); return PURGE_TYPE == self::PURGE_NONE ? Success::create(true) : self::purgeItems($feedId);
} }
/** /**
* Add an RSS feed * Add an RSS feed
* *
* @param string $url The URL of the RSS feed to add * @param string $url The URL of the RSS feed to add
* @return array ['ok' => feedId] if successful, ['error' => message] if not * @return Result<int, string> The feed ID if successful, an error message if not
*/ */
public static function add(string $url): array public static function add(string $url): Result
{ {
$feedExtract = ParsedFeed::retrieve($url); $tryRetrieve = ParsedFeed::retrieve($url);
if (key_exists('error', $feedExtract)) return $feedExtract; if ($tryRetrieve->error()->isDefined()) return $tryRetrieve->error()->get();
$feed = $tryRetrieve->success()->get();
$feed = $feedExtract['ok'];
try { try {
$fields = [Field::EQ('user_id', $_SESSION[Key::USER_ID]), Field::EQ('url', $feed->url)]; $fields = [Field::EQ('user_id', $_SESSION[Key::USER_ID]), Field::EQ('url', $feed->url)];
if (Exists::byFields(Table::FEED, $fields)) { if (Exists::byFields(Table::FEED, $fields)) {
return ['error' => "Already subscribed to feed $feed->url"]; return Error::create("Already subscribed to feed $feed->url");
} }
Document::insert(Table::FEED, self::fromParsed($feed)); Document::insert(Table::FEED, self::fromParsed($feed));
$doc = Find::firstByFields(Table::FEED, $fields, static::class); $tryDoc = Find::firstByFields(Table::FEED, $fields, static::class);
if (!$doc) return ['error' => 'Could not retrieve inserted feed']; if ($tryDoc->isEmpty()) return Error::create('Could not retrieve inserted feed');
$doc = $tryDoc->get();
$result = self::updateItems($doc->id, $feed, date_create_immutable(WWW_EPOCH)); $result = self::updateItems($doc->id, $feed, date_create_immutable(WWW_EPOCH));
if (key_exists('error', $result)) return $result; return $result->error()->isDefined() ? $result->error()->get() : Success::create($doc->id);
return ['ok' => $doc->id];
} catch (DocumentException $ex) { } catch (DocumentException $ex) {
return ['error' => "$ex"]; return Error::create("$ex");
} }
} }
@ -206,9 +212,9 @@ class Feed
* *
* @param Feed $existing The existing feed * @param Feed $existing The existing feed
* @param string $url The URL with which the existing feed should be modified * @param string $url The URL with which the existing feed should be modified
* @return bool[]|string[] [ 'ok' => true ] if successful, [ 'error' => message ] if not * @return Result<true, string> True if successful, an error message if not
*/ */
public static function update(Feed $existing, string $url): array public static function update(Feed $existing, string $url): Result
{ {
try { try {
Patch::byFields(Table::FEED, Patch::byFields(Table::FEED,
@ -217,7 +223,7 @@ class Feed
return self::refreshFeed($existing->id, $url); return self::refreshFeed($existing->id, $url);
} catch (DocumentException $ex) { } catch (DocumentException $ex) {
return ['error' => "$ex"]; return Error::create("$ex");
} }
} }
@ -238,10 +244,9 @@ class Feed
/** /**
* Refresh all feeds * Refresh all feeds
* *
* @return array|true[]|string[] ['ok' => true] if successful, * @return Result<true, string> True if successful an error message if not (may have multiple error lines)
* ['error' => message] if not (may have multiple error lines)
*/ */
public static function refreshAll(): array public static function refreshAll(): Result
{ {
try { try {
$feeds = self::retrieveAll($_SESSION[Key::USER_ID]); $feeds = self::retrieveAll($_SESSION[Key::USER_ID]);
@ -249,25 +254,25 @@ class Feed
$errors = []; $errors = [];
foreach ($feeds->items() as $feed) { foreach ($feeds->items() as $feed) {
$result = self::refreshFeed($feed->id, $feed->url); $result = self::refreshFeed($feed->id, $feed->url);
if (key_exists('error', $result)) $errors[] = $result['error']; if ($result->error()->isDefined()) $errors[] = $result->error()->get();
} }
} catch (DocumentException $ex) { } catch (DocumentException $ex) {
return ['error' => "$ex"]; return Error::create("$ex");
} }
return sizeof($errors) == 0 ? ['ok' => true] : ['error' => implode("\n", $errors)]; return sizeof($errors) == 0 ? Success::create(true) : Error::create(implode("\n", $errors));
} }
/** /**
* Retrieve a feed by its ID for the current user * Retrieve a feed by its ID for the current user
* *
* @param int $feedId The ID of the feed to retrieve * @param int $feedId The ID of the feed to retrieve
* @return static|false The data for the feed if found, false if not found * @return Option<static> A `Some` value with the data for the feed if found, `None` otherwise
* @throws DocumentException If any is encountered * @throws DocumentException If any is encountered
*/ */
public static function retrieveById(int $feedId): static|false public static function retrieveById(int $feedId): Option
{ {
$doc = Find::byId(Table::FEED, $feedId, static::class); return Find::byId(Table::FEED, $feedId, static::class)
return $doc && $doc->user_id == $_SESSION[Key::USER_ID] ? $doc : false; ->filter(fn ($it) => $it->user_id == $_SESSION[Key::USER_ID]);
} }
} }

View File

@ -4,6 +4,7 @@ namespace FeedReaderCentral;
use BitBadger\PDODocument\{Configuration, Custom, DocumentException, Field, Parameters, Query}; use BitBadger\PDODocument\{Configuration, Custom, DocumentException, Field, Parameters, Query};
use BitBadger\PDODocument\Mapper\{DocumentMapper, ExistsMapper}; use BitBadger\PDODocument\Mapper\{DocumentMapper, ExistsMapper};
use PhpOption\Option;
/** /**
* A combined item and feed (used for lists) * A combined item and feed (used for lists)
@ -55,10 +56,10 @@ class ItemWithFeed extends Item
* Retrieve an item via its ID * Retrieve an item via its ID
* *
* @param int $id The ID of the item to be retrieved * @param int $id The ID of the item to be retrieved
* @return ItemWithFeed|false The item if it is found, false if not * @return Option<ItemWithFeed> A `Some` value with the item if it is found, `None` otherwise
* @throws DocumentException If any is encountered * @throws DocumentException If any is encountered
*/ */
public static function retrieveById(int $id): ItemWithFeed|false public static function retrieveById(int $id): Option
{ {
$fields = self::idAndUserFields($id); $fields = self::idAndUserFields($id);
return Custom::single(self::SELECT_WITH_FEED . ' WHERE ' . Query::whereByFields($fields), return Custom::single(self::SELECT_WITH_FEED . ' WHERE ' . Query::whereByFields($fields),

View File

@ -6,6 +6,9 @@ use DOMDocument;
use DOMElement; use DOMElement;
use DOMException; use DOMException;
use DOMNode; use DOMNode;
use GrahamCampbell\ResultType\Error;
use GrahamCampbell\ResultType\Result;
use GrahamCampbell\ResultType\Success;
class ParsedFeed class ParsedFeed
{ {
@ -53,16 +56,16 @@ class ParsedFeed
* Parse a feed into an XML tree * Parse a feed into an XML tree
* *
* @param string $content The feed's RSS content * @param string $content The feed's RSS content
* @return array|DOMDocument[]|string[] ['ok' => feed] if successful, ['error' => message] if not * @return Result<DOMDocument, string> The feed if successful, an error message if not
*/ */
public static function parseFeed(string $content): array { public static function parseFeed(string $content): Result {
set_error_handler(self::xmlParseError(...)); set_error_handler(self::xmlParseError(...));
try { try {
$feed = new DOMDocument(); $feed = new DOMDocument();
$feed->loadXML($content); $feed->loadXML($content);
return ['ok' => $feed]; return Success::create($feed);
} catch (DOMException $ex) { } catch (DOMException $ex) {
return ['error' => $ex->getMessage()]; return Error::create($ex->getMessage());
} finally { } finally {
restore_error_handler(); restore_error_handler();
} }
@ -85,13 +88,13 @@ class ParsedFeed
* *
* @param DOMDocument $xml The XML received from the feed * @param DOMDocument $xml The XML received from the feed
* @param string $url The actual URL for the feed * @param string $url The actual URL for the feed
* @return array|Feed[]|string[] ['ok' => feed] if successful, ['error' => message] if not * @return Result<Feed, string> The feed if successful, an error message if not
*/ */
private static function fromRSS(DOMDocument $xml, string $url): array { private static function fromRSS(DOMDocument $xml, string $url): Result {
$channel = $xml->getElementsByTagName('channel')->item(0); $channel = $xml->getElementsByTagName('channel')->item(0);
if (!($channel instanceof DOMElement)) { if (!($channel instanceof DOMElement)) {
$type = $channel?->nodeType ?? -1; $type = $channel?->nodeType ?? -1;
return ['error' => "Channel element not found ($type)"]; return Error::create("Channel element not found ($type)");
} }
// The Atom namespace provides a lastBuildDate, which contains the last time an item in the feed was updated; if // The Atom namespace provides a lastBuildDate, which contains the last time an item in the feed was updated; if
@ -108,7 +111,7 @@ class ParsedFeed
$feed->updatedOn = Data::formatDate($updatedOn); $feed->updatedOn = Data::formatDate($updatedOn);
foreach ($channel->getElementsByTagName('item') as $item) $feed->items[] = ParsedItem::fromRSS($item); foreach ($channel->getElementsByTagName('item') as $item) $feed->items[] = ParsedItem::fromRSS($item);
return ['ok' => $feed]; return Success::create($feed);
} }
/** /**
@ -150,7 +153,7 @@ class ParsedFeed
* *
* @param DOMDocument $xml The XML received from the feed * @param DOMDocument $xml The XML received from the feed
* @param string $url The actual URL for the feed * @param string $url The actual URL for the feed
* @return array|Feed[] ['ok' => feed] * @return Result<Feed, string> The feed (does not have any error handling)
*/ */
private static function fromAtom(DOMDocument $xml, string $url): array { private static function fromAtom(DOMDocument $xml, string $url): array {
$root = $xml->getElementsByTagNameNS(self::ATOM_NS, 'feed')->item(0); $root = $xml->getElementsByTagNameNS(self::ATOM_NS, 'feed')->item(0);
@ -162,91 +165,101 @@ class ParsedFeed
$feed->updatedOn = Data::formatDate($updatedOn); $feed->updatedOn = Data::formatDate($updatedOn);
foreach ($root->getElementsByTagName('entry') as $entry) $feed->items[] = ParsedItem::fromAtom($entry); foreach ($root->getElementsByTagName('entry') as $entry) $feed->items[] = ParsedItem::fromAtom($entry);
return ['ok' => $feed]; return Success::create($feed);
} }
/** /**
* Retrieve a document (http/https) * Retrieve a document (http/https)
* *
* @param string $url The URL of the document to retrieve * @param string $url The URL of the document to retrieve
* @return array ['content' => document content, 'error' => error message, 'code' => HTTP response code, * @return Result<array, string> ['content' => doc content, 'code' => HTTP response code, 'url' => effective URL] if
* 'url' => effective URL] * successful, an error message if not
*/ */
private static function retrieveDocument(string $url): array { private static function retrieveDocument(string $url): Result {
$docReq = curl_init($url); $docReq = curl_init($url);
curl_setopt($docReq, CURLOPT_FOLLOWLOCATION, true); try {
curl_setopt($docReq, CURLOPT_RETURNTRANSFER, true); curl_setopt($docReq, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($docReq, CURLOPT_CONNECTTIMEOUT, 5); curl_setopt($docReq, CURLOPT_RETURNTRANSFER, true);
curl_setopt($docReq, CURLOPT_TIMEOUT, 15); curl_setopt($docReq, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($docReq, CURLOPT_USERAGENT, self::USER_AGENT); curl_setopt($docReq, CURLOPT_TIMEOUT, 15);
curl_setopt($docReq, CURLOPT_USERAGENT, self::USER_AGENT);
$result = [ $error = curl_error($docReq);
'content' => curl_exec($docReq), if ($error <> '') return Error::create($error);
'error' => curl_error($docReq),
'code' => curl_getinfo($docReq, CURLINFO_RESPONSE_CODE),
'url' => curl_getinfo($docReq, CURLINFO_EFFECTIVE_URL)
];
curl_close($docReq); return Success::create([
return $result; 'content' => curl_exec($docReq),
'code' => curl_getinfo($docReq, CURLINFO_RESPONSE_CODE),
'url' => curl_getinfo($docReq, CURLINFO_EFFECTIVE_URL)
]);
} finally {
curl_close($docReq);
}
} }
/** /**
* Derive a feed URL from an HTML document * Derive a feed URL from an HTML document
* *
* @param string $content The HTML document content from which to derive a feed URL * @param string $content The HTML document content from which to derive a feed URL
* @return array|string[] ['ok' => feed URL] if successful, ['error' => message] if not * @return Result<string, string> The feed URL if successful, an error message if not
*/ */
private static function deriveFeedFromHTML(string $content): array { private static function deriveFeedFromHTML(string $content): Result {
$html = new DOMDocument(); $html = new DOMDocument();
$html->loadHTML(substr($content, 0, strpos($content, '</head>') + 7)); $html->loadHTML(substr($content, 0, strpos($content, '</head>') + 7));
$headTags = $html->getElementsByTagName('head'); $headTags = $html->getElementsByTagName('head');
if ($headTags->length < 1) return ['error' => 'Cannot find feed at this URL']; if ($headTags->length < 1) return Error::create('Cannot find feed at this URL');
$head = $headTags->item(0); $head = $headTags->item(0);
foreach ($head->getElementsByTagName('link') as $link) { foreach ($head->getElementsByTagName('link') as $link) {
if (self::attrValue($link, 'rel') == 'alternate') { if (self::attrValue($link, 'rel') == 'alternate') {
$type = self::attrValue($link, 'type'); $type = self::attrValue($link, 'type');
if ($type == 'application/rss+xml' || $type == 'application/atom+xml') { if ($type == 'application/rss+xml' || $type == 'application/atom+xml') {
return ['ok' => self::attrValue($link, 'href')]; return Success::create(self::attrValue($link, 'href'));
} }
} }
} }
return ['error' => 'Cannot find feed at this URL']; return Error::create('Cannot find feed at this URL');
} }
/** /**
* Retrieve the feed * Retrieve the feed
* *
* @param string $url The URL of the feed to retrieve * @param string $url The URL of the feed to retrieve
* @return array|ParsedFeed[]|string[] ['ok' => feed] if successful, ['error' => message] if not * @return Result<ParsedFeed, string> The feed if successful, an error message if not
*/ */
public static function retrieve(string $url): array { public static function retrieve(string $url): Result {
$doc = self::retrieveDocument($url); $tryDoc = self::retrieveDocument($url);
if ($doc['error'] != '') return ['error' => $doc['error']]; if ($tryDoc->error()->isDefined()) return $tryDoc->error()->get();
$doc = $tryDoc->success()->get();
if ($doc['code'] != 200) { if ($doc['code'] != 200) {
return ['error' => "Prospective feed URL $url returned HTTP Code {$doc['code']}: {$doc['content']}"]; return Error::create("Prospective feed URL $url returned HTTP Code {$doc['code']}: {$doc['content']}");
} }
$start = strtolower(strlen($doc['content']) >= 9 ? substr($doc['content'], 0, 9) : $doc['content']); $start = strtolower(strlen($doc['content']) >= 9 ? substr($doc['content'], 0, 9) : $doc['content']);
if ($start == '<!doctype' || str_starts_with($start, '<html')) { if ($start == '<!doctype' || str_starts_with($start, '<html')) {
$derivedURL = self::deriveFeedFromHTML($doc['content']); $derivedURL = self::deriveFeedFromHTML($doc['content']);
if (key_exists('error', $derivedURL)) return ['error' => $derivedURL['error']]; if ($derivedURL->error()->isDefined()) return $derivedURL->error()->get();
$feedURL = $derivedURL['ok']; $feedURL = $derivedURL->success()->get();
if (!str_starts_with($feedURL, 'http')) { if (!str_starts_with($feedURL, 'http')) {
// Relative URL; feed should be retrieved in the context of the original URL // Relative URL; feed should be retrieved in the context of the original URL
$original = parse_url($url); $original = parse_url($url);
$port = key_exists('port', $original) ? ":{$original['port']}" : ''; $port = key_exists('port', $original) ? ":{$original['port']}" : '';
$feedURL = $original['scheme'] . '://' . $original['host'] . $port . $feedURL; $feedURL = $original['scheme'] . '://' . $original['host'] . $port . $feedURL;
} }
$doc = self::retrieveDocument($feedURL); $tryDoc = self::retrieveDocument($feedURL);
if ($tryDoc->error()->isDefined()) return $tryDoc->error()->get();
$doc = $tryDoc->success()->get();
if ($doc['code'] != 200) {
return Error::create("Derived feed URL $url returned HTTP Code {$doc['code']}: {$doc['content']}");
}
} }
$parsed = self::parseFeed($doc['content']); $tryParse = self::parseFeed($doc['content']);
if (key_exists('error', $parsed)) return ['error' => $parsed['error']]; if ($tryParse->error()->isDefined()) return $tryParse->error()->get();
$extract = $parsed['ok']->getElementsByTagNameNS(self::ATOM_NS, 'feed')->length > 0 $parsed = $tryParse->success()->get();
$extract = $parsed->getElementsByTagNameNS(self::ATOM_NS, 'feed')->length > 0
? self::fromAtom(...) : self::fromRSS(...); ? self::fromAtom(...) : self::fromRSS(...);
return $extract($parsed['ok'], $doc['url']); return $extract($parsed, $doc['url']);
} }
} }

View File

@ -66,7 +66,7 @@ class Security
$dbEmail = $email; $dbEmail = $email;
} }
$user = User::findByEmail($dbEmail); $user = User::findByEmail($dbEmail);
if ($user) self::verifyPassword($user, $password, $returnTo); if ($user->isDefined()) self::verifyPassword($user->get(), $password, $returnTo);
add_error('Invalid credentials; log on unsuccessful'); add_error('Invalid credentials; log on unsuccessful');
} }
@ -89,11 +89,11 @@ class Security
*/ */
private static function logOnSingleUser(): void { private static function logOnSingleUser(): void {
$user = User::findByEmail(self::SINGLE_USER_EMAIL); $user = User::findByEmail(self::SINGLE_USER_EMAIL);
if (!$user) { if ($user->isEmpty()) {
User::add(self::SINGLE_USER_EMAIL, self::SINGLE_USER_PASSWORD); User::add(self::SINGLE_USER_EMAIL, self::SINGLE_USER_PASSWORD);
$user = User::findByEmail(self::SINGLE_USER_EMAIL); $user = User::findByEmail(self::SINGLE_USER_EMAIL);
} }
self::verifyPassword($user, self::SINGLE_USER_PASSWORD, $_GET['returnTo']); self::verifyPassword($user->get(), self::SINGLE_USER_PASSWORD, $_GET['returnTo']);
} }
/** /**

View File

@ -4,6 +4,7 @@ namespace FeedReaderCentral;
use BitBadger\PDODocument\{Custom, Document, DocumentException, Field, Find, Parameters, Query}; use BitBadger\PDODocument\{Custom, Document, DocumentException, Field, Find, Parameters, Query};
use BitBadger\PDODocument\Mapper\ExistsMapper; use BitBadger\PDODocument\Mapper\ExistsMapper;
use PhpOption\Option;
/** /**
* A user of Feed Reader Central * A user of Feed Reader Central
@ -23,10 +24,10 @@ class User
* Find a user by their e=mail address * Find a user by their e=mail address
* *
* @param string $email The e-mail address of the user to retrieve * @param string $email The e-mail address of the user to retrieve
* @return User|false The user information, or null if the user is not found * @return Option<User> A `Some` value with the user information if found, `None` otherwise
* @throws DocumentException If any is encountered * @throws DocumentException If any is encountered
*/ */
public static function findByEmail(string $email): User|false public static function findByEmail(string $email): Option
{ {
return Find::firstByFields(Table::USER, [Field::EQ('email', $email)], User::class); return Find::firstByFields(Table::USER, [Field::EQ('email', $email)], User::class);
} }

View File

@ -13,9 +13,8 @@ include '../start.php';
FeedReaderCentral\Security::verifyUser(); FeedReaderCentral\Security::verifyUser();
$id = key_exists('id', $_GET) ? (int)$_GET['id'] : -1; $id = key_exists('id', $_GET) ? (int)$_GET['id'] : -1;
$item = ItemWithFeed::retrieveById($id)->getOrCall(not_found(...));
if (!$item = ItemWithFeed::retrieveById($id)) not_found();
if (key_exists('action', $_GET)) { if (key_exists('action', $_GET)) {
$flag = match ($_GET['action']) { $flag = match ($_GET['action']) {

View File

@ -8,6 +8,7 @@
use BitBadger\PDODocument\{Delete, DocumentException, Field}; use BitBadger\PDODocument\{Delete, DocumentException, Field};
use FeedReaderCentral\{Feed, Security, Table}; use FeedReaderCentral\{Feed, Security, Table};
use GrahamCampbell\ResultType\Error;
include '../../start.php'; include '../../start.php';
@ -17,7 +18,7 @@ $feedId = key_exists('id', $_GET) ? (int)$_GET['id'] : -1;
if ($_SERVER['REQUEST_METHOD'] == 'DELETE') { if ($_SERVER['REQUEST_METHOD'] == 'DELETE') {
try { try {
if (!($feed = Feed::retrieveById($feedId))) not_found(); $feed = Feed::retrieveById($feedId)->getOrCall(not_found(...));
Delete::byFields(Table::ITEM, [Field::EQ('feed_id', $feed->id)]); Delete::byFields(Table::ITEM, [Field::EQ('feed_id', $feed->id)]);
Delete::byId(Table::FEED, $feed->id); Delete::byId(Table::FEED, $feed->id);
add_info('Feed &ldquo;' . htmlentities($feed->title) . '&rdquo; deleted successfully'); add_info('Feed &ldquo;' . htmlentities($feed->title) . '&rdquo; deleted successfully');
@ -35,15 +36,15 @@ if ($_SERVER['REQUEST_METHOD'] == 'POST') {
} else { } else {
$feedId = (int)$_POST['id']; $feedId = (int)$_POST['id'];
$toEdit = Feed::retrieveById($feedId); $toEdit = Feed::retrieveById($feedId);
$result = $toEdit $result = $toEdit->isDefined()
? Feed::update($toEdit, $_POST['url']) ? Feed::update($toEdit->get(), $_POST['url'])
: ['error' => "Feed $feedId not found"]; : Error::create("Feed $feedId not found");
} }
if (key_exists('ok', $result)) { if ($result->success()->isDefined()) {
add_info('Feed saved successfully'); add_info('Feed saved successfully');
frc_redirect('/feeds'); frc_redirect('/feeds');
} }
add_error($result['error']); add_error($result->error()->get());
$feedId = 'error'; $feedId = 'error';
} catch (DocumentException $ex) { } catch (DocumentException $ex) {
add_error("$ex"); add_error("$ex");
@ -55,9 +56,9 @@ if ($feedId == -1) {
$feed = new Feed(id: -1); $feed = new Feed(id: -1);
} else { } else {
$title = 'Edit RSS Feed'; $title = 'Edit RSS Feed';
if ($feedId == 'error') { $feed = $feedId == 'error'
$feed = new Feed(id: (int)$_POST['id'], url: $_POST['url'] ?? ''); ? new Feed(id: (int)$_POST['id'], url: $_POST['url'] ?? '')
} elseif (!($feed = Feed::retrieveById((int)$feedId))) not_found(); : Feed::retrieveById((int)$feedId)->getOrCall(not_found(...));
} }
page_head($title); ?> page_head($title); ?>

View File

@ -13,7 +13,7 @@ include '../../start.php';
FeedReaderCentral\Security::verifyUser(); FeedReaderCentral\Security::verifyUser();
$id = key_exists('id', $_GET) ? (int)$_GET['id'] : -1; $id = key_exists('id', $_GET) ? (int)$_GET['id'] : -1;
if (!($feed = Feed::retrieveById($id))) not_found(); $feed = Feed::retrieveById($id)->getOrCall(not_found(...));
$list = match (true) { $list = match (true) {
key_exists('unread', $_GET) => ItemList::unreadForFeed($feed->id), key_exists('unread', $_GET) => ItemList::unreadForFeed($feed->id),

View File

@ -26,7 +26,7 @@ foreach ($feeds->items() as /** @var Feed $feed */ $feed) {
SELECT (SELECT COUNT(*) FROM $item WHERE data->>'feed_id' = :feed) AS total, SELECT (SELECT COUNT(*) FROM $item WHERE data->>'feed_id' = :feed) AS total,
(SELECT COUNT(*) FROM $item WHERE data->>'feed_id' = :feed AND data->>'is_read' = 0) AS unread, (SELECT COUNT(*) FROM $item WHERE data->>'feed_id' = :feed AND data->>'is_read' = 0) AS unread,
(SELECT COUNT(*) FROM $item WHERE data->>'feed_id' = :feed AND data->>'is_bookmarked' = 1) AS marked (SELECT COUNT(*) FROM $item WHERE data->>'feed_id' = :feed AND data->>'is_bookmarked' = 1) AS marked
SQL, [':feed' => $feed->id], new ArrayMapper()) ?? ['total' => 0, 'unread' => 0, 'marked' => 0]; SQL, [':feed' => $feed->id], new ArrayMapper())->getOrElse(['total' => 0, 'unread' => 0, 'marked' => 0]);
echo '<p><strong>' . htmlentities($feed->title) . '</strong><br>' echo '<p><strong>' . htmlentities($feed->title) . '</strong><br>'
. '<span class=meta><em>Last Updated ' . date_time($feed->updated_on) . ' &bull; ' . '<span class=meta><em>Last Updated ' . date_time($feed->updated_on) . ' &bull; '
. 'As of ' . date_time($feed->checked_on) . '</em><br>' . hx_get("/feed/?id=$feed->id", 'Edit') . ' &bull; ' . 'As of ' . date_time($feed->checked_on) . '</em><br>' . hx_get("/feed/?id=$feed->id", 'Edit') . ' &bull; '

View File

@ -14,10 +14,10 @@ FeedReaderCentral\Security::verifyUser();
if (key_exists('refresh', $_GET)) { if (key_exists('refresh', $_GET)) {
$refreshResult = Feed::refreshAll(); $refreshResult = Feed::refreshAll();
if (key_exists('ok', $refreshResult)) { if ($refreshResult->success()->isDefined()) {
add_info('All feeds refreshed successfully'); add_info('All feeds refreshed successfully');
} else { } else {
add_error(nl2br($refreshResult['error'])); add_error(nl2br($refreshResult->error()->get()));
} }
} }

View File

@ -42,7 +42,7 @@ if ($_SERVER['REQUEST_METHOD'] == 'DELETE') {
frc_redirect($from); frc_redirect($from);
} }
if (!$item = ItemWithFeed::retrieveById($id)) not_found(); !$item = ItemWithFeed::retrieveById($id)->getOrCall(not_found(...));
try { try {
Patch::byId(Table::ITEM, $id, ['is_read' => 1]); Patch::byId(Table::ITEM, $id, ['is_read' => 1]);
} catch (DocumentException $ex) { } catch (DocumentException $ex) {

View File

@ -41,7 +41,8 @@ function display_help(): never
function json_column_exists(): bool function json_column_exists(): bool
{ {
try { try {
$table = Custom::single("SELECT sql FROM sqlite_master WHERE tbl_name='frc_user'", [], new ArrayMapper()); $table = Custom::single("SELECT sql FROM sqlite_master WHERE tbl_name='frc_user'", [], new ArrayMapper())
->getOrElse(['sql' => '']);
return $table && substr_compare(strtolower($table['sql']), 'data text not null', 0) >= 0; return $table && substr_compare(strtolower($table['sql']), 'data text not null', 0) >= 0;
} catch (DocumentException $ex) { } catch (DocumentException $ex) {
printfn("ERR $ex"); printfn("ERR $ex");

View File

@ -37,10 +37,13 @@ function refresh_all(): void
foreach (Feed::retrieveAll()->items() as /** @var Feed $feed */ $feed) { foreach (Feed::retrieveAll()->items() as /** @var Feed $feed */ $feed) {
$result = Feed::refreshFeed($feed->id, $feed->url); $result = Feed::refreshFeed($feed->id, $feed->url);
$userKey = "$feed->user_id"; $userKey = "$feed->user_id";
if (!key_exists($userKey, $users)) $users[$userKey] = Find::byId(Table::USER, $feed->user_id, User::class); if (!key_exists($userKey, $users)) {
if (array_key_exists('error', $result)) { $users[$userKey] = Find::byId(Table::USER, $feed->user_id, User::class)
->getOrElse(new User(email: 'user-not-found'));
}
if ($result->error()->isDefined()) {
printfn('ERR (%s) %s', $users[$userKey]->email, $feed->url); printfn('ERR (%s) %s', $users[$userKey]->email, $feed->url);
printfn(' %s', $result['error']); printfn(' %s', $result->error()->get());
} else { } else {
printfn('OK (%s) %s', $users[$userKey]->email, $feed->url); printfn('OK (%s) %s', $users[$userKey]->email, $feed->url);
} }

View File

@ -92,7 +92,7 @@ function add_user(): void
try { try {
// Ensure there is not already a user with this e-mail address // Ensure there is not already a user with this e-mail address
$user = User::findByEmail($argv[2]); $user = User::findByEmail($argv[2]);
if ($user) { if ($user->isDefined()) {
printfn('A user with e-mail address "%s" already exists', $argv[2]); printfn('A user with e-mail address "%s" already exists', $argv[2]);
return; return;
} }
@ -126,7 +126,7 @@ function set_password(string $email, string $password): void
// Ensure this user exists // Ensure this user exists
$user = User::findByEmail($email); $user = User::findByEmail($email);
if (!$user) { if ($user->isEmpty()) {
printfn('No %s exists', $displayUser); printfn('No %s exists', $displayUser);
return; return;
} }
@ -152,12 +152,13 @@ function delete_user(string $email): void
$displayUser = display_user($email); $displayUser = display_user($email);
// Get the user for the provided e-mail address // Get the user for the provided e-mail address
$user = User::findByEmail($email); $tryUser = User::findByEmail($email);
if (!$user) { if ($tryUser->isEmpty()) {
printfn('No %s exists', $displayUser); printfn('No %s exists', $displayUser);
return; return;
} }
$user = $tryUser->get();
try { try {
$feedCount = Count::byFields(Table::FEED, [Field::EQ('user_id', $user->id)]); $feedCount = Count::byFields(Table::FEED, [Field::EQ('user_id', $user->id)]);
} catch (DocumentException $ex) { } catch (DocumentException $ex) {
@ -196,12 +197,13 @@ function migrate_single_user(): void
global $argv; global $argv;
try { try {
if (!$single = User::findByEmail(Security::SINGLE_USER_EMAIL)) { $single = User::findByEmail(Security::SINGLE_USER_EMAIL);
if ($single->isEmpty()) {
printfn('There is no single-user mode user to be migrated'); printfn('There is no single-user mode user to be migrated');
return; return;
} }
Patch::byId(Table::USER, $single->id, Patch::byId(Table::USER, $single->get()->id,
['email' => $argv[2], 'password' => password_hash($argv[3], Security::PW_ALGORITHM)]); ['email' => $argv[2], 'password' => password_hash($argv[3], Security::PW_ALGORITHM)]);
printfn('The single user has been moved to "%s", with password "%s"', $argv[2], $argv[3]); printfn('The single user has been moved to "%s", with password "%s"', $argv[2], $argv[3]);