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