| 1 |
<?php |
| 2 |
|
| 3 |
namespace Wikimedia\Purtle; |
| 4 |
|
| 5 |
/** |
| 6 |
* Base class for RdfWriter implementations that output an N3 dialect. |
| 7 |
* |
| 8 |
* @license GPL-2.0-or-later |
| 9 |
* @author Daniel Kinzler |
| 10 |
*/ |
| 11 |
abstract class N3RdfWriterBase extends RdfWriterBase { |
| 12 |
|
| 13 |
/** |
| 14 |
* @var N3Quoter |
| 15 |
*/ |
| 16 |
protected $quoter; |
| 17 |
|
| 18 |
/** |
| 19 |
* @param string $role |
| 20 |
* @param BNodeLabeler|null $labeler |
| 21 |
* @param N3Quoter|null $quoter |
| 22 |
*/ |
| 23 |
public function __construct( |
| 24 |
$role = parent::DOCUMENT_ROLE, |
| 25 |
?BNodeLabeler $labeler = null, |
| 26 |
?N3Quoter $quoter = null |
| 27 |
) { |
| 28 |
parent::__construct( $role, $labeler ); |
| 29 |
|
| 30 |
$this->quoter = $quoter ?: new N3Quoter(); |
| 31 |
} |
| 32 |
|
| 33 |
/** |
| 34 |
* @param string $base |
| 35 |
* @param string|null $local |
| 36 |
*/ |
| 37 |
protected function writeRef( $base, $local = null ) { |
| 38 |
if ( $local === null ) { |
| 39 |
if ( $base === 'a' ) { |
| 40 |
$this->write( 'a' ); |
| 41 |
} else { |
| 42 |
$this->writeIRI( $base ); |
| 43 |
} |
| 44 |
} else { |
| 45 |
$this->write( "$base:$local" ); |
| 46 |
} |
| 47 |
} |
| 48 |
|
| 49 |
/** |
| 50 |
* @param string $iri |
| 51 |
* @param bool $trustIRI |
| 52 |
*/ |
| 53 |
protected function writeIRI( $iri, $trustIRI = false ) { |
| 54 |
if ( !$trustIRI ) { |
| 55 |
$iri = $this->quoter->escapeIRI( $iri ); |
| 56 |
} |
| 57 |
$this->write( "<$iri>" ); |
| 58 |
} |
| 59 |
|
| 60 |
/** |
| 61 |
* @inheritDoc |
| 62 |
*/ |
| 63 |
protected function writeText( $text, $language = null ) { |
| 64 |
$value = $this->quoter->escapeLiteral( $text ); |
| 65 |
$this->write( '"' . $value . '"' ); |
| 66 |
|
| 67 |
if ( $this->isValidLanguageCode( $language ) ) { |
| 68 |
$this->write( '@' . $language ); |
| 69 |
} |
| 70 |
} |
| 71 |
|
| 72 |
/** |
| 73 |
* @param string $value |
| 74 |
* @param string|null $typeBase |
| 75 |
* @param string|null $typeLocal |
| 76 |
*/ |
| 77 |
protected function writeValue( $value, $typeBase, $typeLocal = null ) { |
| 78 |
$value = $this->quoter->escapeLiteral( $value ); |
| 79 |
$this->write( '"' . $value . '"' ); |
| 80 |
|
| 81 |
if ( $typeBase !== null ) { |
| 82 |
$this->write( '^^' ); |
| 83 |
$this->writeRef( $typeBase, $typeLocal ); |
| 84 |
} |
| 85 |
} |
| 86 |
|
| 87 |
} |