snipe-it/app/Importer/AccessoryImporter.php

110 lines
3.6 KiB
PHP
Raw Normal View History

<?php
/**
* Created by PhpStorm.
* User: parallelgrapefruit
* Date: 12/24/16
* Time: 12:56 PM
*/
namespace App\Importer;
use App\Helpers\Helper;
use App\Models\Accessory;
class AccessoryImporter extends ItemImporter
{
protected $accessories;
function __construct($filename, $logCallback, $progressCallback, $errorCallback, $testRun = false, $user_id = -1, $updating = false, $usernameFormat = null)
{
parent::__construct($filename, $logCallback, $progressCallback, $errorCallback, $testRun, $user_id, $updating, $usernameFormat);
$this->accessories = Accessory::all();
}
protected function handle($row)
{
parent::handle($row); // TODO: Change the autogenerated stub
$this->createAccessoryIfNotExists();
}
/**
* Create an accessory if a duplicate does not exist
*
* @author Daniel Melzter
* @since 3.0
*/
public function createAccessoryIfNotExists()
{
$accessory = null;
$editingAccessory = false;
$this->log("Creating Accessory");
$accessory = $this->accessories->search(function ($key) {
return strcasecmp($key->name, $this->item['item_name']) == 0;
});
if($accessory) {
$editingAccessory = true;
if (!$this->updating) {
$this->log('A matching Accessory ' . $this->item["item_name"] . ' already exists. ');
return;
}
} else {
$this->log("No Matching Accessory, Creating a new one");
$accessory = new Accessory();
}
if (!$editingAccessory) {
$accessory->name = $this->item["item_name"];
}
if (!empty($this->item["purchase_date"])) {
$accessory->purchase_date = $this->item["purchase_date"];
} else {
$accessory->purchase_date = null;
}
if (!empty($this->item["purchase_cost"])) {
$accessory->purchase_cost = Helper::ParseFloat($this->item["purchase_cost"]);
}
if (isset($this->item["location"])) {
$accessory->location_id = $this->item["location"]->id;
}
$accessory->user_id = $this->user_id;
if (isset($this->item["company"])) {
$accessory->company_id = $this->item["company"]->id;
}
if (!empty($this->item["order_number"])) {
$accessory->order_number = $this->item["order_number"];
}
if (isset($this->item["category"])) {
$accessory->category_id = $this->item["category"]->id;
}
//TODO: Implement
// $accessory->notes = e($item_notes);
if (!empty($this->item["requestable"])) {
$accessory->requestable = filter_var($this->item["requestable"], FILTER_VALIDATE_BOOLEAN);
}
//Must have at least zero of the item if we import it.
if (!empty($this->item["quantity"])) {
if ($this->item["quantity"] > -1) {
$accessory->qty = $this->item["quantity"];
} else {
$accessory->qty = 1;
}
}
if (!$this->testRun) {
if ($accessory->save()) {
$accessory->logCreate('Imported using CSV Importer');
$this->log('Accessory ' . $this->item["item_name"] . ' was created');
// $this->comment('Accessory ' . $this->item["item_name"] . ' was created');
} else {
$this->jsonError($accessory,'Accessory', $accessory->getErrors()) ;
}
} else {
$this->log('TEST RUN - Accessory ' . $this->item["item_name"] . ' not created');
}
}
}