2022-03-15 14:47:07 +01:00
< ? php
namespace App\Api\v1\Controllers ;
2023-02-17 17:12:53 +01:00
use App\Api\v1\Requests\SettingUpdateRequest ;
2023-02-19 23:00:39 +01:00
use App\Api\v1\Resources\UserResource ;
2022-03-15 14:47:07 +01:00
use App\Http\Controllers\Controller ;
2022-03-24 14:58:30 +01:00
use Illuminate\Http\Request ;
2023-02-17 17:12:53 +01:00
use Illuminate\Support\Arr ;
2023-03-16 13:25:43 +01:00
use Illuminate\Support\Facades\Log ;
2022-03-15 14:47:07 +01:00
class UserController extends Controller
{
/**
2023-02-19 23:00:39 +01:00
* Get detailed information about the authenticated user
2022-11-22 15:15:52 +01:00
*
2022-08-26 15:57:18 +02:00
* @ return \App\Api\v1\Resources\UserResource | \Illuminate\Http\JsonResponse
2022-03-15 14:47:07 +01:00
*/
2022-03-24 14:58:30 +01:00
public function show ( Request $request )
2022-03-15 14:47:07 +01:00
{
2023-02-19 23:00:39 +01:00
return new UserResource ( $request -> user ());
2022-03-15 14:47:07 +01:00
}
2023-02-17 17:12:53 +01:00
/**
* List all preferences
*
* @ return \Illuminate\Http\JsonResponse
*/
public function allPreferences ( Request $request )
{
$preferences = $request -> user () -> preferences ;
$jsonPrefs = collect ([]);
$preferences -> each ( function ( mixed $item , string $key ) use ( $jsonPrefs ) {
$jsonPrefs -> push ([
'key' => $key ,
'value' => $item ,
]);
});
return response () -> json ( $jsonPrefs -> all (), 200 );
}
/**
* Display a preference
*
* @ param \Illuminate\Http\Request $request
* @ param string $preferenceName
* @ return \Illuminate\Http\JsonResponse
*/
public function showPreference ( Request $request , string $preferenceName )
{
if ( ! Arr :: exists ( $request -> user () -> preferences , $preferenceName )) {
abort ( 404 );
}
return response () -> json ([
'key' => $preferenceName ,
'value' => $request -> user () -> preferences [ $preferenceName ],
], 200 );
}
/**
* Save a preference
*
* @ param \App\Api\v1\Requests\SettingUpdateRequest $request
* @ param string $preferenceName
* @ return \Illuminate\Http\JsonResponse
*/
public function setPreference ( SettingUpdateRequest $request , string $preferenceName )
{
if ( ! Arr :: exists ( $request -> user () -> preferences , $preferenceName )) {
abort ( 404 );
}
$validated = $request -> validated ();
2023-02-19 23:00:39 +01:00
$request -> user ()[ 'preferences->' . $preferenceName ] = $validated [ 'value' ];
2023-02-17 17:12:53 +01:00
$request -> user () -> save ();
2023-03-16 13:25:43 +01:00
Log :: info ( sprintf ( 'User ID #%s changed its preference %s to %s' , $request -> user () -> id , var_export ( $preferenceName , true ), var_export ( $validated [ 'value' ], true )));
2023-02-17 17:12:53 +01:00
return response () -> json ([
'key' => $preferenceName ,
'value' => $request -> user () -> preferences [ $preferenceName ],
], 201 );
}
2022-11-22 15:15:52 +01:00
}