Fetch users from Azure AD

2019-07-14 00:42发布

问题:

I can't figure out why my loop isn't working at all. I have successfully connected to my clients directory and I am able to fetch some users. I have followed the PHP instructions. But this tutorial doesn't include example for fetching all users only the default page size of 100 users.

I am aware of the skipToken (explained here) but for some reason I am not been able to get it work with my loop.

Basically first I define an array, and two sub arrays.

 $myArray = array();
 $myArray['skipToken'] = "";
 $myArray['users'] = "";

Then I'll perform the first fetch so I can get skipToken and bunch of users that come along.

 require_once("GraphServiceAccessHelper.php");
 $users = GraphServiceAccessHelper::getFeed('users');

Pushing values into already existing arrays.

 $myArray['skipToken'] = $users->{'odata.nextLink'};
 $myArray['users'][] = $users->{'value'};

Now they are filled with information. Now its time to loop!

 for($i = 0; $i < 2; $i++){
    if($myArray['skipToken'] != ""){
      $skipToken = $myArray['skipToken'];
      require_once("GraphServiceAccessHelper.php");
      $users = GraphServiceAccessHelper::getNextFeed('users', $skipToken);
      $myArray['skipToken'] = $users->{'odata.nextLink'};
      $myArray['users'][] = $users->{'value'};
    }
 }

Console fires up from error, that points to loop skipToken defining part:

Notice: Undefined property: stdClass::$odata.nextLink

$myArray['skipToken'] = $users->{'odata.nextLink'};

回答1:

Okay I figured it out.

First I had to remove everything before actual token.

$skipToken = $users->{'odata.nextLink'};
$skipToken = substr($skipToken, strpos($skipToken, "=") + 1);

Then inside the loop use that get new skipToken and do the same like above:

$new = GraphServiceAccessHelper::getNextFeed('users', $skipToken);
if(isset($new->{'odata.nextLink'})){
  $skipToken = empty($new->{'odata.nextLink'});
} else{
  break;
}
$skipToken = substr($skipToken, strpos($skipToken, "=") + 1);
$myArray['tokens'] = $skipToken;
$myArray['users'][] = $new->{'value'};

By checking if 'odata.nextLink" exists I can easily stop the while loop since lastpage doesn't contain 'odata.nextLink'.

if(isset($new->{'odata.nextLink'})){
  $skipToken = empty($new->{'odata.nextLink'});
} else{
  break;
}

I am appending each 100 user array to another array that I can call easily use it outside PHP.