Completed
Pull Request — master (#123)
by
unknown
02:21
created

FileHandler::expand()   B

Complexity

Conditions 4
Paths 5

Size

Total Lines 27
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 0
loc 27
rs 8.5806
cc 4
eloc 17
nc 5
nop 1
1
<?php
2
3
namespace Drupal\Driver\Fields\Drupal8;
4
5
/**
6
 * File field handler for Drupal 8.
7
 */
8
class FileHandler extends AbstractHandler {
9
10
  /**
11
   * {@inheritdoc}
12
   */
13
  public function expand($values) {
14
    $data = file_get_contents($values[0]);
15
    if (FALSE === $data) {
16
      throw new \Exception("Error reading file");
17
    }
18
19
    $ext = pathinfo($values[0], PATHINFO_EXTENSION);
20
    $ext = !empty($ext) ? '.' . $ext : '';
21
22
    /* @var \Drupal\file\FileInterface $file */
23
    $file = file_save_data(
24
        $data,
25
        'public://' . uniqid() . $ext);
26
27
    if (FALSE === $file) {
28
      throw new \Exception("Error saving file");
29
    }
30
31
    $file->save();
32
33
    $return = array(
34
      'target_id' => $file->id(),
35
      'display' => '1',
36
      'description' => 'Behat test file',
37
    );
38
    return $return;
39
  }
40
41
}
42