- Add `Json` string and output functions
- Add documentation for these functions

Reviewed-on: #10
This commit was merged in pull request #10.
This commit is contained in:
2025-04-25 01:17:52 +00:00
parent f6756d79f1
commit 44c3670f2e
15 changed files with 1449 additions and 262 deletions

View File

@@ -10,6 +10,7 @@ namespace BitBadger\PDODocument;
use BitBadger\InspiredByFSharp\Option;
use BitBadger\PDODocument\Mapper\Mapper;
use BitBadger\PDODocument\Mapper\StringMapper;
use PDO;
use PDOException;
use PDOStatement;
@@ -93,7 +94,42 @@ class Custom
}
/**
* Execute a query that returns one or no results (returns false if not found)
* Execute a query that returns a JSON string of results
*
* @param string $query The query to be executed
* @param array<string, mixed> $parameters Parameters to use in executing the query
* @return string A JSON array with the results (empty results will be `[]`)
* @throws DocumentException If any is encountered
*/
public static function jsonArray(string $query, array $parameters): string
{
return '[' . implode(',', self::array($query, $parameters, new StringMapper('data'))) . ']';
}
/**
* Execute a query, echoing the results to the output
*
* @param string $query The query to be executed
* @param array<string, mixed> $parameters Parameters to use in executing the query
* @throws DocumentException If any is encountered
*/
public static function outputJsonArray(string $query, array $parameters): void
{
$isFirst = true;
echo '[';
foreach (self::list($query, $parameters, new StringMapper('data'))->items as $doc) {
if ($isFirst) {
$isFirst = false;
} else {
echo ',';
}
echo $doc;
}
echo ']';
}
/**
* Execute a query that returns one or no results
*
* @template TDoc The domain type of the document to retrieve
* @param string $query The query to be executed (will have "LIMIT 1" appended)
@@ -112,6 +148,19 @@ class Custom
}
}
/**
* Execute a query that returns one or no JSON results
*
* @param string $query The query to be executed (will have "LIMIT 1" appended)
* @param array<string, mixed> $parameters Parameters to use in executing the query
* @return string The JSON document (returns `{}` if no document is found)
* @throws DocumentException If any is encountered
*/
public static function jsonSingle(string $query, array $parameters): string
{
return self::single($query, $parameters, new StringMapper('data'))->getOrDefault('{}');
}
/**
* Execute a query that does not return a value
*