summaryrefslogtreecommitdiff
path: root/includes/model/Category.php
blob: 8aa489c92c4f71e94f2497533a2079298ed60f03 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
<?php

include_once 'Thread.php';

class Category
{
	public $id;
	public $name;
	public $description;
	public $thread_count = 0;
	public $post_count = 0;

	// If an invalid id was passed into the constructor, the database will not have
	// returned a result, but the object will not be null. 
	// We need to keep track of whether or not this object has a value.
	private $has_value = false;

	public function __construct($id)
	{
		$sql = "SELECT category_name, category_description, category_thread_count, category_post_count FROM categories WHERE category_id = ?;";
		$result = Database::get()->query($sql, "i", $id);

		if (empty($result)) {
			return;
		}

		$this->id = $id;
		$this->name = $result[0]['category_name'];
		$this->description = $result[0]['category_description'];
		$this->thread_count = $result[0]['category_thread_count'];
		$this->post_count = $result[0]['category_post_count'];

		$this->has_value = true;
	}

	// Returns true if this object was successfully fetched from the database
	public function has_value(): bool
    {
		return $this->has_value;
	}

	public static function get_all_categories(): array
	{
		$sql = "SELECT category_id FROM categories ORDER BY category_id;";
		$result = Database::get()->query($sql);

		$categories = array();

		foreach ($result as $row) {
			$category = new Category($row['category_id']);
			array_push($categories, $category);
		}

		return $categories;
	}

	public function get_threads(): array
	{
		$sql = "SELECT thread_id FROM threads WHERE thread_category = ? ORDER BY thread_last_post_date DESC";
		$result = Database::get()->query($sql, "i", $this->id);
		$threads = array();

		foreach ($result as $row) {
			$thread = new Thread($row['thread_id']);
			if ($thread->has_value())
				array_push($threads, $thread);
		}

		return $threads;
	}

	public function get_latest_thread(): Thread
	{
		$sql = "SELECT thread_id FROM threads WHERE thread_category = ? ORDER BY thread_last_post_date DESC LIMIT 1";
		$result = Database::get()->query($sql, "i", $this->id);
		return new Thread($result[0]['thread_id']);
	}
}