Skip to content

Instantly share code, notes, and snippets.

@emyb
Last active May 21, 2020 21:01
Show Gist options
  • Save emyb/0a31e576ef20b37d3e8c925809906239 to your computer and use it in GitHub Desktop.
Save emyb/0a31e576ef20b37d3e8c925809906239 to your computer and use it in GitHub Desktop.
Code to support oauth2 properties that are an array of things.
<?php
$map = [
'otherMails-0' => 'email'
];
$userinfo = json_decode('{
"@odata.context": "https://graph.microsoft.com/v1.0/$metadata#users(*)/$entity",
"otherMails": [
"0@",
"1",
"2"
],
"displayName": "Megan Bowen",
"givenName": "Megan",
"jobTitle": "Auditor",
"mail": "MeganB@M365x214355.onmicrosoft.com",
"mobilePhone": null,
"officeLocation": "12/1110",
"preferredLanguage": "en-US",
"test": {
"foo": "bar",
"bar": "foo"
},
"surname": "Bowen",
"userPrincipalName": "MeganB@M365x214355.onmicrosoft.com",
"id": "48d31887-5fad-4d73-a9f5-3c356e68a038"
}');
$user = new stdClass();
foreach ($map as $openidproperty => $moodleproperty) {
// We support nested objects via a-b-c syntax.
$getfunc = function($obj, $prop) use (&$getfunc) {
$proplist = explode('-', $prop, 2);
if (is_array($obj) && count($obj) > 0) {
if (count($proplist) > 1) {
return $getfunc($obj, $proplist[0]);
}
return $obj[$proplist[0]];
}
if ((empty($proplist[0]) || empty($obj->{$proplist[0]}))) {
return false;
}
$obj = $obj->{$proplist[0]};
if (count($proplist) > 1) {
return $getfunc($obj, $proplist[1]);
}
return $obj;
};
$resolved = $getfunc($userinfo, $openidproperty);
if (!empty($resolved)) {
$user->$moodleproperty = $resolved;
}
}
var_dump($user);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment