3 namespace Wikimedia\Purtle;
6 * RdfWriter implementation for generating Turtle output.
9 * @author Daniel Kinzler
11 class TurtleRdfWriter extends N3RdfWriterBase {
15 private $trustIRIs = true;
20 public function getTrustIRIs() {
21 return $this->trustIRIs;
25 * @param bool $trustIRIs
27 public function setTrustIRIs( $trustIRIs ) {
28 $this->trustIRIs = $trustIRIs;
31 public function __construct(
32 $role = parent::DOCUMENT_ROLE,
33 BNodeLabeler $labeler = null,
34 N3Quoter $quoter = null
36 parent::__construct( $role, $labeler, $quoter );
37 $this->transitionTable[self::STATE_OBJECT] = [
38 self::STATE_DOCUMENT => " .\n",
39 self::STATE_SUBJECT => " .\n\n",
40 self::STATE_PREDICATE => " ;\n\t",
41 self::STATE_OBJECT => ",\n\t\t",
43 $this->transitionTable[self::STATE_DOCUMENT][self::STATE_SUBJECT] = "\n";
44 $this->transitionTable[self::STATE_SUBJECT][self::STATE_PREDICATE] = ' ';
45 $this->transitionTable[self::STATE_PREDICATE][self::STATE_OBJECT] = ' ';
46 $this->transitionTable[self::STATE_START][self::STATE_DOCUMENT] = function () {
47 $this->beginDocument();
54 private function beginDocument() {
55 foreach ( $this->getPrefixes() as $prefix => $uri ) {
56 $this->write( "@prefix $prefix: <" . $this->quoter->escapeIRI( $uri ) . "> .\n" );
60 protected function writeSubject( $base, $local = null ) {
61 if ( $local !== null ) {
62 $this->write( "$base:$local" );
64 $this->writeIRI( $base, $this->trustIRIs );
68 protected function writePredicate( $base, $local = null ) {
69 if ( $base === 'a' ) {
73 if ( $local !== null ) {
74 $this->write( "$base:$local" );
76 $this->writeIRI( $base, $this->trustIRIs );
80 protected function writeResource( $base, $local = null ) {
81 if ( $local !== null ) {
82 $this->write( "$base:$local" );
84 $this->writeIRI( $base );
90 * @param BNodeLabeler $labeler
92 * @return RdfWriterBase
94 protected function newSubWriter( $role, BNodeLabeler $labeler ) {
95 $writer = new self( $role, $labeler, $this->quoter );
101 * @return string a MIME type
103 public function getMimeType() {
104 return 'text/turtle; charset=UTF-8';