jwilsson / spotify-web-api-php

A PHP wrapper for Spotify's Web API.
MIT License
862 stars 156 forks source link

TypeError when API returns null on getMyCurrentTrack #269

Closed joeygallegos closed 9 months ago

joeygallegos commented 9 months ago

I am writing an application that tracks what song I am currently listening to. When I stop playing music and exit the desktop app, I get the below TypeError exception because the API is returning a null response but the function is declared to only allow array|object as return types. Right now, when I wrap the code in a try/catch, it doesn't even run the caught exception. When playing music, I get no error.

Exception:

Type: TypeError
Code: 0
Message: SpotifyWebAPI\SpotifyWebAPI::getMyCurrentTrack(): Return value must be of type object|array, null returned
File: D:\Dropbox\Web Work\joey\vendor\jwilsson\spotify-web-api-php\src\SpotifyWebAPI.php
Line: 1149

I have my code setup like this:

$options = [
    'auto_refresh' => true,
    'return_assoc' => true
];
$api = new SpotifyWebAPI\SpotifyWebAPI($options, $session);
try {
    $spotify = $this->container->get('spotify');
    $currentTrack = $spotify['api']->getMyCurrentTrack();
    // TODO: Exception when no music is playing. Null value comes forward, but function throws exception because not expected
} catch (\Exception $e) {
        // we don't even reach this exception
    $this->logger->error('Exception encountered while accessing current track');
    $this->logger->error($e);
}

Composer version:

"jwilsson/spotify-web-api-php": "^6.0",

Expectation: Ideally, when SpotifyAPI returns null because the player is fully exited and the music isn't technically "paused" or "playing", then I should be allowed to check getMyCurrentTrack() for null value(s) and handle my code based around that.

jwilsson commented 9 months ago

Hey! I totally agree, looks like the Spotify docs doesn't reflect reality. The endpoint returns a HTTP 204 with an empty body when nothing is playing which of course will cause null to be returned.

I'll update the function declaration to reflect this and I've posted on Spotify's developer forum asking them to update the docs.

jwilsson commented 9 months ago

And updated function declarations are available in 6.0.2.

joeygallegos commented 9 months ago

@jwilsson many thanks for fixing the issue! I tried again with the new version, and the issue is resolved. Working as expected.