Skip to content

A free open source IT asset/license management system

Apply pint to Importer directory

snipe3e831bf9b3cc
diff --git a/app/Http/Controllers/Users/LDAPImportController.php b/app/Http/Controllers/Users/LDAPImportController.php
index 56f88f0c74..84a2214942 100644
--- a/app/Http/Controllers/Users/LDAPImportController.php
+++ b/app/Http/Controllers/Users/LDAPImportController.php
@@ -10,7 +10,7 @@ use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Artisan;
- // Note that this is awful close to 'Users' the namespace above; be careful
+// Note that this is awful close to 'Users' the namespace above; be careful
class LDAPImportController extends Controller
{
diff --git a/app/Http/Kernel.php b/app/Http/Kernel.php
index f8005879e5..4736b9df8f 100644
--- a/app/Http/Kernel.php
+++ b/app/Http/Kernel.php
@@ -2,7 +2,37 @@
namespace App\Http;
+use App\Http\Middleware\AssetCountForSidebar;
+use App\Http\Middleware\CheckColorSettings;
+use App\Http\Middleware\CheckForDebug;
+use App\Http\Middleware\CheckForSetup;
+use App\Http\Middleware\CheckForTwoFactor;
+use App\Http\Middleware\CheckLocale;
+use App\Http\Middleware\CheckPermissions;
+use App\Http\Middleware\CheckUserIsActivated;
+use App\Http\Middleware\EncryptCookies;
+use App\Http\Middleware\NoSessionStore;
+use App\Http\Middleware\PreventBackHistory;
+use App\Http\Middleware\RedirectIfAuthenticated;
+use App\Http\Middleware\SecurityHeaders;
+use App\Http\Middleware\SetAPIResponseHeaders;
+use App\Http\Middleware\TrimStrings;
+use App\Http\Middleware\TrustProxies;
+use App\Http\Middleware\VerifyCsrfToken;
+use Illuminate\Auth\Middleware\Authenticate;
+use Illuminate\Auth\Middleware\AuthenticateWithBasicAuth;
+use Illuminate\Auth\Middleware\Authorize;
+use Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
+use Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull;
+use Illuminate\Foundation\Http\Middleware\PreventRequestsDuringMaintenance;
+use Illuminate\Http\Middleware\HandleCors;
+use Illuminate\Routing\Middleware\SubstituteBindings;
+use Illuminate\Routing\Middleware\ThrottleRequests;
+use Illuminate\Session\Middleware\AuthenticateSession;
+use Illuminate\Session\Middleware\StartSession;
+use Illuminate\View\Middleware\ShareErrorsFromSession;
+use Laravel\Passport\Http\Middleware\CreateFreshApiToken;
class Kernel extends HttpKernel
{
@@ -14,18 +44,18 @@ class Kernel extends HttpKernel
* @var array
*/
protected $middleware = [
- \App\Http\Middleware\TrustProxies::class,
- \App\Http\Middleware\NoSessionStore::class,
- \Illuminate\Foundation\Http\Middleware\PreventRequestsDuringMaintenance::class,
- \Illuminate\Session\Middleware\StartSession::class,
- \Illuminate\View\Middleware\ShareErrorsFromSession::class,
- \App\Http\Middleware\CheckForSetup::class,
- \App\Http\Middleware\CheckForDebug::class,
- \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
- \App\Http\Middleware\TrimStrings::class,
- \App\Http\Middleware\SecurityHeaders::class,
- \App\Http\Middleware\PreventBackHistory::class,
- \Illuminate\Http\Middleware\HandleCors::class,
+ TrustProxies::class,
+ NoSessionStore::class,
+ PreventRequestsDuringMaintenance::class,
+ StartSession::class,
+ ShareErrorsFromSession::class,
+ CheckForSetup::class,
+ CheckForDebug::class,
+ ConvertEmptyStringsToNull::class,
+ TrimStrings::class,
+ SecurityHeaders::class,
+ PreventBackHistory::class,
+ HandleCors::class,
];
@@ -36,23 +66,23 @@ class Kernel extends HttpKernel
*/
protected $middlewareGroups = [
'web' => [
- \App\Http\Middleware\EncryptCookies::class,
- \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
- \App\Http\Middleware\VerifyCsrfToken::class,
- \App\Http\Middleware\CheckLocale::class,
- \App\Http\Middleware\CheckUserIsActivated::class,
- \App\Http\Middleware\CheckForTwoFactor::class,
- \Laravel\Passport\Http\Middleware\CreateFreshApiToken::class,
- \App\Http\Middleware\AssetCountForSidebar::class,
- \App\Http\Middleware\CheckColorSettings::class,
- \Illuminate\Session\Middleware\AuthenticateSession::class,
- \Illuminate\Routing\Middleware\SubstituteBindings::class,
+ EncryptCookies::class,
+ AddQueuedCookiesToResponse::class,
+ VerifyCsrfToken::class,
+ CheckLocale::class,
+ CheckUserIsActivated::class,
+ CheckForTwoFactor::class,
+ CreateFreshApiToken::class,
+ AssetCountForSidebar::class,
+ CheckColorSettings::class,
+ AuthenticateSession::class,
+ SubstituteBindings::class,
],
'api' => [
'auth:api',
- \App\Http\Middleware\CheckLocale::class,
- \Illuminate\Routing\Middleware\SubstituteBindings::class,
+ CheckLocale::class,
+ SubstituteBindings::class,
],
'health' => [
@@ -68,13 +98,13 @@ class Kernel extends HttpKernel
* @var array
*/
protected $routeMiddleware = [
- 'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
- 'authorize' => \App\Http\Middleware\CheckPermissions::class,
- 'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
- 'can' => \Illuminate\Auth\Middleware\Authorize::class,
- 'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
- 'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
- 'api-throttle' => \App\Http\Middleware\SetAPIResponseHeaders::class,
+ 'auth' => Authenticate::class,
+ 'authorize' => CheckPermissions::class,
+ 'auth.basic' => AuthenticateWithBasicAuth::class,
+ 'can' => Authorize::class,
+ 'guest' => RedirectIfAuthenticated::class,
+ 'throttle' => ThrottleRequests::class,
+ 'api-throttle' => SetAPIResponseHeaders::class,
'health' => null,
];
}
diff --git a/app/Importer/AccessoryImporter.php b/app/Importer/AccessoryImporter.php
index bc9c1909ff..12714fb785 100644
--- a/app/Importer/AccessoryImporter.php
+++ b/app/Importer/AccessoryImporter.php
@@ -21,6 +21,7 @@ class AccessoryImporter extends ItemImporter
* Create an accessory if a duplicate does not exist
*
* @author Daniel Melzter
+ *
* @since 3.0
*/
public function createAccessoryIfNotExists($row)
@@ -34,17 +35,17 @@ class AccessoryImporter extends ItemImporter
}
$this->log('Updating Accessory');
- $this->item['model_number'] = trim($this->findCsvMatch($row, "model_number"));
+ $this->item['model_number'] = trim($this->findCsvMatch($row, 'model_number'));
$accessory->update($this->sanitizeItemForUpdating($accessory));
$accessory->save();
return;
}
$this->log('No Matching Accessory, Creating a new one');
- $accessory = new Accessory();
+ $accessory = new Accessory;
$accessory->created_by = auth()->id();
- $this->item['model_number'] = $this->findCsvMatch($row, "model_number");
- $this->item['min_amt'] = $this->findCsvMatch($row, "min_amt");
+ $this->item['model_number'] = $this->findCsvMatch($row, 'model_number');
+ $this->item['min_amt'] = $this->findCsvMatch($row, 'min_amt');
$accessory->fill($this->sanitizeItemForStoring($accessory));
// This sets an attribute on the Loggable trait for the action log
diff --git a/app/Importer/AssetImporter.php b/app/Importer/AssetImporter.php
index c17ede35e8..2710622244 100644
--- a/app/Importer/AssetImporter.php
+++ b/app/Importer/AssetImporter.php
@@ -2,10 +2,10 @@
namespace App\Importer;
+use App\Events\CheckoutableCheckedIn;
use App\Models\Asset;
use App\Models\Statuslabel;
use App\Models\User;
-use App\Events\CheckoutableCheckedIn;
use Illuminate\Support\Facades\Crypt;
class AssetImporter extends ItemImporter
@@ -18,7 +18,7 @@ class AssetImporter extends ItemImporter
$this->defaultStatusLabelId = Statuslabel::first()?->id;
- if (!is_null(Statuslabel::deployable()->first())) {
+ if (! is_null(Statuslabel::deployable()->first())) {
$this->defaultStatusLabelId = Statuslabel::deployable()->first()?->id;
}
@@ -44,7 +44,7 @@ class AssetImporter extends ItemImporter
foreach ($this->customFields as $customField) {
$customFieldValue = $this->array_smart_custom_field_fetch($row, $customField);
- if (!is_null($customFieldValue)) {
+ if (! is_null($customFieldValue)) {
if ($customField->field_encrypted == 1) {
$this->item['custom_fields'][$customField->db_column_name()] = Crypt::encrypt($customFieldValue);
$this->log('Custom Field '.$customField->name.': '.Crypt::encrypt($customFieldValue));
@@ -59,7 +59,6 @@ class AssetImporter extends ItemImporter
}
}
-
$this->createAssetIfNotExists($row);
}
@@ -67,8 +66,9 @@ class AssetImporter extends ItemImporter
* Create the asset if it does not exist.
*
* @author Daniel Melzter
+ *
* @since 3.0
- * @param array $row
+ *
* @return Asset|mixed|null
*/
public function createAssetIfNotExists(array $row)
@@ -76,25 +76,24 @@ class AssetImporter extends ItemImporter
$editingAsset = false;
$asset_tag = $this->findCsvMatch($row, 'asset_tag');
- if (empty($asset_tag)){
+ if (empty($asset_tag)) {
$asset_tag = Asset::autoincrement_asset();
}
-
-
- if ($this->findCsvMatch($row, 'id')!='') {
+ if ($this->findCsvMatch($row, 'id') != '') {
// Override asset if an ID was given
\Log::debug('Finding asset by ID: '.$this->findCsvMatch($row, 'id'));
$asset = Asset::with('assignedTo')->find($this->findCsvMatch($row, 'id'));
} else {
$asset = Asset::with('assignedTo')->where(['asset_tag' => (string) $asset_tag])->first();
}
-
+
if ($asset) {
if (! $this->updating) {
$exists_error = trans('general.import_asset_tag_exists', ['asset_tag' => $asset_tag]);
$this->log($exists_error);
$this->addErrorToBag($asset, 'asset_tag', $exists_error);
+
return $exists_error;
}
@@ -141,12 +140,11 @@ class AssetImporter extends ItemImporter
$item['rtd_location_id'] = $this->item['location_id'];
}
-
/**
* We use this to backdate the checkin action further down
*/
$checkin_date = date('Y-m-d H:i:s');
- if ($this->item['last_checkin']!='') {
+ if ($this->item['last_checkin'] != '') {
$item['last_checkin'] = $this->parseOrNullDate('last_checkin', 'datetime');
$checkout_date = $this->item['last_checkin'];
}
@@ -155,28 +153,27 @@ class AssetImporter extends ItemImporter
* We use this to backdate the checkout action further down
*/
$checkout_date = date('Y-m-d H:i:s');
- if ($this->item['last_checkout']!='') {
+ if ($this->item['last_checkout'] != '') {
$item['last_checkout'] = $this->parseOrNullDate('last_checkout', 'datetime');
$checkout_date = $this->item['last_checkout'];
}
- if ($this->item['expected_checkin']!='') {
+ if ($this->item['expected_checkin'] != '') {
$item['expected_checkin'] = $this->parseOrNullDate('expected_checkin');
}
- if ($this->item['last_audit_date']!='') {
+ if ($this->item['last_audit_date'] != '') {
$item['last_audit_date'] = $this->parseOrNullDate('last_audit_date');
}
- if ($this->item['next_audit_date']!='') {
+ if ($this->item['next_audit_date'] != '') {
$item['next_audit_date'] = $this->parseOrNullDate('next_audit_date');
}
- if ($this->item['asset_eol_date']!='') {
+ if ($this->item['asset_eol_date'] != '') {
$item['asset_eol_date'] = $this->parseOrNullDate('asset_eol_date');
}
-
if ($editingAsset) {
$asset->update($item);
} else {
@@ -198,22 +195,20 @@ class AssetImporter extends ItemImporter
$this->log('Asset '.$this->item['name'].' with serial number '.$this->item['serial'].' was created');
// If we have a target to checkout to, lets do so.
- //-- created_by is a property of the abstract class Importer, which this class inherits from and it's set by
- //-- the class that needs to use it (command importer or GUI importer inside the project).
+ // -- created_by is a property of the abstract class Importer, which this class inherits from and it's set by
+ // -- the class that needs to use it (command importer or GUI importer inside the project).
if (isset($target) && ($target !== false)) {
- if (!is_null($asset->assigned_to)){
+ if (! is_null($asset->assigned_to)) {
if ($asset->assigned_to != $target->id) {
event(new CheckoutableCheckedIn($asset, $asset->assigned, auth()->user(), 'Checkin from CSV Importer', $checkin_date));
}
}
- $asset->fresh()->checkOut($target, $this->created_by, $checkout_date, null, 'Checkout from CSV Importer', $asset->name);
+ $asset->fresh()->checkOut($target, $this->created_by, $checkout_date, null, 'Checkout from CSV Importer', $asset->name);
}
return;
}
$this->logError($asset, 'Asset "'.$this->item['name'].'"');
}
-
-
}
diff --git a/app/Importer/AssetModelImporter.php b/app/Importer/AssetModelImporter.php
index b458742313..7a78cd1655 100644
--- a/app/Importer/AssetModelImporter.php
+++ b/app/Importer/AssetModelImporter.php
@@ -3,8 +3,8 @@
namespace App\Importer;
use App\Models\AssetModel;
-use App\Models\Depreciation;
use App\Models\CustomFieldset;
+use App\Models\Depreciation;
use Illuminate\Support\Facades\Log;
/**
@@ -30,11 +30,12 @@ class AssetModelImporter extends ItemImporter
/**
* Create a model if a duplicate does not exist.
+ *
* @todo Investigate how this should interact with Importer::createModelIfNotExists
*
* @author A. Gianotto
+ *
* @since 6.1.0
- * @param array $row
*/
public function createAssetModelIfNotExists(array $row)
{
@@ -52,7 +53,7 @@ class AssetModelImporter extends ItemImporter
$assetModel = AssetModel::where('name', '=', $this->findCsvMatch($row, 'name'))->where('model_number', '=', $this->findCsvMatch($row, 'model_number'))->first();
} else {
- if ($this->findCsvMatch($row, 'id')!='') {
+ if ($this->findCsvMatch($row, 'id') != '') {
// Override model if an ID was given
$this->log('Finding model by ID: '.$this->findCsvMatch($row, 'id'));
$assetModel = AssetModel::find($this->findCsvMatch($row, 'id'));
@@ -62,10 +63,10 @@ class AssetModelImporter extends ItemImporter
}
}
-
if ($assetModel) {
if (! $this->updating) {
$this->log('A matching Model '.$this->item['name'].' already exists and we are not updating. Skipping.');
+
return;
}
@@ -73,7 +74,7 @@ class AssetModelImporter extends ItemImporter
$editingAssetModel = true;
} else {
$this->log('No Matching Model, Create a new one');
- $assetModel = new AssetModel();
+ $assetModel = new AssetModel;
}
// Pull the records from the CSV to determine their values
@@ -89,24 +90,24 @@ class AssetModelImporter extends ItemImporter
$this->item['requestable'] = trim(($this->fetchHumanBoolean($this->findCsvMatch($row, 'requestable'))) == 1) ? 1 : 0;
$this->item['require_serial'] = trim(($this->fetchHumanBoolean($this->findCsvMatch($row, 'require_serial'))) == 1) ? 1 : 0;
- if (!empty($this->item['category'])) {
+ if (! empty($this->item['category'])) {
if ($category = $this->createOrFetchCategory($this->item['category'])) {
$this->item['category_id'] = $category;
}
}
- if (!empty($this->item['manufacturer'])) {
+ if (! empty($this->item['manufacturer'])) {
if ($manufacturer = $this->createOrFetchManufacturer($this->item['manufacturer'])) {
$this->item['manufacturer_id'] = $manufacturer;
}
}
- if (!empty($this->item['depreciation'])) {
+ if (! empty($this->item['depreciation'])) {
if ($depreciation = $this->fetchDepreciation($this->item['depreciation'])) {
$this->item['depreciation_id'] = $depreciation;
}
}
- if (!empty($this->item['fieldset'])) {
+ if (! empty($this->item['fieldset'])) {
if ($fieldset = $this->createOrFetchCustomFieldset($this->item['fieldset'])) {
$this->item['fieldset_id'] = $fieldset;
}
@@ -115,7 +116,6 @@ class AssetModelImporter extends ItemImporter
Log::debug('Item array is: ');
Log::debug(print_r($this->item, true));
-
if ($editingAssetModel) {
Log::debug('Updating existing model');
$assetModel->update($this->sanitizeItemForUpdating($assetModel));
@@ -127,17 +127,18 @@ class AssetModelImporter extends ItemImporter
if ($assetModel->save()) {
$this->log('AssetModel '.$assetModel->name.' created or updated from CSV import');
+
return $assetModel;
} else {
$this->log($assetModel->getErrors()->first());
- $this->addErrorToBag($assetModel, $assetModel->getErrors()->keys()[0], $assetModel->getErrors()->first());
+ $this->addErrorToBag($assetModel, $assetModel->getErrors()->keys()[0], $assetModel->getErrors()->first());
+
return $assetModel->getErrors();
}
}
-
/**
* Fetch an existing depreciation, or create new if it doesn't exist.
*
@@ -145,16 +146,19 @@ class AssetModelImporter extends ItemImporter
* and cannot be created without them (months, for example.))
*
* @author A. Gianotto
+ *
* @since 7.1.3
- * @param $depreciation_name string
+ *
+ * @param $depreciation_name string
* @return int id of depreciation created/found
*/
- public function fetchDepreciation($depreciation_name) : ?int
+ public function fetchDepreciation($depreciation_name): ?int
{
if ($depreciation_name != '') {
if ($depreciation = Depreciation::where('name', '=', $depreciation_name)->first()) {
$this->log('A matching Depreciation '.$depreciation_name.' already exists');
+
return $depreciation->id;
}
}
@@ -166,21 +170,24 @@ class AssetModelImporter extends ItemImporter
* Fetch an existing fieldset, or create new if it doesn't exist
*
* @author A. Gianotto
+ *
* @since 7.1.3
- * @param $fieldset_name string
+ *
+ * @param $fieldset_name string
* @return int id of fieldset created/found
*/
- public function createOrFetchCustomFieldset($fieldset_name) : ?int
+ public function createOrFetchCustomFieldset($fieldset_name): ?int
{
if ($fieldset_name != '') {
$fieldset = CustomFieldset::where('name', '=', $fieldset_name)->first();
if ($fieldset) {
$this->log('A matching fieldset '.$fieldset_name.' already exists');
+
return $fieldset->id;
}
- $fieldset = new CustomFieldset();
+ $fieldset = new CustomFieldset;
$fieldset->name = $fieldset_name;
if ($fieldset->save()) {
@@ -193,4 +200,4 @@ class AssetModelImporter extends ItemImporter
return null;
}
-}
\ No newline at end of file
+}
diff --git a/app/Importer/CategoryImporter.php b/app/Importer/CategoryImporter.php
index f9ca22fbab..c547b4ea89 100644
--- a/app/Importer/CategoryImporter.php
+++ b/app/Importer/CategoryImporter.php
@@ -28,11 +28,12 @@ class CategoryImporter extends ItemImporter
/**
* Create a category if a duplicate does not exist.
+ *
* @todo Investigate how this should interact with Importer::createCategoryIfNotExists
*
* @author A. Gianotto
+ *
* @since 6.1.0
- * @param array $row
*/
public function createCategoryIfNotExists(array $row)
{
@@ -41,16 +42,16 @@ class CategoryImporter extends ItemImporter
$category = Category::where('name', '=', $this->findCsvMatch($row, 'name'))->first();
- if ($this->findCsvMatch($row, 'id')!='') {
+ if ($this->findCsvMatch($row, 'id') != '') {
// Override category if an ID was given
\Log::debug('Finding category by ID: '.$this->findCsvMatch($row, 'id'));
$category = Category::find($this->findCsvMatch($row, 'id'));
}
-
if ($category) {
if (! $this->updating) {
$this->log('A matching Category '.$this->item['name'].' already exists');
+
return;
}
@@ -72,11 +73,9 @@ class CategoryImporter extends ItemImporter
$this->item['checkin_email'] = trim(($this->fetchHumanBoolean($this->findCsvMatch($row, 'checkin_email'))) == 1) ? 1 : 0;
$this->item['tag_color'] = trim($this->findCsvMatch($row, 'tag_color'));
-
Log::debug('Item array is: ');
Log::debug(print_r($this->item, true));
-
if ($editingCategory) {
Log::debug('Updating existing category');
$category->update($this->sanitizeItemForUpdating($category));
@@ -87,14 +86,15 @@ class CategoryImporter extends ItemImporter
if ($category->save()) {
$this->log('Category '.$category->name.' created or updated from CSV import');
+
return $category;
} else {
Log::debug($category->getErrors());
$this->logError($category, 'Category "'.$this->item['name'].'"');
+
return $category->errors;
}
-
}
-}
\ No newline at end of file
+}
diff --git a/app/Importer/ComponentImporter.php b/app/Importer/ComponentImporter.php
index 3979ba499d..312da48eed 100644
--- a/app/Importer/ComponentImporter.php
+++ b/app/Importer/ComponentImporter.php
@@ -22,6 +22,7 @@ class ComponentImporter extends ItemImporter
* Create a component if a duplicate does not exist
*
* @author Daniel Melzter
+ *
* @since 3.0
*/
public function createComponentIfNotExists()
@@ -29,8 +30,8 @@ class ComponentImporter extends ItemImporter
$component = null;
$this->log('Creating Component');
$component = Component::where('name', trim($this->item['name']))
- ->where('serial', trim($this->item['serial']))
- ->first();
+ ->where('serial', trim($this->item['serial']))
+ ->first();
if ($component) {
$this->log('A matching Component '.$this->item['name'].' with serial '.$this->item['serial'].' already exists. ');
diff --git a/app/Importer/ConsumableImporter.php b/app/Importer/ConsumableImporter.php
index 40c597e896..b1eb7eb5c4 100644
--- a/app/Importer/ConsumableImporter.php
+++ b/app/Importer/ConsumableImporter.php
@@ -21,7 +21,9 @@ class ConsumableImporter extends ItemImporter
* Create a consumable if a duplicate does not exist
*
* @author Daniel Melzter
- * @param array $row CSV Row Being parsed.
+ *
+ * @param array $row CSV Row Being parsed.
+ *
* @since 3.0
*/
public function createConsumableIfNotExists($row)
@@ -31,6 +33,7 @@ class ConsumableImporter extends ItemImporter
if (! $this->updating) {
$this->log('A matching Consumable '.$this->item['name'].' already exists. ');
+
return;
}
$this->log('Updating Consumable');
@@ -41,7 +44,7 @@ class ConsumableImporter extends ItemImporter
}
$this->log('No matching consumable, creating one');
- $consumable = new Consumable();
+ $consumable = new Consumable;
$consumable->created_by = auth()->id();
$consumable->fill($this->sanitizeItemForStoring($consumable));
diff --git a/app/Importer/Importer.php b/app/Importer/Importer.php
index 0075a8de9f..6cfef6f042 100644
--- a/app/Importer/Importer.php
+++ b/app/Importer/Importer.php
@@ -9,24 +9,24 @@ use App\Models\User;
use Carbon\CarbonImmutable;
use ForceUTF8\Encoding;
use Illuminate\Database\Eloquent\Model;
-use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
-use League\Csv\Reader;
use Illuminate\Support\Facades\Log;
+use League\Csv\Reader;
abstract class Importer
{
protected $csv;
+
/**
* Id of User performing import
- * @var
*/
protected $created_by;
+
/**
* Are we updating items in the import
+ *
* @var bool
*/
-
protected $updating;
/**
@@ -36,6 +36,7 @@ abstract class Importer
* This private variable is ONLY used for the cli-importer.
*
* @todo - find a way to make this less duplicative
+ *
* @var array
*/
private $defaultFieldMap = [
@@ -95,24 +96,31 @@ abstract class Importer
'vip' => 'vip',
'tag_color' => 'tag color',
];
+
/**
* Map of item fields->csv names
+ *
* @var array
*/
protected $fieldMap = [];
+
/**
* @var callable
*/
protected $logCallback;
+
protected $tempPassword;
+
/**
* @var callable
*/
protected $progressCallback;
+
/**
* @var null
*/
protected $usernameFormat;
+
/**
* @var callable
*/
@@ -120,7 +128,8 @@ abstract class Importer
/**
* ObjectImporter constructor.
- * @param string $file
+ *
+ * @param string $file
*/
public function __construct($file)
{
@@ -145,13 +154,15 @@ abstract class Importer
* Sets up the database transaction and logging for the importer
*
* @return void
+ *
* @author Daniel Meltzer
+ *
* @since 5.0
*/
public function import()
{
$headerRow = $this->csv->fetchOne();
- $this->csv->setHeaderOffset(0); //explicitly sets the CSV document header record
+ $this->csv->setHeaderOffset(0); // explicitly sets the CSV document header record
$this->populateCustomFields($headerRow);
@@ -160,7 +171,7 @@ abstract class Importer
Model::unguard();
foreach ($this->csv->getRecords($headerRow) as $row) {
- //Lowercase header values to ensure we're comparing values properly.
+ // Lowercase header values to ensure we're comparing values properly.
$row = array_change_key_case($row, CASE_LOWER);
$this->handle($row);
@@ -182,8 +193,11 @@ abstract class Importer
/**
* Fetch custom fields from database and translate/parse them into a format
* appropriate for use in the importer.
+ *
* @return void
+ *
* @author Daniel Meltzer
+ *
* @since 5.0
*/
protected function populateCustomFields($headerRow)
@@ -210,10 +224,12 @@ abstract class Importer
* Check to see if the given key exists in the array, and trim excess white space before returning it
*
* @author Daniel Melzter
+ *
* @since 3.0
- * @param $array array
- * @param $key string
- * @param $default string
+ *
+ * @param $array array
+ * @param $key string
+ * @param $default string
* @return string
*/
public function findCsvMatch(array $array, $key, $default = null)
@@ -221,11 +237,12 @@ abstract class Importer
$val = $default;
$key = $this->lookupCustomKey($key);
- // $this->log("Custom Key: ${key}");
+ // $this->log("Custom Key: ${key}");
if (array_key_exists($key, $array)) {
$val = Encoding::toUTF8(trim($array[$key]));
}
- //$this->log("${key}: ${val}");
+
+ // $this->log("${key}: ${val}");
return $val;
}
@@ -233,8 +250,10 @@ abstract class Importer
* Looks up A custom key in the custom field map
*
* @author Daniel Melzter
+ *
* @since 4.0
- * @param $key string
+ *
+ * @param $key string
* @return string|null
*/
public function lookupCustomKey($key)
@@ -242,6 +261,7 @@ abstract class Importer
if (array_key_exists($key, $this->fieldMap)) {
return $this->fieldMap[$key];
}
+
// Otherwise no custom key, return original.
return $key;
}
@@ -250,8 +270,10 @@ abstract class Importer
* Figure out the fieldname of the custom field
*
* @author A. Gianotto <[email protected]>
+ *
* @since 3.0
- * @param $array array
+ *
+ * @param $array array
* @return string
*/
public function array_smart_custom_field_fetch(array $array, $key)
@@ -275,7 +297,7 @@ abstract class Importer
}
}
- protected function addErrorToBag($item, $field, $error_message)
+ protected function addErrorToBag($item, $field, $error_message)
{
if ($this->errorCallback) {
call_user_func($this->errorCallback, $item, $field, [$field => [$error_message]]);
@@ -289,9 +311,12 @@ abstract class Importer
* the same time. [ALG]
*
* @author Daniel Melzter
+ *
* @since 3.0
- * @param $row array
+ *
+ * @param $row array
* @return User Model w/ matching name
+ *
* @internal param array $user_array User details parsed from csv
*/
protected function createOrFetchUser($row, $type = 'user')
@@ -302,12 +327,12 @@ abstract class Importer
'first_name' => $this->findCsvMatch($row, 'first_name'),
'last_name' => $this->findCsvMatch($row, 'last_name'),
'display_name' => $this->findCsvMatch($row, 'display_name'),
- 'email' => $this->findCsvMatch($row, 'email'),
- 'manager_id'=> '',
- 'department_id' => '',
- 'username' => $this->findCsvMatch($row, 'username'),
- 'activated' => $this->fetchHumanBoolean($this->findCsvMatch($row, 'activated')),
- 'remote' => $this->fetchHumanBoolean(($this->findCsvMatch($row, 'remote'))),
+ 'email' => $this->findCsvMatch($row, 'email'),
+ 'manager_id' => '',
+ 'department_id' => '',
+ 'username' => $this->findCsvMatch($row, 'username'),
+ 'activated' => $this->fetchHumanBoolean($this->findCsvMatch($row, 'activated')),
+ 'remote' => $this->fetchHumanBoolean(($this->findCsvMatch($row, 'remote'))),
];
if ($type == 'manager') {
@@ -316,24 +341,24 @@ abstract class Importer
}
// Maybe we're lucky and the username was passed and it already exists.
- if (!empty($user_array['username'])) {
+ if (! empty($user_array['username'])) {
if ($user = User::where('username', $user_array['username'])->first()) {
$this->log('User '.$user_array['username'].' already exists');
+
return $user;
}
}
-
// If the full name and username is empty, bail out--we need this to extract first name (at the very least)
if ((empty($user_array['username'])) && (empty($user_array['full_name'])) && (empty($user_array['first_name']))) {
$this->log('Insufficient user data provided (Full name, first name or username is required) - skipping user creation.');
Log::debug('User array: ');
Log::debug(print_r($user_array, true));
Log::debug(print_r($row, true));
+
return false;
}
-
// Populate email if it does not exist.
if (empty($user_array['email'])) {
$user_array['email'] = User::generateEmailFromFullName($user_array['full_name']);
@@ -357,6 +382,7 @@ abstract class Importer
// Check for a matching username one more time after trying to guess username.
if ($user = User::where('username', $user_array['username'])->first()) {
$this->log('User '.$user_array['username'].' already exists');
+
return $user;
}
}
@@ -383,6 +409,7 @@ abstract class Importer
if ($user->save()) {
$this->log('User '.$user_array['username'].' created');
+
return $user;
}
@@ -393,8 +420,9 @@ abstract class Importer
/**
* Matches a user by created_by if user_name provided is a number
- * @param string $user_name users full name from csv
- * @return User User Matching ID
+ *
+ * @param string $user_name users full name from csv
+ * @return User User Matching ID
*/
protected function findUserByNumber($user_name)
{
@@ -409,8 +437,7 @@ abstract class Importer
/**
* Sets the Id of User performing import.
*
- * @param mixed $created_by the user id
- *
+ * @param mixed $created_by the user id
* @return self
*/
public function setCreatedBy($created_by)
@@ -423,8 +450,7 @@ abstract class Importer
/**
* Sets the Are we updating items in the import.
*
- * @param bool $updating the updating
- *
+ * @param bool $updating the updating
* @return self
*/
public function setUpdating($updating)
@@ -437,8 +463,7 @@ abstract class Importer
/**
* Sets whether or not we should notify the user with a welcome email
*
- * @param bool $send_welcome the send-welcome flag
- *
+ * @param bool $send_welcome the send-welcome flag
* @return self
*/
public function setShouldNotify($send_welcome)
@@ -451,8 +476,7 @@ abstract class Importer
/**
* Defines mappings of csv fields
*
- * @param bool $updating the updating
- *
+ * @param bool $updating the updating
* @return self
*/
public function setFieldMappings($fields)
@@ -468,10 +492,9 @@ abstract class Importer
/**
* Sets the callbacks for the import
*
- * @param callable $logCallback Function to call when we have data to log
- * @param callable $progressCallback Function to call to display progress
- * @param callable $errorCallback Function to call when we have errors
- *
+ * @param callable $logCallback Function to call when we have data to log
+ * @param callable $progressCallback Function to call to display progress
+ * @param callable $errorCallback Function to call when we have errors
* @return self
*/
public function setCallbacks(callable $logCallback, callable $progressCallback, callable $errorCallback)
@@ -486,8 +509,7 @@ abstract class Importer
/**
* Sets the value of usernameFormat.
*
- * @param string $usernameFormat the username format
- *
+ * @param string $usernameFormat the username format
* @return self
*/
public function setUsernameFormat($usernameFormat)
@@ -516,8 +538,10 @@ abstract class Importer
* Fetch an existing department, or create new if it doesn't exist
*
* @author A. Gianotto
+ *
* @since 4.6.5
- * @param $user_department string
+ *
+ * @param $user_department string
* @return int id of company created/found
*/
public function createOrFetchDepartment($user_department_name)
@@ -531,7 +555,7 @@ abstract class Importer
return $department->id;
}
- $department = new Department();
+ $department = new Department;
$department->name = $user_department_name;
if ($department->save()) {
@@ -545,13 +569,14 @@ abstract class Importer
return null;
}
-
/**
* Fetch an existing manager
*
* @author A. Gianotto
+ *
* @since 4.6.5
- * @param $user_manager string
+ *
+ * @param $user_manager string
* @return int id of company created/found
*/
public function fetchManager($user_manager_first_name, $user_manager_last_name)
@@ -572,13 +597,13 @@ abstract class Importer
* Parse a date or return null
*
* @author A. Gianotto
+ *
* @since 7.0.0
- * @param $field
- * @param $format
+ *
* @return string|null
-
*/
- public function parseOrNullDate($field, $format = 'date') {
+ public function parseOrNullDate($field, $format = 'date')
+ {
$date_format = 'Y-m-d';
@@ -590,12 +615,15 @@ abstract class Importer
try {
$value = CarbonImmutable::parse($this->item[$field])->format($date_format);
+
return $value;
} catch (\Exception $e) {
- $this->log('Unable to parse date: ' . $this->item[$field]);
+ $this->log('Unable to parse date: '.$this->item[$field]);
+
return null;
}
}
+
return null;
}
}
diff --git a/app/Importer/ItemImporter.php b/app/Importer/ItemImporter.php
index 92f44d991d..5cfa8973ca 100644
--- a/app/Importer/ItemImporter.php
+++ b/app/Importer/ItemImporter.php
@@ -10,8 +10,6 @@ use App\Models\Manufacturer;
use App\Models\Statuslabel;
use App\Models\Supplier;
use App\Models\User;
-use Carbon\CarbonImmutable;
-use Illuminate\Support\Facades\Log;
class ItemImporter extends Importer
{
@@ -87,7 +85,6 @@ class ItemImporter extends Importer
$this->item['serial'] = $this->findCsvMatch($row, 'serial');
$this->item['item_no'] = trim($this->findCsvMatch($row, 'item_no'));
-
$this->item['purchase_date'] = null;
if ($this->findCsvMatch($row, 'purchase_date') != '') {
$this->item['purchase_date'] = date('Y-m-d', strtotime($this->findCsvMatch($row, 'purchase_date')));
@@ -104,17 +101,18 @@ class ItemImporter extends Importer
/**
* Parse row to determine what (if anything) we should checkout to.
- * @param array $row CSV Row being parsed
- * @return ?SnipeModel Model to be checked out to
+ *
+ * @param array $row CSV Row being parsed
+ * @return ?SnipeModel Model to be checked out to
*/
protected function determineCheckout($row)
{
// Locations don't get checked out to anyone/anything
- if ((get_class($this) == LocationImporter::class) || (get_class($this) == AssetModelImporter::class) || (get_class($this) == SupplierImporter::class) || (get_class($this) == ManufacturerImporter::class) || (get_class($this) == CategoryImporter::class)) {
+ if ((get_class($this) == LocationImporter::class) || (get_class($this) == AssetModelImporter::class) || (get_class($this) == SupplierImporter::class) || (get_class($this) == ManufacturerImporter::class) || (get_class($this) == CategoryImporter::class)) {
return;
}
- if (strtolower($this->item['checkout_class']) === 'location' && $this->findCsvMatch($row, 'checkout_location') != null ) {
+ if (strtolower($this->item['checkout_class']) === 'location' && $this->findCsvMatch($row, 'checkout_location') != null) {
return Location::findOrFail($this->createOrFetchLocation($this->findCsvMatch($row, 'checkout_location')));
}
@@ -127,9 +125,11 @@ class ItemImporter extends Importer
* Also, if updating, we remove any fields from the array that are empty.
*
* @author Daniel Melzter
+ *
* @since 4.0
- * @param $model SnipeModel Model that's being updated.
- * @param $updating boolean Should we remove blank values?
+ *
+ * @param $model SnipeModel Model that's being updated.
+ * @param $updating boolean Should we remove blank values?
* @return array
*/
protected function sanitizeItemForStoring($model, $updating = false)
@@ -151,7 +151,8 @@ class ItemImporter extends Importer
/**
* Convenience function for updating that strips the empty values.
- * @param $model SnipeModel Model that's being updated.
+ *
+ * @param $model SnipeModel Model that's being updated.
* @return array
*/
protected function sanitizeItemForUpdating($model)
@@ -166,8 +167,10 @@ class ItemImporter extends Importer
* If We are updating, we only update the field if it's not empty.
*
* @author Daniel Melzter
+ *
* @since 4.0
- * @param $field string
+ *
+ * @param $field string
* @return bool
*/
protected function shouldUpdateField($field)
@@ -183,15 +186,18 @@ class ItemImporter extends Importer
* Select the asset model if it exists, otherwise create it.
*
* @author Daniel Melzter
+ *
* @since 3.0
+ *
* @param array
- * @param $row Row
+ * @param $row Row
* @return int Id of asset model created/found
+ *
* @internal param $asset_modelno string
*/
public function createOrFetchAssetModel(array $row)
{
- $condition = array();
+ $condition = [];
$asset_model_name = $this->findCsvMatch($row, 'asset_model');
$asset_model_category = $this->findCsvMatch($row, 'category');
$asset_modelNumber = $this->findCsvMatch($row, 'model_number');
@@ -209,10 +215,10 @@ class ItemImporter extends Importer
$asset_model = AssetModel::select('id');
- if (!empty($asset_model_name)) {
+ if (! empty($asset_model_name)) {
$asset_model = $asset_model->where('name', '=', $asset_model_name);
- if (!empty($asset_modelNumber)) {
+ if (! empty($asset_modelNumber)) {
$asset_model = $asset_model->where('model_number', '=', $asset_modelNumber);
}
}
@@ -224,6 +230,7 @@ class ItemImporter extends Importer
if (! $this->updating) {
$this->log('A matching model already exists, returning it.');
+
return $asset_model->id;
}
@@ -232,20 +239,20 @@ class ItemImporter extends Importer
$item['name'] = $asset_model_name;
$item['notes'] = $this->findCsvMatch($row, 'model_notes');
- if (!empty($asset_modelNumber)){
+ if (! empty($asset_modelNumber)) {
$item['model_number'] = $asset_modelNumber;
}
$asset_model->update($item);
$asset_model->save();
$this->log('Asset Model Updated');
-
+
return $asset_model->id;
}
$this->log('No Matching Model, Creating a new one');
- $asset_model = new AssetModel();
+ $asset_model = new AssetModel;
$asset_model->created_by = auth()->id();
$item = $this->sanitizeItemForStoring($asset_model, $editingModel);
$item['name'] = $asset_model_name;
@@ -271,9 +278,12 @@ class ItemImporter extends Importer
* Finds a category with the same name and item type in the database, otherwise creates it
*
* @author Daniel Melzter
+ *
* @since 3.0
- * @param $asset_category string
+ *
+ * @param $asset_category string
* @return int Id of category created/found
+ *
* @internal param string $item_type
*/
public function createOrFetchCategory($asset_category)
@@ -291,16 +301,15 @@ class ItemImporter extends Importer
$asset_category = 'Unnamed Category';
}
-
$category = Category::where(['name' => $asset_category, 'category_type' => $item_type])->first();
-
if ($category) {
$this->log('A matching category: '.$category->name.' already exists');
+
return $category->id;
}
- $category = new Category();
+ $category = new Category;
$category->created_by = auth()->id();
$category->name = $asset_category;
$category->category_type = $item_type;
@@ -310,7 +319,7 @@ class ItemImporter extends Importer
return $category->id;
}
- $this->logError($category, 'Category "'. $asset_category. '"');
+ $this->logError($category, 'Category "'.$asset_category.'"');
return null;
}
@@ -319,8 +328,10 @@ class ItemImporter extends Importer
* Fetch an existing company, or create new if it doesn't exist
*
* @author Daniel Melzter
+ *
* @since 3.0
- * @param $asset_company_name string
+ *
+ * @param $asset_company_name string
* @return int id of company created/found
*/
public function createOrFetchCompany($asset_company_name)
@@ -331,7 +342,7 @@ class ItemImporter extends Importer
return $company->id;
}
- $company = new Company();
+ $company = new Company;
$company->created_by = auth()->id();
$company->name = $asset_company_name;
@@ -349,16 +360,18 @@ class ItemImporter extends Importer
* Fetch an existing manager
*
* @author A. Gianotto
+ *
* @since 4.6.5
- * @param $user_manager string
+ *
+ * @param $user_manager string
* @return int id of company created/found
*/
public function fetchManager($user_manager_username = null, $user_manager_employee_num = null, $user_manager_first_name = null, $user_manager_last_name = null)
{
- if ($user_manager_username!='') {
+ if ($user_manager_username != '') {
$manager = User::where('username', '=', $user_manager_username)->first();
$this->log('Checking on username '.$user_manager_username);
- } elseif ($user_manager_employee_num!='') {
+ } elseif ($user_manager_employee_num != '') {
$manager = User::where('employee_num', '=', $user_manager_employee_num)->first();
$this->log('Checking on employee_num '.$user_manager_employee_num);
} else {
@@ -382,8 +395,10 @@ class ItemImporter extends Importer
* Fetch the existing status label or create new if it doesn't exist.
*
* @author Daniel Melzter
+ *
* @since 3.0
- * @param string $asset_statuslabel_name
+ *
+ * @param string $asset_statuslabel_name
* @return Statuslabel|null
*/
public function createOrFetchStatusLabel($asset_statuslabel_name)
@@ -391,7 +406,7 @@ class ItemImporter extends Importer
if (empty($asset_statuslabel_name)) {
return null;
}
- $status = Statuslabel::where(['name' => trim($asset_statuslabel_name)])->first();
+ $status = Statuslabel::where(['name' => trim($asset_statuslabel_name)])->first();
if ($status) {
$this->log('A matching Status '.$asset_statuslabel_name.' already exists');
@@ -399,7 +414,7 @@ class ItemImporter extends Importer
return $status->id;
}
$this->log('Creating a new status');
- $status = new Statuslabel();
+ $status = new Statuslabel;
$status->created_by = auth()->id();
$status->name = trim($asset_statuslabel_name);
@@ -409,10 +424,12 @@ class ItemImporter extends Importer
if ($status->save()) {
$this->log('Status '.$asset_statuslabel_name.' was created');
+
return $status->id;
}
$this->logError($status, 'Status "'.$asset_statuslabel_name.'"');
+
return null;
}
@@ -420,8 +437,10 @@ class ItemImporter extends Importer
* Finds a manufacturer with matching name, otherwise create it.
*
* @author Daniel Melzter
+ *
* @since 3.0
- * @param $item_manufacturer string
+ *
+ * @param $item_manufacturer string
* @return Manufacturer
*/
public function createOrFetchManufacturer($item_manufacturer)
@@ -429,7 +448,7 @@ class ItemImporter extends Importer
if (empty($item_manufacturer)) {
$item_manufacturer = 'Unknown';
}
- $manufacturer = Manufacturer::where(['name'=> $item_manufacturer])->first();
+ $manufacturer = Manufacturer::where(['name' => $item_manufacturer])->first();
if ($manufacturer) {
$this->log('Manufacturer '.$item_manufacturer.' already exists');
@@ -437,8 +456,8 @@ class ItemImporter extends Importer
return $manufacturer->id;
}
- //Otherwise create a manufacturer.
- $manufacturer = new Manufacturer();
+ // Otherwise create a manufacturer.
+ $manufacturer = new Manufacturer;
$manufacturer->name = trim($item_manufacturer);
$manufacturer->created_by = auth()->id();
@@ -456,14 +475,17 @@ class ItemImporter extends Importer
* Checks the DB to see if a location with the same name exists, otherwise create it
*
* @author Daniel Melzter
+ *
* @since 3.0
- * @param $asset_location string
+ *
+ * @param $asset_location string
* @return Location|null
*/
public function createOrFetchLocation($asset_location)
{
if (empty($asset_location)) {
$this->log('No location given, so none created.');
+
return null;
}
@@ -471,10 +493,11 @@ class ItemImporter extends Importer
if ($location) {
$this->log('Location '.$asset_location.' already exists');
+
return $location->id;
}
// No matching locations in the collection, create a new one.
- $location = new Location();
+ $location = new Location;
$location->name = $asset_location;
$location->address = '';
$location->city = '';
@@ -496,8 +519,10 @@ class ItemImporter extends Importer
* Fetch an existing supplier or create new if it doesn't exist
*
* @author Daniel Melzter
+ *
* @since 3.0
- * @param $row array
+ *
+ * @param $row array
* @return Supplier
*/
public function createOrFetchSupplier($item_supplier)
@@ -514,17 +539,17 @@ class ItemImporter extends Importer
return $supplier->id;
}
- $supplier = new Supplier();
+ $supplier = new Supplier;
$supplier->name = $item_supplier;
$supplier->created_by = auth()->id();
if ($supplier->save()) {
$this->log('Supplier '.$item_supplier.' was created');
+
return $supplier->id;
}
$this->logError($supplier, 'Supplier');
return null;
}
-
}
diff --git a/app/Importer/LicenseImporter.php b/app/Importer/LicenseImporter.php
index d5df4aba3c..108981fe10 100644
--- a/app/Importer/LicenseImporter.php
+++ b/app/Importer/LicenseImporter.php
@@ -4,7 +4,6 @@ namespace App\Importer;
use App\Models\Asset;
use App\Models\License;
-use Illuminate\Support\Facades\Auth;
class LicenseImporter extends ItemImporter
{
@@ -24,26 +23,26 @@ class LicenseImporter extends ItemImporter
* Create the license if it does not exist.
*
* @author Daniel Melzter
+ *
* @since 4.0
- * @param array $row
+ *
* @return License|mixed|null
- * updated @author Jes Vinsmoke
- * @since 6.1
+ * updated @author Jes Vinsmoke
*
+ * @since 6.1
*/
public function createLicenseIfNotExists(array $row)
{
$editingLicense = false;
$license = License::where('serial', $this->item['serial'])->where('name', $this->item['name'])
- ->first();
+ ->first();
if ($license) {
if (! $this->updating) {
- if($this->item['serial'] != "") {
- $this->log('A matching License ' . $this->item['name'] . ' with serial ' . $this->item['serial'] . ' already exists');
- }
- else {
- $this->log('A matching License ' . $this->item['name'] . ' with no serial number already exists');
+ if ($this->item['serial'] != '') {
+ $this->log('A matching License '.$this->item['name'].' with serial '.$this->item['serial'].' already exists');
+ } else {
+ $this->log('A matching License '.$this->item['name'].' with no serial number already exists');
}
return;
@@ -57,9 +56,9 @@ class LicenseImporter extends ItemImporter
}
$asset_tag = $this->item['asset_tag'] = trim($this->findCsvMatch($row, 'asset_tag')); // used for checkout out to an asset.
- $this->item["expiration_date"] = null;
- if ($this->findCsvMatch($row, "expiration_date")!='') {
- $this->item["expiration_date"] = date("Y-m-d 00:00:01", strtotime(trim($this->findCsvMatch($row, "expiration_date"))));
+ $this->item['expiration_date'] = null;
+ if ($this->findCsvMatch($row, 'expiration_date') != '') {
+ $this->item['expiration_date'] = date('Y-m-d 00:00:01', strtotime(trim($this->findCsvMatch($row, 'expiration_date'))));
}
$this->item['license_email'] = trim($this->findCsvMatch($row, 'license_email'));
$this->item['license_name'] = trim($this->findCsvMatch($row, 'license_name'));
@@ -70,15 +69,14 @@ class LicenseImporter extends ItemImporter
$this->item['manufacturer'] = $this->createOrFetchManufacturer(trim($this->findCsvMatch($row, 'manufacturer')));
$this->item['min_amt'] = trim($this->findCsvMatch($row, 'min_amt'));
- if($this->item['reassignable'] == "")
- {
+ if ($this->item['reassignable'] == '') {
$this->item['reassignable'] = 1;
}
$this->item['seats'] = $this->findCsvMatch($row, 'seats');
-
- $this->item["termination_date"] = null;
- if ($this->findCsvMatch($row, "termination_date")!='') {
- $this->item["termination_date"] = date("Y-m-d 00:00:01", strtotime($this->findCsvMatch($row, "termination_date")));
+
+ $this->item['termination_date'] = null;
+ if ($this->findCsvMatch($row, 'termination_date') != '') {
+ $this->item['termination_date'] = date('Y-m-d 00:00:01', strtotime($this->findCsvMatch($row, 'termination_date')));
}
if ($editingLicense) {
@@ -99,7 +97,7 @@ class LicenseImporter extends ItemImporter
$asset = Asset::where('asset_tag', $asset_tag)->first();
$targetLicense = $license->freeSeat();
- if (is_null($targetLicense)){
+ if (is_null($targetLicense)) {
return;
}
diff --git a/app/Importer/LocationImporter.php b/app/Importer/LocationImporter.php
index bed7f680e6..f6c72efe77 100644
--- a/app/Importer/LocationImporter.php
+++ b/app/Importer/LocationImporter.php
@@ -28,11 +28,12 @@ class LocationImporter extends ItemImporter
/**
* Create a location if a duplicate does not exist.
+ *
* @todo Investigate how this should interact with Importer::createLocationIfNotExists
*
* @author A. Gianotto
+ *
* @since 6.1.0
- * @param array $row
*/
public function createLocationIfNotExists(array $row)
{
@@ -41,16 +42,16 @@ class LocationImporter extends ItemImporter
$location = Location::where('name', '=', $this->findCsvMatch($row, 'name'))->first();
- if ($this->findCsvMatch($row, 'id')!='') {
+ if ($this->findCsvMatch($row, 'id') != '') {
// Override location if an ID was given
\Log::debug('Finding location by ID: '.$this->findCsvMatch($row, 'id'));
$location = Location::find($this->findCsvMatch($row, 'id'));
}
-
if ($location) {
if (! $this->updating) {
$this->log('A matching Location '.$this->item['name'].' already exists');
+
return;
}
@@ -77,12 +78,11 @@ class LocationImporter extends ItemImporter
$this->item['notes'] = trim($this->findCsvMatch($row, 'notes'));
$this->item['tag_color'] = trim($this->findCsvMatch($row, 'tag_color'));
-
if ($this->findCsvMatch($row, 'parent_location')) {
$this->item['parent_id'] = $this->createOrFetchLocation(trim($this->findCsvMatch($row, 'parent_location')));
}
- if (!empty($this->item['manager'])) {
+ if (! empty($this->item['manager'])) {
if ($manager = $this->createOrFetchUser($row, 'manager')) {
$this->item['manager_id'] = $manager->id;
}
@@ -91,7 +91,6 @@ class LocationImporter extends ItemImporter
Log::debug('Item array is: ');
Log::debug(print_r($this->item, true));
-
if ($editingLocation) {
Log::debug('Updating existing location');
$location->update($this->sanitizeItemForUpdating($location));
@@ -105,14 +104,15 @@ class LocationImporter extends ItemImporter
if ($location->save()) {
$this->log('Location '.$location->name.' created or updated from CSV import');
+
return $location;
} else {
Log::debug($location->getErrors());
$this->logError($location, 'Location "'.$this->item['name'].'"');
+
return $location->errors;
}
-
}
-}
\ No newline at end of file
+}
diff --git a/app/Importer/ManufacturerImporter.php b/app/Importer/ManufacturerImporter.php
index 460b42c811..e4f277f698 100644
--- a/app/Importer/ManufacturerImporter.php
+++ b/app/Importer/ManufacturerImporter.php
@@ -28,11 +28,12 @@ class ManufacturerImporter extends ItemImporter
/**
* Create a manufacturer if a duplicate does not exist.
+ *
* @todo Investigate how this should interact with Importer::createManufacturerIfNotExists
*
* @author A. Gianotto
+ *
* @since 6.1.0
- * @param array $row
*/
public function createManufacturerIfNotExists(array $row)
{
@@ -41,16 +42,16 @@ class ManufacturerImporter extends ItemImporter
$manufacturer = Manufacturer::where('name', '=', $this->findCsvMatch($row, 'name'))->first();
- if ($this->findCsvMatch($row, 'id')!='') {
+ if ($this->findCsvMatch($row, 'id') != '') {
// Override manufacturer if an ID was given
\Log::debug('Finding manufacturer by ID: '.$this->findCsvMatch($row, 'id'));
$manufacturer = Manufacturer::find($this->findCsvMatch($row, 'id'));
}
-
if ($manufacturer) {
if (! $this->updating) {
$this->log('A matching Manufacturer '.$this->item['name'].' already exists');
+
return;
}
@@ -74,11 +75,9 @@ class ManufacturerImporter extends ItemImporter
$this->item['notes'] = trim($this->findCsvMatch($row, 'notes'));
$this->item['tag_color'] = trim($this->findCsvMatch($row, 'tag_color'));
-
Log::debug('Item array is: ');
Log::debug(print_r($this->item, true));
-
if ($editingManufacturer) {
Log::debug('Updating existing manufacturer');
$manufacturer->update($this->sanitizeItemForUpdating($manufacturer));
@@ -89,14 +88,15 @@ class ManufacturerImporter extends ItemImporter
if ($manufacturer->save()) {
$this->log('Manufacturer '.$manufacturer->name.' created or updated from CSV import');
+
return $manufacturer;
} else {
Log::debug($manufacturer->getErrors());
$this->logError($manufacturer, 'Manufacturer "'.$this->item['name'].'"');
+
return $manufacturer->errors;
}
-
}
-}
\ No newline at end of file
+}
diff --git a/app/Importer/SupplierImporter.php b/app/Importer/SupplierImporter.php
index 398a4f4d3b..ccc1a97a60 100644
--- a/app/Importer/SupplierImporter.php
+++ b/app/Importer/SupplierImporter.php
@@ -28,11 +28,12 @@ class SupplierImporter extends ItemImporter
/**
* Create a supplier if a duplicate does not exist.
+ *
* @todo Investigate how this should interact with Importer::createSupplierIfNotExists
*
* @author A. Gianotto
+ *
* @since 6.1.0
- * @param array $row
*/
public function createSupplierIfNotExists(array $row)
{
@@ -41,16 +42,16 @@ class SupplierImporter extends ItemImporter
$supplier = Supplier::where('name', '=', $this->findCsvMatch($row, 'name'))->first();
- if ($this->findCsvMatch($row, 'id')!='') {
+ if ($this->findCsvMatch($row, 'id') != '') {
// Override supplier if an ID was given
\Log::debug('Finding supplier by ID: '.$this->findCsvMatch($row, 'id'));
$supplier = Supplier::find($this->findCsvMatch($row, 'id'));
}
-
if ($supplier) {
if (! $this->updating) {
$this->log('A matching Supplier '.$this->item['name'].' already exists');
+
return;
}
@@ -78,11 +79,9 @@ class SupplierImporter extends ItemImporter
$this->item['notes'] = trim($this->findCsvMatch($row, 'notes'));
$this->item['tag_color'] = trim($this->findCsvMatch($row, 'tag_color'));
-
Log::debug('Item array is: ');
Log::debug(print_r($this->item, true));
-
if ($editingSupplier) {
Log::debug('Updating existing supplier');
$supplier->update($this->sanitizeItemForUpdating($supplier));
@@ -93,14 +92,15 @@ class SupplierImporter extends ItemImporter
if ($supplier->save()) {
$this->log('Supplier '.$supplier->name.' created or updated from CSV import');
+
return $supplier;
} else {
Log::debug($supplier->getErrors());
$this->logError($supplier, 'Supplier "'.$this->item['name'].'"');
+
return $supplier->errors;
}
-
}
-}
\ No newline at end of file
+}
diff --git a/app/Importer/UserImporter.php b/app/Importer/UserImporter.php
index 81e0156f13..1deab4c3bd 100644
--- a/app/Importer/UserImporter.php
+++ b/app/Importer/UserImporter.php
@@ -7,10 +7,9 @@ use App\Models\Department;
use App\Models\Setting;
use App\Models\User;
use App\Notifications\WelcomeNotification;
+use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\Log;
-use Illuminate\Support\Facades\Password;
-use Illuminate\Support\Facades\Auth;
/**
* This is ONLY used for the User Import. When we are importing users
@@ -22,6 +21,7 @@ use Illuminate\Support\Facades\Auth;
class UserImporter extends ItemImporter
{
protected $users;
+
protected $send_welcome = false;
public function __construct($filename)
@@ -37,11 +37,12 @@ class UserImporter extends ItemImporter
/**
* Create a user if a duplicate does not exist.
+ *
* @todo Investigate how this should interact with Importer::createOrFetchUser
*
* @author Daniel Melzter
+ *
* @since 4.0
- * @param array $row
*/
public function createUserIfNotExists(array $row)
{
@@ -68,9 +69,9 @@ class UserImporter extends ItemImporter
$this->item['employee_num'] = trim($this->findCsvMatch($row, 'employee_num'));
$this->item['department_id'] = trim($this->createOrFetchDepartment(trim($this->findCsvMatch($row, 'department'))));
$this->item['manager_id'] = $this->fetchManager(trim($this->findCsvMatch($row, 'manager_username')), trim($this->findCsvMatch($row, 'manager_employee_num')), trim($this->findCsvMatch($row, 'manager_first_name')), trim($this->findCsvMatch($row, 'manager_last_name')));
- $this->item['remote'] = ($this->fetchHumanBoolean(trim($this->findCsvMatch($row, 'remote'))) == 1 ) ? '1' : 0;
- $this->item['vip'] = ($this->fetchHumanBoolean(trim($this->findCsvMatch($row, 'vip'))) ==1 ) ? '1' : 0;
- $this->item['autoassign_licenses'] = ($this->fetchHumanBoolean(trim($this->findCsvMatch($row, 'autoassign_licenses'))) ==1 ) ? '1' : 0;
+ $this->item['remote'] = ($this->fetchHumanBoolean(trim($this->findCsvMatch($row, 'remote'))) == 1) ? '1' : 0;
+ $this->item['vip'] = ($this->fetchHumanBoolean(trim($this->findCsvMatch($row, 'vip'))) == 1) ? '1' : 0;
+ $this->item['autoassign_licenses'] = ($this->fetchHumanBoolean(trim($this->findCsvMatch($row, 'autoassign_licenses'))) == 1) ? '1' : 0;
$this->handleEmptyStringsForDates();
@@ -79,15 +80,14 @@ class UserImporter extends ItemImporter
$this->item['department_id'] = $this->createOrFetchDepartment($user_department);
}
- if (is_null($this->item['username']) || $this->item['username'] == "") {
- $user_full_name = $this->item['first_name'] . ' ' . $this->item['last_name'];
+ if (is_null($this->item['username']) || $this->item['username'] == '') {
+ $user_full_name = $this->item['first_name'].' '.$this->item['last_name'];
$user_formatted_array = User::generateFormattedNameFromFullName($user_full_name, Setting::getSettings()->username_format);
$this->item['username'] = $user_formatted_array['username'];
}
-
// Check if a numeric ID was passed. If it does, use that above all else.
- if ((array_key_exists('id', $this->item) && ($this->item['id'] != "") && (is_numeric($this->item['id'])))) {
+ if ((array_key_exists('id', $this->item) && ($this->item['id'] != '') && (is_numeric($this->item['id'])))) {
$user = User::find($this->item['id']);
} else {
$user = User::where('username', $this->item['username'])->first();
@@ -98,12 +98,13 @@ class UserImporter extends ItemImporter
// If the user does not want to update existing values, only add new ones, bail out
if (! $this->updating) {
Log::debug('A matching User '.$this->item['name'].' already exists. ');
+
return;
}
$this->log('Updating User');
- if (Auth::check() && (!Gate::allows('canEditAuthFields', $user))) {
+ if (Auth::check() && (! Gate::allows('canEditAuthFields', $user))) {
unset($user->username);
unset($user->email);
unset($user->password);
@@ -119,26 +120,23 @@ class UserImporter extends ItemImporter
Asset::where('assigned_type', User::class)
->where('assigned_to', $user->id)
->update(['location_id' => $user->location_id]);
-
+
// Log::debug('UserImporter.php Updated User ' . print_r($user, true));
return;
}
-
-
// This needs to be applied after the update logic, otherwise we'll overwrite user passwords
// Issue #5408
$this->item['password'] = $this->tempPassword;
$this->log('No matching user, creating one');
- $user = new User();
+ $user = new User;
$user->created_by = auth()->id();
$user->fill($this->sanitizeItemForStoring($user));
// TODO - check for gate here I guess
-
if ($user->save()) {
$this->log('User '.$this->item['name'].' was created');
@@ -149,7 +147,7 @@ class UserImporter extends ItemImporter
try {
$user->notify(new WelcomeNotification($user));
} catch (\Exception $e) {
- Log::warning('Could not send welcome notification for user: ' . $e->getMessage());
+ Log::warning('Could not send welcome notification for user: '.$e->getMessage());
}
}
@@ -164,41 +162,44 @@ class UserImporter extends ItemImporter
$this->logError($user, 'User');
}
-
/**
* Fetch an existing department, or create new if it doesn't exist
*
* @author Daniel Melzter
+ *
* @since 5.0
- * @param $department_name string
+ *
+ * @param $department_name string
* @return int id of department created/found
*/
public function createOrFetchDepartment($department_name)
{
- if (is_null($department_name) || $department_name == ''){
+ if (is_null($department_name) || $department_name == '') {
return null;
}
-
$department = Department::where(['name' => $department_name])->first();
if ($department) {
- $this->log('A matching department ' . $department_name . ' already exists');
+ $this->log('A matching department '.$department_name.' already exists');
+
return $department->id;
}
- $department = new department();
+ $department = new Department;
$department->name = $department_name;
$department->created_by = $this->created_by;
if ($department->save()) {
- $this->log('department ' . $department_name . ' was created');
+ $this->log('department '.$department_name.' was created');
+
return $department->id;
}
$this->logError($department, 'Department');
+
return null;
}
-
+
public function sendWelcome($send = true)
{
$this->send_welcome = $send;
@@ -208,8 +209,6 @@ class UserImporter extends ItemImporter
* Since the findCsvMatch() method will set '' for columns that are present but empty,
* we need to set those empty strings to null to avoid passing bad data to the database
* (ie ending up with 0000-00-00 instead of the intended null).
- *
- * @return void
*/
private function handleEmptyStringsForDates(): void
{