is_received('import')) {
return $this->import();
} elseif($this->is_received('clean')) {
return $this->clean();
}
}
public function clean() : self {
$mapper = new customers_mapper(
$this->get_database(),
$this->get_tables()
);
$customers = $mapper->load_all();
try {
foreach ($customers as $customer) {
$mapper->remove($customer);
}
$this->success_toast('Customers database cleaned success.');
} catch (\exception $exception) {
$this->error_toast($exception->getMessage());
}
return $this;
}
public function import() : self {
if (!isset($_FILES['upload'])) {
$this->error_toast('Input with file not exists.');
return $this;
}
if (!is_uploaded_file($_FILES['upload']['tmp_name'])) {
$this->error_toast('Not upload file that would be imported.');
return $this;
}
$coded = file_get_contents($_FILES['upload']['tmp_name']);
$decoded = json_decode($coded, true);
$group = null;
if ($this->get_received('group') !== 'NULL') {
$group = $this->get_received('group');
}
if ($decoded === null) {
$this->error_toast('Uploaded JSON is not valid.');
return $this;
}
ini_set('max_execution_time', '360');
$mapper = new customers_mapper(
$this->get_database(),
$this->get_tables()
);
$validator = new customer_validator(
$this->get_database(),
$this->get_tables()
);
$converter = new customers_converter();
$added = 0;
$failed = 0;
foreach ($decoded as $item) {
$item['grouped'] = $group;
try {
$customer = $converter->load_array($item)->get_object();
$validator->load($customer)->check();
if (!$validator->is_valid()) {
$failed += 1;
continue;
}
} catch (\exception $exception) {
$error = new \cx_appengine\string_builder();
$error->push(
__('Customers file is corrupted.', 'cx_newsletter').' '
);
$error->push($exception->getMessage());
$this->error_toast($error->get());
$failed += 1;
continue;
}
try {
$mapper->create($customer);
$added += 1;
} catch (\exception $exception) {
$this->error_toast($exception->getMessage());
$failed += 1;
continue;
}
}
$result = new \cx_appengine\string_builder();
$result->push(__('Import new customers success.', 'cx_newsletter'));
$result->push('
');
$result->push(__('Added: ', 'cx_newsletter').$added.'
');
$result->push(__('Failed: ', 'cx_newsletter').$failed);
$this->success_toast($result->get());
return $this;
}
}