-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhelpers.php
More file actions
1340 lines (1222 loc) · 43.9 KB
/
helpers.php
File metadata and controls
1340 lines (1222 loc) · 43.9 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
if ( ! function_exists('request')) {
/**
* Get the value of a request variable from $_REQUEST.
*
* @param mixed $key
* @param mixed|null $default
*
* @return mixed
*
* @example
* <code>
* $value = request('items'); // if items is not set, $value will be null
* $value = request('items', 'default value'); // if items is not set, $value will be 'default value'
* $value = request(['items', 'other']); // if items is not set, $value will be ['items' => null, 'other' => null]
* </code>
*/
function request(mixed $key, mixed $default = null): mixed
{
if (is_array($key)) {
// If mapping multiple keys, retrieve each one without sanitizing here
$results = [];
foreach ($key as $k) {
// Use array_key_exists for explicit null check vs missing key
$results[$k] = array_key_exists($k, $_REQUEST) ? $_REQUEST[$k] : $default;
}
return $results;
// Or using the simpler map if default handling is sufficient:
// return array_map(fn($k) => request($k, $default), $key);
}
// Don't filter/sanitize here. Return raw value or default.
return $_REQUEST[$key] ?? $default;
}
}
if ( ! function_exists('dd')) {
/**
* Dump the given value and die.
*
* @param mixed $data
*
* @return void
*
* @example
* <code>
* dd($myVariable); // Dumps the variable and stops execution
* </code>
*/
function dd(...$data): void
{
foreach ($data as $value) {
echo '<pre>';
var_dump($value);
echo '</pre>';
}
die();
}
}
if ( ! function_exists('dump')) {
/**
* Dump the given values.
*
* @param mixed ...$data The values to dump.
*
* @return void
*
* @example
* <code>
* dump($myVariable); // Outputs the contents of $myVariable in a readable format
* dump($var1, $var2, $var3); // Outputs multiple variables
* </code>
*/
function dump(...$data): void
{
foreach ($data as $value) {
echo '<pre>';
var_dump($value);
echo '</pre>';
}
}
}
if ( ! function_exists('env')) {
/**
* Get the value of an environment variable from a .env file.
*
* This function reads environment variables from a .env file located in the document root.
* The values are cached after the first read for better performance.
*
* Usage:
* 1. Ensure you have a .env file in your document root.
* The .env file should contain key-value pairs, each on a new line, like this:
* APP_ENV=production
* DB_HOST=localhost
* DB_USER=root
* DB_PASS=secret
*
* 2. Use the env() function to retrieve environment variables:
* $appEnv = env('APP_ENV', 'production'); // Returns 'production' if APP_ENV is not set
* $databaseHost = env('DB_HOST', '127.0.0.1'); // Returns '127.0.0.1' if DB_HOST is not set
*
* @param string $key The key of the environment variable.
* @param mixed|null $default The default value to return if the environment variable is not set.
*
* @return mixed The value of the environment variable or the default value.
*/
function env(string $key, mixed $default = null): mixed
{
static $env = null;
if ($env === null) {
$env = [];
$envFilePath = realpath(server('DOCUMENT_ROOT') . '/.env');
if ($envFilePath && file_exists($envFilePath)) {
$envFile = @fopen($envFilePath, 'r');
if ($envFile) {
while (($line = fgets($envFile)) !== false) {
$line = trim($line);
if ($line && $line[0] !== '#' && str_contains($line, '=')) {
list($name, $value) = explode('=', $line, 2);
$name = trim($name);
$value = trim($value);
$env[$name] = $value;
$_ENV[$name] = $value;
}
}
fclose($envFile);
}
}
}
if (isset($env[$key])) {
return $env[$key];
}
if (isset($_ENV[$key])) {
return $_ENV[$key];
}
$value = getenv($key);
return $value !== false ? $value : $default;
}
}
if ( ! function_exists('config')) {
/**
* Get the value of a configuration setting.
*
* This function reads configuration settings from a config.php file located in the document root.
* The configuration values are cached after the first read for better performance.
*
* Usage:
* 1. Ensure you have a config.php file in your document root.
* The config.php file should return an associative array of configuration settings, like this:
* <?php
* return [
* 'database' => [
* 'host' => 'localhost',
* 'user' => 'root',
* 'pass' => 'secret',
* ],
* 'app' => [
* 'env' => 'production',
* 'debug' => true,
* ],
* ];
*
* 2. Use the config() function to retrieve configuration settings:
* $dbHost = config('database.host', 'localhost'); // Returns 'localhost' if database.host is not set
* $appEnv = config('app.env', 'production'); // Returns 'production' if app.env is not set
*
* @param mixed|null $key The key of the configuration setting, using dot notation for nested settings.
* @param mixed|null $default The default value to return if the configuration setting is not set.
*
* @return mixed The value of the configuration setting or the default value.
*/
function config(mixed $key = null, mixed $default = null): mixed
{
static $config = null;
// Reset mechanism for testing - use special key '__RESET__'
if ($key === '__RESET__') {
$config = null;
return null;
}
// Initialize once from global state and config file
if ($config === null) {
$config = $GLOBALS['app_config'] ?? [];
$configFilePath = server('DOCUMENT_ROOT', sys_get_temp_dir()) . '/config.php';
if (file_exists($configFilePath)) {
$fileConfig = include $configFilePath;
$config = array_merge($config, $fileConfig ?: []);
}
}
// Set mode: write-through to both static and global
if (is_array($key)) {
foreach ($key as $k => $v) {
data_set($config, $k, $v);
}
$GLOBALS['app_config'] = $config;
return null;
}
// Get mode: read from static cache only
if ($key === null) {
return $config;
}
return data_get($config, $key, $default);
}
}
if ( ! function_exists('redirect')) {
/**
* Redirect to a specified URL.
*
* @param string $url The URL to redirect to
* @param int $status The HTTP status code (default: 302)
*
* @return void
*
* @example
* <code>
* redirect('https://example.com'); // Redirects with 302 status
* redirect('https://example.com', 301); // Permanent redirect
* redirect('/login', 303); // See other redirect
* </code>
*/
function redirect(string $url, int $status = 302): void
{
header("Location: $url", true, $status);
exit();
}
}
if ( ! function_exists('asset')) {
/**
* Generate a URL for an asset.
*
* @param string $path
*
* @return string
*
* @example
* <code>
* $assetUrl = asset('images/logo.png'); // Generates the URL for the asset
* </code>
*/
function asset(string $path): string
{
$baseUrl = rtrim(config('base_url', sprintf('%s://%s', server('REQUEST_SCHEME'), server('HTTP_HOST'))), '/');
$path = ltrim($path, '/');
return $path ? $baseUrl . '/' . $path : $baseUrl;
}
}
if ( ! function_exists('old')) {
/**
* Retrieve an old input value.
*
* @param string $key
* @param mixed|null $default
*
* @return mixed
*
* @example
* <code>
* $oldValue = old('username'); // Gets the old input value for 'username'
* </code>
*/
function old(string $key, mixed $default = null): mixed
{
return session('_old_input.' . $key, $default);
}
}
if ( ! function_exists('csrf_field')) {
/**
* Generate a CSRF token field.
*
* @return string
*
* @example
* <code>
* echo csrf_field(); // Outputs the CSRF token field
* </code>
*/
function csrf_field(): string
{
$token = session('csrf_token', '');
return '<input type="hidden" name="csrf_token" value="' . htmlspecialchars($token, ENT_QUOTES, 'UTF-8') . '">';
}
}
if ( ! function_exists('method_field')) {
/**
* Generate a hidden input field for the HTTP method.
*
* @param string $method
*
* @return string
*
* @example
* <code>
* echo method_field('PUT'); // Outputs the hidden input field for the PUT method
* </code>
*/
function method_field(string $method): string
{
return '<input type="hidden" name="_method" value="' . htmlspecialchars(strtoupper($method), ENT_QUOTES, 'UTF-8') . '">';
}
}
if ( ! function_exists('dispatch')) {
/**
* Dispatch the current HTTP request to a handler function.
*
* This function handles request dispatching by matching the HTTP method and URI to a corresponding function.
* It dynamically constructs the function name based on the HTTP method and the first segment of the URI path.
*
* Example Usage:
* 1. Define request handler functions:
* - The function name should be a combination of the HTTP method and the first URI segment.
* For example, for a GET request to '/user/123', the function should be named 'getUser'.
*
* // Handles GET requests to /user/{id}
* function getUser($id) {
* // Handle GET request for user with ID $id
* echo "Handling GET request for user with ID: $id";
* }
*
* // Handles POST requests to /user/{id}
* function postUser($id) {
* // Handle POST request for user with ID $id
* echo "Handling POST request for user with ID: $id";
* }
*
* // Handles GET requests to / (root)
* function getIndex() {
* echo "Home page";
* }
*
* 2. Call the dispatch() function to handle the incoming request:
* dispatch(); // Matches the HTTP method and URI to the appropriate function
*
* How It Works:
* 1. It retrieves the HTTP method of the request (e.g., GET, POST) and the requested URI path.
* 2. For root path (/), it calls {method}Index function.
* 3. For other paths, it constructs the function name by combining the lowercase HTTP method and the capitalized URI segment.
* 4. All URI segments after the first are passed as separate parameters to the handler function.
* 5. If no matching function is found, it aborts with a 404 status code.
*
* @return void
*
* @example
* <code>
* // Define request handler functions
*
* // Handles GET requests to /
* function getIndex() {
* echo "Home page";
* }
*
* // Handles GET requests to /user/{id}
* function getUser($id) {
* echo "Handling GET request for user with ID: $id";
* }
*
* // Handles GET requests to /user/{id}/edit
* function getUser($id, $action) {
* echo "Handling GET request for user $id, action: $action";
* }
*
* // Call the dispatch function to handle the request
* dispatch();
* </code>
*/
function dispatch(): void
{
$requestedMethod = $_SERVER['REQUEST_METHOD'];
$requestedPath = trim(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH), '/');
// Handle root path
if (empty($requestedPath)) {
$functionToCall = strtolower($requestedMethod) . 'Index';
if (function_exists($functionToCall)) {
call_user_func($functionToCall);
return;
}
} else {
// Handle normal paths
$segments = explode('/', $requestedPath);
$resource = array_shift($segments);
$functionToCall = strtolower($requestedMethod) . ucfirst($resource);
if (function_exists($functionToCall)) {
call_user_func_array($functionToCall, $segments);
return;
}
}
abort(404, "Not Found");
}
}
if ( ! function_exists('route')) {
/**
* Generate a URL for a named route.
*
* This function generates URLs based on route names and parameters.
* Route patterns are defined in the global $routes array.
*
* Usage:
* 1. Define routes in global scope or config:
* $GLOBALS['routes'] = [
* 'home' => '/',
* 'user.show' => '/user/{id}',
* 'user.edit' => '/user/{id}/edit',
* 'posts.index' => '/posts',
* ];
*
* 2. Generate URLs:
* route('home'); // Returns '/'
* route('user.show', ['id' => 123]); // Returns '/user/123'
* route('user.edit', ['id' => 123]); // Returns '/user/123/edit'
*
* @param string $name The name of the route.
* @param array $parameters An array of parameters to substitute in the route pattern.
*
* @return string The generated URL.
* @throws InvalidArgumentException If the route name is not found.
*
* @example
* <code>
* // Define routes
* $GLOBALS['routes'] = [
* 'home' => '/',
* 'user.show' => '/user/{id}',
* 'user.edit' => '/user/{id}/edit',
* ];
*
* echo route('home'); // Returns '/'
* echo route('user.show', ['id' => 123]); // Returns '/user/123'
* echo route('user.edit', ['id' => 123]); // Returns '/user/123/edit'
* </code>
*/
function route(string $name, array $parameters = []): string
{
$routes = $GLOBALS['routes'] ?? [];
if (!isset($routes[$name])) {
throw new InvalidArgumentException("Route [{$name}] not found.");
}
$pattern = $routes[$name];
// Replace {parameter} placeholders with actual values
foreach ($parameters as $key => $value) {
$pattern = str_replace('{' . $key . '}', urlencode((string)$value), $pattern);
}
return $pattern;
}
}
if ( ! function_exists('auth')) {
/**
* Get the authenticated user.
*
* @return mixed
*
* @example
* <code>
* $user = auth(); // Gets the authenticated user
* </code>
*/
function auth(): mixed
{
return session('user');
}
}
if ( ! function_exists('abort')) {
/**
* Abort the request with a specified status code and message.
*
* @param int $code
* @param string $message
*
* @return void
*
* @example
* <code>
* abort(404, 'Not Found'); // Aborts the request with a 404 status code and message
* </code>
*/
function abort(int $code, string $message = ''): void
{
http_response_code($code);
echo htmlspecialchars($message, ENT_QUOTES, 'UTF-8');
exit();
}
}
if ( ! function_exists('session')) {
/**
* Get or set session values.
*
* @param mixed|null $key
* @param mixed|null $default
*
* @return mixed
*/
function session(mixed $key = null, mixed $default = null): mixed
{
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
if (is_null($key)) {
return $_SESSION;
}
if (is_array($key)) {
foreach ($key as $sessionKey => $sessionValue) {
$_SESSION[$sessionKey] = $sessionValue;
}
return null;
}
return data_get($_SESSION, $key, $default);
}
}
if ( ! function_exists('server')) {
/**
* Get a value from the $_SERVER superglobal.
*
* @param string $key
* @param mixed|null $default
*
* @return mixed
*
* @example
* <code>
* $host = server('HTTP_HOST'); // Gets the value of HTTP_HOST from the $_SERVER superglobal
* </code>
*/
function server(string $key, mixed $default = null): mixed
{
return $_SERVER[$key] ?? $default;
}
}
if ( ! function_exists('data_get')) {
/**
* Get a value from an array or object using dot notation.
*
* @param mixed $target
* @param array|string $key
* @param mixed|null $default
*
* @return mixed
*
* @example
* <code>
* $value = data_get($array, 'key'); // Gets the value of 'key' from the array
* </code>
*/
function data_get(mixed $target, array|string $key, mixed $default = null): mixed
{
$key = is_array($key) ? $key : explode('.', $key);
if (empty($key)) {
return $target;
}
foreach ($key as $segment) {
if (is_array($target)) {
if ( ! array_key_exists($segment, $target)) {
return value($default);
}
$target = $target[$segment];
} elseif ($target instanceof ArrayAccess) {
if ( ! $target->offsetExists($segment)) {
return value($default);
}
$target = $target[$segment];
} elseif (is_object($target)) {
if ( ! property_exists($target, $segment) && ! isset($target->{$segment})) {
return value($default);
}
$target = $target->{$segment};
} else {
return value($default);
}
}
return $target;
}
}
if ( ! function_exists('value')) {
/**
* Return the default value of the given value.
*
* @param mixed $value
*
* @return mixed
*
* @example
* <code>
* $default = value($someValue); // Returns the default value of $someValue
* </code>
*/
function value(mixed $value): mixed
{
return $value instanceof Closure ? $value() : $value;
}
}
if ( ! function_exists('cache')) {
/**
* Simple cache helper function to store and retrieve data from a file-based cache.
*
* This function allows you to cache data using a key-value system and retrieve it later.
* The cache is stored in files within a specified directory.
*
* Usage:
* 1. Ensure the cache directory exists or can be created by the function.
* By default, the cache directory is '/cache' within the document root.
* The function will attempt to create this directory if it does not exist.
*
* 2. Store data in the cache:
* cache('my_key', 'my_value', 1800); // Caches 'my_value' under 'my_key' for 1800 seconds (30 minutes)
*
* 3. Retrieve data from the cache:
* $value = cache('my_key'); // Retrieves the cached value for 'my_key'
*
* 4. If the cached value has expired or does not exist, null is returned.
*
* Directory Permissions:
* - The cache directory must be writable by the web server.
* - The function attempts to create the directory with 0777 permissions if it does not exist.
*
* @param mixed|null $key The cache key. Use null to return the cache directory path.
* @param mixed|null $value The value to cache. If null, the function will return the cached value.
* @param int|null $seconds The number of seconds to cache the value. Default is 3600 seconds (1 hour).
*
* @return mixed|null The cached value, or null if not found or expired.
*
* @example
* <code>
* // Caching a value
* cache('my_key', 'my_value', 1800); // Cache 'my_value' for 1800 seconds (30 minutes)
*
* // Retrieving a cached value
* $value = cache('my_key'); // Retrieve the cached value for 'my_key'
*
* // Retrieving the cache directory path
* $cacheDirectory = cache(); // Returns the path to the cache directory
* </code>
*/
function cache(mixed $key = null, mixed $value = null, int $seconds = null): mixed
{
$cacheDir = $_SERVER['DOCUMENT_ROOT'] . '/cache';
if (!file_exists($cacheDir)) {
mkdir($cacheDir, 0777, true);
}
if (is_null($key)) {
return $cacheDir;
}
$filePath = $cacheDir . '/' . md5($key) . '.cache';
// Get mode: retrieve cached value
if (is_null($value)) {
$content = @file_get_contents($filePath);
if ($content === false) {
return null;
}
$cachedData = @json_decode($content, true);
if (!$cachedData || !isset($cachedData['timestamp'], $cachedData['seconds'], $cachedData['value'])) {
return null;
}
if ((time() - $cachedData['timestamp']) >= $cachedData['seconds']) {
@unlink($filePath); // Clean up expired cache
return null;
}
return $cachedData['value'];
}
// Set mode: store value in cache
$seconds = $seconds ?? 3600;
$data = json_encode(['value' => $value, 'timestamp' => time(), 'seconds' => $seconds]);
file_put_contents($filePath, $data, LOCK_EX);
return $value;
}
}
if ( ! function_exists('data_set')) {
/**
* Set a value within an array or object using dot notation.
*
* @param mixed $target
* @param array|string $key
* @param mixed $value
* @param bool $overwrite
*
* @return mixed
*
* @example
* <code>
* data_set($array, 'key', 'value'); // Sets the value of 'key' in the array
* </code>
*/
function data_set(mixed &$target, array|string $key, mixed $value, bool $overwrite = true): mixed
{
$segments = is_array($key) ? $key : explode('.', $key);
// Handle empty key
if (empty($segments) || (count($segments) === 1 && $segments[0] === '')) {
return $target;
}
// Store original reference for return
$original = &$target;
// Convert non-array/object to array at the start
if (!is_array($target) && !is_object($target)) {
$target = [];
}
foreach ($segments as $i => $segment) {
unset($segments[$i]);
if (is_array($target)) {
if (count($segments)) {
if ( ! array_key_exists($segment, $target)) {
$target[$segment] = [];
}
$target = &$target[$segment];
} else {
if ($overwrite || ! isset($target[$segment])) {
$target[$segment] = $value;
}
}
} elseif (is_object($target)) {
if (count($segments)) {
if ( ! isset($target->{$segment})) {
$target->{$segment} = new stdClass();
}
$target = &$target->{$segment};
} else {
if ($overwrite || ! isset($target->{$segment})) {
$target->{$segment} = $value;
}
}
}
}
return $original;
}
}
if ( ! function_exists('encrypt')) {
/**
* Encrypt the given value.
*
* This function encrypts a given value using AES-256-CBC encryption.
* The encrypted value is base64 encoded for safe storage and transmission.
* The encryption key is retrieved from the environment variables.
*
* @param mixed $value The value to encrypt.
* @param bool $serialize Whether to serialize the value before encryption. Default is true.
*
* @return string The encrypted value, base64 encoded.
*
* @throws Exception If the encryption key is not set or encryption fails.
* @example
* <code>
* $encrypted = encrypt('my_secret_value'); // Returns the encrypted string
* </code>
*
* Usage:
* 1. Ensure the APP_KEY is set in your environment variables (e.g., in the .env file).
* 2. Use the encrypt() function to encrypt any value.
* Example: $encryptedValue = encrypt('my_secret_value');
*
*/
function encrypt(mixed $value, bool $serialize = true): string
{
$key = env('APP_KEY');
if (empty($key)) {
throw new Exception("Encryption key not set.");
}
// Handle base64 encoded keys (Laravel-style)
if (strpos($key, 'base64:') === 0) {
$key = base64_decode(substr($key, 7));
}
// Validate key length (32 bytes for AES-256)
if (strlen($key) < 32) {
throw new Exception("Encryption key must be at least 32 bytes.");
}
// Use HKDF for proper key derivation
$salt = 'encryption-salt';
$authKey = hash_hkdf('sha256', $key, 32, 'auth-key', $salt);
$encKey = hash_hkdf('sha256', $key, 32, 'enc-key', $salt);
$iv = random_bytes(openssl_cipher_iv_length('AES-256-CBC'));
$value = $serialize ? serialize($value) : $value;
$encrypted = openssl_encrypt($value, 'AES-256-CBC', $encKey, OPENSSL_RAW_DATA, $iv);
if ($encrypted === false) {
throw new Exception("Encryption failed.");
}
$mac = hash_hmac('sha256', $iv . $encrypted, $authKey, true);
// Combine IV, MAC, and Ciphertext. Base64 encode the whole payload.
return base64_encode($iv . $mac . $encrypted);
}
}
if ( ! function_exists('decrypt')) {
/**
* Decrypt the given value.
*
* This function decrypts a given encrypted value that was encrypted using AES-256-CBC.
* The input value should be a base64 encoded string.
* The encryption key is retrieved from the environment variables.
*
* @param string $value The encrypted value to decrypt, base64 encoded.
* @param bool $unserialize Whether to unserialize the value after decryption. Default is true.
*
* @return mixed The decrypted value.
*
* @throws Exception If the encryption key is not set or decryption fails.
* @example
* <code>
* $decrypted = decrypt($encryptedValue); // Returns the decrypted value
* </code>
*
* Usage:
* 1. Ensure the APP_KEY is set in your environment variables (e.g., in the .env file).
* 2. Use the decrypt() function to decrypt any value that was encrypted with encrypt().
* Example: $decryptedValue = decrypt($encryptedValue);
*
*/
function decrypt(string $payload, bool $unserialize = true): mixed
{
$key = env('APP_KEY');
if (empty($key)) {
throw new Exception("Encryption key not set.");
}
// Handle base64 encoded keys (Laravel-style)
if (strpos($key, 'base64:') === 0) {
$key = base64_decode(substr($key, 7));
}
// Validate key length (32 bytes for AES-256)
if (strlen($key) < 32) {
throw new Exception("Encryption key must be at least 32 bytes.");
}
// Use HKDF for proper key derivation (must match encrypt function)
$salt = 'encryption-salt';
$authKey = hash_hkdf('sha256', $key, 32, 'auth-key', $salt);
$encKey = hash_hkdf('sha256', $key, 32, 'enc-key', $salt);
$decoded = base64_decode($payload);
if ($decoded === false) {
throw new Exception("Decryption failed: Invalid payload.");
}
$ivLength = openssl_cipher_iv_length('AES-256-CBC');
$macLength = 32; // SHA256 outputs 32 bytes
if (strlen($decoded) < $ivLength + $macLength) {
throw new Exception("Decryption failed: Invalid payload.");
}
$iv = substr($decoded, 0, $ivLength);
$storedMac = substr($decoded, $ivLength, $macLength);
$encrypted = substr($decoded, $ivLength + $macLength);
$calculatedMac = hash_hmac('sha256', $iv . $encrypted, $authKey, true);
if ( ! hash_equals($storedMac, $calculatedMac)) {
throw new Exception("Decryption failed: Invalid payload.");
}
$decrypted = openssl_decrypt($encrypted, 'AES-256-CBC', $encKey, OPENSSL_RAW_DATA, $iv);
if ($decrypted === false) {
throw new Exception("Decryption failed.");
}
return $unserialize ? unserialize($decrypted) : $decrypted;
}
}
if ( ! function_exists('info')) {
/**
* Log an informational message.
*
* @param string $message The message to log.
* @param array $context An array of context information. Default is an empty array.
*
* @return void
*
* @example
* <code>
* info('User logged in', ['user_id' => 123]); // Logs the message with context
* </code>
*/
function info(string $message, array $context = []): void
{
logger('info', $message, $context);
}
}
if ( ! function_exists('logger')) {
/**
* Log a message.
*
* This function logs a message to a file. Each log entry includes a timestamp, log level, message, and optional context information.
* Logs are stored in files within a specified directory, with a new log file created for each day.
*
* Usage:
* 1. Ensure the logs directory exists or can be created by the function.
* By default, the logs directory is '/logs' within the document root.
* The function will attempt to create this directory if it does not exist.
*
* 2. Log a message:
* logger('info', 'User logged in', ['user_id' => 123]); // Logs an info message with context
* logger('error', 'An error occurred'); // Logs an error message
*
* Directory Permissions:
* - The logs directory must be writable by the web server.
* - The function attempts to create the directory with 0777 permissions if it does not exist.
*
* Log File Naming:
* - Log files are named based on the date they are created (e.g., '2024-06-01.log').
* - A new log file is created each day.
*
* Log Entry Format:
* - Each log entry includes a timestamp, log level, message, and optional context information in JSON format.
*
* @param string $level The log level (e.g., 'info', 'error').
* @param string $message The message to log.
* @param array $context An array of context information. Default is an empty array.
*
* @return void
*
* @example
* <code>
* // Log an informational message with context
* logger('info', 'User logged in', ['user_id' => 123]);
*
* // Log an error message without context
* logger('error', 'An error occurred');
* </code>
*/
function logger(string $level, string $message, array $context = []): void
{
// Define the log directory within the document root
$logDir = server('DOCUMENT_ROOT') . '/logs';
// Ensure the log directory exists or create it with 0777 permissions
if ( ! file_exists($logDir)) {
mkdir($logDir, 0777, true);
}
// Define the log file path, creating a new log file each day
$logFile = $logDir . '/' . date('Y-m-d') . '.log';