Skip to main content

Lesson 5 of 6

Code Quality - PHPStan, PSR-12 & Testing Basics

Code quality tools catch bugs before runtime - PHPStan performs static analysis (finds type errors, unreachable code, missing methods) and PSR-12 enforces consistent formatting. PHPUnit tests verify that your code does what it says. These tools together form the minimum quality gate for production PHP code.

12 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

PHPStan, PSR-12 & PHPUnit - Quality Pipeline

PHPStan, PSR-12 & PHPUnit - Quality Pipeline
# ── PHPStan - static analysis ─────────────────────────────────
# composer require phpstan/phpstan --dev
# phpstan analyse src tests --level=8

# Error levels 0-9:
# 0: basic checks
# 5: type checking, unknown methods
# 8: strict types, nullable issues
# 9: max strictness - catches almost all type issues

# phpstan.neon configuration
# parameters:
#   level: 8
#   paths:
#     - src
#     - tests
#   ignoreErrors:
#     - '#Call to an undefined method Mockery\\MockInterface#'
#   checkMissingIterableValueType: true
#   checkGenericClassInNonGenericObjectType: true

# ── PSR-12 - formatting standard ─────────────────────────────
# composer require squizlabs/php_codesniffer --dev
# phpcs src --standard=PSR12        (check)
# phpcbf src --standard=PSR12       (auto-fix)

<?php
// PSR-12 key rules:
// - 4 spaces indentation (no tabs)
// - Opening braces on same line for control structures: if () {
// - Opening braces on new line for classes and methods:
//   class Foo
//   {
//       public function bar(): void
//       {
//       }
//   }
// - declare(strict_types=1); at top of every file
// - blank line between methods
// - Type declarations on all parameters and return types
// - Visibility modifier on all properties and methods

// ── PHPUnit - unit testing ────────────────────────────────────
// composer require phpunit/phpunit --dev
// Already demonstrated in Module 5's InMemoryPostRepository!

use PHPUnitFrameworkTestCase;

class PostServiceTest extends TestCase {
    private PostService  $service;
    private InMemoryPostRepository $repo;

    protected function setUp(): void {
        $this->repo    = new InMemoryPostRepository();
        $this->service = new PostService($this->repo, new NullEventDispatcher());
    }

    public function test_list_published_returns_only_published(): void {
        $draft    = $this->makePost(status: "draft");
        $published = $this->makePost(status: "published");
        $this->repo->save($draft);
        $this->repo->save($published);

        $result = $this->service->listPublished(page: 1, perPage: 10);
        $this->assertCount(1, $result["items"]);
        $this->assertSame("published", $result["items"][0]->getStatus()->value);
    }

    public function test_publish_sets_status_to_published(): void {
        $post = $this->repo->save($this->makePost(status: "draft"));
        $published = $this->service->publishPost($post->id);
        $this->assertSame("published", $published->getStatus()->value);
    }

    public function test_publish_already_published_throws(): void {
        $post = $this->repo->save($this->makePost(status: "published"));
        $this->expectException(LogicException::class);
        $this->service->publishPost($post->id);
    }

    private function makePost(string $status = "draft"): Post {
        return new Post(
            id:     0,
            title:  "Test Post",
            slug:   "test-post-" . uniqid(),
            body:   "Test body content here.",
            status: PostStatus::from($status),
            author: new Author("Test User", new Email("test@example.com")),
        );
    }
}

# ── Run quality checks ─────────────────────────────────────────
# composer test          → PHPUnit
# composer analyse       → PHPStan level 8
# composer cs            → PSR-12 check
# composer cs-fix        → PSR-12 auto-fix

# ── GitHub Actions CI pipeline ────────────────────────────────
# .github/workflows/ci.yml
# on: [push, pull_request]
# jobs:
#   quality:
#     runs-on: ubuntu-latest
#     steps:
#       - uses: actions/checkout@v4
#       - uses: shivammathur/setup-php@v2
#         with: { php-version: '8.2', extensions: 'mbstring, pdo, pdo_mysql' }
#       - run: composer install --no-dev --optimize-autoloader
#       - run: composer analyse
#       - run: composer cs
#       - run: composer test

Quick Quiz

Tip

Tip

Practice Code Quality PHPStan PSR12 Testing Basics in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagram…

Visual architecture and concepts for Code Quality - PHPStan, PSR-12 & Testing Basics

Practice Task

Note

Practice Task - (1) Write a working example of Code Quality PHPStan PSR12 Testing Basics from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Common Mistake

Warning

A common mistake with Code Quality PHPStan PSR12 Testing Basics is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready php code.

Hands-on Practice Tools for this Course

Test what you learn using these free in-browser developer utilities (no signup required).

All 40+ Tools

Topics in This Module

0/6 done