I am writing a bash script to ease installing a new site.
The laravel project needs included files which just contain functions and not classes, and currently I have manually edited composer.json
which works fine.
"autoload": {
"psr-4": {
"App\\": "app/"
},
"classmap": [
"database/seeds",
"database/factories"
],
"files": [
"app/DD_laravelAp/Helpers/php_extend/php_extend.php"
]
},
However, I would like the bash script to automatically update the composer.json file to result in e.g.:
"autoload": {
"psr-4": {
"App\\": "app/"
},
"classmap": [
"database/seeds",
"database/factories"
],
"files": [
"app/DD_laravelAp/Helpers/php_extend/php_extend.php",
"app/DD_laravelAp/Helpers/php_extend/array_extend.php"
]
},
My question is the syntax from the command line to include a new file from a bash script for example when in the site directory
composer require "app/DD_laravelAp/Helpers/php_extend/array_extend.php"
to update the composer.json file to the second one above. I am sure I have seen this documented but cannot find where
Composer does not offer a feature to modify the autoload
section from the command-line interface.
It was requested many years ago, but it was officially rejected a couple of years after that:
Yup I don't think we really want to offer this from CLI it's gonna be a bunch of code for very limited use as typically this is done once on package creation.
If you check that issue thread, you'll see many scripts that deal with similar use-cases, some of which you can tailor to your specific need.
A very crude PHP implementation you could use within your bash script:
#!/usr/bin/env php
<?php
if (count($argv) < 2) {
exit;
}
$json = json_decode(file_get_contents('composer.json'), true);
array_shift($argv);
foreach ($argv as $arg) {
$json['autoload']['files'][] = $arg;
}
file_put_contents('composer.json', json_encode($json, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT));
Use it as:
./patch_autoload.php "app/DD_laravelAp/Helpers/php_extend/array_extend.php" "app/DD_laravelAp/Helpers/php_extend/php_extend.php"
(Assuming you call the script patch_autoload.php
and make it executable).