3 namespace Wikimedia\Purtle;
5 use InvalidArgumentException;
11 * @author Daniel Kinzler
13 class RdfWriterFactory {
16 * Returns a list of canonical format names.
17 * These names for internal use with getMimeTypes() and getFileExtension(),
18 * they are not themselves MIME types or file extensions.
22 public function getSupportedFormats() {
23 return [ 'n3', 'turtle', 'ntriples', 'rdfxml' ];
27 * Returns a list of mime types that correspond to the format.
29 * @param string $format a format name, as returned by getSupportedFormats() or getFormatName().
31 * @throws InvalidArgumentException if $format is not a cononical format name
34 public function getMimeTypes( $format ) {
35 //NOTE: Maintaining mime types and file extensions in the RdfWriter implementations
36 // is tempting, but means we have to load all these classes to find the right
37 // one for a requested name. Better avoid that overhead when serving lots of
40 switch ( strtolower( $format ) ) {
42 return [ 'text/n3', 'text/rdf+n3' ];
45 return [ 'text/turtle', 'application/x-turtle' ];
48 return [ 'application/n-triples', 'text/n-triples', 'text/plain' ];
51 return [ 'application/rdf+xml', 'application/xml', 'text/xml' ];
54 throw new InvalidArgumentException( 'Bad format: ' . $format );
59 * Returns a file extension that correspond to the format.
61 * @param string $format a format name, as returned by getSupportedFormats() or getFormatName().
63 * @throws InvalidArgumentException if $format is not a cononical format name
66 public function getFileExtension( $format ) {
67 switch ( strtolower( $format ) ) {
81 throw new InvalidArgumentException( 'Bad format: ' . $format );
86 * Returns an RdfWriter for the given format name.
88 * @param string $format a format name, as returned by getSupportedFormats() or getFormatName().
90 * @throws InvalidArgumentException if $format is not a cononical format name
91 * @return RdfWriter the format object, or null if not found.
93 public function getWriter( $format ) {
94 switch ( strtolower( $format ) ) {
96 // falls through to turtle
99 return new TurtleRdfWriter();
102 return new NTriplesRdfWriter();
105 return new XmlRdfWriter();
108 throw new InvalidArgumentException( 'Bad format: ' . $format );
113 * Returns the canonical format name for $format. $format may be a file extension,
114 * a mime type, or a common or canonical name of the format.
116 * If no format is found for $format, this method returns false.
118 * @param string $format the name (file extension, mime type) of the desired format.
120 * @return string|false the canonical format name
122 public function getFormatName( $format ) {
123 switch ( strtolower( $format ) ) {
132 case 'application/x-turtle':
139 case 'text/n-triples':
140 case 'application/ntriples':
141 case 'application/n-triples':
147 case 'application/rdf+xml':
148 case 'application/xml':