22
33namespace ApiSkeletons \Laravel \Doctrine \ApiKey \Console \Command ;
44
5+ use ApiSkeletons \Laravel \Doctrine \ApiKey \Entity \ApiKey ;
6+ use ApiSkeletons \Laravel \Doctrine \ApiKey \Entity \Scope ;
7+ use ApiSkeletons \Laravel \Doctrine \ApiKey \Exception \ApiKeyDoesNotHaveScope ;
8+ use ApiSkeletons \Laravel \Doctrine \ApiKey \Exception \DuplicateScopeForApiKey ;
9+ use ApiSkeletons \Laravel \Doctrine \ApiKey \Service \ApiKeyService ;
510use Illuminate \Console \Command ;
611
712final class RemoveScope extends Command
813{
14+ private ApiKeyService $ apiKeyService ;
15+
916 /**
1017 * The name and signature of the console command.
1118 *
1219 * @var string
1320 */
14- protected $ signature = 'apikey:scope:remove {scopeName } {apiKeyName } ' ;
21+ protected $ signature = 'apikey:scope:remove {apiKeyName } {scopeName } ' ;
1522
1623 /**
1724 * The console command description.
1825 *
1926 * @var string
2027 */
21- protected $ description = 'Remove a scope from an ApiKey ' ;
28+ protected $ description = 'Remove a Scope from an ApiKey ' ;
2229
2330 /**
2431 * Create a new command instance.
2532 *
2633 * @return void
2734 */
28- public function __construct ()
35+ public function __construct (ApiKeyService $ apiKeyService )
2936 {
3037 parent ::__construct ();
38+
39+ $ this ->apiKeyService = $ apiKeyService ;
3140 }
3241
3342 /**
@@ -37,6 +46,56 @@ public function __construct()
3746 */
3847 public function handle ()
3948 {
40- // $drip->send(User::find($this->argument('user')));
49+ $ apiKeyName = $ this ->argument ('apiKeyName ' );
50+ $ scopeName = $ this ->argument ('scopeName ' );
51+
52+ $ apiKeyRepository = $ this ->apiKeyService ->getEntityManager ()
53+ ->getRepository (ApiKey::class);
54+ $ scopeRepository = $ this ->apiKeyService ->getEntityManager ()
55+ ->getRepository (Scope::class);
56+
57+ $ apiKey = $ apiKeyRepository ->findOneBy ([
58+ 'name ' => $ apiKeyName ,
59+ ]);
60+ if (! $ apiKey ) {
61+ $ this ->error ('Cannot find ApiKey with name: ' . $ apiKeyName );
62+
63+ return 1 ;
64+ }
65+
66+ $ scope = $ scopeRepository ->findOneBy ([
67+ 'name ' => $ scopeName ,
68+ ]);
69+ if (! $ scope ) {
70+ $ this ->error ('Cannot find scope with name: ' . $ scopeName );
71+
72+ return 1 ;
73+ }
74+
75+ try {
76+ $ apiKeyRepository ->removeScope ($ apiKey , $ scope );
77+ $ this ->apiKeyService ->getEntityManager ()->flush ();
78+ } catch (ApiKeyDoesNotHaveScope $ e ) {
79+ $ this ->error ($ e ->getMessage ());
80+
81+ return 1 ;
82+ }
83+
84+ $ scopeNames = [];
85+ foreach ($ apiKey ->getScopes () as $ s ) {
86+ $ scopeNames [] = $ s ->getName ();
87+ }
88+
89+ $ headers = ['name ' , 'key ' , 'status ' , 'scopes ' ];
90+ $ rows = [[
91+ $ apiKey ->getName (),
92+ $ apiKey ->getKey (),
93+ $ apiKey ->getIsActive () ? 'active ' : 'deactivated ' ,
94+ implode (', ' , $ scopeNames )
95+ ]];
96+
97+ $ this ->table ($ headers , $ rows );
98+
99+ return 0 ;
41100 }
42101}
0 commit comments