Php: how to lower complexity of method I have this method rated B on Scrutinizer (direct link: https://scrutinizer-ci.com/g/sineverba/domotic-panel/inspections/76996c9f-543f-43b4-9475-c64fe810a278/code-structure/operation/App%5CHttp%5CControllers%5CApi%5CPublicIpController%3A%3Aupdate)

public function update()
{
    try {
        $data = array();
        $update = false;
        $string_previous_public_ip = null;
        $current_public_ip = $this-&gt;getGateway()-&gt;fetchPublicIp($this-&gt;getIp());
        $previous_public_ip = $this-&gt;getGateway()-&gt;getLastRecord();
        $data[ 'ip_address' ] = $current_public_ip;
        if (isset($previous_public_ip-&gt;ip_address)) {
            $string_previous_public_ip = $previous_public_ip-&gt;ip_address;
            $data[ 'id' ] = $previous_public_ip-&gt;id;
        }
        if ($current_public_ip != $string_previous_public_ip) {
            $update = $this-&gt;updateOrCreate($data);
        }
        return response()-&gt;json([
            'updated' =&gt; $update
        ], 200);
    } catch (ConnectionError $e) {
        // Will return error 500
    } catch (ServiceError $e) {
        // Will return error 500
    } catch (\Exception $e) {
        // Will return error 500
    }
    return response()-&gt;json([
        'updated' =&gt; $update
    ], 500);
}


Can I lower the cyclomatic complexity? I did move yet a if/else for the update (updateOrCreate method I think it is clear his work), but it is not sufficient.

Thank you!
Your three catch blocks and two returns do the same thing as each other.  You only need one of each.

$update is referenced outside of try, should be defined there too.

$current_public_ip is just another name for $data[ 'ip_address' ].  It's not any shorter or clearer and doesn't resemble its other name very closely.

$previous_public_ip isn't an IP address, it's an object that contains an IP address and other stuff.  It would be clearer to simply name it $previous, which lets you drop the redundant string_ from $string_previous_public_ip.  _public can go too.

public function update()
{
    $update = false;
    $status = 500; // default
    try {
        $data = array();
        $previous_ip = null;
        $data[ 'ip_address' ] = $this-&gt;getGateway()-&gt;fetchPublicIp($this-&gt;getIp());
        $previous = $this-&gt;getGateway()-&gt;getLastRecord();
        if ( isset($previous-&gt;ip_address) ) {
            $previous_ip = $previous-&gt;ip_address;
            $data[ 'id' ] = $previous-&gt;id;
        }
        if ( $data[ 'ip_address' ] != $previous_ip ) {
            $update = $this-&gt;updateOrCreate($data);
        }
        $status = 200;
    } catch ( \Exception $e ) {
        // return default status (500)
    }
    return response()-&gt;json([ 'updated' =&gt; $update ], $status);
}