1+ <?php
2+
3+ namespace FlexAuth ;
4+
5+ /**
6+ * Class AuthFlexTypeProviderFactory
7+ * @author Aleksandr Arofikin <sashaaro@gmail.com>
8+ */
9+ class AuthFlexTypeProviderFactory
10+ {
11+ public static function fromEnv (string $ envVar )
12+ {
13+ return new AuthFlexTypeCallbackProvider (function () use ($ envVar ) {
14+ return self ::resolveParamsFromEnv ($ envVar );
15+ });
16+ }
17+
18+ public static function resolveParamsFromEnv ($ envVar )
19+ {
20+ if (!array_key_exists ($ envVar , $ _ENV )) {
21+ throw new \Exception (sprintf ('Env variable "%s" is not found ' , $ envVar ));
22+ }
23+ $ type = $ _ENV [$ envVar ];
24+
25+ try {
26+ $ params = self ::resolveParamsFromLine ($ type );
27+ } catch (\InvalidArgumentException $ e ) {
28+ $ params = [];
29+ foreach ($ _ENV as $ key => $ value ) {
30+ if (strpos ($ key , $ envVar .'_ ' ) === 0 ) {
31+ $ paramKey = substr ($ key , 0 , strlen ($ key .'_ ' ));
32+ $ params [strtolower ($ paramKey )] = $ value ;
33+ }
34+ }
35+ $ params ['type ' ] = $ type ;
36+ }
37+
38+ return $ params ;
39+ }
40+
41+ /**
42+ * @param $line string Type and params as string in format type?param1=value1¶m2=value2
43+ * @example entity?class=\App\Entities\User&property=username
44+ * @example userbase?dsn=https://username:password@userbase.example.com
45+ *
46+ * @return array
47+ */
48+ public static function resolveParamsFromLine (string $ line ): array {
49+ $ parts = [];
50+ preg_match ('/([A-Z0-9_]+)\?((.|\n)+)/i ' , $ line , $ parts );
51+
52+ if (!array_key_exists (2 , $ parts )) {
53+ throw new \InvalidArgumentException ();
54+ }
55+
56+ $ stringParams = $ parts [2 ];
57+ foreach (explode ("& " , $ stringParams ) as $ keyValue ) {
58+ [$ key , $ value ] = explode ("= " , $ keyValue );
59+ if ($ key && $ value ) {
60+ $ params [$ key ] = $ value ;
61+ }
62+ }
63+ $ params ['type ' ] = $ parts [1 ];
64+
65+ return $ params ;
66+ }
67+ }
0 commit comments