Executes PHP Code Sniffer against all phpcs.filesets files.

By default, these include custom themes, modules, and tests.

@command tests:phpcs:sniff:all

@aliases tpsa phpcs tests:phpcs:sniff validate:phpcs
320032
public function sniffFileSets() {
    $bin = $this->getConfigValue('composer.bin');
    $result = $this->taskExecStack()
      ->dir($this->getConfigValue('repo.root'))
      ->exec("$bin/phpcs")
      ->run();
    $exit_code = $result->getExitCode();
    if ($exit_code) {
      if ($this->input()->isInteractive()) {
        $this->fixViolationsInteractively();
        throw new BltException("Initial execution of PHPCS failed. Re-run now that PHPCBF has fixed some violations.");
      }
      else {
        $this->logger->notice('Try running `blt source:fix:php-standards` to automatically fix standards violations.');
        throw new BltException("PHPCS failed.");
      }
    }
  }
521364
public function process(\PHP_CodeSniffer\Files\File $phpcsFile, $typePointer): void
    {
        $tokens = $phpcsFile->getTokens();

        /** @var int $namePointer */
        $namePointer = TokenHelper::findNext($phpcsFile, T_STRING, $typePointer + 1);
        $namespacePointer = TokenHelper::findPrevious($phpcsFile, T_NAMESPACE, $typePointer - 1);

        if (!$this->hasNamespace($namespacePointer)) {
            return;
        }

        $typeName = NamespaceHelper::normalizeToCanonicalName(
            ClassHelper::getFullyQualifiedName($phpcsFile, $typePointer)
        );

        $rootDirectory = \getcwd() . \DIRECTORY_SEPARATOR;
        $fileInfo = new \SplFileInfo($phpcsFile->getFilename());

        foreach ($this->rootNamespaces as $directory => $namespace) {
            if ($this->shouldSkip($directory)) {
                return;
            }

            if (StringHelper::startsWith($typeName, $namespace)) {
                $expectedTypeName = rtrim($fileInfo->getPathname(), '.' . $fileInfo->getExtension());
                $expectedTypeName = \str_replace($rootDirectory . $directory, '', $expectedTypeName);
                $expectedTypeName = \str_replace(\DIRECTORY_SEPARATOR, '\\', $expectedTypeName);
                $expectedTypeName = $namespace . '\\' . ltrim($expectedTypeName, '\\');

                if (strcasecmp($typeName, $expectedTypeName) === 0) {
                    return;
                }
            }
        }

        $phpcsFile->addError(
            sprintf(
                '%s name %s does not match filepath %s.',
                ucfirst($tokens[$typePointer]['content']),
                $typeName,
                $phpcsFile->getFilename()
            ),
            $namePointer,
            self::CODE_NO_MATCH_BETWEEN_TYPE_NAME_AND_FILE_NAME
        );
    }
1313073
public function execute()
    {
        list($ignore, $standard, $suffixes) = $this->getFlags();

        $phpcs = $this->phpci->findBinary('phpcs');

        $this->phpci->logExecOutput(false);

        $cmd = $phpcs . ' --report=json %s %s %s %s %s "%s"';
        $this->phpci->executeCommand(
            $cmd,
            $standard,
            $suffixes,
            $ignore,
            $this->tab_width,
            $this->encoding,
            $this->phpci->buildPath . $this->path
        );

        $output = $this->phpci->getLastOutput();
        list($errors, $warnings) = $this->processReport($output);

        $this->phpci->logExecOutput(true);

        $success = true;
        $this->build->storeMeta('phpcs-warnings', $warnings);
        $this->build->storeMeta('phpcs-errors', $errors);

        if ($this->allowed_warnings != -1 && $warnings > $this->allowed_warnings) {
            $success = false;
        }

        if ($this->allowed_errors != -1 && $errors > $this->allowed_errors) {
            $success = false;
        }

        return $success;
    }
974098
public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
	{
		$tokens = $phpcsFile->getTokens();
		$className = $phpcsFile->findNext(T_STRING, $stackPtr);
		$name      = trim($tokens[$className]['content']);
		$errorData = array(ucfirst($tokens[$stackPtr]['content']));

		$endsWithInterface = substr($name, -5) == 'Trait';
		$isClass = $tokens[$stackPtr]['code'] === T_CLASS;

		if ($isClass && $endsWithInterface) {
			$error = '%s name must not end with "Trait"';
			$phpcsFile->addError($error, $stackPtr, 'EndNotWithTrait', $errorData);
		}

		if (!$isClass && !$endsWithInterface) {
			$error = '%s name must end with "Trait"';
			$phpcsFile->addError($error, $stackPtr, 'EndWithTrait', $errorData);
		}
	}
754807
public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
    {
        $tokens = $phpcsFile->getTokens();

        $beforeToken = $tokens[$stackPtr - 1];
        if ($beforeToken['code'] !== T_WHITESPACE) {
            $phpcsFile->addError('Expected 1 space before =>, 0 found', $stackPtr, 'SpaceBeforeArrow');
        } elseif ($beforeToken['content'] !== ' ') {
            $phpcsFile->addError('Expected 1 space before =>, %s found', $stackPtr, 'SpaceBeforeArrow', [strlen($beforeToken['content'])]);
        }

        $afterToken = $tokens[$stackPtr + 1];
        if ($afterToken['code'] !== T_WHITESPACE) {
            $phpcsFile->addError('Expected 1 space after =>, 0 found', $stackPtr, 'SpaceAfterArrow');
        } elseif ($afterToken['content'] !== ' ') {
            $phpcsFile->addError('Expected 1 space after =>, %s found', $stackPtr, 'SpaceAfterArrow', [strlen($afterToken['content'])]);
        }
    }
683436
public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
    {
        $tokens = $phpcsFile->getTokens();

        // Only check use statements in the global scope.
        if (empty($tokens[$stackPtr]['conditions']) === false) {
            return;
        }

        // Seek to the end of the statement and get the string before the semi colon.
        $semiColon = $phpcsFile->findEndOfStatement($stackPtr);
        if ($tokens[$semiColon]['code'] !== T_SEMICOLON) {
            return;
        }

        $classPtr = $phpcsFile->findPrevious(
            PHP_CodeSniffer_Tokens::$emptyTokens,
            ($semiColon - 1),
            null,
            true
        );

        if ($tokens[$classPtr]['code'] !== T_STRING) {
            return;
        }

        // Search where the class name is used. PHP treats class names case
        // insensitive, that's why we cannot search for the exact class name string
        // and need to iterate over all T_STRING tokens in the file.
        $classUsed      = $phpcsFile->findNext(T_STRING, ($classPtr + 1));
        $lowerClassName = strtolower($tokens[$classPtr]['content']);

        // Check if the referenced class is in the same namespace as the current
        // file. If it is then the use statement is not necessary.
        $namespacePtr = $phpcsFile->findPrevious([T_NAMESPACE], $stackPtr);
        // Check if the use statement does aliasing with the "as" keyword. Aliasing
        // is allowed even in the same namespace.
        $aliasUsed = $phpcsFile->findPrevious(T_AS, ($classPtr - 1), $stackPtr);

        if ($namespacePtr !== false && $aliasUsed === false) {
            $nsEnd     = $phpcsFile->findNext(
                [
                 T_NS_SEPARATOR,
                 T_STRING,
                 T_WHITESPACE,
                ],
                ($namespacePtr + 1),
                null,
                true
            );
            $namespace = trim($phpcsFile->getTokensAsString(($namespacePtr + 1), ($nsEnd - $namespacePtr - 1)));

            $useNamespacePtr = $phpcsFile->findNext([T_STRING], ($stackPtr + 1));
            $useNamespaceEnd = $phpcsFile->findNext(
                [
                 T_NS_SEPARATOR,
                 T_STRING,
                ],
                ($useNamespacePtr + 1),
                null,
                true
            );
            $use_namespace   = rtrim($phpcsFile->getTokensAsString($useNamespacePtr, ($useNamespaceEnd - $useNamespacePtr - 1)), '\\');

            if (strcasecmp($namespace, $use_namespace) === 0) {
                $classUsed = false;
            }
        }//end if

        while ($classUsed !== false) {
            if (strtolower($tokens[$classUsed]['content']) === $lowerClassName) {
                // If the name is used in a PHP 7 function return type declaration
                // stop.
                if ($tokens[$classUsed]['code'] === T_RETURN_TYPE) {
                    return;
                }

                $beforeUsage = $phpcsFile->findPrevious(
                    PHP_CodeSniffer_Tokens::$emptyTokens,
                    ($classUsed - 1),
                    null,
                    true
                );
                // If a backslash is used before the class name then this is some other
                // use statement.
                if ($tokens[$beforeUsage]['code'] !== T_USE && $tokens[$beforeUsage]['code'] !== T_NS_SEPARATOR) {
                    return;
                }

                // Trait use statement within a class.
                if ($tokens[$beforeUsage]['code'] === T_USE && empty($tokens[$beforeUsage]['conditions']) === false) {
                    return;
                }
            }//end if

            $classUsed = $phpcsFile->findNext([T_STRING, T_RETURN_TYPE], ($classUsed + 1));
        }//end while

        $warning = 'Unused use statement';
        $fix     = $phpcsFile->addFixableWarning($warning, $stackPtr, 'UnusedUse');
        if ($fix === true) {
            // Remove the whole use statement line.
            $phpcsFile->fixer->beginChangeset();
            for ($i = $stackPtr; $i <= $semiColon; $i++) {
                $phpcsFile->fixer->replaceToken($i, '');
            }

            // Also remove whitespace after the semicolon (new lines).
            while (isset($tokens[$i]) === true && $tokens[$i]['code'] === T_WHITESPACE) {
                $phpcsFile->fixer->replaceToken($i, '');
                if (strpos($tokens[$i]['content'], $phpcsFile->eolChar) !== false) {
                    break;
                }

                $i++;
            }

            // Replace @var data types in doc comments with the fully qualified class
            // name.
            $useNamespacePtr = $phpcsFile->findNext([T_STRING], ($stackPtr + 1));
            $useNamespaceEnd = $phpcsFile->findNext(
                [
                 T_NS_SEPARATOR,
                 T_STRING,
                ],
                ($useNamespacePtr + 1),
                null,
                true
            );
            $fullNamespace   = $phpcsFile->getTokensAsString($useNamespacePtr, ($useNamespaceEnd - $useNamespacePtr));

            $tag = $phpcsFile->findNext(T_DOC_COMMENT_TAG, ($stackPtr + 1));

            while ($tag !== false) {
                if (($tokens[$tag]['content'] === '@var' || $tokens[$tag]['content'] === '@return')
                    && isset($tokens[($tag + 1)]) === true
                    && $tokens[($tag + 1)]['code'] === T_DOC_COMMENT_WHITESPACE
                    && isset($tokens[($tag + 2)]) === true
                    && $tokens[($tag + 2)]['code'] === T_DOC_COMMENT_STRING
                    && strpos($tokens[($tag + 2)]['content'], $tokens[$classPtr]['content']) === 0
                ) {
                    $replacement = '\\'.$fullNamespace.substr($tokens[($tag + 2)]['content'], strlen($tokens[$classPtr]['content']));
                    $phpcsFile->fixer->replaceToken(($tag + 2), $replacement);
                }

                $tag = $phpcsFile->findNext(T_DOC_COMMENT_TAG, ($tag + 1));
            }

            $phpcsFile->fixer->endChangeset();
        }//end if

    }
737507
public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
    {
        $tokens = $phpcsFile->getTokens();
        if (
            $tokens[$stackPtr + 2]['type'] == 'T_STRING'
            &&
            (
                $tokens[$stackPtr + 3]['type'] == 'T_OPEN_PARENTHESIS'
                ||
                (
                    $tokens[$stackPtr + 3]['type'] == 'T_WHITESPACE'
                    &&
                    $tokens[$stackPtr + 4]['type'] == 'T_OPEN_PARENTHESIS'
                )
            )
        ) {
            $className = $tokens[$stackPtr + 2]['content'];
            if (array_key_exists($className, $this->newClasses) === false) {
                return;
            }
            $this->addError($phpcsFile, $stackPtr, $className);
        }



    }
218770
public function fire()
    {
        parent::fire();

        if ($this->option('install-ruleset')) {
            if ($this->installRuleset()) {
                $this->info('Copied ruleset to '.$this->pathRulesetLocal);
            }
        }

        $this->info('Running PHP Code Sniffer...');

        $commandParts = array(
            $this->pathCli,
            '--standard='.$this->pathRuleset,
            // Laravel likes tabs, phpcs doesn't.
            sprintf('--tab-width=%d', $this->option('tab-width')),
        );

        $commandParts = $this->appendCommandOptions($commandParts);

        $commandParts[] = sprintf('%s/%s', base_path(), $this->option('path'));

        $command = implode(' ', $commandParts);

        passthru($command, $exitCode);

        $this->info('Done.');

        return $exitCode;
    }
1199781
public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
    {
        $tokens = $phpcsFile->getTokens();

        if (isset($tokens[$stackPtr]['scope_opener']) === false && $tokens[$stackPtr]['code'] !== T_RETURN)
        {
            return;
        }

        $prev = $phpcsFile->findPrevious([T_SEMICOLON, T_CLOSE_CURLY_BRACKET], ($stackPtr - 1), null, false);

        if ($tokens[$stackPtr]['line'] - 1 === $tokens[$prev]['line'])
        {
            $error = 'Please consider an empty line before the %s statement;';
            $data  = [$tokens[$stackPtr]['content']];
            $fix   = $phpcsFile->addFixableError($error, $stackPtr, 'SpaceBefore', $data);

            if ($fix === true)
            {
                $phpcsFile->fixer->addNewlineBefore($stackPtr);
            }
        }
    }
525097
public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
    {
        $tokens = $phpcsFile->getTokens();

		$valid = false;

		if (preg_match('|//\s|', $tokens[$stackPtr]['content']))
		{
			$valid = true;
		}

		if (preg_match('|\*[\s/]|', $tokens[$stackPtr]['content']))
		{
			$valid = true;
		}

		if ($valid === false)
		{
            $error = 'A space is required at the start of the comment %s';
            $data  = array(trim($tokens[$stackPtr]['content']));
            $phpcsFile->addError($error, $stackPtr, 'Found', $data);
        }

    }
1196175
public function execute()
    {
        if (empty($this->xmlConfigFile) && empty($this->directory)) {
            $this->phpci->logFailure('Neither configuration file nor test directory found.');
            return false;
        }

        $success = true;

        $this->phpci->logExecOutput(false);

        // Run any config files first. This can be either a single value or an array.
        if ($this->xmlConfigFile !== null) {
            $success &= $this->runConfigFile($this->xmlConfigFile);
        }

        // Run any dirs next. Again this can be either a single value or an array.
        if ($this->directory !== null) {
            $success &= $this->runDir($this->directory);
        }

        $tapString = $this->phpci->getLastOutput();
        $tapString = mb_convert_encoding($tapString, "UTF-8", "ISO-8859-1");

        try {
            $tapParser = new TapParser($tapString);
            $output = $tapParser->parse();
        } catch (\Exception $ex) {
            $this->phpci->logFailure($tapString);
            throw $ex;
        }

        $failures = $tapParser->getTotalFailures();

        $this->build->storeMeta('phpunit-errors', $failures);
        $this->build->storeMeta('phpunit-data', $output);

        $this->phpci->logExecOutput(true);

        return $success;
    }
1165676
public function run() {
		
		// various set-up options
		$options                 = array();
		$options["patternPaths"] = $this->patternPaths;
		$patternDataStore        = PatternData::get();
		$stringLoader            = Template::getStringLoader();
		
		// load the pattern loader
		$patternEngineBasePath   = PatternEngine::getInstance()->getBasePath();
		$patternLoaderClass      = $patternEngineBasePath."\Loaders\PatternLoader";
		$patternLoader           = new $patternLoaderClass($options);
		
		// parse all of the CSS in the project
		$kss = new Parser(Config::getOption("sourceDir"));
		
		foreach ($patternDataStore as $patternStoreKey => $patternStoreData) {
			
			if ($patternStoreData["category"] == "pattern") {
				
				$kssSection = "";
				
				try {
					$kssSection = $kss->getSection($patternStoreKey);
				} catch(\Exception $e) {
					$kssSection = "";
				}
				
				// see if this pattern has a section in the loaded KSS
				if (!empty($kssSection)) {
					
					// update the name and desc based on the KSS
					PatternData::setPatternOption($patternStoreKey, "name", $kssSection->getTitle());
					PatternData::setPatternOption($patternStoreKey, "desc", $kssSection->getDescription());
					PatternData::setPatternOption($patternStoreKey, "descExists", true);
					
					// find the kss modifiers
					$modifiers = $kssSection->getModifiers();
					
					if (!empty($modifiers)) {
						
						$patternModifiers = array();
						
						// work through each modifier
						foreach ($modifiers as $modifier) {
							
							$name               = $modifier->getName();
							$class              = $modifier->getClassName();
							$desc               = $modifier->getDescription();
							$code               = "";
							$modifierCodeExists = false;
							
							// if it's not a pseudo class render it
							if (strpos($name,":") !== false) {
								
								$data    = Data::getPatternSpecificData($patternStoreKey);
								$data    = array_merge($data,array("styleModifier" => $class));
								
								$srcPath = (isset($patternStoreData["pseudo"])) ? PatternData::getPatternOption($patternStoreData["original"],"pathName") : $patternStoreData["pathName"];
								$code    = $patternLoader->render(array("pattern" => $srcPath, "data" => $data));
								
								$modifierCodeExists    = true;
								
							}
							
							// add pattern modifier info
							$patternModifiers[] = array("modifierName"       => $name,
														"modifierDesc"       => $desc,
														"modifierCode"       => $code,
														"modifierCodeExists" => $modifierCodeExists);
							
							$patternModifiersOutput[] = array("modifierName" => $name,
														      "modifierDesc" => $desc);
							
						}
						
						// this is silly but keeps it looking cleaner to me
						$patternModifierData = array("patternModifiers" => $patternModifiers);
						$patternModifierOutputData = array("patternModifiersExist" => true, "patternModifiers" => $patternModifiersOutput);
						
						// grab extra sections based on KSS syntax
						if (!empty($kssSection->getCompatibility())) {
							$patternModifierData["compatibility"]             = $kssSection->getCompatibility();
							$patternModifierData["compatibilityExists"]       = true;
							$patternModifierOutputData["compatibility"]       = $kssSection->getCompatibility();
							$patternModifierOutputData["compatibilityExists"] = true;
						}
						if (!empty($kssSection->getExperimental())) {
							$patternModifierData["experimental"]              = $kssSection->getExperimental();
							$patternModifierData["experimentalExists"]        = true;
							$patternModifierOutputData["experimental"]        = $kssSection->getExperimental();
							$patternModifierOutputData["experimentalExists"]  = true;
						}
						if (!empty($kssSection->getDeprecated())) {
							$patternModifierData["deprected"]                 = $kssSection->getDeprecated();
							$patternModifierData["deprecatedExists"]          = true;
							$patternModifierOutputData["deprecated"]          = $kssSection->getDeprecated();
							$patternModifierOutputData["deprecatedExists"]    = true;
						}
						if (!empty($kssSection->getParameters())) {
							$patternModifierData["parameters"]                = $kssSection->getParameters();
							$patternModifierData["parametersExist"]           = true;
							$patternModifierOutputData["parameters"]          = $kssSection->getParameters();
							$patternModifierOutputData["parametersExists"]    = true;
						}
						
						// render the views for the plug-in
						$partialViewDescAddition    = $stringLoader->render(array("string" => $this->descTemplate, "data" => $patternModifierData));
						$partialViewExampleAddition = $stringLoader->render(array("string" => $this->exampleTemplate, "data" => $patternModifierData));
						
						// add the views to the appropriate containers in the patterndata::$store
						PatternData::setPatternOptionArray($patternStoreKey, "partialViewDescAdditions", $partialViewDescAddition);
						PatternData::setPatternOptionArray($patternStoreKey, "partialViewExampleAdditions", $partialViewExampleAddition);
						PatternData::setPatternOptionArray($patternStoreKey, "extraOutput", $patternModifierOutputData, "patternLabPluginKSS");
						
					}
					
				}
				
			}
			
		}
		
		unset($kss);
		
	}
148439
function(file, enc, callback) {
            var report = file.phpcsReport || {};

            if (report.error) {
                phpcsError = true;

                if (options.failOnFirst) {
                    var errorMessage = 'PHP Code Sniffer failed' +
                        ' on ' + chalk.magenta(file.path);

                    this.emit('error', new gutil.PluginError('gulp-phpcs', errorMessage));
                    callback();

                    return;
                }  else {
                    badFiles.push(chalk.magenta(file.path));
                }
            }

            this.push(file);
            callback();
        }
403289
public function main()
    {
        // INIT
        $tsSetup = $GLOBALS['TSFE']->tmpl->setup;
        $headers = array();

        // don't send any headers if headers are already sent
        if (headers_sent()) {
            return;
        }

        // Init caches
        $cacheIdentification = sprintf(
            '%s_%s_http',
            $GLOBALS['TSFE']->id,
            substr(sha1(FrontendUtility::getCurrentUrl()), 10, 30)
        );

        /** @var \TYPO3\CMS\Core\Cache\CacheManager $cacheManager */
        $objectManager = Typo3GeneralUtility::makeInstance(
            'TYPO3\\CMS\\Extbase\\Object\\ObjectManager'
        );
        $cacheManager  = $objectManager->get('TYPO3\\CMS\\Core\\Cache\\CacheManager');
        $cache         = $cacheManager->getCache('cache_pagesection');

        if (!empty($GLOBALS['TSFE']->tmpl->loaded)) {
            // ##################################
            // Non-Cached page
            // ##################################

            if (!empty($tsSetup['plugin.']['metaseo.']['metaTags.'])) {
                $tsSetupSeo = $tsSetup['plugin.']['metaseo.']['metaTags.'];

                // ##################################
                // W3C P3P Tags
                // ##################################
                $p3pCP        = null;
                $p3pPolicyUrl = null;

                if (!empty($tsSetupSeo['p3pCP'])) {
                    $p3pCP = $tsSetupSeo['p3pCP'];
                }

                if (!empty($tsSetupSeo['p3pPolicyUrl'])) {
                    $p3pPolicyUrl = $tsSetupSeo['p3pPolicyUrl'];
                }

                if (!empty($p3pCP) || !empty($p3pPolicyUrl)) {
                    $p3pHeader = array();

                    if (!empty($p3pCP)) {
                        $p3pHeader[] = 'CP="' . $p3pCP . '"';
                    }

                    if (!empty($p3pPolicyUrl)) {
                        $p3pHeader[] = 'policyref="' . $p3pPolicyUrl . '"';
                    }

                    $headers['P3P'] = implode(' ', $p3pHeader);
                }
            }

            // Store headers into cache
            $cache->set($cacheIdentification, $headers, array('pageId_' . $GLOBALS['TSFE']->id));
        } else {
            // #####################################
            // Cached page
            // #####################################

            // Fetched cached headers
            $cachedHeaders = $cache->get($cacheIdentification);

            if (!empty($cachedHeaders)) {
                $headers = $cachedHeaders;
            }
        }

        // Call hook
        GeneralUtility::callHookAndSignal(__CLASS__, 'httpHeaderOutput', $this, $headers);

        // #####################################
        // Sender headers
        // #####################################
        if (!empty($headers['P3P'])) {
            header('P3P: ' . $headers['P3P']);
        }
    }
909964
public function execute()
    {
        $composerLocation = $this->phpci->findBinary(array('composer', 'composer.phar'));

        $cmd = '';

        if (IS_WIN) {
            $cmd = 'php ';
        }

        $cmd .= $composerLocation . ' --no-ansi --no-interaction ';

        if ($this->preferDist) {
            $this->phpci->log('Using --prefer-dist flag');
            $cmd .= ' --prefer-dist';
        }

        if ($this->preferSource) {
            $this->phpci->log('Using --prefer-source flag');
            $cmd .= ' --prefer-source';
        }

        if ($this->nodev) {
            $this->phpci->log('Using --no-dev flag');
            $cmd .= ' --no-dev';
        }

        $cmd .= ' --working-dir="%s" %s';

        return $this->phpci->executeCommand($cmd, $this->directory, $this->action);
    }
459502
def run():
    
    #Define the import statements
    impheader = """import sys
import conv_base

"""
    #Define the test case pattern
    pattern="""class Test%d(conv_base.%sCase):
    @classmethod
    def setUpClass(cls):
        cls.obsmode="%s"
        cls.spectrum="%s"
        cls.fname="C%s_%s.fits"
        cls.setup2()\n\n"""


    #We're going to split these by obsmode.
    outfiles = {'None':'sponly/sponly.py',
                'acs':'acs/acs.py',
                'nicmos':'nicmos/nicmos.py',
                'stis':'stis/stis.py',
                'wfc3,ir':'wfc3_ir/wfc3_ir.py',
                'wfc3,uvis1':'wfc3_uvis1/wfc3_uvis1.py',
                'wfc3,uvis2':'wfc3_uvis2/wfc3_uvis2.py',
                'oops':'oops/oops.py'
                }

    #And subclass for spectrum-only and thermal cases based on obsmode.
    casetype = {"None": "Spec",
                "nicmos": "Therm",
                "wfc3,ir": "Therm"}
    #Use with default=Comm
                
    #Open the database
    db = sqlite3.connect("/ssbwebv1/data1/pandokia/old/pdk/c3/db/pdk.db")


    #Open and initialize the output files
    setdirs(outfiles)
    for k in outfiles:
        outfiles[k] = open(outfiles[k], 'w')
        outfiles[k].write(impheader)

    count=0

    #Select unique (obsmode,spectrum) pairs from our database table of
    #commissioning tests. Sort them by obsmode.

    #Omit cases where spectrum is None, because we've verified that all
    #those obsmodes are duplicated elsewhere.

    #First the bp only. The purpose of these is thermal.
    c = db.execute(""" SELECT DISTINCT obsmode, spectrum
                       FROM synpysyn
                       WHERE spectrum != "None"
                       ORDER BY obsmode""")

    #Now loop over them, and define test cases.
    for x in c:
       obsmode, spectrum = x
       count+=1
       outkey=pickname(obsmode,outfiles)
       defn=pattern%(count,
                     casetype.get(outkey, "Comm"),
                     obsmode,spectrum,count,"%s")
       outfiles[outkey].write(defn)

    #Close all the files
    for k in outfiles:
        outfiles[k].close()
958675
protected function loadStatements(File $phpcsFile): void
    {
        $this->className = $this->findClassName($phpcsFile);

        if ($this->existingStatements !== null) {
            return;
        }

        $existingStatements = $this->getUseStatements($phpcsFile);
        $this->existingStatements = $existingStatements;
        $this->allStatements = $existingStatements;
        $this->newStatements = [];
    }