-
-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathphpvm.sh
More file actions
executable file
Β·2974 lines (2605 loc) Β· 97.3 KB
/
phpvm.sh
File metadata and controls
executable file
Β·2974 lines (2605 loc) Β· 97.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
#!/bin/bash
# phpvm - A PHP Version Manager for macOS and Linux
# Author: Jerome Thayananthajothy (tjthavarshan@gmail.com)
# Version: 1.9.1
#
# IMPORTANT: This script is written for bash and uses bashisms (arrays, process substitution, etc.)
# For sourcing into your shell, use bash only. Zsh users should run phpvm via:
# bash -c 'source ~/.phpvm/phpvm.sh && phpvm <command>'
# Or consider creating a zsh wrapper function that delegates to bash.
# shellcheck disable=SC2155 # Allow declare and assign on same line for better readability
PHPVM_VERSION="1.9.4"
# Test mode flag
PHPVM_TEST_MODE="${PHPVM_TEST_MODE:-false}"
PHPVM_DIR="${PHPVM_DIR:-$HOME/.phpvm}"
PHPVM_VERSIONS_DIR="$PHPVM_DIR/versions"
PHPVM_ACTIVE_VERSION_FILE="$PHPVM_DIR/active_version"
PHPVM_CURRENT_SYMLINK="$PHPVM_DIR/current"
DEBUG=false # Set to true to enable debug logs
PHPVM_LOG_TIMESTAMPS="${PHPVM_LOG_TIMESTAMPS:-false}"
PHPVM_PATCH_VERSION_WARNING_SHOWN="${PHPVM_PATCH_VERSION_WARNING_SHOWN:-false}"
# Exit codes for consistent error handling
# These follow common Unix conventions and provide specific error information
PHPVM_EXIT_SUCCESS=0 # Operation completed successfully
PHPVM_EXIT_ERROR=1 # General error
PHPVM_EXIT_INVALID_ARG=2 # Invalid argument or usage error
PHPVM_EXIT_NOT_FOUND=3 # Version not found (not available)
PHPVM_EXIT_NOT_INSTALLED=4 # Version not installed locally
PHPVM_EXIT_FILE_ERROR=5 # File or permission error
PHPVM_EXIT_UNKNOWN_CMD=127 # Unknown command
# Cache for command availability checks
PHPVM_CACHE_PHP_CONFIG=""
PHPVM_CACHE_PHP=""
# Helper to check if a command exists (DRY for 'command -v X > /dev/null 2>&1')
# Usage: command_exists <command_name>
# Returns: 0 if command exists, 1 otherwise
command_exists() {
command -v "$1" > /dev/null 2>&1
}
# Test mode helpers
phpvm_is_test_mode() {
[ "${PHPVM_TEST_MODE}" = "true" ]
}
phpvm_test_prefix() {
echo "${TEST_PREFIX:-/tmp}"
}
phpvm_test_cellar_root() {
echo "$(phpvm_test_prefix)/opt/homebrew/Cellar"
}
phpvm_test_php_cellar_dir() {
local version="$1"
echo "$(phpvm_test_cellar_root)/php@${version}"
}
phpvm_test_php_bin_dir() {
local version="$1"
echo "$(phpvm_test_php_cellar_dir "$version")/bin"
}
phpvm_test_php_installed() {
local version="$1"
[ -d "$(phpvm_test_php_cellar_dir "$version")" ]
}
phpvm_test_install_php() {
local version="$1"
local bin_dir
local php_binary
bin_dir="$(phpvm_test_php_bin_dir "$version")"
mkdir -p "$bin_dir"
# Create a mock PHP binary that behaves like real php for basic operations
php_binary="$bin_dir/php"
cat > "$php_binary" << 'EOF'
#!/bin/sh
# Mock PHP binary for phpvm tests
version="${PHP_TEST_VERSION:-8.2.0}"
if [ "$1" = "-v" ]; then
echo "PHP ${version} (cli) (built: Jan 1 2024 00:00:00) (NTS)"
exit 0
elif [ "$1" = "-r" ]; then
# Handle php -r 'code' for version extraction
shift
code="$1"
case "$code" in
*PHP_MAJOR_VERSION*PHP_MINOR_VERSION*)
# Extract major.minor from our version
echo "${version}" | cut -d. -f1-2
;;
*)
# Simple eval-like behavior for other code
echo "${version}"
;;
esac
exit 0
fi
echo "PHP ${version}"
exit 0
EOF
chmod +x "$php_binary"
}
phpvm_test_php_path() {
local version="$1"
echo "$(phpvm_test_php_cellar_dir "$version")/bin/php"
}
# State helpers
set_active_version() {
local version="$1"
if ! phpvm_atomic_write "$PHPVM_ACTIVE_VERSION_FILE" "$version"; then
phpvm_err "Failed to write active version file"
return 1
fi
return 0
}
# Update the current symlink to point to the active PHP binary
# This links to whatever `command -v php` resolves to, ensuring the symlink
# points to the actual php binary that the shell would execute.
# SAFETY: Verifies target exists before creating symlink to prevent broken symlinks.
update_current_symlink() {
local target
# In test mode, use the test prefix path
if phpvm_is_test_mode; then
target="$PHP_BIN_PATH/php"
else
# Use command -v to get the actual resolved php path
target=$(command -v php 2> /dev/null) || true
fi
# Verify we have a target and it exists
if [ -z "$target" ]; then
phpvm_warn "No php binary found in PATH (skipping symlink update)"
return 0 # Non-fatal - symlink is convenience, not critical
fi
if [ ! -e "$target" ] && [ ! -L "$target" ]; then
phpvm_warn "Symlink target does not exist: $target (skipping symlink update)"
return 0 # Non-fatal - symlink is convenience, not critical
fi
rm -f "$PHPVM_CURRENT_SYMLINK"
ln -s "$target" "$PHPVM_CURRENT_SYMLINK" || {
phpvm_err "Failed to update symlink."
return 1
}
return 0
}
# Helper function to run commands with sudo if needed
run_with_sudo() {
if [ "$(id -u)" -ne 0 ]; then
sudo "$@"
else
"$@"
fi
}
# Helper function to log messages with timestamps
log_with_timestamp() {
local level="$1"
shift
printf "%s [%s] %s\n" "$(date '+%Y-%m-%d %H:%M:%S')" "$level" "$*"
}
# Check if terminal supports colors
phpvm_has_colors() {
# Check if stdout is a terminal
if [ ! -t 1 ]; then
return 1
fi
# Check TERM variable
case "${TERM:-}" in
dumb | '') return 1 ;;
esac
# Check for NO_COLOR environment variable (https://no-color.org/)
if [ -n "${NO_COLOR:-}" ]; then
return 1
fi
# Check tput for color support
if command_exists tput; then
local colors
colors=$(tput colors 2> /dev/null || echo 0)
[ "$colors" -ge 8 ] && return 0
fi
# Fallback: assume colors are supported for common terminals
return 0
}
# Initialize ANSI color codes based on terminal support
phpvm_init_colors() {
if phpvm_has_colors; then
RED=$(printf '\033[31m')
GREEN=$(printf '\033[32m')
YELLOW=$(printf '\033[33m')
RESET=$(printf '\033[0m')
else
RED=''
GREEN=''
YELLOW=''
RESET=''
fi
}
# Initialize colors on load
phpvm_init_colors
# Output functions
phpvm_log() {
local level="$1"
shift
local color_prefix=""
local color_suffix=""
if [ -n "${RESET:-}" ]; then
case "$level" in
ERROR) color_prefix="${RED}" ;;
WARNING) color_prefix="${YELLOW}" ;;
INFO) color_prefix="${GREEN}" ;;
esac
color_suffix="${RESET}"
fi
if [ "$DEBUG" = "true" ] || [ "$PHPVM_LOG_TIMESTAMPS" = "true" ]; then
log_with_timestamp "$level" "${color_prefix}$*${color_suffix}"
else
printf "%s\n" "${color_prefix}$*${color_suffix}"
fi
}
phpvm_echo() { phpvm_log "INFO" "$*"; }
phpvm_err() { phpvm_log "ERROR" "$*" >&2; }
phpvm_warn() { phpvm_log "WARNING" "$*" >&2; }
phpvm_debug() { if [ "$DEBUG" = "true" ]; then log_with_timestamp "DEBUG" "$*"; fi; }
# Atomic file write - writes to temp file then moves to target
# This prevents race conditions and partial writes
phpvm_atomic_write() {
local target_file="$1"
local content="$2"
local temp_file
local target_dir
# Get directory of target file
target_dir="$(dirname "$target_file")"
# Create secure temp file using mktemp (more secure than predictable filename)
temp_file=$(mktemp "${target_dir}/.phpvm_tmp.XXXXXXXXXX") || {
phpvm_debug "Failed to create temp file with mktemp"
return 1
}
# Set safe permissions
chmod 0644 "$temp_file" 2> /dev/null || {
rm -f "$temp_file" 2> /dev/null
return 1
}
# Write content to temp file
if ! printf '%s\n' "$content" > "$temp_file" 2> /dev/null; then
rm -f "$temp_file" 2> /dev/null
return 1
fi
# Atomically move temp file to target
if ! mv -f "$temp_file" "$target_file" 2> /dev/null; then
rm -f "$temp_file" 2> /dev/null
return 1
fi
return 0
}
# Ensure all required phpvm directories exist (DRY for repeated mkdir -p calls)
# Usage: ensure_phpvm_dirs
# Returns: 0 on success, 1 on failure
ensure_phpvm_dirs() {
# Core phpvm directory
if [ ! -d "$PHPVM_DIR" ]; then
mkdir -p "$PHPVM_DIR" || {
phpvm_err "Failed to create directory $PHPVM_DIR"
return 1
}
fi
# Versions directory - critical for phpvm operation
if [ ! -d "$PHPVM_VERSIONS_DIR" ]; then
mkdir -p "$PHPVM_VERSIONS_DIR" || {
phpvm_err "Failed to create directory $PHPVM_VERSIONS_DIR"
return 1
}
fi
# Alias directory for version aliases (e.g., default -> 8.2) - required for alias commands
if [ ! -d "$PHPVM_DIR/alias" ]; then
mkdir -p "$PHPVM_DIR/alias" || {
phpvm_err "Failed to create alias directory $PHPVM_DIR/alias"
return 1
}
fi
# Cache directory for metadata and downloads
mkdir -p "$PHPVM_DIR/cache" 2> /dev/null || true
return 0
}
# Create the required directory structure (wrapper for compatibility)
create_directories() {
ensure_phpvm_dirs
}
# Locking mechanism to prevent concurrent operations
# Uses mkdir for atomic lock creation (POSIX-compliant)
phpvm_lock() {
local lockdir="$PHPVM_DIR/.lock"
local max_wait=30
local waited=0
local lock_pid
while ! mkdir "$lockdir" 2> /dev/null; do
# Reset lock_pid at top of each iteration to avoid staleness
lock_pid=""
# Check if lock is stale (process no longer exists)
if [ -f "$lockdir/pid" ]; then
lock_pid=$(cat "$lockdir/pid" 2> /dev/null || echo "")
if [ -n "$lock_pid" ] && ! kill -0 "$lock_pid" 2> /dev/null; then
phpvm_warn "Removing stale lock from process $lock_pid"
rm -rf "$lockdir" 2> /dev/null || true
continue
fi
fi
if [ "$waited" -ge "$max_wait" ]; then
phpvm_err "Failed to acquire lock after ${max_wait}s. Another phpvm operation may be running."
if [ -n "$lock_pid" ]; then
phpvm_warn "Lock held by process: $lock_pid"
fi
phpvm_warn "If no other phpvm process is running, remove: $lockdir"
return 1
fi
sleep 1
waited=$((waited + 1))
done
# Store PID in lock directory for debugging
echo "$$" > "$lockdir/pid" 2> /dev/null || true
return 0
}
phpvm_unlock() {
local lockdir="$PHPVM_DIR/.lock"
# Belt-and-suspenders safety checks before rm -rf
[ -n "${PHPVM_DIR:-}" ] || return 0
[ "$PHPVM_DIR" != "/" ] || return 0
# Verify lockdir is actually under PHPVM_DIR before removal
case "$lockdir" in
"$PHPVM_DIR"/.lock)
rm -rf "$lockdir" 2> /dev/null || true
;;
*)
phpvm_warn "Lock directory path looks suspicious, skipping removal: $lockdir"
return 1
;;
esac
}
# Execute a command with lock protection
# Usage: phpvm_with_lock <function_name> [args...]
phpvm_with_lock() {
local func="$1"
shift
if ! phpvm_lock; then
return "$PHPVM_EXIT_ERROR"
fi
# Save existing traps to restore them after lock release
# This is critical for shell integration - don't clobber user's traps
local saved_exit_trap saved_int_trap saved_term_trap saved_hup_trap
saved_exit_trap=$(trap -p EXIT)
saved_int_trap=$(trap -p INT)
saved_term_trap=$(trap -p TERM)
saved_hup_trap=$(trap -p HUP)
# Set our cleanup traps
trap 'phpvm_unlock' EXIT INT TERM HUP
local result
"$func" "$@"
result=$?
# Unlock BEFORE restoring traps to prevent lock leaks if interrupted
# between trap restoration and unlock
phpvm_unlock
# Restore original traps (or explicitly clear if user had none)
# Critical: if saved_*_trap is empty, user had no trap, so clear ours with 'trap -'
if [ -n "$saved_exit_trap" ]; then
eval "$saved_exit_trap"
else
trap - EXIT
fi
if [ -n "$saved_int_trap" ]; then
eval "$saved_int_trap"
else
trap - INT
fi
if [ -n "$saved_term_trap" ]; then
eval "$saved_term_trap"
else
trap - TERM
fi
if [ -n "$saved_hup_trap" ]; then
eval "$saved_hup_trap"
else
trap - HUP
fi
return "$result"
}
# Get OS information
get_os_info() {
PHPVM_OS_TYPE="$(command uname -s)"
PHPVM_OS_ARCH="$(command uname -m)"
# Detect macOS version
if [ "$PHPVM_OS_TYPE" = "Darwin" ]; then
if command_exists sw_vers; then
PHPVM_MACOS_VERSION="$(sw_vers -productVersion)"
PHPVM_MACOS_MAJOR="$(echo "$PHPVM_MACOS_VERSION" | command cut -d. -f1)"
PHPVM_MACOS_MINOR="$(echo "$PHPVM_MACOS_VERSION" | command cut -d. -f2)"
fi
fi
# Detect Linux distribution and WSL
if [ "$PHPVM_OS_TYPE" = "Linux" ]; then
# Check for WSL (Windows Subsystem for Linux)
if [ -f "/proc/version" ] && command grep -qi "microsoft\|WSL" /proc/version 2> /dev/null; then
PHPVM_IS_WSL=true
if command grep -qi "wsl2" /proc/version 2> /dev/null; then
PHPVM_WSL_VERSION="2"
else
PHPVM_WSL_VERSION="1"
fi
phpvm_debug "Detected WSL $PHPVM_WSL_VERSION environment"
else
PHPVM_IS_WSL=false
fi
# Try modern method first
if [ -f "/etc/os-release" ]; then
# shellcheck disable=SC1091
. /etc/os-release
PHPVM_LINUX_DISTRO="$ID"
PHPVM_LINUX_VERSION="$VERSION_ID"
elif [ -f "/etc/lsb-release" ]; then
# shellcheck disable=SC1091
. /etc/lsb-release
PHPVM_LINUX_DISTRO="$(echo "$DISTRIB_ID" | tr '[:upper:]' '[:lower:]')"
PHPVM_LINUX_VERSION="$DISTRIB_RELEASE"
elif [ -f "/etc/redhat-release" ]; then
PHPVM_LINUX_DISTRO="rhel"
PHPVM_LINUX_VERSION="$(command grep -o '[0-9]' /etc/redhat-release | command head -1)"
elif [ -f "/etc/debian_version" ]; then
PHPVM_LINUX_DISTRO="debian"
PHPVM_LINUX_VERSION="$(command cat /etc/debian_version)"
fi
# WSL-specific adjustments
if [ "$PHPVM_IS_WSL" = "true" ]; then
phpvm_debug "WSL detected - applying WSL-specific configurations"
# WSL may have different PATH requirements
if [ "$PHPVM_WSL_VERSION" = "1" ]; then
phpvm_warn "WSL 1 detected. Some features may not work as expected."
fi
fi
fi
}
# Detect the system's package manager and OS
detect_system() {
# Get detailed OS information
get_os_info
# In test mode, use sandbox defaults without requiring real package managers
if phpvm_is_test_mode; then
PKG_MANAGER="brew"
HOMEBREW_PREFIX=$(phpvm_test_prefix)
PHP_BIN_PATH="$HOMEBREW_PREFIX/bin"
phpvm_debug "Test mode: using brew-style sandbox at $HOMEBREW_PREFIX"
return 0
fi
if [ "$PHPVM_OS_TYPE" = "Darwin" ]; then
PKG_MANAGER="brew"
if ! command_exists brew; then
phpvm_err "Homebrew is not installed. Please install Homebrew first."
phpvm_warn "Visit https://brew.sh to install Homebrew."
return 1
fi
# Use brew --prefix directly (simpler and more reliable)
if command_exists brew; then
HOMEBREW_PREFIX=$(brew --prefix 2> /dev/null)
fi
# Fallback for different macOS versions
if [ -z "$HOMEBREW_PREFIX" ]; then
if [ "$PHPVM_OS_ARCH" = "arm64" ] && [ -d "/opt/homebrew" ]; then
HOMEBREW_PREFIX="/opt/homebrew"
elif [ -d "/usr/local" ]; then
HOMEBREW_PREFIX="/usr/local"
fi
fi
PHP_BIN_PATH="$HOMEBREW_PREFIX/bin"
phpvm_debug "Detected macOS $PHPVM_MACOS_VERSION on $PHPVM_OS_ARCH, Homebrew prefix: $HOMEBREW_PREFIX"
return 0
fi
# Enhanced Linux package manager detection with distribution-specific logic
if [ "$PHPVM_OS_TYPE" = "Linux" ]; then
phpvm_debug "Detected Linux distribution: $PHPVM_LINUX_DISTRO $PHPVM_LINUX_VERSION"
# Debian/Ubuntu family
if command_exists apt-get; then
PKG_MANAGER="apt"
PHP_BIN_PATH="/usr/bin"
# Check for specific Ubuntu/Debian PHP package patterns
if [ "$PHPVM_LINUX_DISTRO" = "ubuntu" ] || [ "$PHPVM_LINUX_DISTRO" = "debian" ]; then
# Modern Ubuntu/Debian uses ondrej/sury PPA for multiple PHP versions
# No additional adjustments needed - handled by package abstraction layer
:
fi
# RHEL/Fedora/CentOS family
elif command_exists dnf; then
PKG_MANAGER="dnf"
PHP_BIN_PATH="/usr/bin"
elif command_exists yum; then
PKG_MANAGER="yum"
PHP_BIN_PATH="/usr/bin"
# RHEL/CentOS specific adjustments
if [ "$PHPVM_LINUX_DISTRO" = "rhel" ] || [ "$PHPVM_LINUX_DISTRO" = "centos" ]; then
# May need EPEL repository for modern PHP versions
if [ -n "$PHPVM_LINUX_VERSION" ] && [ "$PHPVM_LINUX_VERSION" -lt 8 ]; then
phpvm_warn "RHEL/CentOS $PHPVM_LINUX_VERSION may require EPEL repository for modern PHP versions"
fi
fi
# Arch Linux family
elif command_exists pacman; then
PKG_MANAGER="pacman"
PHP_BIN_PATH="/usr/bin"
# Linuxbrew as fallback
elif command_exists brew; then
PKG_MANAGER="brew"
# Enhanced Linuxbrew detection
if [ -n "$HOMEBREW_PREFIX" ]; then
# Use existing prefix
:
elif [ -d "/home/linuxbrew/.linuxbrew" ]; then
HOMEBREW_PREFIX="/home/linuxbrew/.linuxbrew"
elif [ -d "$HOME/.linuxbrew" ]; then
HOMEBREW_PREFIX="$HOME/.linuxbrew"
elif command_exists brew; then
HOMEBREW_PREFIX=$(brew --prefix 2> /dev/null || echo "/usr/local")
else
HOMEBREW_PREFIX="/usr/local"
fi
PHP_BIN_PATH="$HOMEBREW_PREFIX/bin"
phpvm_debug "Using Linuxbrew at $HOMEBREW_PREFIX"
else
phpvm_err "No supported package manager found (apt, dnf, yum, pacman, or brew)."
phpvm_warn "Detected: $PHPVM_LINUX_DISTRO $PHPVM_LINUX_VERSION"
phpvm_warn "Consider installing one of the supported package managers or Linuxbrew."
return 1
fi
else
phpvm_err "Unsupported operating system: $PHPVM_OS_TYPE"
return 1
fi
return 0
}
# Sanitize user input to prevent command injection
# Returns sanitized string via stdout, returns 1 if input contains dangerous characters
sanitize_input() {
local input="$1"
local max_length="${2:-20}"
# Check for empty input
if [ -z "$input" ]; then
return 1
fi
# Check length (prevent buffer overflow style attacks)
if [ ${#input} -gt "$max_length" ]; then
phpvm_err "Input too long (max $max_length characters)"
return 1
fi
# Allowlist only: letters, digits, dot, hyphen, underscore (for versions and aliases)
# Use printf to avoid echo interpretation of strings like -n, -e, backslash escapes
if ! printf '%s\n' "$input" | command grep -Eq '^[a-zA-Z0-9._-]+$'; then
phpvm_err "Input contains invalid characters"
return 1
fi
# Prevent values starting with '-' (defensive against option parsing issues)
case "$input" in
-*)
phpvm_err "Input cannot start with '-'"
return 1
;;
esac
printf '%s\n' "$input"
return 0
}
# Normalize PHP version for package operations (X.Y.Z -> X.Y)
# Usage: phpvm_normalize_version <version>
# Outputs normalized version or nothing on failure
phpvm_normalize_version() {
local version="$1"
if is_valid_version_format "$version"; then
printf '%s\n' "$version" | command awk -F. '{print $1 "." $2}'
return 0
fi
return 1
}
# Check if string matches valid PHP version format (X.Y or X.Y.Z)
# Usage: is_valid_version_format <version>
# Returns: 0 if valid, 1 if invalid
is_valid_version_format() {
local version="$1"
printf '%s\n' "$version" | command grep -qE '^[0-9]+\.[0-9]+(\.[0-9]+)?$'
}
phpvm_warn_patch_version_once() {
local input_version="$1"
local normalized_version="$2"
if [ -n "$input_version" ] && [ -n "$normalized_version" ] && [ "$input_version" != "$normalized_version" ]; then
if [ "${PHPVM_PATCH_VERSION_WARNING_SHOWN:-false}" != "true" ]; then
phpvm_warn "Using $normalized_version for package operations."
PHPVM_PATCH_VERSION_WARNING_SHOWN=true
export PHPVM_PATCH_VERSION_WARNING_SHOWN
fi
fi
}
# Portable version sorter (works on BSD and GNU sort)
# Reads versions on stdin, outputs latest X.Y[.Z]
phpvm_latest_from_list() {
command awk -F. '
NF==2 { printf "%d.%d.%d %s\n",$1,$2,0,$0; next }
NF>=3 { printf "%d.%d.%d %s\n",$1,$2,$3,$0; next }
' |
command sort -k1,1n -k2,2n -k3,3n |
command tail -1 |
command awk '{print $2}'
}
# ============================================================================
# PACKAGE MANAGER ABSTRACTION LAYER
# Helper functions to reduce code duplication across package managers
# ============================================================================
# Get the package name format for a given PHP version
# Usage: get_php_package_name <version>
# Returns: Formatted package name (e.g., "php@8.2", "php8.2-cli", "php-cli")
get_php_package_name() {
local version="$1"
local normalized_version
local formula
normalized_version=$(phpvm_normalize_version "$version") || return 1
case "$PKG_MANAGER" in
brew)
# Use helper to resolve actual installed formula
if formula=$(brew_resolve_formula_for_version "$normalized_version"); then
echo "$formula"
else
# Fallback to versioned format if not installed yet
echo "php@${normalized_version}"
fi
;;
apt)
# Ubuntu/Debian use phpX.Y-cli as the main package
# This works with ondrej/sury PPA which is the standard way to get multiple PHP versions
echo "php${normalized_version}-cli"
;;
dnf | yum)
# Fedora/RHEL: Use base php package + module streams
# Note: Version switching on RHEL/Fedora typically requires:
# 1. dnf module enable php:X.Y
# 2. dnf install php-cli
# We install the base package; module management happens in install function
echo "php-cli"
;;
pacman)
# Arch typically uses unversioned 'php' package
echo "php"
;;
*)
echo "php${normalized_version}"
;;
esac
}
# Get the binary path for a PHP version
# Usage: get_php_binary_path <version>
# Returns: Full path to PHP binary
get_php_binary_path() {
local version="$1"
local normalized_version
local formula
normalized_version=$(phpvm_normalize_version "$version") || return 1
case "$PKG_MANAGER" in
brew)
if [ -n "${HOMEBREW_PREFIX:-}" ]; then
# Try to resolve actual formula first
if formula=$(brew_resolve_formula_for_version "$normalized_version"); then
if [ "$formula" = "php" ]; then
# Unversioned php can be in bin or opt/php/bin
if [ -x "${HOMEBREW_PREFIX}/bin/php" ]; then
echo "${HOMEBREW_PREFIX}/bin/php"
else
echo "${HOMEBREW_PREFIX}/opt/php/bin/php"
fi
else
echo "${HOMEBREW_PREFIX}/opt/${formula}/bin/php"
fi
else
# Fallback to versioned path
echo "${HOMEBREW_PREFIX}/opt/php@${normalized_version}/bin/php"
fi
else
echo "/opt/homebrew/opt/php@${normalized_version}/bin/php"
fi
;;
apt | dnf | yum | pacman)
# Use linux_find_php_binary for reliable path resolution
# Capture output to prevent any stdout side-effects from mixing with fallback
local found_binary
if found_binary=$(linux_find_php_binary "$normalized_version"); then
echo "$found_binary"
else
echo "/usr/bin/php${normalized_version}"
fi
;;
*)
echo "/usr/bin/php${normalized_version}"
;;
esac
}
# Check if a PHP package is installed
# Usage: is_php_package_installed <version>
# Returns: 0 if installed, 1 if not
is_php_package_installed() {
local version="$1"
local package_name
local php_binary
local actual_version
package_name=$(get_php_package_name "$version") || return 1
case "$PKG_MANAGER" in
brew)
brew list --versions "$package_name" > /dev/null 2>&1
;;
apt)
# Use dpkg-query for exact package status check
dpkg-query -W -f='${Status}' "$package_name" 2> /dev/null | command grep -Fq "install ok installed"
;;
dnf | yum)
# For dnf/yum, verify the actual binary resolves to the requested version
# since these package managers use modules/streams and generic package names
php_binary=$(linux_find_php_binary "$version" 2> /dev/null) || return 1
# Verify binary exists and reports correct major.minor version
if [ -x "$php_binary" ]; then
actual_version=$("$php_binary" -r 'echo PHP_MAJOR_VERSION,".",PHP_MINOR_VERSION;' 2> /dev/null || true)
[ "$actual_version" = "$version" ]
else
return 1
fi
;;
pacman)
pacman -Qi "$package_name" > /dev/null 2>&1
;;
*)
return 1
;;
esac
}
# Install PHP package using the appropriate package manager
# Usage: pkg_install_php <version>
# Returns: 0 on success, 1 on failure
pkg_install_php() {
local version="$1"
local package_name
package_name=$(get_php_package_name "$version") || return 1
case "$PKG_MANAGER" in
brew)
brew install "$package_name"
;;
apt)
run_with_sudo apt-get install -y "$package_name"
;;
dnf)
run_with_sudo dnf install -y "$package_name"
;;
yum)
run_with_sudo yum install -y "$package_name"
;;
pacman)
run_with_sudo pacman -S --noconfirm "$package_name"
;;
*)
return 1
;;
esac
}
# Uninstall PHP package using the appropriate package manager
# Usage: pkg_uninstall_php <version>
# Returns: 0 on success, 1 on failure
pkg_uninstall_php() {
local version="$1"
local package_name
local normalized_version
package_name=$(get_php_package_name "$version") || return 1
normalized_version=$(phpvm_normalize_version "$version") || return 1
case "$PKG_MANAGER" in
brew)
brew uninstall "$package_name"
;;
apt)
# Symmetrical with install: remove cli+common+fpm packages
run_with_sudo apt-get remove -y \
"php${normalized_version}-cli" \
"php${normalized_version}-common" \
"php${normalized_version}-fpm" 2> /dev/null ||
run_with_sudo apt-get remove -y "$package_name"
;;
dnf)
run_with_sudo dnf remove -y "$package_name"
;;
yum)
run_with_sudo yum remove -y "$package_name"
;;
pacman)
run_with_sudo pacman -R --noconfirm "$package_name"
;;
*)
return 1
;;
esac
}
# Search for PHP packages in repositories
# Usage: pkg_search_php <version>
# Returns: 0 if found, 1 if not found, 2 if some PHP packages exist but not requested version
pkg_search_php() {
local version="$1"
local package_name
local mm
package_name=$(get_php_package_name "$version") || return 1
case "$PKG_MANAGER" in
brew)
# Use brew info for reliable formula existence check (more stable than search)
brew info "$package_name" > /dev/null 2>&1
;;
apt)
# Use apt-cache policy for exact package check
# Explicitly fail if candidate is "(none)" to avoid false positives
local policy_output
policy_output=$(apt-cache policy "$package_name" 2> /dev/null)
if echo "$policy_output" | command grep -Fq "Candidate:"; then
# Check that candidate is not "(none)"
! echo "$policy_output" | command grep -Eq "Candidate:.*\(none\)"
else
return 1
fi
;;
dnf)
# Check for module stream availability (preferred for versioned PHP)
if dnf module list php 2> /dev/null | command grep -Eq "php[[:space:]]+${version}[[:space:]]|${version}[[:space:]]+\["; then
return 0
fi
# If any php module exists, signal "some versions exist"
if dnf module list php 2> /dev/null | command grep -q "^php"; then
return 2
fi
# Fallback: check generic package
if dnf info "$package_name" > /dev/null 2>&1; then
return 0
fi
return 1
;;
yum)
# If Remi enabled, check for remi-style packages (e.g., php82-php-cli for 8.2)
if check_remi_repository; then
mm="${version/./}" # 8.2 -> 82
if yum info "php${mm}-php-cli" > /dev/null 2>&1; then
return 0
fi
fi
# Check if any php packages exist
if yum search php 2> /dev/null | command grep -q "php"; then
return 2
fi
return 1
;;
pacman)
pacman -Si "$package_name" > /dev/null 2>&1
;;
*)
return 1
;;
esac
}
# ============================================================================
# END PACKAGE MANAGER ABSTRACTION LAYER
# ============================================================================
# Validate PHP version format
validate_php_version() {
local version="$1"
# Allow 'system' as a special case
[ "$version" = "system" ] && return "$PHPVM_EXIT_SUCCESS"
# First sanitize the input
if ! sanitize_input "$version" 10 > /dev/null 2>&1; then
return "$PHPVM_EXIT_INVALID_ARG"
fi
# Check for basic PHP version format (X.Y or X.Y.Z)
if is_valid_version_format "$version"; then
return "$PHPVM_EXIT_SUCCESS"
fi
return "$PHPVM_EXIT_INVALID_ARG"
}
# Resolve version alias to actual version number
# Returns the resolved version or the input if no alias is found
phpvm_resolve_version() {
local input="$1"
local resolved=""