Skip to content
Merged
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
2 changes: 1 addition & 1 deletion src/App/templates/partial/left-menu.html.twig
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@
<li>
<a href="{{ url('page::category-resource', {slug: category.slug}) }}">
{{ category.name }}
<span class="cat-count">{{ category.posts.count() }}</span>
<span class="cat-count">{{ category.publishedPostsCount }}</span>
</a>
</li>
{% endfor %}
Expand Down
12 changes: 11 additions & 1 deletion src/Blog/src/Entity/Category.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,11 @@

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\Common\Collections\Criteria;
use Doctrine\Common\Collections\Selectable;
use Doctrine\ORM\Mapping as ORM;
use Light\App\Entity\AbstractEntity;
use Light\Blog\Enum\PostStatusEnum;
use Light\Blog\Repository\CategoryRepository;

#[ORM\Entity(repositoryClass: CategoryRepository::class)]
Expand All @@ -24,7 +27,7 @@ class Category extends AbstractEntity
#[ORM\Column(name: 'isVisible', type: 'boolean')]
private bool $isVisible = true;

/** @var Collection<int, Post> */
/** @var Collection<int, Post>&Selectable<int, Post> */
#[ORM\OneToMany(mappedBy: 'category', targetEntity: Post::class)]
private Collection $posts;

Expand Down Expand Up @@ -73,6 +76,13 @@ public function getPosts(): Collection
return $this->posts;
}

public function getPublishedPostsCount(): int
{
$criteria = Criteria::create()->where(Criteria::expr()->eq('status', PostStatusEnum::Published));

return $this->posts->matching($criteria)->count();
}

/**
* @return array{
* id: non-empty-string,
Expand Down
33 changes: 33 additions & 0 deletions test/Unit/Blog/Entity/CategoryTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
<?php

declare(strict_types=1);

namespace LightTest\Unit\Blog\Entity;

use Light\Blog\Entity\Category;
use Light\Blog\Entity\Post;
use Light\Blog\Enum\PostStatusEnum;
use LightTest\Unit\UnitTest;

class CategoryTest extends UnitTest
{
public function testGetPublishedPostsCountOnlyCountsPublishedPosts(): void
{
$category = new Category();

$published = new Post();
$published->setStatus(PostStatusEnum::Published);

$draft = new Post();
$draft->setStatus(PostStatusEnum::Draft);

$private = new Post();
$private->setStatus(PostStatusEnum::Private);

$category->getPosts()->add($published);
$category->getPosts()->add($draft);
$category->getPosts()->add($private);

self::assertSame(1, $category->getPublishedPostsCount());
}
}