String literal matching specific regex annotation

Open
#154 3 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Assessment

Difficulty
5/5
Estimated time
Over a week
Newbie friendliness
25/100
Issue type
Feature
Clarity
Needs clarification
Activity status
Stale
Tech stack
php
Domain
devtools

Research direction

The issue names no source files, entry points, or tests. Start by reviewing how PHPStan represents string types and evaluates preg_match results, then determine whether regex-constrained string literals belong in this project. Done would require an agreed design and corresponding analysis coverage for the example.

Written by the indexing model from the issue text.

Description

Hello,

Often I want to prepare a package for my colleagues that defines very strict rules about the expectation of what input strings a method argument or property can handle.

If I implement the format validation as an assert, we will only learn about the error at runtime and it may never occur. If there is a native way to define the expected string format, it will be possible to automatically check huge code structures at compiletime.

For example (possible value can be v1.2.3):

function getFirstVersionPart(string $version): int
{
   preg_match('/^v(\d+)/', $version, $parser);

   return (int) $parser[1];
}

This annotation would help PhpStan recognize how to evaluate a regular expression and that all indexes will exist (and I don't need to handle the occurrence of the 1 index).

Thanks.

Dominant language
PHP
Stars
709
Forks
62
Avg merge
5d 19h
Merged PRs (30d)
3

Contributor guide

No contributing guide indexed for this repository

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from phpstan/phpstan-strict-rules

All issues in phpstan/phpstan-strict-rules

Similar issues

More PHP issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.