@@ -163,7 +163,7 @@ public function isBrewServiceRunning(string $name, bool $exactMatch = true): boo
163163 public function isBrewServiceRunningAsRoot (string $ name , bool $ exactMatch = true ): bool
164164 {
165165 if (! $ this ->brewServicesRootOutput ) {
166- $ this ->brewServicesRootOutput = json_decode ( $ this ->cli -> run ('brew services info --all --json ' ), false );
166+ $ this ->brewServicesRootOutput = $ this ->jsonFromCli ('brew services info --all --json ' , true );
167167 }
168168
169169 return $ this ->isBrewServiceRunningGivenServiceList ($ this ->brewServicesRootOutput , $ name , $ exactMatch );
@@ -172,12 +172,26 @@ public function isBrewServiceRunningAsRoot(string $name, bool $exactMatch = true
172172 public function isBrewServiceRunningAsUser (string $ name , bool $ exactMatch = true ): bool
173173 {
174174 if (! $ this ->brewServicesUserOutput ) {
175- $ this ->brewServicesUserOutput = json_decode ( $ this ->cli -> runAsUser ('brew services info --all --json ' ) , false );
175+ $ this ->brewServicesUserOutput = $ this ->jsonFromCli ('brew services info --all --json ' , false );
176176 }
177177
178178 return $ this ->isBrewServiceRunningGivenServiceList ($ this ->brewServicesUserOutput , $ name , $ exactMatch );
179179 }
180180
181+ public function jsonFromCli (string $ input , bool $ sudo = false ): array
182+ {
183+ $ contents = $ sudo ? $ this ->cli ->run ($ input ) : $ this ->cli ->runAsUser ($ input );
184+ // Skip to the JSON, to avoid warnings; we're only getting arrays so start with [
185+ $ contents = substr ($ contents , strpos ($ contents , '[ ' ));
186+
187+ try {
188+ return json_decode ($ contents , false , 512 , JSON_THROW_ON_ERROR );
189+ } catch (\Throwable $ e ) {
190+ $ command = $ sudo ? 'sudo ' .$ input : $ input ;
191+ throw new \Exception ('Invalid JSON returned from command: ' .$ command );
192+ }
193+ }
194+
181195 protected function isBrewServiceRunningGivenServiceList (array $ serviceList , string $ name , bool $ exactMatch = true ): bool
182196 {
183197 foreach ($ serviceList as $ service ) {
0 commit comments