1+ <?php
2+ /**
3+ * Sends all eligible files into PHP's opcode cache before server startup
4+ */
5+ $ LOGPREFIX = '[opcache] ' ;
6+ $ MEMORY_USAGE_WARNING_PERCENTAGE = 85 ;
7+ $ app_root = getenv ('APP_ROOT ' );
8+
9+ if (!$ app_root ) {
10+ echo ("$ {LOGPREFIX } cannot preload, APP_ROOT is empty " );
11+ return ;
12+ }
13+
14+ echo "$ {LOGPREFIX } preloading from $ {app_root}\n" ;
15+ $ start_time = microtime (true );
16+
17+ [ $ count , $ success , $ failure ] = compileFiles ($ app_root );
18+
19+ $ end_time = microtime (true );
20+ $ elapsed = ($ end_time - $ start_time );
21+ $ elapsed = round ($ elapsed , 3 );
22+
23+ echo "$ {LOGPREFIX } preloaded: processed $ {count} files - $ {success} successful / $ {failure} failed, in $ {elapsed} seconds \n" ;
24+
25+ $ opcache_status = opcache_get_status (false );
26+ $ memory_usage = $ opcache_status ['memory_usage ' ] ?? [];
27+
28+ if (empty ($ memory_usage )) {
29+ echo "$ {LOGPREFIX } error: no memory reported \n" ;
30+ return ;
31+ }
32+
33+ $ free_memory = $ memory_usage ['free_memory ' ] ?? 0 ;
34+ $ wasted_memory = $ memory_usage ['wasted_memory ' ] ?? 0 ;
35+ $ used_memory = $ memory_usage ['used_memory ' ] ?? 0 ;
36+
37+ $ memory_total = $ wasted_memory + $ free_memory + $ used_memory ;
38+ $ memory_consumed = $ used_memory + $ wasted_memory ;
39+ $ percentage_used = ($ memory_consumed / $ memory_total ) * 100 ;
40+ $ percentage_used = round ($ percentage_used , 2 );
41+
42+ if ($ percentage_used >= $ MEMORY_USAGE_WARNING_PERCENTAGE ) {
43+ echo "$ {LOGPREFIX } warning: $ {percentage_used}% memory usage, consider raising PHP_OPCACHE_MEMORY_CONSUMPTION env variable \n" ;
44+ } else {
45+ echo "$ {LOGPREFIX } complete: $ {percentage_used}% memory utilized \n" ;
46+ }
47+
48+ function compileFiles ($ input ) {
49+ $ directory = new RecursiveDirectoryIterator ($ input );
50+ $ fullTree = new RecursiveIteratorIterator ($ directory );
51+
52+ $ phpunit_filter = '/^(?:(?!test).)*\.php$/i ' ; // Removes PHPUnit-style filenames (ie. calculatortest.php)
53+
54+ $ all_files = new RegexIterator ($ fullTree , $ phpunit_filter , RecursiveRegexIterator::GET_MATCH );
55+ $ success = 0 ;
56+ $ failure = 0 ;
57+ $ results = [];
58+
59+ foreach ($ all_files as $ file ) {
60+ if (@opcache_compile_file ($ file [0 ])) {
61+ ++$ success ;
62+ } else {
63+ ++$ failure ;
64+ }
65+ }
66+
67+ $ count = $ success + $ failure ;
68+
69+ return [ $ count , $ success , $ failure ];
70+ }
0 commit comments