@recaptime-dev's working patches + fork for Phorge, a community fork of Phabricator. (Upstream dev and stable branches are at upstream/main and upstream/stable respectively.) hq.recaptime.dev/wiki/Phorge
phorge phabricator
at recaptime-dev/main 81 lines 2.1 kB view raw
1<?php 2 3final class PhabricatorJSONDocumentEngine 4 extends PhabricatorTextDocumentEngine { 5 6 const ENGINEKEY = 'json'; 7 8 public function getViewAsLabel(PhabricatorDocumentRef $ref) { 9 return pht('View as JSON'); 10 } 11 12 protected function getDocumentIconIcon(PhabricatorDocumentRef $ref) { 13 return 'fa-database'; 14 } 15 16 protected function getContentScore(PhabricatorDocumentRef $ref) { 17 18 $name = $ref->getName(); 19 if ($name !== null) { 20 if (preg_match('/\.json\z/', $name)) { 21 return 2000; 22 } 23 } 24 25 if ($ref->isProbablyJSON()) { 26 return 1750; 27 } 28 29 return 500; 30 } 31 32 protected function newDocumentContent(PhabricatorDocumentRef $ref) { 33 $raw_data = $this->loadTextData($ref); 34 35 try { 36 $data = phutil_json_decode($raw_data); 37 38 // See T13635. "phutil_json_decode()" always turns JSON into a PHP array, 39 // and we lose the distinction between "{}" and "[]". This distinction is 40 // important when rendering a document. 41 $data = json_decode($raw_data, false); 42 if (!$data) { 43 throw new PhabricatorDocumentEngineParserException( 44 pht( 45 'Failed to "json_decode(...)" JSON document after successfully '. 46 'decoding it with "phutil_json_decode(...).')); 47 } 48 49 if (preg_match('/^\s*\[/', $raw_data)) { 50 $content = id(new PhutilJSON())->encodeAsList($data); 51 } else { 52 $content = id(new PhutilJSON())->encodeFormatted($data); 53 } 54 55 $message = null; 56 $content = PhabricatorSyntaxHighlighter::highlightWithLanguage( 57 'json', 58 $content); 59 } catch (PhutilJSONParserException $ex) { 60 $message = $this->newMessage( 61 pht( 62 'This document is not valid JSON: %s', 63 $ex->getMessage())); 64 65 $content = $raw_data; 66 } catch (PhabricatorDocumentEngineParserException $ex) { 67 $message = $this->newMessage( 68 pht( 69 'Unable to parse this document as JSON: %s', 70 $ex->getMessage())); 71 72 $content = $raw_data; 73 } 74 75 return array( 76 $message, 77 $this->newTextDocumentContent($ref, $content), 78 ); 79 } 80 81}