rspec/rules/S5911/php/rule.adoc

58 lines
1.3 KiB
Plaintext
Raw Normal View History

2021-04-28 16:49:39 +02:00
When specifying the class of objects in a catch clause it is important to make sure that the class exists.
Since no PHP error will be raised if the class does not exist, this can lead to difficult to debug problems as the catch clause will have no effect and the reason might not be obvious.
This mistake often occurs when being in a namespace and catching PHP built-in exception classes without escaping to the global namespace or importing the classes.
This rule raises an issue when, being in a namespace, an undefined class belonging to that namespace is caught.
2021-04-28 16:49:39 +02:00
== Noncompliant Code Example
2022-02-04 17:28:24 +01:00
[source,php]
2021-04-28 16:49:39 +02:00
----
namespace Foo\Bar;
try {
doSomething();
} catch (Exception $e) { // Noncompliant - Exception will never be caught because the class Exception does not exist in the namespace
echo $e->message;
}
----
2021-04-28 16:49:39 +02:00
== Compliant Solution
2022-02-04 17:28:24 +01:00
[source,php]
2021-04-28 16:49:39 +02:00
----
namespace Foo\Bar;
try {
doSomething();
} catch (\Exception $e) { // Compliant used by global namespace
echo $e->message;
}
// or
namespace Foo\Bar;
use Exception;
try {
doSomething();
} catch (Exception $e) { // Compliant imported by use statement
echo $e->message;
}
----
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
include::message.adoc[]
endif::env-github,rspecator-view[]