Access node machine name in Drupal 8 function

You are here

At times you need to know the machine name of the current node. The function below will allow you to access the machine name anywhere on a page load.

/**
 * @return array|null
 */
function _access_current_node_machine_name()
{
    $nidResult = \Drupal::service('path.current')->getPath();
    $nid = explode('/', $nidResult);
    if ($nid[2] != NULL) {
        $node = \Drupal\node\Entity\Node::load($nid[2]);
        return array(
            'node_id' => $nid[2],
            'node_content_type' => $node->getType(),
        );
    }
    return NULL;
}