Consider following a standard guide
Many PHP developers follow the PSR standards - e.g. PSR-12 which contains a section about lines:
2.3 Lines
There MUST NOT be a hard limit on line length.
The soft limit on line length MUST be 120 characters.
Lines SHOULD NOT be longer than 80 characters; lines longer than that
SHOULD be split into multiple subsequent lines of no more than 80
characters each.
Some of those long lines can be split to multiple lines - e.g.
} else {
\Drupal::logger('my_change_node_type_module')->error('Node type mismatch for node ID: @nid', ['@nid' => $nid]);
Can be updated to this, which requires no scrolling over if the window is narrow:
} else {
\Drupal::logger('my_change_node_type_module')
->error('Node type mismatch for node ID: @nid', ['@nid' => $nid]);
Consider using strict equality checks
If $node->getType()
always returns a string then the strict equality operator ===
can be used instead of the loose equality operator ==
. It is a good habit to use strict equality operators whenever possible as it requires no type juggling.
Consider returning early to decrease indentation levels
There are three levels of nested conditionals and the lines within the blocks are quite long. One could reverse the logic a bit to "return early" (or exit if not in a function/method) which can decrease indentation levels. For example:
if (empty($nid) || !is_numeric($nid)) {
exit;
}
try {
$node = Node::load($nid);
if (!$node) {
\Drupal::logger('my_change_node_type_module')
->error('Node not found for ID: @nid', ['@nid' => $nid]);
exit;
}
if ($node->getType() !== 'EXISTING_NODE_TYPE_COMES_HERE') {
\Drupal::logger('my_change_node_type_module')
->error('Node type mismatch for node ID: @nid', ['@nid' => $nid]);
exit;
}
$node->set('type', 'NEW_NODE_TYPE_COMES_HERE');
$node->save();
} catch (\Exception $e) {
\Drupal::logger('my_change_node_type_module')
->error('Error loading node with ID @nid: @message', ['@nid' => $nid, '@message' => $e->getMessage()]);
}
}
Obviously it requires additional lines to call exit;
however the indentation levels are minimal and some may find it simpler to read.
If there is a desire not to utilize exit
then the else
keyword could be used:
if (!empty($nid) && is_numeric($nid)) {
try {
$node = Node::load($nid);
if (!$node) {
\Drupal::logger('my_change_node_type_module')
->error('Node not found for ID: @nid', ['@nid' => $nid]);
} elseif ($node->getType() !== 'EXISTING_NODE_TYPE_COMES_HERE') {
\Drupal::logger('my_change_node_type_module')
->error('Node type mismatch for node ID: @nid', ['@nid' => $nid]);
} else {
$node->set('type', 'NEW_NODE_TYPE_COMES_HERE');
$node->save();
}
} catch (\Exception $e) {
\Drupal::logger('my_change_node_type_module')
->error('Error loading node with ID @nid: @message', ['@nid' => $nid, '@message' => $e->getMessage()]);
}
}