[Rector] Apply Rector dead code set list

This commit is contained in:
Abdul Malik Ikhsan 2021-08-17 18:14:12 +07:00
parent 381748a361
commit 0c38916535
No known key found for this signature in database
GPG Key ID: 69AC5BC354C89BE6
31 changed files with 110 additions and 125 deletions

View File

@ -23,7 +23,7 @@
"phpstan/phpstan": "^0.12.91",
"phpunit/phpunit": "^9.1",
"predis/predis": "^1.1",
"rector/rector": "0.11.47",
"rector/rector": "0.11.48",
"symplify/package-builder": "^9.3"
},
"suggest": {

View File

@ -27,13 +27,14 @@ use Rector\CodingStyle\Rector\ClassMethod\MakeInheritedMethodVisibilitySameAsPar
use Rector\CodingStyle\Rector\FuncCall\CountArrayToEmptyArrayComparisonRector;
use Rector\Core\Configuration\Option;
use Rector\Core\ValueObject\PhpVersion;
use Rector\DeadCode\Rector\Array_\RemoveDuplicatedArrayKeyRector;
use Rector\DeadCode\Rector\Assign\RemoveDoubleAssignRector;
use Rector\DeadCode\Rector\Assign\RemoveUnusedVariableAssignRector;
use Rector\DeadCode\Rector\Concat\RemoveConcatAutocastRector;
use Rector\DeadCode\Rector\Foreach_\RemoveUnusedForeachKeyRector;
use Rector\DeadCode\Rector\Property\RemoveUnusedPrivatePropertyRector;
use Rector\DeadCode\Rector\Switch_\RemoveDuplicatedCaseInSwitchRector;
use Rector\DeadCode\Rector\Cast\RecastingRemovalRector;
use Rector\DeadCode\Rector\ClassMethod\RemoveUnusedPrivateMethodRector;
use Rector\DeadCode\Rector\ClassMethod\RemoveUnusedPromotedPropertyRector;
use Rector\DeadCode\Rector\ClassMethod\RemoveUselessReturnTagRector;
use Rector\DeadCode\Rector\Expression\RemoveDeadStmtRector;
use Rector\DeadCode\Rector\If_\UnwrapFutureCompatibleIfPhpVersionRector;
use Rector\DeadCode\Rector\MethodCall\RemoveEmptyMethodCallRector;
use Rector\DeadCode\Rector\StaticCall\RemoveParentCallWithoutParentRector;
use Rector\EarlyReturn\Rector\Foreach_\ChangeNestedForeachIfsToEarlyContinueRector;
use Rector\EarlyReturn\Rector\If_\ChangeIfElseValueAssignToEarlyReturnRector;
use Rector\EarlyReturn\Rector\If_\RemoveAlwaysElseRector;
@ -51,6 +52,7 @@ use Utils\Rector\RemoveVarTagFromClassConstantRector;
use Utils\Rector\UnderscoreToCamelCaseVariableNameRector;
return static function (ContainerConfigurator $containerConfigurator): void {
$containerConfigurator->import(SetList::DEAD_CODE);
$containerConfigurator->import(SetList::PHP_73);
$parameters = $containerConfigurator->parameters();
@ -72,6 +74,43 @@ return static function (ContainerConfigurator $containerConfigurator): void {
__DIR__ . '/tests/_support',
JsonThrowOnErrorRector::class,
StringifyStrNeedlesRector::class,
// requires php 8
RemoveUnusedPromotedPropertyRector::class,
// currently buggy on call inside assign, wait for next release
RemoveParentCallWithoutParentRector::class,
// private method called via getPrivateMethodInvoker
RemoveUnusedPrivateMethodRector::class => [
__DIR__ . '/system/Entity/Entity.php',
__DIR__ . '/tests/system/Test/ReflectionHelperTest.php',
],
// call on purpose for nothing happen check
RemoveEmptyMethodCallRector::class => [
__DIR__ . '/tests',
],
// currently buggy on class implements ArrayAccess, wait for next release
RemoveDeadStmtRector::class => [
__DIR__ . '/tests/system/Cookie/CookieTest.php',
],
// check on constant compare
UnwrapFutureCompatibleIfPhpVersionRector::class => [
__DIR__ . '/system/CodeIgniter.php',
],
// check context ResponseTrait
RemoveUselessReturnTagRector::class => [
__DIR__ . '/system/HTTP/MessageTrait.php',
],
// casted to Entity via EntityTest->getCastEntity()
RecastingRemovalRector::class => [
__DIR__ . '/tests/system/Entity/EntityTest.php',
],
]);
// auto import fully qualified class names
@ -92,17 +131,13 @@ return static function (ContainerConfigurator $containerConfigurator): void {
$services->set(SimplifyStrposLowerRector::class);
$services->set(CombineIfRector::class);
$services->set(SimplifyIfReturnBoolRector::class);
$services->set(RemoveDuplicatedCaseInSwitchRector::class);
$services->set(InlineIfToExplicitIfRector::class);
$services->set(PreparedValueToEarlyReturnRector::class);
$services->set(ShortenElseIfRector::class);
$services->set(RemoveUnusedForeachKeyRector::class);
$services->set(SimplifyIfElseToTernaryRector::class);
$services->set(UnusedForeachValueToArrayKeysRector::class);
$services->set(RemoveConcatAutocastRector::class);
$services->set(ChangeArrayPushToArrayAssignRector::class);
$services->set(UnnecessaryTernaryExpressionRector::class);
$services->set(RemoveUnusedPrivatePropertyRector::class);
$services->set(RemoveErrorSuppressInTryCatchStmtsRector::class);
$services->set(TernaryToNullCoalescingRector::class);
$services->set(ListToArrayDestructRector::class);
@ -110,9 +145,6 @@ return static function (ContainerConfigurator $containerConfigurator): void {
$services->set(AddPregQuoteDelimiterRector::class);
$services->set(SimplifyRegexPatternRector::class);
$services->set(RemoveExtraParametersRector::class);
$services->set(RemoveUnusedVariableAssignRector::class);
$services->set(FuncGetArgsToVariadicParamRector::class);
$services->set(MakeInheritedMethodVisibilitySameAsParentRector::class);
$services->set(RemoveDuplicatedArrayKeyRector::class);
$services->set(RemoveDoubleAssignRector::class);
};

View File

@ -996,20 +996,18 @@ class Forge
'SET DEFAULT',
];
if ($this->foreignKeys !== []) {
foreach ($this->foreignKeys as $field => $fkey) {
$nameIndex = $table . '_' . $field . '_foreign';
foreach ($this->foreignKeys as $field => $fkey) {
$nameIndex = $table . '_' . $field . '_foreign';
$sql .= ",\n\tCONSTRAINT " . $this->db->escapeIdentifiers($nameIndex)
. ' FOREIGN KEY(' . $this->db->escapeIdentifiers($field) . ') REFERENCES ' . $this->db->escapeIdentifiers($this->db->DBPrefix . $fkey['table']) . ' (' . $this->db->escapeIdentifiers($fkey['field']) . ')';
$sql .= ",\n\tCONSTRAINT " . $this->db->escapeIdentifiers($nameIndex)
. ' FOREIGN KEY(' . $this->db->escapeIdentifiers($field) . ') REFERENCES ' . $this->db->escapeIdentifiers($this->db->DBPrefix . $fkey['table']) . ' (' . $this->db->escapeIdentifiers($fkey['field']) . ')';
if ($fkey['onDelete'] !== false && in_array($fkey['onDelete'], $allowActions, true)) {
$sql .= ' ON DELETE ' . $fkey['onDelete'];
}
if ($fkey['onDelete'] !== false && in_array($fkey['onDelete'], $allowActions, true)) {
$sql .= ' ON DELETE ' . $fkey['onDelete'];
}
if ($fkey['onUpdate'] !== false && in_array($fkey['onUpdate'], $allowActions, true)) {
$sql .= ' ON UPDATE ' . $fkey['onUpdate'];
}
if ($fkey['onUpdate'] !== false && in_array($fkey['onUpdate'], $allowActions, true)) {
$sql .= ' ON UPDATE ' . $fkey['onUpdate'];
}
}

View File

@ -89,7 +89,7 @@ class Result extends BaseResult
$retVal[$i]->type = $data->type;
$retVal[$i]->type_name = in_array($data->type, [1, 247], true) ? 'char' : ($dataTypes[$data->type] ?? null);
$retVal[$i]->max_length = $data->max_length;
$retVal[$i]->primary_key = (int) ($data->flags & 2);
$retVal[$i]->primary_key = $data->flags & 2;
$retVal[$i]->length = $data->length;
$retVal[$i]->default = $data->def;
}

View File

@ -354,7 +354,7 @@ class Connection extends BaseConnection
*/
protected function _transBegin(): bool
{
return (bool) sqlsrv_begin_transaction($this->connID);
return sqlsrv_begin_transaction($this->connID);
}
/**
@ -362,7 +362,7 @@ class Connection extends BaseConnection
*/
protected function _transCommit(): bool
{
return (bool) sqlsrv_commit($this->connID);
return sqlsrv_commit($this->connID);
}
/**
@ -370,7 +370,7 @@ class Connection extends BaseConnection
*/
protected function _transRollback(): bool
{
return (bool) sqlsrv_rollback($this->connID);
return sqlsrv_rollback($this->connID);
}
/**

View File

@ -224,21 +224,19 @@ class Forge extends BaseForge
$allowActions = ['CASCADE', 'SET NULL', 'NO ACTION', 'RESTRICT', 'SET DEFAULT'];
if ($this->foreignKeys !== []) {
foreach ($this->foreignKeys as $field => $fkey) {
$nameIndex = $table . '_' . $field . '_foreign';
foreach ($this->foreignKeys as $field => $fkey) {
$nameIndex = $table . '_' . $field . '_foreign';
$sql .= ",\n\t CONSTRAINT " . $this->db->escapeIdentifiers($nameIndex)
. ' FOREIGN KEY (' . $this->db->escapeIdentifiers($field) . ') '
. ' REFERENCES ' . $this->db->escapeIdentifiers($this->db->getPrefix() . $fkey['table']) . ' (' . $this->db->escapeIdentifiers($fkey['field']) . ')';
$sql .= ",\n\t CONSTRAINT " . $this->db->escapeIdentifiers($nameIndex)
. ' FOREIGN KEY (' . $this->db->escapeIdentifiers($field) . ') '
. ' REFERENCES ' . $this->db->escapeIdentifiers($this->db->getPrefix() . $fkey['table']) . ' (' . $this->db->escapeIdentifiers($fkey['field']) . ')';
if ($fkey['onDelete'] !== false && in_array($fkey['onDelete'], $allowActions, true)) {
$sql .= ' ON DELETE ' . $fkey['onDelete'];
}
if ($fkey['onDelete'] !== false && in_array($fkey['onDelete'], $allowActions, true)) {
$sql .= ' ON DELETE ' . $fkey['onDelete'];
}
if ($fkey['onUpdate'] !== false && in_array($fkey['onUpdate'], $allowActions, true)) {
$sql .= ' ON UPDATE ' . $fkey['onUpdate'];
}
if ($fkey['onUpdate'] !== false && in_array($fkey['onUpdate'], $allowActions, true)) {
$sql .= ' ON UPDATE ' . $fkey['onUpdate'];
}
}

View File

@ -66,17 +66,14 @@ class Toolbar
/**
* Returns all the data required by Debug Bar
*
* @param float $startTime App start time
* @param float $startTime App start time
* @param IncomingRequest $request
* @param Response $response
*
* @return string JSON encoded data
*/
public function run(float $startTime, float $totalTime, RequestInterface $request, ResponseInterface $response): string
{
/**
* @var IncomingRequest $request
* @var Response $response
*/
// Data items used within the view.
$data['url'] = current_url();
$data['method'] = $request->getMethod(true);

View File

@ -45,7 +45,7 @@ class Files extends BaseCollector
*/
public function getTitleDetails(): string
{
return '( ' . (int) count(get_included_files()) . ' )';
return '( ' . count(get_included_files()) . ' )';
}
/**

View File

@ -71,9 +71,7 @@ class Events
return;
}
/**
* @var Modules
*/
/** @var Modules $config */
$config = config('Modules');
$events = APPPATH . 'Config' . DIRECTORY_SEPARATOR . 'Events.php';
$files = [];

View File

@ -254,8 +254,6 @@ class Filters
* Restores instance to its pre-initialized state.
* Most useful for testing so the service can be
* re-initialized to a different path.
*
* @return $this
*/
public function reset(): self
{
@ -427,8 +425,6 @@ class Filters
if (array_key_exists($method, $this->config->methods)) {
$this->filters['before'] = array_merge($this->filters['before'], $this->config->methods[$method]);
return;
}
}

View File

@ -997,9 +997,6 @@ class URI
* Section 5.2
*
* @see http://tools.ietf.org/html/rfc3986#section-5.2.3
*
* @param URI $base
* @param URI $reference
*/
protected function mergePaths(self $base, self $reference): string
{

View File

@ -304,10 +304,8 @@ if (! function_exists('video')) {
$video .= ">\n";
if (! empty($tracks)) {
foreach ($tracks as $track) {
$video .= _space_indent() . $track . "\n";
}
foreach ($tracks as $track) {
$video .= _space_indent() . $track . "\n";
}
if (! empty($unsupportedMessage)) {
@ -352,10 +350,8 @@ if (! function_exists('audio')) {
$audio .= '>';
if (! empty($tracks)) {
foreach ($tracks as $track) {
$audio .= "\n" . _space_indent() . $track;
}
foreach ($tracks as $track) {
$audio .= "\n" . _space_indent() . $track;
}
if (! empty($unsupportedMessage)) {
@ -388,10 +384,8 @@ if (! function_exists('_media')) {
$media .= _space_indent() . $option . "\n";
}
if (! empty($tracks)) {
foreach ($tracks as $track) {
$media .= _space_indent() . $track . "\n";
}
foreach ($tracks as $track) {
$media .= _space_indent() . $track . "\n";
}
if (! empty($unsupportedMessage)) {

View File

@ -395,10 +395,8 @@ if (! function_exists('word_wrap')) {
}
// Put our markers back
if (! empty($unwrap)) {
foreach ($unwrap as $key => $val) {
$output = str_replace('{{unwrapped' . $key . '}}', $val, $output);
}
foreach ($unwrap as $key => $val) {
$output = str_replace('{{unwrapped' . $key . '}}', $val, $output);
}
// remove any trailing newline

View File

@ -282,7 +282,7 @@ class Logger implements LoggerInterface
}
/**
* @var HandlerInterface
* @var HandlerInterface $handler
*/
$handler = $this->handlers[$className];

View File

@ -363,8 +363,6 @@ class Pager implements PagerInterface
/**
* Sets only allowed queries on pagination links.
*
* @return Pager
*/
public function only(array $queries): self
{

View File

@ -239,7 +239,7 @@ class PagerRenderer
$uri = $this->segment === 0 ? $uri->addQuery($this->pageSelector, $i) : $uri->setSegment($this->segment, $i);
$links[] = [
'uri' => URI::createURIString($uri->getScheme(), $uri->getAuthority(), $uri->getPath(), $uri->getQuery(), $uri->getFragment()),
'title' => (int) $i,
'title' => $i,
'active' => ($i === $this->current),
];
}
@ -260,8 +260,8 @@ class PagerRenderer
return;
}
$this->first = $this->current - $count > 0 ? (int) ($this->current - $count) : 1;
$this->last = $this->current + $count <= $this->pageCount ? (int) ($this->current + $count) : (int) $this->pageCount;
$this->first = $this->current - $count > 0 ? $this->current - $count : 1;
$this->last = $this->current + $count <= $this->pageCount ? $this->current + $count : (int) $this->pageCount;
}
/**

View File

@ -92,8 +92,6 @@ interface RouteCollectionInterface
* defined routes.
*
* If FALSE, will stop searching and do NO automatic routing.
*
* @return RouteCollectionInterface
*/
public function setAutoRoute(bool $value): self;
@ -105,8 +103,6 @@ interface RouteCollectionInterface
* This setting is passed to the Router class and handled there.
*
* @param callable|null $callable
*
* @return RouteCollectionInterface
*/
public function set404Override($callable = null): self;

View File

@ -268,8 +268,6 @@ class Router implements RouterInterface
* it a blank.
*
* @param string $page
*
* @return $this
*/
public function setIndexPage($page): self
{
@ -281,10 +279,6 @@ class Router implements RouterInterface
/**
* Tells the system whether we should translate URI dashes or not
* in the URI from a dash to an underscore.
*
* @param bool|false $val
*
* @return $this
*/
public function setTranslateURIDashes(bool $val = false): self
{

View File

@ -125,7 +125,9 @@ class Security implements SecurityInterface
*/
public function __construct(App $config)
{
/** @var SecurityConfig */
/**
* @var SecurityConfig $security
*/
$security = config('Security');
// Store CSRF-related configurations
@ -134,7 +136,9 @@ class Security implements SecurityInterface
$this->regenerate = $security->regenerate ?? $config->CSRFRegenerate ?? $this->regenerate;
$rawCookieName = $security->cookieName ?? $config->CSRFCookieName ?? $this->cookieName;
/** @var CookieConfig */
/**
* @var CookieConfig $cookie
*/
$cookie = config('Cookie');
$cookiePrefix = $cookie->prefix ?? $config->cookiePrefix;

View File

@ -182,7 +182,9 @@ class Session implements SessionInterface
$this->cookieSecure = $config->cookieSecure ?? $this->cookieSecure;
$this->cookieSameSite = $config->cookieSameSite ?? $this->cookieSameSite;
/** @var CookieConfig */
/**
* @var CookieConfig $cookie
*/
$cookie = config('Cookie');
$this->cookie = new Cookie($this->sessionCookieName, '', [

View File

@ -233,8 +233,6 @@ class Fabricator
*
* @param array $overrides Array of [field => value]
* @param bool $persist Whether these overrides should persist through the next operation
*
* @return $this
*/
public function setOverrides(array $overrides = [], $persist = true): self
{
@ -259,8 +257,6 @@ class Fabricator
* Set the formatters to use. Will attempt to autodetect if none are available.
*
* @param array|null $formatters Array of [field => formatter], or null to detect
*
* @return $this
*/
public function setFormatters(?array $formatters = null): self
{
@ -277,8 +273,6 @@ class Fabricator
/**
* Try to identify the appropriate Faker formatter for each field.
*
* @return $this
*/
protected function detectFormatters(): self
{

View File

@ -12,12 +12,7 @@
namespace CodeIgniter\Test\Mock;
use CodeIgniter\Database\BaseBuilder;
use CodeIgniter\Database\ConnectionInterface;
class MockBuilder extends BaseBuilder
{
public function __construct($tableName, ConnectionInterface &$db, ?array $options = null)
{
parent::__construct($tableName, $db, $options);
}
}

View File

@ -139,8 +139,6 @@ class Throttler implements ThrottlerInterface
/**
* @param string $key The name of the bucket
*
* @return $this
*/
public function remove(string $key): self
{

View File

@ -113,7 +113,7 @@ class Rules
$row = $row->where($whereField, $whereValue);
}
return (bool) ($row->get()->getRow() !== null);
return $row->get()->getRow() !== null;
}
/**
@ -158,7 +158,7 @@ class Rules
$row = $row->where("{$ignoreField} !=", $ignoreValue);
}
return (bool) ($row->get()->getRow() === null);
return $row->get()->getRow() === null;
}
/**

View File

@ -64,8 +64,8 @@ final class ResponseTraitTest extends CIUnitTestCase
}
if ($this->request === null) {
$this->request = new MockIncomingRequest((object) $config, new URI($uri), null, new UserAgent());
$this->response = new MockResponse((object) $config);
$this->request = new MockIncomingRequest($config, new URI($uri), null, new UserAgent());
$this->response = new MockResponse($config);
}
// Insert headers into request.

View File

@ -345,7 +345,7 @@ final class BaseTestFileHandler extends FileHandler
public function getFileInfoTest()
{
$tmpHandle = tmpfile();
stream_get_meta_data($tmpHandle)['uri'];
stream_get_meta_data($tmpHandle);
return $this->getFileInfo(stream_get_meta_data($tmpHandle)['uri'], [
'name',

View File

@ -110,7 +110,7 @@ final class CookieStoreTest extends CIUnitTestCase
$prod = $cookies['prod']->getOptions();
/**
* @var MockObject&CookieStore
* @var MockObject&CookieStore $store
*/
$store = $this->getMockBuilder(CookieStore::class)
->setConstructorArgs([$cookies])

View File

@ -58,8 +58,6 @@ final class UpdateTest extends CIUnitTestCase
// This DB doesn't support Where and Limit together
// but we don't want it called a "Risky" test.
$this->assertTrue(true);
return;
}
}
@ -95,8 +93,6 @@ final class UpdateTest extends CIUnitTestCase
// This DB doesn't support Where and Limit together
// but we don't want it called a "Risky" test.
$this->assertTrue(true);
return;
}
}

View File

@ -48,7 +48,7 @@ final class EventsTest extends CIUnitTestCase
public function testInitialize()
{
/**
* @var Modules
* @var Modules $config
*/
$config = config('Modules');
$config->aliases = [];

View File

@ -241,7 +241,7 @@ final class PagerTest extends CIUnitTestCase
$expected = current_url(true);
$expected = (string) $expected->setQuery('page_foo=3');
$this->assertSame((string) $expected, $this->pager->getNextPageURI('foo'));
$this->assertSame($expected, $this->pager->getNextPageURI('foo'));
}
public function testGetNextURIReturnsNullOnLastPage()
@ -270,7 +270,7 @@ final class PagerTest extends CIUnitTestCase
$expected = current_url(true);
$expected = (string) $expected->setQuery('page_foo=1');
$this->assertSame((string) $expected, $this->pager->getPreviousPageURI('foo'));
$this->assertSame($expected, $this->pager->getPreviousPageURI('foo'));
}
public function testGetNextURIReturnsNullOnFirstPage()
@ -292,7 +292,7 @@ final class PagerTest extends CIUnitTestCase
$this->pager->store('foo', $_GET['page_foo'] - 1, 12, 70);
$this->assertSame((string) $expected, $this->pager->getNextPageURI('foo'));
$this->assertSame($expected, $this->pager->getNextPageURI('foo'));
}
public function testGetPreviousURIWithQueryStringUsesCurrentURI()
@ -306,7 +306,7 @@ final class PagerTest extends CIUnitTestCase
$this->pager->store('foo', $_GET['page_foo'] + 1, 12, 70);
$this->assertSame((string) $expected, $this->pager->getPreviousPageURI('foo'));
$this->assertSame($expected, $this->pager->getPreviousPageURI('foo'));
}
public function testGetOnlyQueries()
@ -453,7 +453,7 @@ final class PagerTest extends CIUnitTestCase
$expected = current_url(true);
$expected = (string) $expected->setQuery('page_foo=1');
$this->assertSame((string) $expected, $this->pager->getPreviousPageURI('foo'));
$this->assertSame($expected, $this->pager->getPreviousPageURI('foo'));
}
public function testAccessPageMoreThanPageCountGetLastPage()

View File

@ -180,9 +180,9 @@ final class SessionTest extends CIUnitTestCase
$session = $this->getInstance();
$session->start();
$session->set('foo', (int) 0);
$session->set('foo', 0);
$this->assertSame((int) 0, $session->get('foo'));
$this->assertSame(0, $session->get('foo'));
}
public function testGetReturnsAllWithNoKeys()