PHPackages                             ncac/phpcs-standard - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [PSR &amp; Standards](/categories/psr-standards)
4. /
5. ncac/phpcs-standard

ActivePhpcodesniffer-standard[PSR &amp; Standards](/categories/psr-standards)

ncac/phpcs-standard
===================

NCAC PHPCS Standard - TypeScript-like approach to PHP code quality with strict rules for modern, type-safe development

v4.1.5(4mo ago)1425↓50%MITPHPPHP ^8.1CI passing

Since Oct 22Pushed 4mo ago1 watchersCompare

[ Source](https://github.com/NCAC/phpcs-standard)[ Packagist](https://packagist.org/packages/ncac/phpcs-standard)[ Docs](https://github.com/ncac/phpcs-standard)[ RSS](/packages/ncac-phpcs-standard/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (10)Dependencies (11)Versions (15)Used By (0)

NCAC PHPCS Standard
===================

[](#ncac-phpcs-standard)

[![Build Status](https://github.com/ncac/phpcs-standard/actions/workflows/ci.yml/badge.svg)](https://github.com/ncac/phpcs-standard/actions/workflows/ci.yml)[![Latest Stable Version](https://camo.githubusercontent.com/b92b88d8b34cca5394a6526c81a4d2eee0e8b67acdc667b0c4a0fcdc88766b65/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6e6361632f70687063732d7374616e64617264)](https://packagist.org/packages/ncac/phpcs-standard)[![Total Downloads](https://camo.githubusercontent.com/647e44e51d657d525076326ec250f8356044ade0c2f7e228a67163cddfe6e3b2/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f6e6361632f70687063732d7374616e64617264)](https://packagist.org/packages/ncac/phpcs-standard)[![PHP Version](https://camo.githubusercontent.com/2c1052ac2cc215ef1c394861c235be984f70cfb27f0d31cb456c89b306bfda9d/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f7068702d762f6e6361632f70687063732d7374616e64617264)](https://packagist.org/packages/ncac/phpcs-standard)[![codecov](https://camo.githubusercontent.com/7d61d76cd3bdb25b9ba7f6e695d804d9cbb6dca13456bdd32e13511f7197cef7/68747470733a2f2f636f6465636f762e696f2f67682f6e6361632f70687063732d7374616e646172642f6272616e63682f6d61696e2f67726170682f62616467652e737667)](https://codecov.io/gh/ncac/phpcs-standard)[![License](https://camo.githubusercontent.com/e0277f14b675ac0170c80ad55ca65089b5b02a77a7edfa07cb2c84077912d900/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6c6963656e73652f6e6361632f70687063732d7374616e64617264)](https://github.com/ncac/phpcs-standard/blob/main/LICENSE)

> **An opinionated PHP coding standard focused on type safety and consistency**
>
> NCAC is a comprehensive PHP\_CodeSniffer standard that enforces strict typing, consistent naming conventions, and 2-space indentation. Built on top of proven standards like Slevomat, it adds custom rules designed for modern PHP development practices.

🎯 Key Features
--------------

[](#-key-features)

### **Strict Type Safety**

[](#strict-type-safety)

Enforces explicit type declarations for all parameters, return values, and properties to catch errors early and improve code clarity.

```
// ❌ Avoided: ambiguous types
function process($data) {
    return $data->value;
}

// ✅ Required: explicit types
function process(DataObject $data): string {
  return $data->value;
}
```

### **2-Space Indentation with Smart Array Handling**

[](#2-space-indentation-with-smart-array-handling)

Uses 2-space indentation with context-aware formatting for arrays and function arguments.

```
// ✅ Function arguments formatting
$result = my_function([
  'clean' => 'readable',
  'consistent' => 'maintainable'
]);

// ✅ Nested arrays maintain hierarchy
$config = [
  'database' => [
    'host' => 'localhost',
    'port' => 3306
  ]
];
```

### **Consistent Naming Conventions**

[](#consistent-naming-conventions)

Enforces context-appropriate naming: `snake_case` for variables and functions, `camelCase` for class properties and methods, `PascalCase` for classes.

```
// ✅ Consistent naming across contexts
class UserRepository {

  private string $connectionString;  // camelCase property

  public function findUser(int $user_id): User {  // snake_case parameter
    $query_result = $this->executeQuery($user_id);  // snake_case variable
    return $this->mapToUser($query_result);  // camelCase method
  }

}
```

🏗️ What Makes NCAC Different?
-----------------------------

[](#️-what-makes-ncac-different)

This is an **opinionated** standard that makes specific choices about code formatting and structure. While these choices work well for many teams, they may not suit every project or preference.

### **Built on Proven Foundations**

[](#built-on-proven-foundations)

- Extends **Slevomat Coding Standard** for type safety and structural rules
- Adds **7 custom sniffs** for specific formatting requirements
- Requires **PHP 8.0+** for modern type safety features (union types, named arguments, etc.)
- Designed for **auto-fixing** to minimize manual formatting work

> **Note:** For PHP 7.4 support, use version `^1.2.0`. See [BREAKING\_CHANGES.md](BREAKING_CHANGES.md) for migration details.

### **Opinionated Choices**

[](#opinionated-choices)

- **2-space indentation** instead of the more common 4-space
- **Strict type hints** required everywhere (may be challenging for legacy code)
- **Specific naming conventions** that mix snake\_case and camelCase based on context
- **Minimal class spacing** for compact, readable code structure

### **When to Consider NCAC**

[](#when-to-consider-ncac)

✅ **Good fit for:**

- New projects starting fresh
- Teams that prefer strict typing and consistent formatting
- Projects that can adopt 2-space indentation
- Codebases that can enforce type hints everywhere

⚠️ **Consider carefully for:**

- Large legacy codebases (strict typing requirements)
- Teams strongly preferring 4-space indentation
- Projects with existing PSR-12 compliance requirements
- Mixed coding style preferences within the team

📊 Quality Assurance
-------------------

[](#-quality-assurance)

### Continuous Integration (PHP 8.0 - 8.2)

[](#continuous-integration-php-80---82)

[![Psalm Analysis](https://github.com/ncac/phpcs-standard/actions/workflows/ci.yml/badge.svg?branch=main&job=psalm)](https://github.com/ncac/phpcs-standard/actions/workflows/ci.yml)[![PHPCS Analysis](https://github.com/ncac/phpcs-standard/actions/workflows/ci.yml/badge.svg?branch=main&job=phpcs)](https://github.com/ncac/phpcs-standard/actions/workflows/ci.yml)[![PHPUnit Tests](https://github.com/ncac/phpcs-standard/actions/workflows/ci.yml/badge.svg?branch=main&job=phpunit)](https://github.com/ncac/phpcs-standard/actions/workflows/ci.yml)

⚡ Quick Start
-------------

[](#-quick-start)

### Requirements

[](#requirements)

- **PHP 8.0+** (for PHP 7.4 support, use version `^1.2.0`)
- Composer

### Installation

[](#installation)

```
composer require --dev ncac/phpcs-standard
```

### Basic Usage

[](#basic-usage)

#### Quick Start: One-Line Command

[](#quick-start-one-line-command)

The easiest way to apply the full NCAC formatting workflow:

```
# Using the dedicated command (recommended)
vendor/bin/ncac-format src/

# Preview changes without applying them
vendor/bin/ncac-format --dry-run src/

# Format all files in current directory
vendor/bin/ncac-format

# Alternative: Using Composer script
composer format src/

# Alternative: Using bash script directly
bash vendor/ncac/phpcs-standard/scripts/ncac-fix.sh src/
```

This automatically runs the complete 3-step formatting workflow for you (PHP-CS-Fixer → PHPCBF → PHPCS validation).

> 💡 **Pro Tip:** Add a script to your project's `composer.json` for easy access:
>
> ```
> {
>   "scripts": {
>     "format": "vendor/bin/ncac-format",
>     "format:dry": "vendor/bin/ncac-format --dry-run"
>   }
> }
> ```
>
>
>
> Then run: `composer format` or `composer format:dry`

#### Manual: Full Workflow (Advanced)

[](#manual-full-workflow-advanced)

If you prefer running each step manually:

```
# Step 1: Apply PHP-CS-Fixer for complex transformations
vendor/bin/php-cs-fixer fix src/ --config=vendor/ncac/phpcs-standard/.php-cs-fixer.dist.php

# Step 2: Apply PHPCBF for NCAC-specific corrections
vendor/bin/phpcbf --standard=NCAC src/

# Step 3: Check remaining violations
vendor/bin/phpcs --standard=NCAC src/
```

> **Why this workflow?** PHP-CS-Fixer handles ~95% of complex formatting (alternate syntax, spacing), while PHPCBF handles NCAC-specific rules. This combination achieves the best conformity to the standard.

#### Alternative: PHPCS/PHPCBF Only

[](#alternative-phpcsphpcbf-only)

If you prefer to use only PHPCS tools (without PHP-CS-Fixer):

```
# Check your code
vendor/bin/phpcs --standard=NCAC src/

# Auto-fix issues (may not fix all violations)
vendor/bin/phpcbf --standard=NCAC src/
```

> **Note:** Using PHPCBF alone may leave some violations unfixed (~60% auto-fix rate vs ~95% with the full workflow). See [docs/WORKFLOW\_STRATEGY.md](docs/WORKFLOW_STRATEGY.md) for details.

### Project Configuration

[](#project-configuration)

Create a `phpcs.xml` in your project root:

```

    Your project coding standard

    src
    tests

```

📚 Documentation
---------------

[](#-documentation)

- **📖 [Complete Rules Reference](docs/rules-reference.md)** - Detailed examples for all 21 rules
- **⚙️ [Workflow Strategy](docs/WORKFLOW_STRATEGY.md)** - PHP-CS-Fixer + PHPCBF integration and migration plan
- **🔄 [Code Quality Workflow](docs/CODE_QUALITY_WORKFLOW.md)** - Auto-fixing and CI/CD integration
- **🛠️ [Development Setup Guide](docs/dev-container-setup.md)** - VS Code Dev Container setup
- **🤝 [Contributing Guidelines](CONTRIBUTING.md)** - How to contribute to the project

🎨 Code Examples
---------------

[](#-code-examples)

### Before (Inconsistent formatting)

[](#before-inconsistent-formatting)

```
class userRepository
{

    function findUser($userId)
    {
        $queryResult = $this->executeQuery($userId);
        if ($queryResult) {
            return $queryResult;
        }
        return null;
    }

    private $connectionString;
    const CACHE_TTL = 3600;

}
```

### After (NCAC compliant)

[](#after-ncac-compliant)

```
class UserRepository {

    private string $connectionString;

    public const CACHE_TTL = 3600;

    public function findUser(int $user_id): ?User {
      $query_result = $this->executeQuery($user_id);
      if ($query_result !== null) {
        return $this->mapToUser($query_result);
      }
      return null;
    }

}
```

🔧 Advanced Configuration
------------------------

[](#-advanced-configuration)

### Custom Rulesets

[](#custom-rulesets)

Disable specific rules for legacy codebases:

```

```

Customize Slevomat spacing rules (built-in configurability):

```

```

### Drupal Compatibility

[](#drupal-compatibility)

Enable support for Drupal hook naming conventions:

```

```

**Why this is needed:** Drupal uses double underscores (`__`) in hook function names to target specific template suggestions. For example:

```
// ✅ Valid Drupal preprocess hook (with allowDoubleUnderscore enabled)
function mymodule_preprocess_node__homepage(array &$variables): void {
  // Targets node--homepage.html.twig template
}

// ✅ Valid Drupal theme suggestions hook
function mymodule_theme_suggestions_paragraph__alter(array &$suggestions): void {
  $suggestions[] = 'paragraph__custom';
}

// ✅ Valid internal helper function (with allowLeadingUnderscore enabled)
function _mymodule_internal_helper(string $data): string {
  return strtoupper($data);
}
```

**Without these options enabled**, PHPCBF would incorrectly transform:

- `mymodule_preprocess_node__homepage` → `mymodule_preprocess_node_homepage` ❌ (breaks Drupal hooks!)
- `_internal_helper` → `internal_helper` ❌ (loses private function convention)

**Configuration options:**

- **`allowDoubleUnderscore`** (default: `false`): When enabled, allows `__` in function names for Drupal preprocess hooks and theme suggestions
- **`allowLeadingUnderscore`** (default: `false`): When enabled, allows `_` prefix for marking internal/private functions

> **Note:** NCAC custom sniffs (like `NCAC.Formatting.ClassClosingSpacing`, `NCAC.WhiteSpace.TwoSpacesIndent`) are not yet configurable. This is planned for future releases.

🛠️ Development &amp; Contributing
---------------------------------

[](#️-development--contributing)

### Development Setup

[](#development-setup)

#### VS Code Dev Container (Recommended)

[](#vs-code-dev-container-recommended)

1. **Clone the repository**:

    ```
    git clone https://github.com/ncac/phpcs-standard.git
    cd phpcs-standard
    ```
2. **Generate environment** (before opening in VS Code):

    ```
    .docker/generate-env.sh
    ```
3. **Open in VS Code**: The Dev Container will automatically configure everything.

#### Manual Setup

[](#manual-setup)

```
# Install dependencies
composer install
pnpm install

# Run full quality checks
vendor/bin/phing check

# Run specific checks
vendor/bin/psalm              # Static analysis
vendor/bin/phpunit            # Unit tests
vendor/bin/phpcs --standard=NCAC NCAC/  # Self-check
```

🔧 Tool Strategy: PHPCS vs PHP-CS-Fixer
--------------------------------------

[](#-tool-strategy-phpcs-vs-php-cs-fixer)

NCAC uses a **strategic separation** between detection and correction to avoid conflicts and ensure reliable results:

### Current Implementation (v1.0)

[](#current-implementation-v10)

```
# Detection and simple fixes
vendor/bin/phpcs --standard=NCAC src/ --fix

# Some complex rules are detection-only (see below)
vendor/bin/phpcs --standard=NCAC src/
```

### Why Some Rules Are Detection-Only

[](#why-some-rules-are-detection-only)

Certain rules like **NoAlternateControlStructureSniff** intentionally provide **no automatic fixes** due to PHP\_CodeSniffer's token processing limitations:

- **Token conflicts**: Sequential sniffs can overwrite each other's modifications
- **Invalid syntax**: Complex transformations can generate broken PHP code
- **Execution order**: Later sniffs (like indentation) may undo earlier fixes

**Example issue:**

```
// Original: if ($x): ... endif;
// After sniff A: if ($x) { ... }  // Fixed
// After sniff B: if ($x) { ...    // Broken (missing closing brace)
```

### Planned Evolution (v4.x)

[](#planned-evolution-v4x)

```
# 1. Complex transformations via PHP-CS-Fixer
php-cs-fixer fix --config=.ncac-cs-fixer.php src/

# 2. Simple fixes + validation via PHPCS
vendor/bin/phpcs --standard=NCAC src/ --fix

# 3. Final validation
vendor/bin/phpcs --standard=NCAC src/
```

> **📖 Learn more:** See [docs/PHPCS\_VS\_PHPCSFIXER\_STRATEGY.md](docs/PHPCS_VS_PHPCSFIXER_STRATEGY.md) for technical details.

### Contributing

[](#contributing)

We welcome contributions! Please see our [Contributing Guidelines](CONTRIBUTING.md) for:

- 🐛 **Bug reports** with reproducible examples
- ✨ **Feature requests** with clear use cases
- 🔧 **Pull requests** with comprehensive tests
- 📖 **Documentation** improvements

🏆 Acknowledgments
-----------------

[](#-acknowledgments)

NCAC is built upon two excellent foundational projects:

- **[PHP\_CodeSniffer](https://github.com/squizlabs/PHP_CodeSniffer)** by Squiz Labs - provides the tokenization engine and auto-fixing capabilities
- **[Slevomat Coding Standard](https://github.com/slevomat/coding-standard)** - provides many of the type safety and structural rules

NCAC adds **7 custom sniffs** for specific formatting and naming requirements:

- 2-space indentation with context-aware array handling
- Mixed naming conventions (snake\_case variables, camelCase properties, PascalCase classes)
- Minimal class spacing and structure rules
- Modern PHP pattern enforcement

> **License Compliance:** NCAC operates under the MIT license and respects all incorporated project licenses. See [LICENSE](LICENSE) for details.

🚀 Requirements &amp; Compatibility
----------------------------------

[](#-requirements--compatibility)

- **PHP:** 7.4, 8.0, 8.1, 8.2, 8.3
- **PHP\_CodeSniffer:** 3.7.0 or higher
- **Composer:** 2.0 or higher

✨ Features At a Glance
----------------------

[](#-features-at-a-glance)

- ✅ **21 comprehensive rules** covering all aspects of PHP code quality
- ✅ **Auto-fixable formatting** for seamless workflow integration
- ✅ **Type safety enforcement** with mandatory type hints
- ✅ **Modern PHP support** including enums and typed properties
- ✅ **IDE integration** for VS Code, PhpStorm, and others
- ✅ **Performance optimized** for large codebases
- ✅ **Extensive test coverage** ensuring reliability
- ✅ **Rich documentation** with practical examples

📞 Support &amp; Community
-------------------------

[](#-support--community)

- 📚 **[Documentation Hub](docs/)** - Comprehensive guides and references
- 🐛 **[Issue Tracker](https://github.com/ncac/phpcs-standard/issues)** - Bug reports and feature requests
- 💬 **[Discussions](https://github.com/ncac/phpcs-standard/discussions)** - Community Q&amp;A and ideas
- 📊 **[Releases](https://github.com/ncac/phpcs-standard/releases)** - Version history and changelogs

📄 License
---------

[](#-license)

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.

---

**Get started:**

```
composer require --dev ncac/phpcs-standard
vendor/bin/phpcs --standard=NCAC src/
```

###  Health Score

41

—

FairBetter than 89% of packages

Maintenance76

Regular maintenance activity

Popularity18

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity51

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~6 days

Recently: every ~0 days

Total

13

Last Release

131d ago

Major Versions

v1.2.0 → v3.0.02025-12-04

v3.1.0 → v4.0.02025-12-17

PHP version history (2 changes)v1.1.0PHP ^7.4 || ^8.0

v3.0.0PHP ^8.1

### Community

Maintainers

![](https://www.gravatar.com/avatar/5a6ed8b43a9ae77cd618a8c7bbe44d3d0994dbf548ebf06a3e7b41fa9bb406b4?d=identicon)[NCAC](/maintainers/NCAC)

---

Top Contributors

[![NCAC](https://avatars.githubusercontent.com/u/10559545?v=4)](https://github.com/NCAC "NCAC (103 commits)")

---

Tags

psrphpcsstatic analysiscode qualityCoding Standardtypescript-style

###  Code Quality

TestsPHPUnit

Static AnalysisPsalm

Type Coverage Yes

### Embed Badge

![Health badge](/badges/ncac-phpcs-standard/health.svg)

```
[![Health](https://phpackages.com/badges/ncac-phpcs-standard/health.svg)](https://phpackages.com/packages/ncac-phpcs-standard)
```

###  Alternatives

[mayflower/mo4-coding-standard

PHP CodeSniffer ruleset implementing the MO4 coding standards extending the Symfony coding standards.

17508.3k5](/packages/mayflower-mo4-coding-standard)[automattic/vipwpcs

PHP\_CodeSniffer rules (sniffs) to enforce WordPress VIP minimum coding conventions

25510.2M145](/packages/automattic-vipwpcs)[yoast/yoastcs

PHP\_CodeSniffer rules for Yoast projects

221.1M29](/packages/yoast-yoastcs)[orisai/coding-standard

Strict PHP coding standard

19193.5k62](/packages/orisai-coding-standard)[suin/phpcs-psr4-sniff

PHP\_CodeSniffer sniff that checks class name matches PSR-4 project structure.

271.7M16](/packages/suin-phpcs-psr4-sniff)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
