magnific_popup_field_formatter_prepare_view()   F
last analyzed

Complexity

Conditions 16
Paths 418

Size

Total Lines 79
Code Lines 43

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 16
eloc 43
c 1
b 0
f 0
nc 418
nop 7
dl 0
loc 79
rs 2.2083

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
/**
4
 * @file magnific_popup/includes/magnific_popup.formatters.inc
5
 *
6
 * Formatters for Magnific Popup.
7
 */
8
9
/**
10
 * Implements hook_field_formatter_info().
11
 */
12
function magnific_popup_field_formatter_info() {
13
  $gallery_options = _magnific_popup_gallery_options();
14
  return [
15
    'magnific_popup_file_field_formatter' => [
16
        'label' => t('Magnific Popup'),
0 ignored issues
show
Bug introduced by
The function t was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

16
        'label' => /** @scrutinizer ignore-call */ t('Magnific Popup'),
Loading history...
17
        'field types' => ['file', 'image'],
18
        'settings'  => [
19
        'gallery_style' => key($gallery_options)
20
        ]
21
    ]
22
  ];
23
}
24
25
/**
26
 * Implements hook_field_formatter_settings_form().
27
 * @param $field
28
 * @param $instance
29
 * @param $view_mode
30
 * @param $form
31
 * @param $form_state
32
 * @return array
33
 */
34
function magnific_popup_field_formatter_settings_form($field, $instance, $view_mode, $form, &$form_state) {
35
  $display = $instance['display'][$view_mode];
36
  $settings = $display['settings'];
37
  
38
  // Gallery Mode is TRUE when this field supports multiple items.
39
  $gallery_available = 1 !== $field['cardinality'];
40
  $gallery_options = _magnific_popup_gallery_options();
41
  
42
  $element = [];
43
  $element['gallery_available'] = [
44
    '#type' => 'markup',
45
    '#prefix' => '<p>',
46
    '#suffix' => '</p>'
47
  ];
48
  $element['gallery_available']['#markup'] = $gallery_available ?
49
    t('This field configuration <strong>supports multiple items</strong> and can display itself as a gallery of items!') : 
0 ignored issues
show
Bug introduced by
The function t was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

49
    /** @scrutinizer ignore-call */ 
50
    t('This field configuration <strong>supports multiple items</strong> and can display itself as a gallery of items!') : 
Loading history...
50
    t('This field configuration <strong>does not support multiple items</strong> and cannot display itself as a gallery of items.');
51
  $element['gallery_style'] = [
52
    '#type' => 'select',
53
    '#title' => t('Gallery Type'),
54
    '#options' => $gallery_options,
55
    '#disabled' => !$gallery_available,
56
    '#default_value' => $settings['gallery_style'],
57
    '#description' => t('Choose how this gallery displays its triggering element(s).')
58
  ];
59
  return $element;
60
}
61
62
/**
63
 * Implements hook_field_formatter_settings_summary().
64
 * @param $field
65
 * @param $instance
66
 * @param $view_mode
67
 * @return
68
 */
69
function magnific_popup_field_formatter_settings_summary($field, $instance, $view_mode) {
70
  $display = $instance['display'][$view_mode];
71
  $settings = $display['settings'];
72
  $gallery_options = _magnific_popup_gallery_options();
73
  $summary = t('Gallery Type: @gallery_type', ['@gallery_type' => $gallery_options[$settings['gallery_style']]]);
0 ignored issues
show
Bug introduced by
The function t was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

73
  $summary = /** @scrutinizer ignore-call */ t('Gallery Type: @gallery_type', ['@gallery_type' => $gallery_options[$settings['gallery_style']]]);
Loading history...
74
  return $summary;
75
}
76
77
/**
78
 * Implements hook_field_formatter_prepare_view().
79
 * @param $entity_type
80
 * @param $entities
81
 * @param $field
82
 * @param $instances
83
 * @param $langcode
84
 * @param $items
85
 * @param $displays
86
 */
87
function magnific_popup_field_formatter_prepare_view($entity_type, $entities, $field, $instances, $langcode, &$items, $displays) {
88
  // Items are some kind of entity reference, be it via image or file type.
89
  // Load the corresponding items into a common format for our formatter_view().
90
  $static = &drupal_static(__FUNCTION__, ['loaded_items' => [], 'thumbnail_schemes' => NULL]);
0 ignored issues
show
Bug introduced by
The function drupal_static was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

90
  $static = &/** @scrutinizer ignore-call */ drupal_static(__FUNCTION__, ['loaded_items' => [], 'thumbnail_schemes' => NULL]);
Loading history...
91
  $loaded_items = &$static['loaded_items'];
92
  $thumbnail_schemes = &$static['thumbnail_schemes'];
93
  if (!isset($thumbnail_schemes)) {
94
    $thumbnail_schemes = module_invoke_all('magnific_popup_thumbnail_schemes');
0 ignored issues
show
Bug introduced by
The function module_invoke_all was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

94
    $thumbnail_schemes = /** @scrutinizer ignore-call */ module_invoke_all('magnific_popup_thumbnail_schemes');
Loading history...
95
  }
96
  // Iterate through $items looking for valid gallery items. Refactor them into
97
  // a consistent format for magnific_popup_field_formatter_view().
98
  $wrappers = [];
99
  foreach ($entities as $entity_id => $entity) {
100
    foreach ($items[$entity_id] as $delta => &$item) {
101
      // Fail-safe check to not load items 
102
      if (empty($item['uri'])) {
103
        continue;
104
      }
105
      // Check if we've already parsed this fid, and build it if not.
106
      if (!isset($loaded_items[$item['fid']])) {
107
        $loaded_items[$item['fid']] = FALSE;
108
        $scheme = file_uri_scheme($item['uri']);
0 ignored issues
show
Bug introduced by
The function file_uri_scheme was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

108
        $scheme = /** @scrutinizer ignore-call */ file_uri_scheme($item['uri']);
Loading history...
109
        // Attempt to re-use, or load from scratch, a wrapper for this scheme.
110
        if (empty($wrappers[$scheme])) {
111
          // Create a new wrapper.
112
          $wrappers[$scheme] = file_stream_wrapper_get_instance_by_uri($item['uri']);
0 ignored issues
show
Bug introduced by
The function file_stream_wrapper_get_instance_by_uri was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

112
          $wrappers[$scheme] = /** @scrutinizer ignore-call */ file_stream_wrapper_get_instance_by_uri($item['uri']);
Loading history...
113
        }
114
        else {
115
          // Attempt to re-use an existing wrapper.
116
          $wrappers[$scheme]->setUri($item['uri']);
117
        }
118
        // Check that the resource was accessible.
119
        if ($wrappers[$scheme] && FALSE !== $wrappers[$scheme]->url_stat($item['uri'], STREAM_URL_STAT_QUIET)) {
120
          $wrapper = $wrappers[$scheme];
121
          // Determine the file's info and store it.
122
          $thumbnail_path = FALSE;
123
          // MediaYouTubeStreamWrapper implements getLocalThumbnailPath() to
124
          // find the thumbnail path.
125
          if (method_exists($wrapper,'getLocalThumbnailPath')) {
126
            $thumbnail_path = $wrapper->getLocalThumbnailPath();
127
          }
128
          // Try the standard method to get a thumbnail.
129
          else {
130
            if ($uri = $wrapper->getUri()) {
131
              $thumbnail_path = $uri;
132
            }
133
          }
134
          // Adjust $thumbnail_path based on the $scheme.
135
          // @todo Make the default thumbnail_style configurable.
136
          $thumbnail_style = 'magnific_popup_thumbnail';
137
          if (!empty($thumbnail_schemes[$scheme])) {
138
            $thumbnail_style = $thumbnail_schemes[$scheme];
139
          }
140
          $thumbnail_path = image_style_url($thumbnail_style, $thumbnail_path);
0 ignored issues
show
Bug introduced by
The function image_style_url was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

140
          $thumbnail_path = /** @scrutinizer ignore-call */ image_style_url($thumbnail_style, $thumbnail_path);
Loading history...
141
          // Get the title if it exists, or fallback to the filename.
142
          $title = !empty($item['title']) ? $item['title'] : $item['filename'];
143
          // Get the alt if it exists, or fallback to the title.
144
          $alt = !empty($item['alt']) ? $item['alt'] : $title;
145
          // Build the finished gallery item.
146
          $gallery_item = [
147
            'item' => $item,
148
            'title' => $title,
149
            'alt' => $alt,
150
            'thumbnail_path' => $thumbnail_path,
151
            'target_uri' => $wrapper->getExternalUrl()
152
          ];
153
          $loaded_items[$item['fid']] = $gallery_item;
154
        }
155
      }
156
      // Replace $item with the parsed version of info for this fid.
157
      $item = $loaded_items[$item['fid']];
158
      // Check if this item was unloadable and if so remove it from the list.
159
      if (empty($item)) {
160
        unset($items[$entity_id][$delta]);
161
      }
162
    }
163
    // Remove the pointer.
164
    if (isset($item)) {
165
      unset($item);
166
    }
167
  }
168
}
169
170
/**
171
 * Implements hook_field_formatter_view().
172
 * @param $entity_type
173
 * @param $entity
174
 * @param $field
175
 * @param $instance
176
 * @param $langcode
177
 * @param $items
178
 * @param $display
179
 * @return array
180
 */
181
function magnific_popup_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
182
  if (!_magnific_popup_check_status()) {
183
    return FALSE;
0 ignored issues
show
Bug Best Practice introduced by
The expression return FALSE returns the type false which is incompatible with the documented return type array.
Loading history...
184
  }
185
  // Add Magnific Popup library to page.
186
  drupal_add_library('magnific_popup', 'magnific_popup_formatter', FALSE);
0 ignored issues
show
Bug introduced by
The function drupal_add_library was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

186
  /** @scrutinizer ignore-call */ 
187
  drupal_add_library('magnific_popup', 'magnific_popup_formatter', FALSE);
Loading history...
187
  // Add API-derived extension JavaScript to the page; we do this here instead
188
  // of another hook to prevent adding JS when it isn't necessary (i.e. when we
189
  // aren't actually displaying any Magnific Popup content on the page).
190
  _magnific_popup_add_api_js();
191
  // Create the main container.
192
  $element = [];
193
  $settings = $display['settings'];
194
  $popup_gallery = [
195
    '#type' => 'container',
196
    '#attributes' => [
197
      'class' => []
198
    ]
199
  ];
200
  // Determine if/what the allowed trigger item is (which will get a thumbnail).
201
  $trigger_item = key($items);
202
  if ('random_item' === $settings['gallery_style']) {
203
    $trigger_item = array_rand($items);
204
  }
205
  // Figure out the base-class for the gallery/nogallery, which is generally
206
  // something like 'mfp-nogallery-image' or 'mfp-gallery-iframe'.
207
  $gallery_base_class = 'no_gallery' === $settings['gallery_style'] ?
208
    'mfp-nogallery' : 'mfp-gallery';
209
  if ('image' === $field['type']) {
210
    $gallery_base_class .= '-image';
211
  }
212
  else {
213
    $gallery_base_class .= '-iframe';
214
  }
215
  $popup_gallery['#attributes']['class'][] = $gallery_base_class;
216
  // Add each item to our container.
217
  foreach ($items as $delta => $item) {
218
    $popup_gallery['item-' . $delta] = [
219
      '#theme' => 'link',
220
      '#text' => '',
221
      '#path' => $item['target_uri'],
222
      '#options' => [
223
          'attributes' => ['class' => [], 'style' => []],
224
          'html' => TRUE
225
      ]
226
    ];
227
    $popup_gallery['item-' . $delta]['#options']['attributes']['class'][] = 'mfp-item';
228
    // This item has a thumbnail image if:
229
    //  - the Gallery Type is "all items" (because all items have thumbs), or
230
    //  - the Gallery Type is "no gallery", or
231
    //  - the Gallery Type is "first item" and this $delta is the first item, or
232
    //  - the Gallery Type is "random item" and this $delta is the random item.
233
    if ('all_items' === $settings['gallery_style'] || 'no_gallery' === $settings['gallery_style'] || $delta == $trigger_item) {
234
      $image = [
235
          // Try to use a "figure" theme implementation if it exists, or fall back
236
          // to "image".
237
          '#theme' => ['figure', 'image'],
238
          '#path' => $item['thumbnail_path'],
239
          '#alt' => $item['alt'],
240
          '#title' => $item['title'],
241
          '#attributes' => [
242
          'class' => ['mfp-thumbnail']
243
          ]
244
      ];
245
      $popup_gallery['item-' . $delta]['#text'] = render($image);
0 ignored issues
show
Bug introduced by
The function render was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

245
      $popup_gallery['item-' . $delta]['#text'] = /** @scrutinizer ignore-call */ render($image);
Loading history...
246
    }
247
    else {
248
      $popup_gallery['item-' . $delta]['#options']['attributes']['style'][] = 'display: none;';
249
    }
250
  }
251
  if (count($items)) {
252
    $element[0] = $popup_gallery;
253
  }
254
  // dpm(array(
255
    // 'function' => __function__,
256
    // 'entity_type' => $entity_type,
257
    // 'entity' => $entity,
258
    // 'field' => $field,
259
    // 'instance' => $instance,
260
    // 'langcode' => $langcode,
261
    // 'items' => $items,
262
    // 'display' => $display,
263
  // ));
264
  return $element;
265
}
266
267
/**
268
 * @return array
269
 */
270
function _magnific_popup_gallery_options() {
271
  return [
272
    'all_items' => t('Gallery: All Items Displayed'),
0 ignored issues
show
Bug introduced by
The function t was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

272
    'all_items' => /** @scrutinizer ignore-call */ t('Gallery: All Items Displayed'),
Loading history...
273
    'first_item' => t('Gallery: First Item Displayed'),
274
    'random_item' => t('Gallery: Random Item Displayed'),
275
    'no_gallery' => t('No Gallery: Display Each Item Separately')
276
  ];
277
}
278