Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions Server/App/Model/Product.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,13 +28,13 @@ public function __construct(ContainerInterface $container)
$this->db = $container->get(Database::class);
}

public function get(int $productId): stdClass
public function get(int $productId): ?stdClass
{
$stmt = $this->db->prepare(self::QUERY_GET_PRODUCT);
$stmt->bindValue('productId', $productId, PDO::PARAM_INT);
$stmt->execute();

return $stmt->fetchObject();
return $stmt->fetchObject() ?: null;
}

public function search(string $keywords, int $offset = null, int $limit = null): array
Expand Down
40 changes: 40 additions & 0 deletions Test/Server/App/Model/ProductTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
<?php

declare(strict_types=1);

namespace Lifyzer\Test\Server\App\Model;

use Lifyzer\Server\App\Model\Product;
use PDO;
use PHPUnit\Framework\TestCase;
use Psr\Container\ContainerInterface;

/** @requires extension pdo_sqlite */
class ProductTest extends TestCase
{
private function model(): Product
{
$db = new PDO('sqlite::memory:');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->exec('CREATE TABLE product (id INTEGER PRIMARY KEY, product_name TEXT)');
$db->exec("INSERT INTO product VALUES (1, 'Apple')");
$container = new class($db) implements ContainerInterface {
private $db;
public function __construct(PDO $db) { $this->db = $db; }
public function get($id) { return $this->db; }
public function has($id): bool { return true; }
};
return new Product($container);
}

public function testExistingProductRetainsItsData(): void
{
$product = $this->model()->get(1);
self::assertSame('Apple', $product->product_name);
}

public function testMissingProductCanBeHandledByTheController(): void
{
self::assertNull($this->model()->get(999));
}
}