1. Go to this page and download the library: Download azaharizaman/nexus-import library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
enum ImportFormat: string
{
case CSV = 'csv';
case JSON = 'json';
case XML = 'xml';
case EXCEL = 'excel';
public function
enum ImportMode: string
{
case CREATE = 'create'; // Insert new records only
case UPDATE = 'update'; // Update existing records only
case UPSERT = 'upsert'; // Insert or update
case DELETE = 'delete'; // Delete existing records
case SYNC = 'sync'; // Full synchronization
public function canCreate(): bool;
public function canUpdate(): bool;
public function canDelete(): bool;
}
enum ImportStrategy: string
{
case TRANSACTIONAL = 'transactional'; // Single transaction, rollback on error
case BATCH = 'batch'; // Transaction per batch, continue on failure
case STREAM = 'stream'; // No transaction wrapper, row-by-row
public function isMemoryEfficient(): bool;
}
new FieldMapping(
sourceField: 'source_column',
targetField: 'target_field',
in order
);
new ValidationRule(field: 'email', type: 'email', message: 'Invalid email');
new ValidationRule(field: 'age', type: 'numeric', message: 'Must be numeric');
new ValidationRule(field: 'age', type: 'min', message: 'Min 18', constraint: 18);
new ValidationRule(field: 'age', type: 'max', message: 'Max 100', constraint: 100);
new ValidationRule(field: 'name', type: '
use Nexus\Import\Contracts\ImportHandlerInterface;
use Nexus\Import\ValueObjects\ImportMode;
final class CustomerImportHandler implements ImportHandlerInterface
{
public function handle(array $data, ImportMode $mode): void
{
match($mode) {
ImportMode::CREATE => $this->repository->create($data),
ImportMode::UPDATE => $this->repository->update($data),
ImportMode::UPSERT => $this->repository->upsert($data),
ImportMode::DELETE => $this->repository->delete($data),
ImportMode::SYNC => $this->repository->sync($data)
};
}
public function getUniqueKeyFields(): array
{
return ['email']; // Duplicate detection on email
}
public function getRequiredFields(): array
{
return ['name', 'email'];
}
public function supportsMode(ImportMode $mode): bool
{
return $mode !== ImportMode::DELETE; // Don't allow deletions
}
public function exists(array $uniqueData): bool
{
return $this->repository->existsByEmail($uniqueData['email']);
}
public function validateData(array $data): array
{
// Custom domain validation
$errors = [];
if (isset($data['age']) && $data['age'] < 18) {
$errors[] = 'Customer must be 18 or older';
}
return $errors;
}
}
use Nexus\Import\Contracts\TransactionManagerInterface;
final class LaravelTransactionManager implements TransactionManagerInterface
{
public function begin(): void
{
DB::beginTransaction();
}
public function commit(): void
{
DB::commit();
}
public function rollback(): void
{
DB::rollBack();
}
public function savepoint(string $name): void
{
DB::statement("SAVEPOINT {$name}");
}
public function rollbackToSavepoint(string $name): void
{
DB::statement("ROLLBACK TO SAVEPOINT {$name}");
}
public function inTransaction(): bool
{
return DB::transactionLevel() > 0;
}
public function getTransactionLevel(): int
{
return DB::transactionLevel();
}
}
$result = $importManager->import(
strategy: ImportStrategy::STREAM
// No transactionManager needed
);
// Get all errors
$allErrors = $result->getAllErrors();
// Get errors by severity
$errorCounts = $result->getErrorCountBySeverity();
// ['WARNING' => 5, 'ERROR' => 12, 'CRITICAL' => 0]
// Get errors by field
$fieldErrors = $result->getErrorsByField();
// ['email' => [ImportError, ImportError], 'age' => [ImportError]]
// Get errors by row
$rowErrors = $result->getErrorsByRow();
// [1 => [ImportError], 5 => [ImportError, ImportError]]
// Check success rate
return $successRate = $result->getSuccessRate(); // 87.5%
// app/Services/Import/CustomerImportHandler.php
use Nexus\Import\Contracts\ImportHandlerInterface;
final class CustomerImportHandler implements ImportHandlerInterface
{
public function __construct(
private readonly CustomerRepository $repository
) {}
public function handle(array $data, ImportMode $mode): void
{
match($mode) {
ImportMode::CREATE => $this->repository->create($data),
ImportMode::UPSERT => $this->repository->upsert($data),
};
}
public function getUniqueKeyFields(): array
{
return ['email'];
}
}
// routes/web.php
Route::post('/import/customers', function (Request $request, ImportManager $importManager) {
$result = $importManager->import(
filePath: $request->file('import_file')->getRealPath(),
format: ImportFormat::CSV,
handler: app(CustomerImportHandler::class),
mappings: [/* field mappings */],
mode: ImportMode::UPSERT
);
return response()->json([
'success' => $result->successCount,
'failed' => $result->failedCount,
'errors' => $result->getAllErrors()
]);
});
use Nexus\Import\Core\Engine\DataTransformer;
$transformer = new DataTransformer();
// Register custom rule
$transformer->registerRule('encrypt', function($value) {
return encrypt($value);
});
// Use in mapping
new FieldMapping(
sourceField: 'ssn',
targetField: 'encrypted_ssn',
transformations: ['trim', 'encrypt']
);
use Nexus\Import\Core\Engine\FieldMapper;
$fieldMapper = new FieldMapper($transformer);
// Automatically map matching field names
$autoMappings = $fieldMapper->autoMap(
sourceHeaders: ['customer_name', 'email_address', 'phone_number'],
targetFields: ['customer_name', 'email_address', 'phone']
);
// Result: Maps customer_name and email_address (exact match)
// phone_number doesn't match 'phone', must be manually defined
use Nexus\Import\Core\Engine\DuplicateDetector;
$duplicateDetector = new DuplicateDetector();
// Detect duplicates within import file
$duplicates = $duplicateDetector->detectInternal(
rows: $definition->rows,
uniqueKeyFields: ['email']
);
// Detect duplicates against existing data
$externalDuplicate = $duplicateDetector->detectExternal(
row: $data,
uniqueKeyFields: ['email'],
existsCheck: fn($data) => Customer::where('email', $data['email'])->exists(),
rowNumber: 1
);
// apps/Atomy/app/Services/Import/ExcelParser.php
namespace App\Services\Import;
use Nexus\Import\Contracts\ImportParserInterface;
use Nexus\Import\ValueObjects\{ImportDefinition, ImportMetadata, ImportFormat};
use PhpOffice\PhpSpreadsheet\IOFactory;
final class ExcelParser implements ImportParserInterface
{
public function parse(string $filePath, ImportMetadata $metadata): ImportDefinition
{
$spreadsheet = IOFactory::load($filePath);
$worksheet = $spreadsheet->getActiveSheet();
$headers = [];
$rows = [];
foreach ($worksheet->getRowIterator() as $index => $row) {
$cellIterator = $row->getCellIterator();
$cellIterator->setIterateOnlyExistingCells(false);
$data = [];
foreach ($cellIterator as $cell) {
$data[] = $cell->getValue();
}
if ($index === 1) {
$headers = $data;
} else {
$rows[] = array_combine($headers, $data);
}
}
return new ImportDefinition($headers, $rows, $metadata);
}
public function supports(ImportFormat $format): bool
{
return $format === ImportFormat::EXCEL;
}
}
// apps/Atomy/app/Providers/ImportServiceProvider.php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Nexus\Import\Services\{ImportManager, ImportProcessor};
use Nexus\Import\Parsers\{CsvParser, JsonParser, XmlParser};
use Nexus\Import\ValueObjects\ImportFormat;
use App\Services\Import\{ExcelParser, LaravelTransactionManager};
final class ImportServiceProvider extends ServiceProvider
{
public function register(): void
{
// Bind TransactionManager
$this->app->singleton(TransactionManagerInterface::class, LaravelTransactionManager::class);
// Bind ImportManager
$this->app->singleton(ImportManager::class, function ($app) {
$manager = new ImportManager(
processor: $app->make(ImportProcessor::class),
authorizer: null,
context: null,
logger: $app->make(LoggerInterface::class)
);
// Register native parsers
$manager->registerParser(ImportFormat::CSV, new CsvParser());
$manager->registerParser(ImportFormat::JSON, new JsonParser());
$manager->registerParser(ImportFormat::XML, new XmlParser());
// Register Excel parser (Atomy-specific)
$manager->registerParser(ImportFormat::EXCEL, new ExcelParser());
return $manager;
});
}
}
use PHPUnit\Framework\TestCase;
use Nexus\Import\Core\Engine\DataTransformer;
final class CustomTransformationTest extends TestCase
{
public function test_custom_transformation_rule(): void
{
$transformer = new DataTransformer();
$transformer->registerRule('reverse', fn($value) => strrev($value));
$result = $transformer->apply('hello', ['reverse']);
$this->assertSame('olleh', $result);
}
}