1<?php 2 3namespace Wikimedia\Purtle; 4 5/** 6 * RdfWriter implementation for generating Turtle output. 7 * 8 * @license GPL-2.0-or-later 9 * @author Daniel Kinzler 10 */ 11class TurtleRdfWriter extends N3RdfWriterBase { 12 13 /** 14 * @var bool 15 */ 16 private $trustIRIs = true; 17 18 /** 19 * @return bool 20 */ 21 public function getTrustIRIs() { 22 return $this->trustIRIs; 23 } 24 25 /** 26 * @param bool $trustIRIs 27 */ 28 public function setTrustIRIs( $trustIRIs ) { 29 $this->trustIRIs = $trustIRIs; 30 } 31 32 /** 33 * @param string $role 34 * @param BNodeLabeler|null $labeler 35 * @param N3Quoter|null $quoter 36 */ 37 public function __construct( 38 $role = parent::DOCUMENT_ROLE, 39 BNodeLabeler $labeler = null, 40 N3Quoter $quoter = null 41 ) { 42 parent::__construct( $role, $labeler, $quoter ); 43 $this->transitionTable[self::STATE_OBJECT] = [ 44 self::STATE_DOCUMENT => " .\n", 45 self::STATE_SUBJECT => " .\n\n", 46 self::STATE_PREDICATE => " ;\n\t", 47 self::STATE_OBJECT => ",\n\t\t", 48 ]; 49 $this->transitionTable[self::STATE_DOCUMENT][self::STATE_SUBJECT] = "\n"; 50 $this->transitionTable[self::STATE_SUBJECT][self::STATE_PREDICATE] = ' '; 51 $this->transitionTable[self::STATE_PREDICATE][self::STATE_OBJECT] = ' '; 52 $this->transitionTable[self::STATE_START][self::STATE_DOCUMENT] = function () { 53 $this->beginDocument(); 54 }; 55 } 56 57 /** 58 * Write prefixes 59 */ 60 private function beginDocument() { 61 foreach ( $this->getPrefixes() as $prefix => $uri ) { 62 $this->write( "@prefix $prefix: <" . $this->quoter->escapeIRI( $uri ) . "> .\n" ); 63 } 64 } 65 66 protected function writeSubject( $base, $local = null ) { 67 if ( $local !== null ) { 68 $this->write( "$base:$local" ); 69 } else { 70 $this->writeIRI( $base, $this->trustIRIs ); 71 } 72 } 73 74 protected function writePredicate( $base, $local = null ) { 75 if ( $base === 'a' ) { 76 $this->write( 'a' ); 77 return; 78 } 79 if ( $local !== null ) { 80 $this->write( "$base:$local" ); 81 } else { 82 $this->writeIRI( $base, $this->trustIRIs ); 83 } 84 } 85 86 protected function writeResource( $base, $local = null ) { 87 if ( $local !== null ) { 88 $this->write( "$base:$local" ); 89 } else { 90 $this->writeIRI( $base ); 91 } 92 } 93 94 /** 95 * @param string $role 96 * @param BNodeLabeler $labeler 97 * 98 * @return RdfWriterBase 99 */ 100 protected function newSubWriter( $role, BNodeLabeler $labeler ) { 101 $writer = new self( $role, $labeler, $this->quoter ); 102 103 return $writer; 104 } 105 106 /** 107 * @return string a MIME type 108 */ 109 public function getMimeType() { 110 return 'text/turtle; charset=UTF-8'; 111 } 112 113} 114