Completed
Push — master ( 4cfef8...0aaff2 )
by
unknown
08:02
created

ExifPropertyAnnotator::addAnnotation()   B

Complexity

Conditions 7
Paths 6

Size

Total Lines 39

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 19
CRAP Score 7.1243

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 39
ccs 19
cts 22
cp 0.8636
rs 8.3626
cc 7
nc 6
nop 2
crap 7.1243
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 9
	public function __construct( AppFactory $appFactory ) {
50 9
		$this->appFactory = $appFactory;
51 9
	}
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 7
	public function addAnnotation( DIProperty $property, SemanticData $semanticData ) {
68
69 7
		$subject = $semanticData->getSubject();
70 7
		$title = $subject->getTitle();
71
72 7
		if ( !$title->inNamespace( NS_FILE ) ) {
73
			return;
74
		}
75
76 7
		$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 7
		$file = $page->getFile();
78
79 7
		if ( !$file->exists() ) {
80 1
			return;
81
		}
82
83
		// #66
84 6
		$meta = $file->getMetadata();
85
86 6
		if ( !$meta ) {
87
			return false;
88
		}
89
90
		// Guard against "Error at offset 0 of 1 bytes"
91 6
		$exif = @unserialize( $meta );
92
93 6
		if ( !is_array( $exif ) || count( $exif ) === 0 ) {
94
			return;
95
		}
96
97 6
		$exif['ImageWidth']  = $file->getWidth();
98 6
		$exif['ImageLength'] = $file->getHeight();
99
100 6
		$dataItem = $this->getDataItemFromExifData( $subject, $exif );
101
102 6
		if ( $dataItem instanceof DataItem ) {
103 4
			$semanticData->addPropertyObjectValue( $property, $dataItem );
104 4
		}
105 6
	}
106
107 6
	protected function getDataItemFromExifData( $subject, $rawExif ) {
108
109 6
		$containerSemanticData = $this->newContainerSemanticData(
110
			$subject
111 6
		);
112
113 6
		$this->addExifDataTo( $containerSemanticData, $rawExif );
114
115 6
		if ( $containerSemanticData->isEmpty() ) {
116 2
			return;
117
		}
118
119 4
		return new DIContainer( $containerSemanticData );
120
	}
121
122 6
	private function newContainerSemanticData( $subject ) {
123
124 6
		$subject = new DIWikiPage(
125 6
			$subject->getDBkey(),
126 6
			$subject->getNamespace(),
127 6
			$subject->getInterwiki(),
128
			'_EXIFDATA'
129 6
		);
130
131 6
		return new ContainerSemanticData( $subject );
132
	}
133
134 6
	private function addExifDataTo( $containerSemanticData, $rawExif ) {
135
136 6
		$exifDefinitions = $this->appFactory->getPropertyDefinitions()->safeGet( '_EXIF' );
137 6
		$formattedExif = FormatMetadata::getFormattedData( $rawExif );
138
139 6
		foreach ( $formattedExif as $key => $value ) {
140
141 6
			$dataItem = $this->createDataItemFromExif( $id, $key, $value, $rawExif, $exifDefinitions );
142
143 6
			if ( $dataItem instanceof DataItem ) {
144 4
				$containerSemanticData->addPropertyObjectValue( new DIProperty( $id ), $dataItem );
145 4
			}
146 6
		}
147 6
	}
148
149 6
	private function createDataItemFromExif( &$id, $key, $value, $rawExif, $exifDefinitions ) {
150
151 6
		$dataItem = null;
152 6
		$upKey = strtoupper( $key );
153
154 6
		if ( !isset( $exifDefinitions[$upKey] ) || !isset( $exifDefinitions[$upKey]['id'] ) ) {
155 6
			return;
156
		}
157
158 5
		$id = $exifDefinitions[$upKey]['id'];
159 5
		$type = $exifDefinitions[$upKey]['type'];
160
161
		switch ( $type ) {
162 5
			case '_num':
163
				$dataItem = is_numeric( $rawExif[$key] ) ? new DINumber( $rawExif[$key] ) : null;
164
				break;
165 5
			case '_txt':
166 1
				$dataItem = new DIBlob( $value );
167 1
				break;
168 4
			case '_dat':
169 4
				$dataItem = $this->makeDataItemTime( $rawExif[$key] );
170 4
		}
171
172 5
		return $dataItem;
173
	}
174
175 4
	private function makeDataItemTime( $exifValue ) {
176 4
		$datetime = $this->convertExifDate( $exifValue );
177
178 4
		if ( $datetime ) {
179 3
			return new DITime(
180 3
				DITime::CM_GREGORIAN,
181 3
				$datetime->format('Y'),
182 4
				$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...
183 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...
184 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...
185 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...
186 3
			);
187
		}
188 1
	}
189
190 4
	private function convertExifDate( $exifString ) {
191
192
		// Unknown date
193 4
		if ( $exifString == '0000:00:00 00:00:00' || $exifString == '    :  :     :  :  ' ) {
194 1
			return false;
195
		}
196
197
		// Full date
198 3
		if ( preg_match( '/^(?:\d{4}):(?:\d\d):(?:\d\d) (?:\d\d):(?:\d\d):(?:\d\d)$/D', $exifString ) ) {
199 1
			return new \DateTime( $exifString );
200
		}
201
202
		// No second field, timeanddate doesn't include seconds but second still available in api
203 2
		if ( preg_match( '/^(?:\d{4}):(?:\d\d):(?:\d\d) (?:\d\d):(?:\d\d)$/D', $exifString ) ) {
204 1
			return new \DateTime( $exifString . ':00' );
205
		}
206
207
		// Only the date but not the time
208 1
		if (  preg_match( '/^(?:\d{4}):(?:\d\d):(?:\d\d)$/D', $exifString ) ) {
209 1
			return new \DateTime(
210 1
				substr( $exifString, 0, 4 ) . ':' .
211 1
				substr( $exifString, 5, 2 ) . ':' .
212 1
				substr( $exifString, 8, 2 ) . ' 00:00:00'
213 1
			);
214
		}
215
216
		return false;
217
	}
218
219
}
220