symplify/better-phpdoc-parser

This package is abandoned and no longer maintained. The author suggests using the rector/rector package instead.

Slim wrapper around phpstan/phpdoc-parser with format preserving printer


README

Better PhpDoc Parser

Build Status Downloads

Wrapper around phpstan/phpdoc-parser that adds format preserving printer.

When do We Need Format Preserving Printer?

Original code

/**
 * @param   string   $name
 * @param   string   $surname
 * @return  bool
  */

Printed by PHPStan PhpDocParser

/**
 * @param string $name
 * @param string $surname
 * @return bool
 */

Printed by Better PhpDocParser 👍

/**
 * @param   string   $name
 * @param   string   $surname
 * @return  bool
 */

Symplify\CodingStandard and Rector need to modify docblock and put it back in correct format. Other packages often put own spacing, or formats of specific tags.

This package preserve original spacing.

Thanks for inspiration in Format Preserving Printer feature in nikic/php-parser.

Install

composer require symplify/better-phpdoc-parser

Usage

Register services in your Symfony config:

# services.yaml
imports:
    - { resource: 'vendor/symplify/better-phpdoc-parser/config/config.yml' }

or register the needed services from services.yaml in config of your other framework.

<?php

use Symplify\BetterPhpDocParser\PhpDocInfo\PhpDocInfoFactory;
use Symplify\BetterPhpDocParser\Printer\PhpDocInfoPrinter;

class SomeClass
{
    public function __construct(PhpDocInfoFactory $phpDocInfoFactory, PhpDocInfoPrinter $phpDocInfoPrinter)
    {
        $this->phpDocInfoFactory = $phpDocInfoFactory;
        $this->phpDocInfoPrinter = $phpDocInfoPrinter;
    }

    public function changeDocBlockAndPrintItBack(): string
    {
        $docComment = '/**    @var Type $variable    */';

        $phpDocInfo = $this->phpDocInfoFactory->createFrom($docComment);

        // modify `$phpDocInfo` using its methods

        return $this->phpDocInfoPrinter->printFormatPreserving($phpDocInfo);
    }
}