<?php

namespace Drupal\reinstall\EventSubscriber;

use Drupal\reinstall\ReinstallEvents;
use Drupal\reinstall\SourceEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

/**
 * Class UserPreImport is an EventSubscriber filtering user sources.
 */
class UserPreImport implements EventSubscriberInterface {

  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents() {
    return [
      ReinstallEvents::POST_SOURCE_PARSE => 'onPreImport',
    ];
  }

  /**
   * Event callback for POST_SOURCE_PARSE.
   *
   * @param \Drupal\reinstall\SourceEvent $event
   *   The event.
   */
  public function onPreImport(SourceEvent $event) {
    $source = $event->source;
    if ($source->getConfiguration()['type'] !== 'user') {
      return;
    }

    $event->source->records = array_filter($event->source->records, [$this, 'filter01']);
  }

  /**
   * Skip users 0 and 1 in imports, as they are core-provided.
   *
   * @param array $record
   *   The description of a user entity.
   *
   * @return bool
   *   Include it (1) or filter it (0).
   */
  public function filter01(array $record) {
    $ret = ($record['uid'] ?? 0) > 1;
    return $ret;
  }

}