JsonFileInvalidException.php
3 years ago
JsonFileNotFoundException.php
3 years ago
ReadsJsonTrait.php
3 years ago
ReadsJsonTrait.php
83 lines
| 1 | <?php |
| 2 | /** |
| 3 | * @package SureCartAppCore |
| 4 | * @author SureCart <support@surecart.com> |
| 5 | * @copyright SureCart |
| 6 | * @license https://www.gnu.org/licenses/gpl-2.0.html GPL-2.0 |
| 7 | * @link https://surecart.com |
| 8 | */ |
| 9 | |
| 10 | namespace SureCartAppCore\Concerns; |
| 11 | |
| 12 | use SureCartCore\Support\Arr; |
| 13 | |
| 14 | trait ReadsJsonTrait { |
| 15 | /** |
| 16 | * Cache. |
| 17 | * |
| 18 | * @var array|null |
| 19 | */ |
| 20 | protected $cache = null; |
| 21 | |
| 22 | /** |
| 23 | * Get the path to the JSON that should be read. |
| 24 | * |
| 25 | * @return string |
| 26 | */ |
| 27 | abstract protected function getJsonPath(); |
| 28 | |
| 29 | /** |
| 30 | * Load the json file. |
| 31 | * |
| 32 | * @param string $file |
| 33 | * |
| 34 | * @return array |
| 35 | */ |
| 36 | protected function load( $file ) { |
| 37 | /** @var \WP_Filesystem_Base $wp_filesystem */ |
| 38 | global $wp_filesystem; |
| 39 | |
| 40 | require_once ABSPATH . '/wp-admin/includes/file.php'; |
| 41 | |
| 42 | WP_Filesystem(); |
| 43 | |
| 44 | if ( ! $wp_filesystem->exists( $file ) ) { |
| 45 | throw new JsonFileNotFoundException( 'The required ' . basename( $file ) . ' file is missing.' ); |
| 46 | } |
| 47 | |
| 48 | $contents = $wp_filesystem->get_contents( $file ); |
| 49 | $json = json_decode( $contents, true ); |
| 50 | $json_error = json_last_error(); |
| 51 | |
| 52 | if ( $json_error !== JSON_ERROR_NONE ) { |
| 53 | throw new JsonFileInvalidException( 'The required ' . basename( $file ) . ' file is not valid JSON (error code ' . $json_error . ').' ); |
| 54 | } |
| 55 | |
| 56 | return $json; |
| 57 | } |
| 58 | |
| 59 | /** |
| 60 | * Get the entire json array. |
| 61 | * |
| 62 | * @return array |
| 63 | */ |
| 64 | protected function getAll() { |
| 65 | if ( $this->cache === null ) { |
| 66 | $this->cache = $this->load( $this->getJsonPath() ); |
| 67 | } |
| 68 | |
| 69 | return $this->cache; |
| 70 | } |
| 71 | |
| 72 | /** |
| 73 | * Get a json value. |
| 74 | * |
| 75 | * @param string $key |
| 76 | * @param mixed $default |
| 77 | * @return mixed |
| 78 | */ |
| 79 | public function get( $key, $default = null ) { |
| 80 | return Arr::get( $this->getAll(), $key, $default ); |
| 81 | } |
| 82 | } |
| 83 |