1<?php 2 3 4namespace ComboStrap; 5 6 7class Json 8{ 9 10 const TYPE_OBJECT = "{"; 11 const PARENT_TYPE_ARRAY = "["; 12 const TAB_SPACES_COUNTER = 4; 13 const EXTENSION = "json"; 14 15 /** 16 * @var array 17 */ 18 private $jsonArray; 19 20 /** 21 * Json constructor. 22 * @param array|null $jsonValue 23 */ 24 public function __construct(?array $jsonValue = null) 25 { 26 $this->jsonArray = $jsonValue; 27 28 } 29 30 public static function createEmpty(): Json 31 { 32 return new Json([]); 33 } 34 35 public static function createFromArray(array $actual): Json 36 { 37 return new Json($actual); 38 } 39 40 public static function getValidationLink(string $json): string 41 { 42 return "See the errors it by clicking on <a href=\"https://jsonformatter.curiousconcept.com/?data=" . urlencode($json) . "\">this link</a>"; 43 } 44 45 /** 46 * Used to make diff 47 * @return false|string 48 */ 49 public function toNormalizedJsonString() 50 { 51 $jsonArray = $this->getJsonArray(); 52 if ($jsonArray === null) { 53 /** 54 * Edge case empty string 55 */ 56 return ""; 57 } 58 return json_encode($jsonArray, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES); 59 } 60 61 /** 62 * This formatting make the object on one line for a list of object 63 * making the frontmatter compacter (one line, one meta) 64 * @return string 65 * @deprecated You should use the {@link MetadataFrontmatterStore::toFrontmatterJsonString()} instead 66 */ 67 public function toFrontMatterFormat(): string 68 { 69 70 $jsonArray = $this->getJsonArray(); 71 return MetadataFrontmatterStore::toFrontmatterJsonString($jsonArray); 72 73 } 74 75 76 /** 77 * @throws ExceptionCombo 78 */ 79 public 80 static function createFromString($jsonString): Json 81 { 82 if($jsonString===null || $jsonString === "" ){ 83 return new Json(); 84 } 85 $jsonArray = json_decode($jsonString, true); 86 if ($jsonArray === null) { 87 throw new ExceptionCombo("The string is not a valid json. Value: ($jsonString)"); 88 } 89 return new Json($jsonArray); 90 } 91 92 /** 93 * @return mixed 94 */ 95 public 96 function toJsonObject() 97 { 98 $jsonString = $this->getJsonString(); 99 return json_decode($jsonString); 100 101 } 102 103 public 104 function toArray(): ?array 105 { 106 return $this->getJsonArray(); 107 108 } 109 110 public 111 function toPrettyJsonString() 112 { 113 return $this->toNormalizedJsonString(); 114 } 115 116 private 117 function getJsonString() 118 { 119 return json_encode($this->jsonArray, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES); 120 } 121 122 /** 123 * @return array|null 124 */ 125 private 126 function getJsonArray(): ?array 127 { 128 return $this->jsonArray; 129 } 130 131 public 132 function toMinifiedJsonString() 133 { 134 return json_encode($this->jsonArray); 135 } 136 137 138} 139