You are here

public static function Imce::value in FileField Sources 8

Value callback for file field source plugin.

Parameters

array $element: An associative array containing the properties of the element.

mixed $input: The incoming input to populate the form element. If this is FALSE, the element's default value should be returned.

\Drupal\Core\Form\FormStateInterface $form_state: The current state of the form.

Return value

mixed The value to assign to the element.

Overrides FilefieldSourceInterface::value

File

src/Plugin/FilefieldSource/Imce.php, line 30

Class

Imce
A FileField source plugin to allow referencing of files from IMCE.

Namespace

Drupal\filefield_sources\Plugin\FilefieldSource

Code

public static function value(array &$element, &$input, FormStateInterface $form_state) {
  if (isset($input['filefield_imce']['imce_paths']) && $input['filefield_imce']['imce_paths'] != '') {
    $instance = \Drupal::entityTypeManager()
      ->getStorage('field_config')
      ->load($element['#entity_type'] . '.' . $element['#bundle'] . '.' . $element['#field_name']);
    $field_settings = $instance
      ->getSettings();
    $scheme = $field_settings['uri_scheme'];
    $imce_paths = explode(':', $input['filefield_imce']['imce_paths']);
    $uris = [];
    foreach ($imce_paths as $imce_path) {

      // $wrapper = \Drupal::service('stream_wrapper_manager')->getViaScheme($scheme);
      // $file_directory_prefix = $scheme == 'private' ? 'system/files' : $wrapper->getDirectoryPath();
      // $uri = preg_replace('/^' . preg_quote(base_path() . $file_directory_prefix . '/', '/') . '/', $scheme . '://', $imce_path);.
      $uri = rawurldecode($scheme . '://' . $imce_path);
      $uris[] = $uri;
    }

    // Resolve the file path to an FID.
    $connection = \Drupal::service('database');
    $fids = $connection
      ->select('file_managed', 'f')
      ->condition('uri', $uris, 'IN')
      ->fields('f', [
      'fid',
    ])
      ->execute()
      ->fetchCol();
    if ($fids) {
      $files = File::loadMultiple($fids);
      foreach ($files as $file) {
        if (filefield_sources_element_validate($element, $file, $form_state)) {
          if (!in_array($file
            ->id(), $input['fids'])) {
            $input['fids'][] = $file
              ->id();
          }
        }
      }
    }
    else {
      $form_state
        ->setError($element, t('The selected file could not be used because the file does not exist in the database.'));
    }

    // No matter what happens, clear the value from the file path field.
    $input['filefield_imce']['imce_paths'] = '';
  }
}