slevomat / coding-standard

Slevomat Coding Standard for PHP_CodeSniffer provides many useful sniffs
MIT License
1.39k stars 171 forks source link

Missing index breaks phpcbf run #793

Closed mimmi20 closed 4 years ago

mimmi20 commented 4 years ago

When running a fix (phpcbf) I got this error:

Fatal error:  Uncaught PHP_CodeSniffer\Exceptions\RuntimeException: Undefined index: scope_closer in C:\Users\Besitzer\Documents\
GitHub\phing\vendor\slevomat\coding-standard\SlevomatCodingStandard\Helpers\UseStatementHelper.php on line 207 in C:\Users\Besitzer\Documents\GitHub\phing\vendor\squizlabs\php_codesniffer\src\
Runner.php:606
Stack trace:
#0 C:\Users\Besitzer\Documents\GitHub\phing\vendor\slevomat\coding-standard\SlevomatCodingStandard\Helpers\UseStatementHelper.php(207): PHP_CodeSniffer\Runner->handleErrors(8, 'Undefined index
...', 'C:\\Users\\Besitz...', 207, Array)
#1 C:\Users\Besitzer\Documents\GitHub\phing\vendor\slevomat\coding-standard\SlevomatCodingStandard\Helpers\UseStatementHelper.php(149): SlevomatCodingStandard\Helpers\UseStatementHelper::getUs
eStatementPointers(Object(PHP_CodeSniffer\Files\LocalFile), 0)
#2 C:\Users\Besitzer\Documents\GitHub\phing\vendor\slevomat\coding-standard\SlevomatCodingStandard\Helpers\UseStatementHelper.php(111): SlevomatCodingStandard\Helpers\UseStatementHelper::getFi
leUseSta in C:\Users\Besitzer\Documents\GitHub\phing\vendor\squizlabs\php_codesniffer\src\Runner.php on line 606

used version: 5.0.4 (via Doctrine coding standard) PHP version: 7.1.11 OS: Windows

used configuration:

<?xml version="1.0"?>
<ruleset
    name="PHPCS Coding Standards for phing"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:noNamespaceSchemaLocation="vendor/squizlabs/php_codesniffer/phpcs.xsd"
>
    <description>Check the code of phing in phing coding-standards.</description>

    <arg name="basepath" value="."/>
    <arg name="extensions" value="php"/>

    <!-- Code MUST use an indent of 4 spaces, and MUST NOT use tabs for indenting. -->
    <rule ref="Generic.WhiteSpace.ScopeIndent"/>
    <rule ref="Generic.WhiteSpace.DisallowTabIndent"/>

    <!-- PHP code MUST use only UTF-8 without BOM. -->
    <rule ref="Generic.Files.ByteOrderMark"/>

    <!-- Never use shorthand PHP start tags. Always use full PHP tags. -->
    <rule ref="Generic.PHP.DisallowShortOpenTag"/>
    <rule ref="Generic.PHP.DisallowAlternativePHPTags"/>

    <!-- PHP keywords MUST be in lower case. -->
    <rule ref="Generic.PHP.LowerCaseKeyword"/>

    <!-- The PHP constants true, false, and null MUST be in lower case. -->
    <rule ref="Generic.PHP.LowerCaseConstant"/>

    <!-- PHP files should contain an empty line at the end of the file -->
    <rule ref="Generic.Files.EndFileNewline"/>

    <!-- Allow only unix file endings (newlines) -->
    <rule ref="Generic.Files.LineEndings">
        <properties>
            <property name="eolChar" value="\n"/>
        </properties>
    </rule>

    <!-- Braces should always be used, even when they are not required. -->
    <rule ref="Generic.ControlStructures.InlineControlStructure"/>

    <!-- Rule: In general, readability is more important than cleverness or brevity. -->
    <rule ref="Generic.Formatting.DisallowMultipleStatements"/>

    <rule ref="Generic.CodeAnalysis.ForLoopShouldBeWhileLoop"/>
    <rule ref="Generic.CodeAnalysis.UnconditionalIfStatement"/>

    <rule ref="Generic.Functions.OpeningFunctionBraceBsdAllman">
        <exclude name="Generic.Functions.OpeningFunctionBraceBsdAllman.BraceOnSameLine"/>
    </rule>

    <rule ref="PSR12">
        <exclude name="PSR1.Classes.ClassDeclaration.MissingNamespace"/>
        <exclude name="PSR2.Methods.MethodDeclaration.Underscore"/>
        <exclude name="PSR12.Files.FileHeader.SpacingAfterBlock"/>
        <exclude name="Squiz.Functions.LowercaseFunctionKeywords"/><!-- checked by more generic Generic.PHP.LowerCaseKeyword -->
        <exclude name="Squiz.ControlStructures.LowercaseDeclaration"/><!-- checked by more generic Generic.PHP.LowerCaseKeyword -->
    </rule>

    <rule ref="Squiz.WhiteSpace.SuperfluousWhitespace">
        <properties>
            <property name="ignoreBlankLines" value="false"/>
        </properties>
    </rule>

    <rule ref="Doctrine">
        <exclude name="PSR1.Classes.ClassDeclaration.MissingNamespace"/>
        <!-- Allow `!` without trailing whitespace -->
        <exclude name="Generic.Formatting.SpaceAfterNot.Incorrect"/>
        <exclude name="SlevomatCodingStandard.Commenting.ForbiddenAnnotations.AnnotationForbidden"/>
        <!-- will be fixed in a different branch -->
        <exclude name="SlevomatCodingStandard.TypeHints.TypeHintDeclaration.MissingReturnTypeHint"/>
        <exclude name="SlevomatCodingStandard.TypeHints.TypeHintDeclaration.MissingParameterTypeHint"/>
    </rule>
</ruleset>
kukulich commented 4 years ago

@mimmi20 I need the code that throws this error.

mimmi20 commented 4 years ago

It is this file.

<?php
/**
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * This software consists of voluntary contributions made by many individuals
 * and is licensed under the LGPL. For more information please see
 * <http://phing.info>.
 *
 * @package phing.tasks.ext
 */

/**
 * @author Alexey Borzov <avb@php.net>
 * @package phing.tasks.ext
 */
class PDODelimitersTest extends BuildFileTest
{
    protected $queries = [];

    protected $mockTask;

    public function setUp(): void
    {
        $this->configureProject(PHING_TEST_BASE . "/etc/tasks/ext/pdo/empty.xml");
        $this->queries = [];

        $this->mockTask = $this->getMockBuilder('PDOSQLExecTask')
            ->setMethods(['getConnection', 'execSQL'])
            ->getMock();
        $this->mockTask->setProject($this->project);
        // prevents calling beginTransaction() on obviously missing PDO instance
        $this->mockTask->setAutocommit(true);
        $this->mockTask->expects($this->atLeastOnce())->method('execSQL')
            ->will($this->returnCallback([$this, 'storeQuery']));

        $targets = $this->project->getTargets();
        $targets['test']->addTask($this->mockTask);
        $this->mockTask->setOwningTarget($targets['test']);
    }

    public function storeQuery($query)
    {
        $query = trim($query);
        if (strlen($query)) {
            $this->queries[] = str_replace(["\n\n", "\r"], ["\n", ''], $query);
        }
    }

    /**
     * @requires PHP >= 7.2
     */
    public function testDelimiterTypeNormal()
    {
        // for some reason default splitter mangles spaces on subsequent lines
        $expected = [
            <<<SQL
insert into foo (bar, "strange;name""indeed") values ('bar''s value containing ;', 'a value for strange named column')
SQL
            ,
            <<<SQL
delete
 from
 foo where bar = 'some value'
SQL
            ,
            <<<SQL
update dump -- I should not be ignored
 set message = 'I am a string with \\\\ backslash \' escapes and semicolons;'
SQL
            ,
            <<<SQL
create procedure setfoo(newfoo int)
 begin
 set @foo = newfoo;
 end
SQL
            ,
            <<<SQL
insert into dump (message) values ('I am a statement not ending with a delimiter')
SQL
        ];
        // and insists on "\n" linebreaks
        foreach ($expected as &$query) {
            $query = str_replace(["\n\n", "\r"], ["\n", ''], $query);
        }

        $this->mockTask->setSrc(new PhingFile(PHING_TEST_BASE . "/etc/tasks/ext/pdo/delimiters-normal.sql"));
        $this->mockTask->setDelimiterType(PDOSQLExecTask::DELIM_NORMAL);
        $this->project->setProperty('bar.value', "some value");
        $this->project->executeTarget('test');

        $this->assertEquals($expected, $this->queries);
    }

    /**
     * @requires PHP >= 7.2
     */
    public function testDelimiterTypeRow()
    {
        // for some reason default splitter mangles spaces on subsequent lines
        $expected = [
            <<<SQL
insert into "duh" (foo) values ('duh')
SQL
            ,
            <<<SQL
update "duh?" -- I should not be ignored
 set foo = 'some value'
SQL
            ,
            <<<SQL
insert into dump (message) values ('I am a statement not ending with a delimiter')
SQL
        ];
        // and insists on "\n" linebreaks
        foreach ($expected as &$query) {
            $query = str_replace(["\n\n", "\r"], ["\n", ''], $query);
        }

        $this->mockTask->setSrc(new PhingFile(PHING_TEST_BASE . "/etc/tasks/ext/pdo/delimiters-row.sql"));
        $this->mockTask->setDelimiterType(PDOSQLExecTask::DELIM_ROW);
        $this->mockTask->setDelimiter('duh');
        $this->project->setProperty('foo.value', "some value");
        $this->project->executeTarget('test');

        $this->assertEquals($expected, $this->queries);
    }

    /**
     * Checks that PDOSQLExecTask properly understands PostgreSQL dialect
     * (especially "dollar quoting") when working with 'pgsql:' URLs.
     *
     * @link http://www.phing.info/trac/ticket/499
     * @link http://www.postgresql.org/docs/9.0/interactive/sql-syntax-lexical.html#SQL-SYNTAX-DOLLAR-QUOTING
     * @requires PHP >= 7.2
     */
    public function testRequest499()
    {
        $expected = [
            <<<SQL
select 1
# 2
SQL
            ,
            <<<SQL
select 'foo'
// 'bar'
SQL
            ,
            <<<SQL
insert into foo (bar, "strange;name""indeed") values ('bar''s value containing ;', 'a value for strange named column')
SQL
            ,
            <<<SQL
create function foo(text)
returns boolean as
\$function$
BEGIN
    RETURN ($1 ~ \$q$[\\t\\r\\n\\v\\\\]\$q$);
END;
\$function$
language plpgsql
SQL
            ,
            <<<SQL
CREATE FUNCTION phingPDOtest() RETURNS "trigger"
    AS \$_X$
if (1)
{
    # All is well - just continue

    return;
}
else
{
    # Not good - this is probably a fatal error!
    elog(ERROR,"True is not true");

    return "SKIP";
}
\$_X$
    LANGUAGE plperl
SQL
            ,
            "insert into foo (bar) \nvalues ('some value')"
            ,
            <<<SQL
insert into foo (bar) values ($$ a dollar-quoted string containing a few quotes ' ", a \$placeholder$ and a semicolon;$$)
SQL
            ,
            <<<SQL
create rule blah_insert
as on insert to blah do instead (
    insert into foo values (new.id, 'blah');
    insert into bar values (new.id, 'blah-blah');
)
SQL
            ,
            <<<SQL
insert into dump (message) values ('I am a statement not ending with a delimiter')
SQL
        ];
        foreach ($expected as &$query) {
            $query = str_replace(["\n\n", "\r"], ["\n", ''], $query);
        }

        $this->mockTask->setSrc(new PhingFile(PHING_TEST_BASE . "/etc/tasks/ext/pdo/delimiters-pgsql.sql"));
        $this->mockTask->setUrl('pgsql:host=localhost;dbname=phing');
        $this->mockTask->setDelimiterType(PDOSQLExecTask::DELIM_NORMAL);
        $this->project->setProperty('bar.value', "some value");
        $this->project->executeTarget('test');

        $this->assertEquals($expected, $this->queries);
    }
}
mimmi20 commented 4 years ago

I added an isset check (isset($token['scope_closer']) === true) in line 206 to skip out the error.

Then I get this error:

Undefined index: scope_opener in C:\Users\Besitzer\Documents\GitHub\phing\vendor\slevomat\coding-standard\SlevomatCodingStandard\Helpers\ClassHelper.php on line 45 in C:\Users\Besitzer\Documents\GitHub\phing\vendor\squizlabs\php_codesniffer\src\Runner.php:606
Stack trace:
#0 C:\Users\Besitzer\Documents\GitHub\phing\vendor\slevomat\coding-standard\SlevomatCodingStandard\Helpers\ClassHelper.php(45): PHP_CodeSniffer\Runner->handleErrors(8, 'Undefined index...', 'C:\\Users\\Besitz...', 45, Array)
#1 C:\Users\Besitzer\Documents\GitHub\phing\vendor\slevomat\coding-standard\SlevomatCodingStandard\Helpers\ClassHelper.php(58): SlevomatCodingStandard\Helpers\ClassHelper::getName(Object(PHP_CodeSniffer\Files\LocalFile), 117)
#2 [internal function]: SlevomatCodingStandard\Helpers\ClassHelper::SlevomatCodingStandard\Helpers\{closure}(117)
#3 C:\Users\Besitzer\Documents\GitHub\phing\vendor\slevomat\coding-standard\SlevomatCodingStandard\Helpers\ClassHelper.php(60): arra in C:\Users\Besitzer\Documents\GitHub\phing\vendor\squizlabs\php_codesniffer\src\Runner.php on line 606
mimmi20 commented 4 years ago

It looks like version 6 is working on that file.

github-actions[bot] commented 4 years ago

This issue has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.