Completed
Push — master ( 98eea6...214a1e )
by Damian
15s
created

Image::getCMSFields()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 6

Duplication

Lines 0
Ratio 0 %
Metric Value
dl 0
loc 8
rs 9.4285
cc 1
eloc 6
nc 1
nop 0
1
<?php
2
3
/**
4
 * Represents an Image
5
 *
6
 * @package framework
7
 * @subpackage filesystem
8
 */
9
class Image extends File implements ShortcodeHandler {
10
11
	public function __construct($record = null, $isSingleton = false, $model = null, $queryParams = array()) {
12
		parent::__construct($record, $isSingleton, $model, $queryParams);
13
		$this->File->setAllowedCategories('image/supported');
14
	}
15
16
	public function getCMSFields() {
17
		$fields = parent::getCMSFields();
18
		$fields->insertAfter(
19
			'LastEdited',
20
			new ReadonlyField("Dimensions", _t('AssetTableField.DIM','Dimensions') . ':')
21
		);
22
		return $fields;
23
	}
24
25
	public function getIsImage() {
26
		return true;
27
	}
28
29
	/**
30
	 * Replace"[image id=n]" shortcode with an image reference.
31
	 * Permission checks will be enforced by the file routing itself.
32
	 *
33
	 * @param array $args Arguments passed to the parser
34
	 * @param string $content Raw shortcode
35
	 * @param ShortcodeParser $parser Parser
36
	 * @param string $shortcode Name of shortcode used to register this handler
37
	 * @param array $extra Extra arguments
38
	 * @return string Result of the handled shortcode
39
	 */
40
	public static function handle_shortcode($args, $content, $parser, $shortcode, $extra = array()) {
41
		// Find appropriate record, with fallback for error handlers
42
		$record = static::find_shortcode_record($args, $errorCode);
43
		if($errorCode) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $errorCode of type integer|null is loosely compared to true; this is ambiguous if the integer can be zero. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
44
			$record = static::find_error_record($errorCode);
45
		}
46
		if (!$record) {
47
			return null; // There were no suitable matches at all.
48
		}
49
50
		// Check if a resize is required
51
		$src = $record->Link();
52
		if($record instanceof Image) {
53
			$width = isset($args['width']) ? $args['width'] : null;
54
			$height = isset($args['height']) ? $args['height'] : null;
55
			$hasCustomDimensions = ($width && $height);
56
			if ($hasCustomDimensions && (($width != $record->getWidth()) || ($height != $record->getHeight()))) {
57
				$resized = $record->ResizedImage($width, $height);
58
				// Make sure that the resized image actually returns an image
59
				if($resized) {
60
					$src = $resized->getURL();
61
				}
62
			}
63
		}
64
65
		// Build the HTML tag
66
		$attrs = array_merge(
67
			// Set overrideable defaults
68
			['src' => '', 'alt' => $record->Title],
69
			// Use all other shortcode arguments
70
			$args,
71
			// But enforce some values
72
			['id' => '', 'src' => $src]
73
		);
74
75
		// Clean out any empty attributes
76
		$attrs = array_filter($attrs, function($v) {return (bool)$v;});
77
78
		// Condense to HTML attribute string
79
		$attrsStr = join(' ', array_map(function($name) use ($attrs) {
80
			return Convert::raw2att($name) . '="' . Convert::raw2att($attrs[$name]) . '"';
81
		}, array_keys($attrs)));
82
83
		return '<img ' . $attrsStr . ' />';
84
	}
85
86
	/**
87
	 * Regenerates "[image id=n]" shortcode with new src attribute prior to being edited within the CMS.
88
	 *
89
	 * @param array $args Arguments passed to the parser
90
	 * @param string $content Raw shortcode
91
	 * @param ShortcodeParser $parser Parser
92
	 * @param string $shortcode Name of shortcode used to register this handler
93
	 * @param array $extra Extra arguments
94
	 * @return string Result of the handled shortcode
95
	 */
96
	public static function regenerate_shortcode($args, $content, $parser, $shortcode, $extra = array()) {
0 ignored issues
show
Unused Code introduced by
The parameter $extra is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
97
		// Check if there is a suitable record
98
		$record = static::find_shortcode_record($args);
99
		if($record) {
100
			$args['src'] = $record->getURL();
101
		}
102
103
		// Rebuild shortcode
104
		$parts = array();
105
		foreach($args as $name => $value) {
106
			$htmlValue = Convert::raw2att($value ?: $name);
107
			$parts[] = sprintf('%s="%s"', $name, $htmlValue);
108
		}
109
		return sprintf("[%s %s]", $shortcode, implode(' ', $parts));
110
	}
111
112
	/**
113
	 * Helper method to regenerate all shortcode links.
114
	 *
115
	 * @param string $value HTML value
116
	 * @return string value with links resampled
117
	 */
118
	public static function regenerate_html_links($value) {
119
		// Create a shortcode generator which only regenerates links
120
		$regenerator = ShortcodeParser::get('regenerator');
121
		return $regenerator->parse($value);
122
	}
123
}
124