Skip to content

Commit c90a27e

Browse files
committed
feat: add spark optimize command to optimize for production
1 parent 5ceaf06 commit c90a27e

File tree

1 file changed

+114
-0
lines changed

1 file changed

+114
-0
lines changed
Lines changed: 114 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,114 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
/**
6+
* This file is part of CodeIgniter 4 framework.
7+
*
8+
* (c) CodeIgniter Foundation <[email protected]>
9+
*
10+
* For the full copyright and license information, please view
11+
* the LICENSE file that was distributed with this source code.
12+
*/
13+
14+
namespace CodeIgniter\Commands\Utilities;
15+
16+
use CodeIgniter\CLI\BaseCommand;
17+
use CodeIgniter\CLI\CLI;
18+
use CodeIgniter\Publisher\Publisher;
19+
20+
/**
21+
* Optimize for production.
22+
*/
23+
final class Optimize extends BaseCommand
24+
{
25+
/**
26+
* The group the command is lumped under
27+
* when listing commands.
28+
*
29+
* @var string
30+
*/
31+
protected $group = 'CodeIgniter';
32+
33+
/**
34+
* The Command's name
35+
*
36+
* @var string
37+
*/
38+
protected $name = 'optimize';
39+
40+
/**
41+
* The Command's short description
42+
*
43+
* @var string
44+
*/
45+
protected $description = 'Optimize for production.';
46+
47+
/**
48+
* The Command's usage
49+
*
50+
* @var string
51+
*/
52+
protected $usage = 'optimize';
53+
54+
/**
55+
* {@inheritDoc}
56+
*/
57+
public function run(array $params)
58+
{
59+
$this->enableCaching();
60+
$this->clearCache();
61+
$this->removeDevPackages();
62+
63+
return EXIT_SUCCESS;
64+
}
65+
66+
private function clearCache()
67+
{
68+
$cache = WRITEPATH . 'cache/FileLocatorCache';
69+
if (is_file($cache)) {
70+
unlink($cache);
71+
CLI::write('Removed "' . $cache . '".', 'green');
72+
}
73+
74+
$cache = WRITEPATH . 'cache/FactoriesCache_config';
75+
if (is_file($cache)) {
76+
unlink($cache);
77+
CLI::write('Removed "' . $cache . '".', 'green');
78+
}
79+
}
80+
81+
private function enableCaching(): void
82+
{
83+
$publisher = new Publisher(APPPATH, APPPATH);
84+
85+
$result = $publisher->replace(
86+
APPPATH . 'Config/Optimize.php',
87+
[
88+
'public bool $configCacheEnabled = false;' => 'public bool $configCacheEnabled = true;',
89+
'public bool $locatorCacheEnabled = false;' => 'public bool $locatorCacheEnabled = true;',
90+
]
91+
);
92+
93+
if ($result) {
94+
CLI::write(
95+
'Config Caching and FileLocator Caching are enabled in "app/Config/Optimize.php".',
96+
'green'
97+
);
98+
}
99+
}
100+
101+
private function removeDevPackages(): void
102+
{
103+
if (! defined('VENDORPATH')) {
104+
return;
105+
}
106+
107+
chdir(ROOTPATH);
108+
passthru('composer install --no-dev', $status);
109+
110+
if ($status === 0) {
111+
CLI::write('Removed Composer dev packages.', 'green');
112+
}
113+
}
114+
}

0 commit comments

Comments
 (0)