Skip to content

Commit 4c2b2f5

Browse files
authored
Use match instead of switch when a simple value is returned (#1393)
1 parent dae397d commit 4c2b2f5

File tree

9 files changed

+99
-232
lines changed

9 files changed

+99
-232
lines changed

rector.php

+5-4
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
use Rector\Config\RectorConfig;
44
use Rector\DeadCode\Rector\ClassLike\RemoveAnnotationRector;
55
use Rector\Php70\Rector\StmtsAwareInterface\IfIssetToCoalescingRector;
6-
use Rector\Php73\Rector\FuncCall\JsonThrowOnErrorRector;
6+
use Rector\Php80\Rector\Switch_\ChangeSwitchToMatchRector;
77
use Rector\Set\ValueObject\LevelSetList;
88

99
return static function (RectorConfig $rectorConfig): void {
@@ -17,13 +17,14 @@
1717
// Modernize code
1818
$rectorConfig->sets([LevelSetList::UP_TO_PHP_74]);
1919

20+
$rectorConfig->rule(ChangeSwitchToMatchRector::class);
21+
2022
// phpcs:disable Squiz.Arrays.ArrayDeclaration.KeySpecified
2123
$rectorConfig->skip([
2224
// Do not use ternaries extensively
2325
IfIssetToCoalescingRector::class,
24-
// Not necessary in documentation examples
25-
JsonThrowOnErrorRector::class => [
26-
__DIR__ . '/tests/DocumentationExamplesTest.php',
26+
ChangeSwitchToMatchRector::class => [
27+
__DIR__ . '/tests/SpecTests/Operation.php',
2728
],
2829
]);
2930
// phpcs:enable

src/Builder/Encoder/OperatorEncoder.php

+11-22
Original file line numberDiff line numberDiff line change
@@ -38,27 +38,14 @@ public function encode(mixed $value): stdClass
3838
throw UnsupportedValueException::invalidEncodableValue($value);
3939
}
4040

41-
switch ($value::ENCODE) {
42-
case Encode::Single:
43-
return $this->encodeAsSingle($value);
44-
45-
case Encode::Array:
46-
return $this->encodeAsArray($value);
47-
48-
case Encode::Object:
49-
case Encode::FlatObject:
50-
return $this->encodeAsObject($value);
51-
52-
case Encode::DollarObject:
53-
return $this->encodeAsDollarObject($value);
54-
55-
case Encode::Group:
56-
assert($value instanceof GroupStage);
57-
58-
return $this->encodeAsGroup($value);
59-
}
60-
61-
throw new LogicException(sprintf('Class "%s" does not have a valid ENCODE constant.', $value::class));
41+
return match ($value::ENCODE) {
42+
Encode::Single => $this->encodeAsSingle($value),
43+
Encode::Array => $this->encodeAsArray($value),
44+
Encode::Object, Encode::FlatObject => $this->encodeAsObject($value),
45+
Encode::DollarObject => $this->encodeAsDollarObject($value),
46+
Encode::Group => $this->encodeAsGroup($value),
47+
default => throw new LogicException(sprintf('Class "%s" does not have a valid ENCODE constant.', $value::class)),
48+
};
6249
}
6350

6451
/**
@@ -111,8 +98,10 @@ private function encodeAsDollarObject(OperatorInterface $value): stdClass
11198
/**
11299
* $group stage have a specific encoding because the _id argument is required and others are variadic
113100
*/
114-
private function encodeAsGroup(GroupStage $value): stdClass
101+
private function encodeAsGroup(OperatorInterface $value): stdClass
115102
{
103+
assert($value instanceof GroupStage);
104+
116105
$result = new stdClass();
117106
$result->_id = $this->recursiveEncode($value->_id);
118107

tests/SpecTests/ClientSideEncryption/Prose22_RangeExplicitEncryptionTest.php

+8-21
Original file line numberDiff line numberDiff line change
@@ -451,26 +451,13 @@ private function assertMultipleDocumentsMatch(array $expectedDocuments, Iterator
451451

452452
private static function getCastCallableForType(string $type): callable
453453
{
454-
switch ($type) {
455-
case 'DecimalNoPrecision':
456-
case 'DecimalPrecision':
457-
return fn (int $value) => new Decimal128((string) $value);
458-
459-
case 'DoubleNoPrecision':
460-
case 'DoublePrecision':
461-
return fn (int $value) => (double) $value;
462-
463-
case 'Date':
464-
return fn (int $value) => new UTCDateTime($value);
465-
466-
case 'Int':
467-
return fn (int $value) => $value;
468-
469-
case 'Long':
470-
return fn (int $value) => new Int64($value);
471-
472-
default:
473-
throw new LogicException('Unsupported type: ' . $type);
474-
}
454+
return match ($type) {
455+
'DecimalNoPrecision', 'DecimalPrecision' => fn (int $value) => new Decimal128((string) $value),
456+
'DoubleNoPrecision', 'DoublePrecision' => fn (int $value) => (double) $value,
457+
'Date' => fn (int $value) => new UTCDateTime($value),
458+
'Int' => fn (int $value) => $value,
459+
'Long' => fn (int $value) => new Int64($value),
460+
default => throw new LogicException('Unsupported type: ' . $type),
461+
};
475462
}
476463
}

tests/SpecTests/CommandExpectations.php

+9-19
Original file line numberDiff line numberDiff line change
@@ -40,25 +40,15 @@ class CommandExpectations implements CommandSubscriber
4040
private function __construct(private Client $observedClient, array $events)
4141
{
4242
foreach ($events as $event) {
43-
switch (key((array) $event)) {
44-
case 'command_failed_event':
45-
// phpcs:ignore Squiz.NamingConventions.ValidVariableName.MemberNotCamelCaps
46-
$this->expectedEvents[] = [$event->command_failed_event, CommandFailedEvent::class];
47-
break;
48-
49-
case 'command_started_event':
50-
// phpcs:ignore Squiz.NamingConventions.ValidVariableName.MemberNotCamelCaps
51-
$this->expectedEvents[] = [$event->command_started_event, CommandStartedEvent::class];
52-
break;
53-
54-
case 'command_succeeded_event':
55-
// phpcs:ignore Squiz.NamingConventions.ValidVariableName.MemberNotCamelCaps
56-
$this->expectedEvents[] = [$event->command_succeeded_event, CommandSucceededEvent::class];
57-
break;
58-
59-
default:
60-
throw new LogicException('Unsupported event type: ' . key($event));
61-
}
43+
$this->expectedEvents[] = match (key((array) $event)) {
44+
// phpcs:disable Squiz.NamingConventions.ValidVariableName.MemberNotCamelCaps
45+
'command_failed_event' => [$event->command_failed_event, CommandFailedEvent::class],
46+
// phpcs:ignore Squiz.NamingConventions.ValidVariableName.MemberNotCamelCaps
47+
'command_started_event' => [$event->command_started_event, CommandStartedEvent::class],
48+
// phpcs:ignore Squiz.NamingConventions.ValidVariableName.MemberNotCamelCaps
49+
'command_succeeded_event' => [$event->command_succeeded_event, CommandSucceededEvent::class],
50+
default => throw new LogicException('Unsupported event type: ' . key($event)),
51+
};
6252
}
6353
}
6454

tests/SpecTests/Context.php

+10-24
Original file line numberDiff line numberDiff line change
@@ -358,18 +358,11 @@ public function replaceArgumentSessionPlaceholder(array &$args): void
358358
return;
359359
}
360360

361-
switch ($args['session']) {
362-
case 'session0':
363-
$args['session'] = $this->session0;
364-
break;
365-
366-
case 'session1':
367-
$args['session'] = $this->session1;
368-
break;
369-
370-
default:
371-
throw new LogicException('Unsupported session placeholder: ' . $args['session']);
372-
}
361+
$args['session'] = match ($args['session']) {
362+
'session0' => $this->session0,
363+
'session1' => $this->session1,
364+
default => throw new LogicException('Unsupported session placeholder: ' . $args['session']),
365+
};
373366
}
374367

375368
/**
@@ -386,18 +379,11 @@ public function replaceCommandSessionPlaceholder(stdClass $command): void
386379
return;
387380
}
388381

389-
switch ($command->lsid) {
390-
case 'session0':
391-
$command->lsid = $this->session0Lsid;
392-
break;
393-
394-
case 'session1':
395-
$command->lsid = $this->session1Lsid;
396-
break;
397-
398-
default:
399-
throw new LogicException('Unsupported session placeholder: ' . $command->lsid);
400-
}
382+
$command->lsid = match ($command->lsid) {
383+
'session0' => $this->session0Lsid,
384+
'session1' => $this->session1Lsid,
385+
default => throw new LogicException('Unsupported session placeholder: ' . $command->lsid),
386+
};
401387
}
402388

403389
public function selectCollection($databaseName, $collectionName, array $collectionOptions = [], array $databaseOptions = [])

tests/SpecTests/FunctionalTestCase.php

+11-24
Original file line numberDiff line numberDiff line change
@@ -126,18 +126,11 @@ protected function assertOutcomeCollectionData(array $expectedDocuments, int $re
126126
$this->assertNotNull($expectedDocument);
127127
$this->assertNotNull($actualDocument);
128128

129-
switch ($resultExpectation) {
130-
case ResultExpectation::ASSERT_SAME_DOCUMENT:
131-
$this->assertSameDocument($expectedDocument, $actualDocument);
132-
break;
133-
134-
case ResultExpectation::ASSERT_DOCUMENTS_MATCH:
135-
$this->assertDocumentsMatch($expectedDocument, $actualDocument);
136-
break;
137-
138-
default:
139-
$this->fail(sprintf('Invalid result expectation "%d" for %s', $resultExpectation, __METHOD__));
140-
}
129+
match ($resultExpectation) {
130+
ResultExpectation::ASSERT_SAME_DOCUMENT => $this->assertSameDocument($expectedDocument, $actualDocument),
131+
ResultExpectation::ASSERT_DOCUMENTS_MATCH => $this->assertDocumentsMatch($expectedDocument, $actualDocument),
132+
default => $this->fail(sprintf('Invalid result expectation "%d" for %s', $resultExpectation, __METHOD__)),
133+
};
141134
}
142135
}
143136

@@ -284,18 +277,12 @@ private function isServerlessRequirementSatisfied(?string $serverlessMode): bool
284277
return true;
285278
}
286279

287-
switch ($serverlessMode) {
288-
case self::SERVERLESS_ALLOW:
289-
return true;
290-
291-
case self::SERVERLESS_FORBID:
292-
return ! static::isServerless();
293-
294-
case self::SERVERLESS_REQUIRE:
295-
return static::isServerless();
296-
}
297-
298-
throw new UnexpectedValueException(sprintf('Invalid serverless requirement "%s" found.', $serverlessMode));
280+
return match ($serverlessMode) {
281+
self::SERVERLESS_ALLOW => true,
282+
self::SERVERLESS_FORBID => ! static::isServerless(),
283+
self::SERVERLESS_REQUIRE => static::isServerless(),
284+
default => throw new UnexpectedValueException(sprintf('Invalid serverless requirement "%s" found.', $serverlessMode)),
285+
};
299286
}
300287

301288
/**

tests/UnifiedSpecTests/Constraint/IsBsonType.php

+26-71
Original file line numberDiff line numberDiff line change
@@ -90,77 +90,32 @@ public static function anyOf(string ...$types): Constraint
9090

9191
private function doMatches($other): bool
9292
{
93-
switch ($this->type) {
94-
case 'double':
95-
return is_float($other);
96-
97-
case 'string':
98-
return is_string($other);
99-
100-
case 'object':
101-
return self::isObject($other);
102-
103-
case 'array':
104-
return self::isArray($other);
105-
106-
case 'binData':
107-
return $other instanceof BinaryInterface;
108-
109-
case 'undefined':
110-
return $other instanceof Undefined;
111-
112-
case 'objectId':
113-
return $other instanceof ObjectIdInterface;
114-
115-
case 'bool':
116-
return is_bool($other);
117-
118-
case 'date':
119-
return $other instanceof UTCDateTimeInterface;
120-
121-
case 'null':
122-
return $other === null;
123-
124-
case 'regex':
125-
return $other instanceof RegexInterface;
126-
127-
case 'dbPointer':
128-
return $other instanceof DBPointer;
129-
130-
case 'javascript':
131-
return $other instanceof JavascriptInterface && $other->getScope() === null;
132-
133-
case 'symbol':
134-
return $other instanceof Symbol;
135-
136-
case 'javascriptWithScope':
137-
return $other instanceof JavascriptInterface && $other->getScope() !== null;
138-
139-
case 'int':
140-
return is_int($other);
141-
142-
case 'timestamp':
143-
return $other instanceof TimestampInterface;
144-
145-
case 'long':
146-
return is_int($other) || $other instanceof Int64;
147-
148-
case 'decimal':
149-
return $other instanceof Decimal128Interface;
150-
151-
case 'minKey':
152-
return $other instanceof MinKeyInterface;
153-
154-
case 'maxKey':
155-
return $other instanceof MaxKeyInterface;
156-
157-
case 'number':
158-
return is_int($other) || $other instanceof Int64 || is_float($other) || $other instanceof Decimal128Interface;
159-
160-
default:
161-
// This should already have been caught in the constructor
162-
throw new LogicException('Unsupported type: ' . $this->type);
163-
}
93+
return match ($this->type) {
94+
'double' => is_float($other),
95+
'string' => is_string($other),
96+
'object' => self::isObject($other),
97+
'array' => self::isArray($other),
98+
'binData' => $other instanceof BinaryInterface,
99+
'undefined' => $other instanceof Undefined,
100+
'objectId' => $other instanceof ObjectIdInterface,
101+
'bool' => is_bool($other),
102+
'date' => $other instanceof UTCDateTimeInterface,
103+
'null' => $other === null,
104+
'regex' => $other instanceof RegexInterface,
105+
'dbPointer' => $other instanceof DBPointer,
106+
'javascript' => $other instanceof JavascriptInterface && $other->getScope() === null,
107+
'symbol' => $other instanceof Symbol,
108+
'javascriptWithScope' => $other instanceof JavascriptInterface && $other->getScope() !== null,
109+
'int' => is_int($other),
110+
'timestamp' => $other instanceof TimestampInterface,
111+
'long' => is_int($other) || $other instanceof Int64,
112+
'decimal' => $other instanceof Decimal128Interface,
113+
'minKey' => $other instanceof MinKeyInterface,
114+
'maxKey' => $other instanceof MaxKeyInterface,
115+
'number' => is_int($other) || $other instanceof Int64 || is_float($other) || $other instanceof Decimal128Interface,
116+
// This should already have been caught in the constructor
117+
default => throw new LogicException('Unsupported type: ' . $this->type),
118+
};
164119
}
165120

166121
private function doToString(): string

tests/UnifiedSpecTests/Context.php

+9-28
Original file line numberDiff line numberDiff line change
@@ -95,34 +95,15 @@ public function createEntities(array $entities): void
9595
$id = $def->id ?? null;
9696
assertIsString($id);
9797

98-
switch ($type) {
99-
case 'client':
100-
$this->createClient($id, $def);
101-
break;
102-
103-
case 'clientEncryption':
104-
$this->createClientEncryption($id, $def);
105-
break;
106-
107-
case 'database':
108-
$this->createDatabase($id, $def);
109-
break;
110-
111-
case 'collection':
112-
$this->createCollection($id, $def);
113-
break;
114-
115-
case 'session':
116-
$this->createSession($id, $def);
117-
break;
118-
119-
case 'bucket':
120-
$this->createBucket($id, $def);
121-
break;
122-
123-
default:
124-
throw new LogicException('Unsupported entity type: ' . $type);
125-
}
98+
match ($type) {
99+
'client' => $this->createClient($id, $def),
100+
'clientEncryption' => $this->createClientEncryption($id, $def),
101+
'database' => $this->createDatabase($id, $def),
102+
'collection' => $this->createCollection($id, $def),
103+
'session' => $this->createSession($id, $def),
104+
'bucket' => $this->createBucket($id, $def),
105+
default => throw new LogicException('Unsupported entity type: ' . $type),
106+
};
126107
}
127108
}
128109

0 commit comments

Comments
 (0)