-
-
Notifications
You must be signed in to change notification settings - Fork 66
Expand file tree
/
Copy pathAndroidPluginCompiler.php
More file actions
1081 lines (885 loc) · 34.3 KB
/
Copy pathAndroidPluginCompiler.php
File metadata and controls
1081 lines (885 loc) · 34.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
namespace Native\Mobile\Plugins\Compilers;
use Illuminate\Filesystem\Filesystem;
use Illuminate\Support\Collection;
use Native\Mobile\Exceptions\PluginConflictException;
use Native\Mobile\Plugins\Plugin;
use Native\Mobile\Plugins\PluginHookRunner;
use Native\Mobile\Plugins\PluginRegistry;
use Native\Mobile\Support\Stub;
class AndroidPluginCompiler
{
protected string $androidProjectPath;
protected string $generatedPath;
protected array $generatedFiles = [];
protected ?string $appId = null;
protected ?PluginHookRunner $hookRunner = null;
protected $output = null;
protected array $config = [];
public function __construct(
protected Filesystem $files,
protected PluginRegistry $registry,
protected string $basePath
) {
$this->androidProjectPath = $basePath.'/android';
// Detect current app ID from build.gradle.kts (after prepareAndroidBuild has updated it)
$this->appId = $this->detectCurrentAppId() ?? 'com.nativephp.mobile';
// Plugin registration always goes in the core NativePHP package
$this->generatedPath = $this->androidProjectPath.'/app/src/main/java/com/nativephp/mobile/bridge/plugins';
}
/**
* Set the output interface for logging
*/
public function setOutput($output): self
{
$this->output = $output;
return $this;
}
/**
* Output a warning message
*/
protected function warn(string $message): void
{
if ($this->output) {
$this->output->warn($message);
}
}
/**
* Set the app ID for hooks context (overrides detected)
*/
public function setAppId(string $appId): self
{
$this->appId = $appId;
// Note: generatedPath stays at com/nativephp/mobile/bridge/plugins/
// Plugin registration is always in the core NativePHP package
return $this;
}
/**
* Set the build config for hooks context
*/
public function setConfig(array $config): self
{
$this->config = $config;
return $this;
}
/**
* Get the hook runner instance
*/
protected function getHookRunner(): PluginHookRunner
{
if ($this->hookRunner === null) {
$this->hookRunner = new PluginHookRunner(
platform: 'android',
buildPath: $this->androidProjectPath,
appId: $this->appId,
config: $this->config,
plugins: $this->registry->all(),
output: $this->output
);
}
return $this->hookRunner;
}
/**
* Detect current app ID from build.gradle.kts
*/
protected function detectCurrentAppId(): ?string
{
$gradlePath = $this->androidProjectPath.'/app/build.gradle.kts';
if (! $this->files->exists($gradlePath)) {
return null;
}
$contents = $this->files->get($gradlePath);
if (preg_match('/applicationId\s*=\s*"([^"]+)"/', $contents, $matches)) {
return $matches[1];
}
return null;
}
/**
* Compile all plugins for Android
*/
public function compile(): void
{
$this->generatedFiles = [];
// Check for plugin conflicts before compiling
$conflicts = $this->registry->detectConflicts();
if (! empty($conflicts)) {
throw new PluginConflictException($conflicts);
}
$allPlugins = $this->registry->all();
$hookRunner = $this->getHookRunner();
// Run pre-compile hooks
$hookRunner->runPreCompileHooks();
if ($allPlugins->isEmpty()) {
$this->generateEmptyRegistration();
return;
}
// Check if there are any plugins with Android bridge functions or init functions
$hasAndroidFunctions = $allPlugins->filter(function (Plugin $p) {
foreach ($p->getBridgeFunctions() as $function) {
if (! empty($function['android'])) {
return true;
}
}
return false;
})->isNotEmpty();
$hasInitFunctions = $allPlugins->filter(function (Plugin $p) {
return $p->getAndroidInitFunction() !== null;
})->isNotEmpty();
// Ensure generated directory exists
$this->files->ensureDirectoryExists($this->generatedPath);
// Copy plugin source files for plugins that have Android code
$allPlugins->filter(fn (Plugin $p) => $p->hasAndroidCode())
->each(fn (Plugin $plugin) => $this->copyPluginSources($plugin));
// Generate the bridge function registration file
if ($hasAndroidFunctions || $hasInitFunctions) {
$this->generateBridgeFunctionRegistration($allPlugins);
} else {
$this->generateEmptyRegistration();
}
// Merge AndroidManifest entries (even if no bridge functions)
$this->mergeManifestEntries($allPlugins);
// Add Gradle dependencies (even if no bridge functions)
$this->addGradleDependencies($allPlugins);
// Add Maven repositories from plugins
$this->addGradleRepositories($allPlugins);
// Copy manifest-declared assets
$hookRunner->copyManifestAssets();
// Run copy-assets hooks
$hookRunner->runCopyAssetsHooks();
// Run post-compile hooks
$hookRunner->runPostCompileHooks();
}
/**
* Copy Kotlin source files from plugin to Android project
*
* Files are placed at directories matching their package declaration.
*/
protected function copyPluginSources(Plugin $plugin): void
{
$sourcePath = $plugin->getAndroidSourcePath();
if (! $this->files->isDirectory($sourcePath)) {
return;
}
$javaBasePath = $this->androidProjectPath.'/app/src/main/java';
// Copy all Kotlin files
$files = $this->files->allFiles($sourcePath);
foreach ($files as $file) {
if ($file->getExtension() !== 'kt') {
continue;
}
$content = $this->files->get($file->getPathname());
// Extract package declaration
$package = $this->extractPackageFromContent($content);
if ($package === null) {
// Warn about missing package declaration
$this->warn(
"Plugin '{$plugin->name}': {$file->getFilename()} has no package declaration. ".
"Plugins should declare packages like 'package com.yourvendor.pluginname'"
);
// Fallback: use sanitized namespace under bridge/plugins if no package found
$safeNamespace = $this->sanitizeKotlinName($plugin->getNamespace());
$destination = $this->generatedPath.'/'.$safeNamespace.'/'.$file->getFilename();
} else {
// Place file at path matching its package declaration
$packagePath = str_replace('.', '/', $package);
$destination = $javaBasePath.'/'.$packagePath.'/'.$file->getFilename();
}
$this->files->ensureDirectoryExists(dirname($destination));
$this->files->put($destination, $content);
$this->generatedFiles[] = $destination;
}
}
/**
* Extract package declaration from Kotlin file content
*/
protected function extractPackageFromContent(string $content): ?string
{
if (preg_match('/^package\s+([\w.]+)/m', $content, $matches)) {
return $matches[1];
}
return null;
}
/**
* Sanitize a name for Kotlin (replace hyphens with underscores)
*/
protected function sanitizeKotlinName(string $name): string
{
return str_replace('-', '_', $name);
}
/**
* Generate PluginBridgeFunctionRegistration.kt
*/
protected function generateBridgeFunctionRegistration(Collection $plugins): void
{
$registrations = [];
$initFunctions = [];
foreach ($plugins as $plugin) {
// Collect bridge function registrations
foreach ($plugin->getBridgeFunctions() as $function) {
if (empty($function['android'])) {
continue;
}
$registrations[] = [
'name' => $function['name'],
'class' => $function['android'],
'plugin' => $plugin->name,
'params' => $function['android_params'] ?? ['activity'],
];
}
// Collect init functions
$initFunction = $plugin->getAndroidInitFunction();
if ($initFunction) {
$initFunctions[] = [
'function' => $initFunction,
'plugin' => $plugin->name,
];
}
}
$content = $this->renderRegistrationTemplate($registrations, $initFunctions);
$path = $this->generatedPath.'/PluginBridgeFunctionRegistration.kt';
$this->files->put($path, $content);
$this->generatedFiles[] = $path;
}
/**
* Render the Kotlin registration file
*/
protected function renderRegistrationTemplate(array $registrations, array $initFunctions = []): string
{
// Build imports from the android class paths in nativephp.json
$imports = collect($registrations)
->pluck('class')
->map(fn ($class) => $this->extractImportPath($class))
->unique()
->sort()
->map(fn ($package) => "import {$package}")
->implode("\n");
// Add imports for init functions (top-level Kotlin functions need full path import)
$initImports = collect($initFunctions)
->pluck('function')
->unique()
->sort()
->map(fn ($func) => "import {$func}")
->implode("\n");
if ($initImports) {
$imports = $imports ? $imports."\n".$initImports : $initImports;
}
$registerCalls = collect($registrations)
->map(function ($reg) {
$className = $this->extractClassName($reg['class']);
$params = $reg['params'] ?? ['activity'];
$paramString = $this->determineParameter($params);
return " // Plugin: {$reg['plugin']}\n registry.register(\"{$reg['name']}\", {$className}({$paramString}))";
})
->implode("\n\n");
$initCalls = collect($initFunctions)
->map(function ($init) {
// Extract just the function name from the full path
$parts = explode('.', $init['function']);
$funcName = end($parts);
return " // Plugin: {$init['plugin']}\n {$funcName}(context)";
})
->implode("\n\n");
return Stub::make('android/PluginBridgeFunctionRegistration.kt.stub')
->replaceAll([
'IMPORTS' => $imports,
'INIT_FUNCTIONS' => $initCalls,
'REGISTRATIONS' => $registerCalls,
])
->render();
}
/**
* Extract import path from full class reference (package.Class.Method -> package.Class)
*/
protected function extractImportPath(string $classPath): string
{
$parts = explode('.', $classPath);
array_pop($parts); // Remove method name
return implode('.', $parts);
}
/**
* Generate empty registration when no plugins
*/
protected function generateEmptyRegistration(): void
{
$this->files->ensureDirectoryExists($this->generatedPath);
$content = Stub::make('android/PluginBridgeFunctionRegistration.empty.kt.stub')->render();
$path = $this->generatedPath.'/PluginBridgeFunctionRegistration.kt';
$this->files->put($path, $content);
$this->generatedFiles[] = $path;
}
/**
* Merge plugin AndroidManifest.xml entries into main manifest
*/
protected function mergeManifestEntries(Collection $plugins): void
{
$mainManifestPath = $this->androidProjectPath.'/app/src/main/AndroidManifest.xml';
$mainManifest = $this->files->get($mainManifestPath);
$permissionsToAdd = [];
$featuresToAdd = [];
$applicationEntries = [];
foreach ($plugins as $plugin) {
// Always add permissions from nativephp.json
foreach ($plugin->getAndroidPermissions() as $permission) {
$permissionsToAdd[] = $permission;
}
// Add features from nativephp.json
foreach ($plugin->getAndroidFeatures() as $feature) {
$featuresToAdd[] = $feature;
}
// Check for XML manifest file (legacy approach)
$pluginManifestPath = $plugin->path.'/resources/android/AndroidManifest.xml';
if ($this->files->exists($pluginManifestPath)) {
$pluginManifest = $this->files->get($pluginManifestPath);
$extracted = $this->extractManifestEntries($pluginManifest);
$permissionsToAdd = array_merge($permissionsToAdd, $extracted['permissions']);
$applicationEntries = array_merge($applicationEntries, $extracted['application']);
}
// Process JSON-based manifest entries from nativephp.json
$jsonManifest = $plugin->getAndroidManifest();
if (! empty($jsonManifest)) {
$jsonEntries = $this->buildManifestEntriesFromJson($jsonManifest, $plugin);
$applicationEntries = array_merge($applicationEntries, $jsonEntries);
}
}
// Add permissions that don't already exist
$mainManifest = $this->injectPermissions($mainManifest, array_unique($permissionsToAdd));
// Add features that don't already exist
$mainManifest = $this->injectFeatures($mainManifest, $featuresToAdd);
// Add application entries
$mainManifest = $this->injectApplicationEntries($mainManifest, $applicationEntries);
$this->files->put($mainManifestPath, $mainManifest);
}
/**
* Build XML manifest entries from JSON manifest config
*/
protected function buildManifestEntriesFromJson(array $manifest, Plugin $plugin): array
{
$entries = [];
// Process activities
foreach ($manifest['activities'] ?? [] as $activity) {
$entries[] = $this->buildActivityEntry($activity, $plugin);
}
// Process services
foreach ($manifest['services'] ?? [] as $service) {
$entries[] = $this->buildServiceEntry($service, $plugin);
}
// Process receivers
foreach ($manifest['receivers'] ?? [] as $receiver) {
$entries[] = $this->buildReceiverEntry($receiver, $plugin);
}
// Process providers
foreach ($manifest['providers'] ?? [] as $provider) {
$entries[] = $this->buildProviderEntry($provider, $plugin);
}
// Process meta-data
foreach ($manifest['meta_data'] ?? [] as $metaData) {
$entries[] = $this->buildMetaDataEntry($metaData);
}
return $entries;
}
/**
* Build a meta-data XML entry
*/
protected function buildMetaDataEntry(array $metaData): string
{
$name = $metaData['name'];
$value = $metaData['value'];
// Handle different value types
if (is_bool($value)) {
$value = $value ? 'true' : 'false';
}
return "<meta-data android:name=\"{$name}\" android:value=\"{$value}\" />";
}
/**
* Resolve component name - replace relative names with full package path
*/
protected function resolveComponentName(string $name, Plugin $plugin): string
{
// If starts with '.', it's relative to the plugin's package
if (str_starts_with($name, '.')) {
$basePackage = $this->detectPluginBasePackage($plugin);
if ($basePackage === null) {
throw new \InvalidArgumentException(
"Plugin '{$plugin->name}' uses relative component name '{$name}' but has no package declaration in its Kotlin files. ".
'Either add a package declaration to your Kotlin files or use a fully-qualified component name.'
);
}
return "{$basePackage}{$name}";
}
return $name;
}
/**
* Detect the base package from a plugin's Kotlin source files
*/
protected function detectPluginBasePackage(Plugin $plugin): ?string
{
$sourcePath = $plugin->getAndroidSourcePath();
if (! $this->files->isDirectory($sourcePath)) {
return null;
}
// Find first Kotlin file with a package declaration
foreach ($this->files->allFiles($sourcePath) as $file) {
if ($file->getExtension() !== 'kt') {
continue;
}
$content = $this->files->get($file->getPathname());
if (preg_match('/^package\s+([\w.]+)/m', $content, $matches)) {
return $matches[1];
}
}
return null;
}
/**
* Build an activity XML entry
*/
protected function buildActivityEntry(array $activity, Plugin $plugin): string
{
$name = $this->resolveComponentName($activity['name'], $plugin);
$attrs = ["android:name=\"{$name}\""];
if (isset($activity['theme'])) {
$attrs[] = "android:theme=\"{$activity['theme']}\"";
}
if (isset($activity['screenOrientation'])) {
$attrs[] = "android:screenOrientation=\"{$activity['screenOrientation']}\"";
}
if (isset($activity['exported'])) {
$attrs[] = 'android:exported="'.($activity['exported'] ? 'true' : 'false').'"';
}
if (isset($activity['launchMode'])) {
$attrs[] = "android:launchMode=\"{$activity['launchMode']}\"";
}
if (isset($activity['configChanges'])) {
$attrs[] = "android:configChanges=\"{$activity['configChanges']}\"";
}
$attrString = implode("\n ", $attrs);
// Check for intent filters (support both snake_case and kebab-case)
$intentFilters = $activity['intent_filters'] ?? $activity['intent-filters'] ?? [];
if (! empty($intentFilters)) {
$filters = $this->buildIntentFilters($intentFilters);
return "<activity\n {$attrString}>\n{$filters} </activity>";
}
return "<activity\n {$attrString} />";
}
/**
* Build a service XML entry
*/
protected function buildServiceEntry(array $service, Plugin $plugin): string
{
$name = $this->resolveComponentName($service['name'], $plugin);
$attrs = ["android:name=\"{$name}\""];
if (isset($service['exported'])) {
$attrs[] = 'android:exported="'.($service['exported'] ? 'true' : 'false').'"';
}
if (isset($service['permission'])) {
$attrs[] = "android:permission=\"{$service['permission']}\"";
}
if (isset($service['foregroundServiceType'])) {
$type = $service['foregroundServiceType'];
// Support both array and string formats
if (is_array($type)) {
$type = implode('|', $type);
}
$attrs[] = "android:foregroundServiceType=\"{$type}\"";
}
$attrString = implode("\n ", $attrs);
// Support both snake_case and kebab-case
$intentFilters = $service['intent_filters'] ?? $service['intent-filters'] ?? [];
if (! empty($intentFilters)) {
$filters = $this->buildIntentFilters($intentFilters);
return "<service\n {$attrString}>\n{$filters} </service>";
}
return "<service\n {$attrString} />";
}
/**
* Build a receiver XML entry
*/
protected function buildReceiverEntry(array $receiver, Plugin $plugin): string
{
$name = $this->resolveComponentName($receiver['name'], $plugin);
$attrs = ["android:name=\"{$name}\""];
if (isset($receiver['exported'])) {
$attrs[] = 'android:exported="'.($receiver['exported'] ? 'true' : 'false').'"';
}
if (isset($receiver['permission'])) {
$attrs[] = "android:permission=\"{$receiver['permission']}\"";
}
$attrString = implode("\n ", $attrs);
// Support both snake_case and kebab-case
$intentFilters = $receiver['intent_filters'] ?? $receiver['intent-filters'] ?? [];
if (! empty($intentFilters)) {
$filters = $this->buildIntentFilters($intentFilters);
return "<receiver\n {$attrString}>\n{$filters} </receiver>";
}
return "<receiver\n {$attrString} />";
}
/**
* Build a provider XML entry
*/
protected function buildProviderEntry(array $provider, Plugin $plugin): string
{
$name = $this->resolveComponentName($provider['name'], $plugin);
$attrs = ["android:name=\"{$name}\""];
if (isset($provider['authorities'])) {
$authorities = str_replace('${applicationId}', $this->appId, $provider['authorities']);
$attrs[] = "android:authorities=\"{$authorities}\"";
}
if (isset($provider['exported'])) {
$attrs[] = 'android:exported="'.($provider['exported'] ? 'true' : 'false').'"';
}
if (isset($provider['grantUriPermissions'])) {
$attrs[] = 'android:grantUriPermissions="'.($provider['grantUriPermissions'] ? 'true' : 'false').'"';
}
$attrString = implode("\n ", $attrs);
return "<provider\n {$attrString} />";
}
/**
* Build intent filter XML blocks
*/
protected function buildIntentFilters(array $filters): string
{
$xml = '';
foreach ($filters as $filter) {
$xml .= " <intent-filter>\n";
if (isset($filter['action'])) {
$actions = is_array($filter['action']) ? $filter['action'] : [$filter['action']];
foreach ($actions as $action) {
$xml .= " <action android:name=\"{$action}\" />\n";
}
}
if (isset($filter['category'])) {
$categories = is_array($filter['category']) ? $filter['category'] : [$filter['category']];
foreach ($categories as $category) {
$xml .= " <category android:name=\"{$category}\" />\n";
}
}
if (isset($filter['data'])) {
$dataAttrs = [];
foreach ($filter['data'] as $key => $value) {
$dataAttrs[] = "android:{$key}=\"{$value}\"";
}
$xml .= ' <data '.implode(' ', $dataAttrs)." />\n";
}
$xml .= " </intent-filter>\n";
}
return $xml;
}
/**
* Extract permissions and application entries from manifest XML
*/
protected function extractManifestEntries(string $xml): array
{
$permissions = [];
$application = [];
// Extract uses-permission entries
preg_match_all('/<uses-permission[^>]+>/s', $xml, $matches);
$permissions = $matches[0] ?? [];
// Extract application children (activities, services, etc.)
if (preg_match('/<application[^>]*>(.*?)<\/application>/s', $xml, $match)) {
preg_match_all('/<(activity|service|receiver|provider)[^>]*>.*?<\/\1>|<(activity|service|receiver|provider)[^>]*\/>/s', $match[1], $appMatches);
$application = $appMatches[0] ?? [];
}
return [
'permissions' => $permissions,
'application' => $application,
];
}
/**
* Inject permissions into manifest
*/
protected function injectPermissions(string $manifest, array $permissions): string
{
if (empty($permissions)) {
return $manifest;
}
// First, remove any existing plugin permission comments to avoid duplicates
$manifest = preg_replace('/\s*<!-- NativePHP Plugin Permissions -->\n/s', '', $manifest);
$permissionBlock = "\n <!-- NativePHP Plugin Permissions -->\n";
$hasNewPermissions = false;
foreach ($permissions as $permission) {
if (is_string($permission) && ! str_contains($permission, '<')) {
$permission = "<uses-permission android:name=\"{$permission}\" />";
}
if (! str_contains($manifest, $permission)) {
$permissionBlock .= " {$permission}\n";
$hasNewPermissions = true;
}
}
// Only inject if there are new permissions to add
if (! $hasNewPermissions) {
return $manifest;
}
// Insert before <application
return preg_replace(
'/(\s*<application)/s',
$permissionBlock.'$1',
$manifest,
1
);
}
/**
* Inject uses-feature entries into manifest
*/
protected function injectFeatures(string $manifest, array $features): string
{
if (empty($features)) {
return $manifest;
}
// First, remove any existing plugin feature comments to avoid duplicates
$manifest = preg_replace('/\s*<!-- NativePHP Plugin Features -->\n/s', '', $manifest);
$featureBlock = "\n <!-- NativePHP Plugin Features -->\n";
$hasNewFeatures = false;
foreach ($features as $feature) {
$name = $feature['name'] ?? null;
if (! $name) {
continue;
}
// Skip if this feature already exists
if (str_contains($manifest, "android:name=\"{$name}\"")) {
continue;
}
$required = isset($feature['required']) ? ($feature['required'] ? 'true' : 'false') : 'true';
$featureBlock .= " <uses-feature android:name=\"{$name}\" android:required=\"{$required}\" />\n";
$hasNewFeatures = true;
}
// Only inject if there are new features to add
if (! $hasNewFeatures) {
return $manifest;
}
// Insert before <application
return preg_replace(
'/(\s*<application)/s',
$featureBlock.'$1',
$manifest,
1
);
}
/**
* Inject application entries into manifest
*/
protected function injectApplicationEntries(string $manifest, array $entries): string
{
if (empty($entries)) {
return $manifest;
}
// First, remove any existing plugin component sections to avoid duplicates
// This removes the comment and all following plugin-injected entries up until the next non-plugin content
$manifest = preg_replace(
'/\s*<!-- NativePHP Plugin Components -->.*?(?=\s*<\/application>|\s*<!-- (?!NativePHP Plugin))/s',
'',
$manifest
);
$entryBlock = "\n <!-- NativePHP Plugin Components -->\n";
$hasNewEntries = false;
foreach ($entries as $entry) {
// Extract android:name from the entry to check for duplicates
if (preg_match('/android:name="([^"]+)"/', $entry, $matches)) {
$componentName = $matches[1];
// Check if this component already exists in the manifest
if (str_contains($manifest, "android:name=\"{$componentName}\"")) {
continue;
}
}
$entryBlock .= " {$entry}\n";
$hasNewEntries = true;
}
// Only inject if there are new entries to add
if (! $hasNewEntries) {
return $manifest;
}
// Insert before </application>
return preg_replace(
'/(\s*<\/application>)/s',
$entryBlock.'$1',
$manifest,
1
);
}
/**
* Add Maven repositories from plugins to settings.gradle.kts
*/
protected function addGradleRepositories(Collection $plugins): void
{
$settingsGradlePath = $this->androidProjectPath.'/settings.gradle.kts';
if (! $this->files->exists($settingsGradlePath)) {
return;
}
$settingsGradle = $this->files->get($settingsGradlePath);
$repositories = [];
foreach ($plugins as $plugin) {
foreach ($plugin->getAndroidRepositories() as $repo) {
$repositories[] = $repo;
}
}
if (empty($repositories)) {
return;
}
// Build repository blocks
$repoBlocks = [];
foreach ($repositories as $repo) {
$url = $repo['url'] ?? null;
if (! $url) {
continue;
}
// Skip if already exists
if (str_contains($settingsGradle, $url)) {
continue;
}
$repoBlock = $this->buildRepositoryBlock($repo);
if ($repoBlock) {
$repoBlocks[] = $repoBlock;
}
}
if (empty($repoBlocks)) {
return;
}
// Build the injection block
$injection = "\n // NativePHP Plugin Repositories\n";
foreach ($repoBlocks as $block) {
$injection .= $block;
}
// Find the dependencyResolutionManagement.repositories block and inject
// We need to inject after the opening brace of repositories {}
$pattern = '/(dependencyResolutionManagement\s*\{[^}]*repositories\s*\{)/s';
if (preg_match($pattern, $settingsGradle)) {
$settingsGradle = preg_replace(
$pattern,
'$1'.$injection,
$settingsGradle,
1
);
$this->files->put($settingsGradlePath, $settingsGradle);
}
}
/**
* Build a Gradle repository block from config
*/
protected function buildRepositoryBlock(array $repo): ?string
{
$url = $repo['url'];
$credentials = $repo['credentials'] ?? null;
$authentication = $repo['authentication'] ?? null;
if ($credentials) {
$username = $this->substituteEnvPlaceholders($credentials['username'] ?? 'mapbox');
$password = $this->substituteEnvPlaceholders($credentials['password'] ?? '');
$authBlock = '';
if ($authentication === 'basic') {
$authBlock = <<<'KOTLIN'
authentication {
create<BasicAuthentication>("basic")
}
KOTLIN;
}
return <<<KOTLIN
maven {
url = uri("{$url}"){$authBlock}
credentials {
username = "{$username}"
password = "{$password}"
}
}
KOTLIN;
}
return <<<KOTLIN
maven { url = uri("{$url}") }
KOTLIN;
}
/**
* Substitute ${ENV_VAR} placeholders with actual environment values
*/
protected function substituteEnvPlaceholders(string $value): string
{
return preg_replace_callback('/\$\{(\w+)\}/', function ($matches) {
$envVar = $matches[1];
$envValue = env($envVar);
if ($envValue === null) {
// Return the placeholder as-is if not found - validation will catch this
return $matches[0];
}
return $envValue;
}, $value);
}
/**
* Add Gradle dependencies from plugins
*/
protected function addGradleDependencies(Collection $plugins): void
{
$buildGradlePath = $this->androidProjectPath.'/app/build.gradle.kts';
$buildGradle = $this->files->get($buildGradlePath);
$dependenciesByType = [];
foreach ($plugins as $plugin) {
$androidDeps = $plugin->getAndroidDependencies();
foreach ($androidDeps as $type => $libraries) {
if (! isset($dependenciesByType[$type])) {
$dependenciesByType[$type] = [];
}
foreach ($libraries as $library) {