Skip to content

Commit 86d8208

Browse files
authored
Add php-cs-fixer and tweak syntax slightly (#37)
1 parent ef5454b commit 86d8208

7 files changed

Lines changed: 165 additions & 72 deletions

File tree

.php-cs-fixer.php

Lines changed: 97 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,97 @@
1+
<?php
2+
3+
$header = <<<EOF
4+
This file is part of Composer.
5+
6+
(c) Nils Adermann <naderman@naderman.de>
7+
Jordi Boggiano <j.boggiano@seld.be>
8+
9+
For the full copyright and license information, please view the LICENSE
10+
file that was distributed with this source code.
11+
EOF;
12+
13+
$finder = PhpCsFixer\Finder::create()
14+
->files()
15+
->in(__DIR__.'/src')
16+
->in(__DIR__.'/tests')
17+
->name('*.php')
18+
->notPath('Fixtures')
19+
;
20+
21+
$config = new PhpCsFixer\Config();
22+
return $config
23+
->setParallelConfig(PhpCsFixer\Runner\Parallel\ParallelConfigFactory::detect())
24+
->setRules([
25+
'@PSR2' => true,
26+
'binary_operator_spaces' => true,
27+
'blank_line_before_statement' => ['statements' => ['declare', 'return']],
28+
'cast_spaces' => ['space' => 'single'],
29+
'header_comment' => ['header' => $header],
30+
'statement_indentation' => ['stick_comment_to_next_continuous_control_statement' => true],
31+
'include' => true,
32+
33+
'class_attributes_separation' => ['elements' => ['method' => 'one', 'trait_import' => 'none']],
34+
'no_blank_lines_after_class_opening' => true,
35+
'no_blank_lines_after_phpdoc' => true,
36+
'no_empty_statement' => true,
37+
'no_extra_blank_lines' => true,
38+
'no_leading_namespace_whitespace' => true,
39+
'no_trailing_comma_in_singleline' => true,
40+
'no_whitespace_in_blank_line' => true,
41+
'object_operator_without_whitespace' => true,
42+
//'phpdoc_align' => true,
43+
'phpdoc_indent' => true,
44+
'no_empty_comment' => true,
45+
'no_empty_phpdoc' => true,
46+
'phpdoc_no_access' => true,
47+
'phpdoc_no_package' => true,
48+
//'phpdoc_order' => true,
49+
'phpdoc_scalar' => true,
50+
'phpdoc_trim' => true,
51+
'phpdoc_types' => true,
52+
'psr_autoloading' => true,
53+
'blank_lines_before_namespace' => true,
54+
'standardize_not_equals' => true,
55+
'ternary_operator_spaces' => true,
56+
'trailing_comma_in_multiline' => ['elements' => ['arrays']],
57+
'unary_operator_spaces' => true,
58+
59+
'native_function_invocation' => [
60+
'include' => ['@compiler_optimized'], // Targets functions with special Zend opcodes (e.g., strlen, count)
61+
'scope' => 'namespaced', // Only fixes functions inside a namespace
62+
'strict' => true, // Removes leading \ if not native
63+
],
64+
65+
// imports
66+
'no_unused_imports' => true,
67+
'fully_qualified_strict_types' => true,
68+
'single_line_after_imports' => true,
69+
//'global_namespace_import' => ['import_classes' => true],
70+
'no_leading_import_slash' => true,
71+
'single_import_per_statement' => true,
72+
73+
// PHP 7.2 migration
74+
'array_syntax' => true,
75+
'list_syntax' => true,
76+
'regular_callable_call' => true,
77+
'static_lambda' => true,
78+
'nullable_type_declaration_for_default_null_value' => true,
79+
'explicit_indirect_variable' => true,
80+
'visibility_required' => ['elements' => ['property', 'method', 'const']],
81+
'non_printable_character' => true,
82+
'combine_nested_dirname' => true,
83+
'random_api_migration' => true,
84+
'ternary_to_null_coalescing' => true,
85+
'phpdoc_to_param_type' => false,
86+
'declare_strict_types' => true,
87+
'no_superfluous_phpdoc_tags' => [
88+
'allow_mixed' => true,
89+
],
90+
91+
// TODO php 7.4 migration (one day..)
92+
// 'phpdoc_to_property_type' => true,
93+
])
94+
->setUsingCache(true)
95+
->setRiskyAllowed(true)
96+
->setFinder($finder)
97+
;

src/ClassMap.php

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -94,7 +94,7 @@ public function getAmbiguousClasses($duplicatesFilter = '{/(test|fixture|example
9494

9595
$ambiguousClasses = [];
9696
foreach ($this->ambiguousClasses as $class => $paths) {
97-
$paths = array_filter($paths, function ($path) use ($duplicatesFilter): bool {
97+
$paths = array_filter($paths, static function ($path) use ($duplicatesFilter): bool {
9898
return !Preg::isMatch($duplicatesFilter, strtr($path, '\\', '/'));
9999
});
100100
if (\count($paths) > 0) {
@@ -157,7 +157,7 @@ public function clearPsrViolationsByPath(string $pathPrefix): void
157157
$pathPrefix = rtrim(strtr($pathPrefix, '\\', '/'), '/');
158158

159159
foreach ($this->psrViolations as $path => $violations) {
160-
if ($path === $pathPrefix || 0 === \strpos($path, $pathPrefix.'/')) {
160+
if ($path === $pathPrefix || 0 === strpos($path, $pathPrefix.'/')) {
161161
unset($this->psrViolations[$path]);
162162
}
163163
}

src/ClassMapGenerator.php

Lines changed: 9 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,6 @@
2020

2121
use Composer\Pcre\Preg;
2222
use Symfony\Component\Finder\Finder;
23-
use Composer\IO\IOInterface;
2423

2524
/**
2625
* ClassMapGenerator
@@ -57,7 +56,7 @@ public function __construct(array $extensions = ['php', 'inc'])
5756
{
5857
$this->extensions = $extensions;
5958
$this->classMap = new ClassMap;
60-
$this->streamWrappersRegex = sprintf('{^(?:%s)://}', implode('|', array_map('preg_quote', stream_get_wrappers())));
59+
$this->streamWrappersRegex = \sprintf('{^(?:%s)://}', implode('|', array_map('preg_quote', stream_get_wrappers())));
6160
}
6261

6362
/**
@@ -109,21 +108,21 @@ public function getClassMap(): ClassMap
109108
*/
110109
public function scanPaths($path, ?string $excluded = null, string $autoloadType = 'classmap', ?string $namespace = null, array $excludedDirs = []): void
111110
{
112-
if (!in_array($autoloadType, ['psr-0', 'psr-4', 'classmap'], true)) {
111+
if (!\in_array($autoloadType, ['psr-0', 'psr-4', 'classmap'], true)) {
113112
throw new \InvalidArgumentException('$autoloadType must be one of: "psr-0", "psr-4" or "classmap"');
114113
}
115114

116115
if ('classmap' !== $autoloadType) {
117-
if (!is_string($path)) {
116+
if (!\is_string($path)) {
118117
throw new \InvalidArgumentException('$path must be a string when specifying a psr-0 or psr-4 autoload type');
119118
}
120-
if (!is_string($namespace)) {
119+
if (!\is_string($namespace)) {
121120
throw new \InvalidArgumentException('$namespace must be given (even if it is an empty string if you do not want to filter) when specifying a psr-0 or psr-4 autoload type');
122121
}
123122
$basePath = $path;
124123
}
125124

126-
if (is_string($path)) {
125+
if (\is_string($path)) {
127126
if (is_file($path)) {
128127
$path = [new \SplFileInfo($path)];
129128
} elseif (is_dir($path) || strpos($path, '*') !== false) {
@@ -144,7 +143,7 @@ public function scanPaths($path, ?string $excluded = null, string $autoloadType
144143

145144
foreach ($path as $file) {
146145
$filePath = $file->getPathname();
147-
if (!in_array(pathinfo($filePath, PATHINFO_EXTENSION), $this->extensions, true)) {
146+
if (!\in_array(pathinfo($filePath, PATHINFO_EXTENSION), $this->extensions, true)) {
148147
continue;
149148
}
150149

@@ -224,7 +223,7 @@ private function filterByNamespace(array $classes, string $filePath, string $bas
224223
$validClasses = [];
225224
$rejectedClasses = [];
226225

227-
$realSubPath = substr($filePath, strlen($basePath) + 1);
226+
$realSubPath = substr($filePath, \strlen($basePath) + 1);
228227
$dotPosition = strrpos($realSubPath, '.');
229228
$realSubPath = substr($realSubPath, 0, $dotPosition === false ? PHP_INT_MAX : $dotPosition);
230229

@@ -246,7 +245,7 @@ private function filterByNamespace(array $classes, string $filePath, string $bas
246245
$subPath = str_replace('_', DIRECTORY_SEPARATOR, $class);
247246
}
248247
} elseif ('psr-4' === $namespaceType) {
249-
$subNamespace = ('' !== $baseNamespace) ? substr($class, strlen($baseNamespace)) : $class;
248+
$subNamespace = ('' !== $baseNamespace) ? substr($class, \strlen($baseNamespace)) : $class;
250249
$subPath = str_replace('\\', DIRECTORY_SEPARATOR, $subNamespace);
251250
} else {
252251
throw new \InvalidArgumentException('$namespaceType must be "psr-0" or "psr-4"');
@@ -281,9 +280,6 @@ private function filterByNamespace(array $classes, string $filePath, string $bas
281280
* Checks if the given path is absolute
282281
*
283282
* @see Composer\Util\Filesystem::isAbsolutePath
284-
*
285-
* @param string $path
286-
* @return bool
287283
*/
288284
private static function isAbsolutePath(string $path): bool
289285
{
@@ -297,7 +293,6 @@ private static function isAbsolutePath(string $path): bool
297293
* @see Composer\Util\Filesystem::normalizePath
298294
*
299295
* @param string $path Path to the file or directory
300-
* @return string
301296
*/
302297
private static function normalizePath(string $path): string
303298
{
@@ -335,7 +330,7 @@ private static function normalizePath(string $path): string
335330
}
336331

337332
// ensure c: is normalized to C:
338-
$prefix = Preg::replaceCallback('{(?:^|://)[a-z]:$}i', function (array $m) { return strtoupper((string) $m[0]); }, $prefix);
333+
$prefix = Preg::replaceCallback('{(?:^|://)[a-z]:$}i', static function (array $m) { return strtoupper((string) $m[0]); }, $prefix);
339334

340335
return $prefix.$absolute.implode('/', $parts);
341336
}

src/PhpFileCleaner.php

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -120,7 +120,7 @@ public function clean(): string
120120
if ($this->maxMatches === 1 && isset(self::$typeConfig[$char])) {
121121
$type = self::$typeConfig[$char];
122122
if (
123-
\substr($this->contents, $this->index, $type['length']) === $type['name']
123+
substr($this->contents, $this->index, $type['length']) === $type['name']
124124
&& Preg::isMatch($type['pattern'], $this->contents, $match, 0, $this->index - 1)
125125
) {
126126
return $clean . $match[0];
@@ -130,7 +130,7 @@ public function clean(): string
130130
$this->index += 1;
131131
$skip = strcspn($this->contents, self::$rejectChars, $this->index);
132132
if ($skip > 0) {
133-
$clean .= $char . \substr($this->contents, $this->index, $skip);
133+
$clean .= $char . substr($this->contents, $this->index, $skip);
134134
$this->index += $skip;
135135
} else {
136136
$clean .= $char;
@@ -212,7 +212,7 @@ private function skipHeredoc(string $delimiter): void
212212
continue 2;
213213
case $firstDelimiterChar:
214214
if (
215-
\substr($this->contents, $this->index, $delimiterLength) === $delimiter
215+
substr($this->contents, $this->index, $delimiterLength) === $delimiter
216216
&& $this->match($delimiterPattern)
217217
) {
218218
$this->index += $delimiterLength;

src/PhpFileParser.php

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ public static function findClasses(string $path): array
3131
{
3232
$extraTypes = self::getExtraTypes();
3333

34-
if (!function_exists('php_strip_whitespace')) {
34+
if (!\function_exists('php_strip_whitespace')) {
3535
throw new RuntimeException('Classmap generation relies on the php_strip_whitespace function, but it has been disabled by the disable_functions directive.');
3636
}
3737

@@ -55,7 +55,7 @@ public static function findClasses(string $path): array
5555
$message .= PHP_EOL . 'The following message may be helpful:' . PHP_EOL . $error['message'];
5656
}
5757

58-
throw new RuntimeException(sprintf($message, $path));
58+
throw new RuntimeException(\sprintf($message, $path));
5959
}
6060

6161
// return early if there is no chance of matching anything in this file
@@ -64,7 +64,7 @@ public static function findClasses(string $path): array
6464
return [];
6565
}
6666

67-
$p = new PhpFileCleaner($contents, count($matches[0]));
67+
$p = new PhpFileCleaner($contents, \count($matches[0]));
6868
$contents = $p->clean();
6969
unset($p);
7070

@@ -78,12 +78,12 @@ public static function findClasses(string $path): array
7878
$classes = [];
7979
$namespace = '';
8080

81-
for ($i = 0, $len = count($matches['type']); $i < $len; ++$i) {
81+
for ($i = 0, $len = \count($matches['type']); $i < $len; ++$i) {
8282
if (isset($matches['ns'][$i]) && $matches['ns'][$i] !== '') {
8383
$namespace = str_replace([' ', "\t", "\r", "\n"], '', (string) $matches['nsname'][$i]) . '\\';
8484
} else {
8585
$name = $matches['name'][$i];
86-
assert(is_string($name));
86+
\assert(\is_string($name));
8787
// skip anon classes extending/implementing
8888
if ($name === 'extends') {
8989
continue;
@@ -126,7 +126,7 @@ private static function getExtraTypes(): string
126126
if (null === $extraTypes) {
127127
$extraTypes = '';
128128
$extraTypesArray = [];
129-
if (PHP_VERSION_ID >= 80100 || (defined('HHVM_VERSION') && version_compare(HHVM_VERSION, '3.3', '>='))) {
129+
if (PHP_VERSION_ID >= 80100 || (\defined('HHVM_VERSION') && version_compare(HHVM_VERSION, '3.3', '>='))) {
130130
$extraTypes .= '|enum';
131131
$extraTypesArray = ['enum'];
132132
}

0 commit comments

Comments
 (0)