WordPress get_avatar filter to match logins

The get_avatar filter hook doesn’t apply only to the user with the ID 1 – I’m assuming you have this idea because of the example from page about the get_avatar at the codex –, but in reality it targets the user according to the context it is used in, so every possible user, not solely the one. The hook is part of the get_avatar() function, which is a pluggable function and could be overridden, just to mention another possibility. Below I’m using the above mentioned example, basically just removing the conditional that checks for it being the user with the ID 1, to outline an exemplary, untested approach:

add_filter( 'get_avatar' , 'wpse322010_get_avatar' , 1 , 6 );
function wpse322010_get_avatar( $avatar, $id_or_email, $size, $default, $alt, $args ) {
    $user = false;

    if ( is_numeric( $id_or_email ) ) {
        $id = (int) $id_or_email;
        //see: https://developer.wordpress.org/reference/functions/get_user_by/
        $user = get_user_by( 'id' , $id );
    } elseif ( is_object( $id_or_email ) ) {
        if ( ! empty( $id_or_email->user_id ) ) {
            $id = (int) $id_or_email->user_id;
            $user = get_user_by( 'id' , $id );
        }
    } else {
        $user = get_user_by( 'email', $id_or_email );   
    }

    if ( $user && is_object( $user ) ) {
        //get upload dir data
        //see: https://developer.wordpress.org/reference/functions/wp_upload_dir/
        $upload_dir = wp_upload_dir();
        //get user data
        //see: https://developer.wordpress.org/reference/classes/wp_user/
        $user_id = $user->ID;
        //see: https://developer.wordpress.org/reference/functions/get_userdata/
        $user_info = get_userdata( $user_id );
        //using the username for this example
        $username = $user_info->user_login;
        //construct src
        $src = $upload_dir['baseurl'] . '/avatars/' . $username . '.jpg';
        $avatar = "<img alt="{$alt}" src="https://wordpress.stackexchange.com/questions/322010/{$src}" class="avatar avatar-{$size} photo" height="{$size}" width="{$size}" />";
    }

    return $avatar;
}

error code: 523