Debian Codegraph @

lib/3rdParty/composer/mtdowling/jmespath.php/src/Env.php

raw symbols SCIP
1 <?php
2 namespace JmesPath;
3
4 /**
5 * Provides a simple environment based search.
6 *
7 * The runtime utilized by the Env class can be customized via environment
8 * variables. If the JP_PHP_COMPILE environment variable is specified, then the
9 * CompilerRuntime will be utilized. If set to "on", JMESPath expressions will
10 * be cached to the system's temp directory. Set the environment variable to
11 * a string to cache expressions to a specific directory.
12 */
13 final class Env
14 {
15 const COMPILE_DIR = 'JP_PHP_COMPILE';
16
17 /**
18 * Returns data from the input array that matches a JMESPath expression.
19 *
20 * @param string $expression JMESPath expression to evaluate
21 * @param mixed $data JSON-like data to search
22 *
23 * @return mixed Returns the matching data or null
24 */
25 public static function search($expression, $data)
26 {
27 static $runtime;
28
29 if (!$runtime) {
30 $runtime = Env::createRuntime();
31 }
32
33 return $runtime($expression, $data);
34 }
35
36 /**
37 * Creates a JMESPath runtime based on environment variables and extensions
38 * available on a system.
39 *
40 * @return callable
41 */
42 public static function createRuntime()
43 {
44 switch ($compileDir = self::getEnvVariable(self::COMPILE_DIR)) {
45 case false: return new AstRuntime();
46 case 'on': return new CompilerRuntime();
47 default: return new CompilerRuntime($compileDir);
48 }
49 }
50
51 /**
52 * Delete all previously compiled JMESPath files from the JP_COMPILE_DIR
53 * directory or sys_get_temp_dir().
54 *
55 * @return int Returns the number of deleted files.
56 */
57 public static function cleanCompileDir()
58 {
59 $total = 0;
60 $compileDir = self::getEnvVariable(self::COMPILE_DIR);
61 if ($compileDir === 'on' || !$compileDir) {
62 $compileDir = sys_get_temp_dir();
63 }
64
65 foreach (glob("{$compileDir}/jmespath_*.php") as $file) {
66 $total++;
67 unlink($file);
68 }
69
70 return $total;
71 }
72
73 /**
74 * Reads an environment variable from $_SERVER, $_ENV or via getenv().
75 *
76 * @param string $name
77 *
78 * @return string|null
79 */
80 private static function getEnvVariable($name)
81 {
82 if (array_key_exists($name, $_SERVER)) {
83 return $_SERVER[$name];
84 }
85
86 if (array_key_exists($name, $_ENV)) {
87 return $_ENV[$name];
88 }
89
90 $value = getenv($name);
91
92 return $value === false ? null : $value;
93 }
94 }