ExifPropertyAnnotator::isAnnotatorFor()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 3
ccs 2
cts 2
cp 1
rs 10
cc 1
nc 1
nop 1
crap 1
1
<?php
2
3
namespace SESP\PropertyAnnotators;
4
5
use SESP\PropertyAnnotator;
6
use SESP\AppFactory;
7
use SMW\DIProperty;
8
use SMW\DIWikiPage;
9
use SMWContainerSemanticData as ContainerSemanticData;
10
use SMW\SemanticData;
11
use SMWDataItem as DataItem;
12
use SMWDIContainer as DIContainer;
13
use SMWDITime as DITime;
14
use SMWDINumber as DINumber;
15
use SMWDIBlob as DIBlob;
16
use FormatMetadata;
17
use RuntimeException;
18
19
/**
20
 * @private
21
 * @ingroup SESP
22
 *
23
 * @see http://www.exiv2.org/tags.html
24
 *
25
 * @license GNU GPL v2+
26
 * @since 2.0
27
 *
28
 * @author mwjames
29
 * @author rotsee
30
 * @author Stephan Gambke
31
 */
32
class ExifPropertyAnnotator implements PropertyAnnotator {
33
34
	/**
35
	 * Predefined property ID
36
	 */
37
	const PROP_ID = '___EXIFDATA';
38
39
	/**
40
	 * @var AppFactory
41
	 */
42
	private $appFactory;
43
44
	/**
45
	 * @since 2.0
46
	 *
47
	 * @param AppFactory $appFactory
48
	 */
49 10
	public function __construct( AppFactory $appFactory ) {
50 10
		$this->appFactory = $appFactory;
51 10
	}
52
53
	/**
54
	 * @since 2.0
55
	 *
56
	 * {@inheritDoc}
57
	 */
58 1
	public function isAnnotatorFor( DIProperty $property ) {
59 1
		return $property->getKey() === self::PROP_ID;
60
	}
61
62
	/**
63
	 * @since 2.0
64
	 *
65
	 * {@inheritDoc}
66
	 */
67 8
	public function addAnnotation( DIProperty $property, SemanticData $semanticData ) {
68
69 8
		$subject = $semanticData->getSubject();
70 8
		$title = $subject->getTitle();
71
72 8
		if ( !$title->inNamespace( NS_FILE ) ) {
73
			return;
74
		}
75
76 8
		$page = $this->appFactory->newWikiPage( $title );
0 ignored issues
show
Bug introduced by
It seems like $title defined by $subject->getTitle() on line 70 can be null; however, SESP\AppFactory::newWikiPage() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
77 8
		$file = $page->getFile();
78
79 8
		if ( !$file->exists() ) {
80 1
			return;
81
		}
82
83
		// #66
84 7
		$meta = $file->getMetadata();
85
86 7
		if ( !$meta ) {
87
			return false;
88
		}
89
90
		// Guard against "Error at offset 0 of 1 bytes"
91 7
		$exif = @unserialize( $meta );
92
93 7
		if ( !is_array( $exif ) || count( $exif ) === 0 ) {
94
			return;
95
		}
96
97 7
		$exif['ImageWidth']  = $file->getWidth();
98 7
		$exif['ImageLength'] = $file->getHeight();
99
100 7
		$dataItem = $this->getDataItemFromExifData( $subject, $exif );
101
102 7
		if ( $dataItem instanceof DataItem ) {
103 4
			$semanticData->addPropertyObjectValue( $property, $dataItem );
104 4
		}
105 7
	}
106
107 7
	protected function getDataItemFromExifData( $subject, $rawExif ) {
108
109 7
		$containerSemanticData = $this->newContainerSemanticData(
110
			$subject
111 7
		);
112
113 7
		$this->addExifDataTo( $containerSemanticData, $rawExif );
114
115 7
		if ( $containerSemanticData->isEmpty() ) {
116 3
			return;
117
		}
118
119 4
		return new DIContainer( $containerSemanticData );
120
	}
121
122 7
	private function newContainerSemanticData( $subject ) {
123
124 7
		$subject = new DIWikiPage(
125 7
			$subject->getDBkey(),
126 7
			$subject->getNamespace(),
127 7
			$subject->getInterwiki(),
128
			'_EXIFDATA'
129 7
		);
130
131 7
		return new ContainerSemanticData( $subject );
132
	}
133
134 7
	private function addExifDataTo( $containerSemanticData, $rawExif ) {
135
136 7
		$exifDefinitions = $this->appFactory->getPropertyDefinitions()->safeGet( '_EXIF' );
137 7
		$formattedExif = FormatMetadata::getFormattedData( $rawExif );
138
139 7
		foreach ( $formattedExif as $key => $value ) {
140
141 7
			$dataItem = $this->createDataItemFromExif( $id, $key, $value, $rawExif, $exifDefinitions );
142
143 7
			if ( $dataItem instanceof DataItem ) {
144 4
				$containerSemanticData->addPropertyObjectValue( new DIProperty( $id ), $dataItem );
145 4
			}
146 7
		}
147 7
	}
148
149 7
	private function createDataItemFromExif( &$id, $key, $value, $rawExif, $exifDefinitions ) {
150
151 7
		$dataItem = null;
152 7
		$upKey = strtoupper( $key );
153
154 7
		if ( !isset( $exifDefinitions[$upKey] ) || !isset( $exifDefinitions[$upKey]['id'] ) ) {
155 7
			return;
156
		}
157
158 6
		$id = $exifDefinitions[$upKey]['id'];
159 6
		$type = $exifDefinitions[$upKey]['type'];
160
161
		switch ( $type ) {
162 6
			case '_num':
163
				$dataItem = is_numeric( $rawExif[$key] ) ? new DINumber( $rawExif[$key] ) : null;
164
				break;
165 6
			case '_txt':
166 1
				$dataItem = new DIBlob( $value );
167 1
				break;
168 5
			case '_dat':
169 5
				$dataItem = $this->makeDataItemTime( $rawExif[$key] );
170 5
		}
171
172 6
		return $dataItem;
173
	}
174
175 5
	private function makeDataItemTime( $exifValue ) {
176
177
		try {
178 5
			$datetime = $this->convertExifDate( $exifValue );
179 5
		} catch ( \Exception $e ) {
180 1
			$datetime = null;
181
		}
182
183 5
		if ( $datetime ) {
184 3
			return new DITime(
185 3
				DITime::CM_GREGORIAN,
186 3
				$datetime->format('Y'),
187 3
				$datetime->format('n'),
0 ignored issues
show
Documentation introduced by
$datetime->format('n') is of type string, but the function expects a boolean.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
188 3
				$datetime->format('j'),
0 ignored issues
show
Documentation introduced by
$datetime->format('j') is of type string, but the function expects a boolean.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
189 3
				$datetime->format('G'),
0 ignored issues
show
Documentation introduced by
$datetime->format('G') is of type string, but the function expects a boolean.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
190 3
				$datetime->format('i')
0 ignored issues
show
Documentation introduced by
$datetime->format('i') is of type string, but the function expects a boolean.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
191 3
			);
192
		}
193 2
	}
194
195 5
	private function convertExifDate( $exifString ) {
196
197
		// Unknown date
198 5
		if ( $exifString == '0000:00:00 00:00:00' || $exifString == '    :  :     :  :  ' ) {
199 1
			return false;
200
		}
201
202
		// Full date
203 4
		if ( preg_match( '/^(?:\d{4}):(?:\d\d):(?:\d\d) (?:\d\d):(?:\d\d):(?:\d\d)$/D', $exifString ) ) {
204 2
			return new \DateTime( $exifString );
205
		}
206
207
		// No second field, timeanddate doesn't include seconds but second still available in api
208 2
		if ( preg_match( '/^(?:\d{4}):(?:\d\d):(?:\d\d) (?:\d\d):(?:\d\d)$/D', $exifString ) ) {
209 1
			return new \DateTime( $exifString . ':00' );
210
		}
211
212
		// Only the date but not the time
213 1
		if (  preg_match( '/^(?:\d{4}):(?:\d\d):(?:\d\d)$/D', $exifString ) ) {
214 1
			return new \DateTime(
215 1
				substr( $exifString, 0, 4 ) . ':' .
216 1
				substr( $exifString, 5, 2 ) . ':' .
217 1
				substr( $exifString, 8, 2 ) . ' 00:00:00'
218 1
			);
219
		}
220
221
		return false;
222
	}
223
224
}
225