Skip to content

A free open source IT asset/license management system

Refactor for less npath complexity

snipee43b314e8c17
diff --git a/app/SyncAdapters/Jamf/JamfAdapter.php b/app/SyncAdapters/Jamf/JamfAdapter.php
index 7d2a7e5b6f..9b587bb788 100644
--- a/app/SyncAdapters/Jamf/JamfAdapter.php
+++ b/app/SyncAdapters/Jamf/JamfAdapter.php
@@ -3,7 +3,6 @@
namespace App\SyncAdapters\Jamf;
use App\Models\Asset;
-use App\Models\AssetExternalSource;
use App\SyncAdapters\HostInventoryRecord;
use App\SyncAdapters\PushableAdapter;
use App\SyncAdapters\Support\ConfigurableAdapter;
@@ -159,27 +158,14 @@ class JamfAdapter extends ConfigurableAdapter implements PushableAdapter
*/
public function push(Asset $asset, array $changedFields = []): void
{
- $pushFields = $this->pushDirectedFields();
- if ($pushFields === []) {
- return;
- }
-
- if ($changedFields !== [] && array_intersect($changedFields, $pushFields) === []) {
- return;
- }
-
- $externalSource = AssetExternalSource::query()
- ->where('asset_id', $asset->id)
- ->where('source', $this->name())
- ->first();
-
+ $externalSource = $this->pushPrologue($asset, $changedFields);
if ($externalSource === null) {
return;
}
$payload = [];
$touched = [];
- foreach ($pushFields as $field) {
+ foreach ($this->pushDirectedFields() as $field) {
$path = self::sourceFieldToJamfPath($field);
if ($path === null) {
continue;
@@ -194,14 +180,11 @@ class JamfAdapter extends ConfigurableAdapter implements PushableAdapter
$touched[] = $path;
}
- $template = $this->pushNotesTemplate();
- $notesTarget = $this->effectiveNotesTarget();
- if ($template !== '' && $notesTarget !== null) {
- $composed = \App\SyncAdapters\Support\NotesComposer::compose($asset, $template);
- if ($composed !== '') {
- Arr::set($payload, $notesTarget, $composed);
- $touched[] = $notesTarget;
- }
+ $composed = $this->composeNotesForPush($asset);
+ if ($composed !== '') {
+ $notesTarget = $this->effectiveNotesTarget();
+ Arr::set($payload, $notesTarget, $composed);
+ $touched[] = $notesTarget;
}
if ($payload === []) {
diff --git a/app/SyncAdapters/Kandji/KandjiAdapter.php b/app/SyncAdapters/Kandji/KandjiAdapter.php
index a802be6d15..66d47cce7b 100644
--- a/app/SyncAdapters/Kandji/KandjiAdapter.php
+++ b/app/SyncAdapters/Kandji/KandjiAdapter.php
@@ -3,7 +3,6 @@
namespace App\SyncAdapters\Kandji;
use App\Models\Asset;
-use App\Models\AssetExternalSource;
use App\SyncAdapters\HostInventoryRecord;
use App\SyncAdapters\PushableAdapter;
use App\SyncAdapters\Support\ConfigurableAdapter;
@@ -166,30 +165,13 @@ class KandjiAdapter extends ConfigurableAdapter implements PushableAdapter
*/
public function push(Asset $asset, array $changedFields = []): void
{
- $pushFields = $this->pushDirectedFields();
- if ($pushFields === []) {
- return;
- }
-
- // Optional early-exit: if the caller told us which source
- // fields changed and none of them are push-directed, skip
- // the API call entirely. Empty $changedFields = "push all
- // push-directed fields regardless".
- if ($changedFields !== [] && array_intersect($changedFields, $pushFields) === []) {
- return;
- }
-
- $externalSource = AssetExternalSource::query()
- ->where('asset_id', $asset->id)
- ->where('source', $this->name())
- ->first();
-
+ $externalSource = $this->pushPrologue($asset, $changedFields);
if ($externalSource === null) {
return;
}
$payload = [];
- foreach ($pushFields as $field) {
+ foreach ($this->pushDirectedFields() as $field) {
$mapped = self::sourceFieldToKandjiField($field);
if ($mapped === null) {
continue;
@@ -207,13 +189,9 @@ class KandjiAdapter extends ConfigurableAdapter implements PushableAdapter
// override or adapter default) merge into the same payload
// so admins can push both an asset_tag AND a composed notes
// blob in a single API call.
- $template = $this->pushNotesTemplate();
- $notesTarget = $this->effectiveNotesTarget();
- if ($template !== '' && $notesTarget !== null) {
- $composed = \App\SyncAdapters\Support\NotesComposer::compose($asset, $template);
- if ($composed !== '') {
- $payload[$notesTarget] = $composed;
- }
+ $composed = $this->composeNotesForPush($asset);
+ if ($composed !== '') {
+ $payload[$this->effectiveNotesTarget()] = $composed;
}
if ($payload === []) {
diff --git a/app/SyncAdapters/Mosyle/MosyleAdapter.php b/app/SyncAdapters/Mosyle/MosyleAdapter.php
index 43478f25a2..96d9978989 100644
--- a/app/SyncAdapters/Mosyle/MosyleAdapter.php
+++ b/app/SyncAdapters/Mosyle/MosyleAdapter.php
@@ -3,7 +3,6 @@
namespace App\SyncAdapters\Mosyle;
use App\Models\Asset;
-use App\Models\AssetExternalSource;
use App\SyncAdapters\HostInventoryRecord;
use App\SyncAdapters\PushableAdapter;
use App\SyncAdapters\Support\ConfigurableAdapter;
@@ -159,20 +158,7 @@ class MosyleAdapter extends ConfigurableAdapter implements PushableAdapter
*/
public function push(Asset $asset, array $changedFields = []): void
{
- $pushFields = $this->pushDirectedFields();
- if ($pushFields === []) {
- return;
- }
-
- if ($changedFields !== [] && array_intersect($changedFields, $pushFields) === []) {
- return;
- }
-
- $externalSource = AssetExternalSource::query()
- ->where('asset_id', $asset->id)
- ->where('source', $this->name())
- ->first();
-
+ $externalSource = $this->pushPrologue($asset, $changedFields);
if ($externalSource === null) {
return;
}
@@ -189,7 +175,7 @@ class MosyleAdapter extends ConfigurableAdapter implements PushableAdapter
$pushedFields = [];
$client = null;
- foreach ($pushFields as $field) {
+ foreach ($this->pushDirectedFields() as $field) {
if ($field !== 'asset_tag') {
continue;
}
@@ -219,21 +205,19 @@ class MosyleAdapter extends ConfigurableAdapter implements PushableAdapter
// Composed notes push. Independent from the asset_tag push
// because Mosyle's write API dispatches per-op, so notes get
// a second POST to /devices with the notes operation.
- $template = $this->pushNotesTemplate();
- if ($template !== '') {
- $composed = \App\SyncAdapters\Support\NotesComposer::compose($asset, $template);
- if ($composed !== '') {
- if ($this->isPushDryRun()) {
- Log::channel('sync-adapters')->info(sprintf(
- '%s push [dry-run]: would set Mosyle device serial=%s notes=%s',
- $this->name(),
- $serial,
- $composed,
- ));
- } else {
- $client ??= new MosyleClient(baseUrl: $this->url(), token: $this->credential('token'));
- $client->updateDeviceNotesBySerial($serial, $composed);
- }
+ $composed = $this->composeNotesForPush($asset);
+ if ($composed !== '') {
+ if ($this->isPushDryRun()) {
+ Log::channel('sync-adapters')->info(sprintf(
+ '%s push [dry-run]: would set Mosyle device serial=%s notes=%s',
+ $this->name(),
+ $serial,
+ $composed,
+ ));
+ $pushedFields[] = 'notes';
+ } else {
+ $client ??= new MosyleClient(baseUrl: $this->url(), token: $this->credential('token'));
+ $client->updateDeviceNotesBySerial($serial, $composed);
$pushedFields[] = 'notes';
}
}
diff --git a/app/SyncAdapters/NinjaOne/NinjaOneAdapter.php b/app/SyncAdapters/NinjaOne/NinjaOneAdapter.php
index 9816278e8a..6aef6f112b 100644
--- a/app/SyncAdapters/NinjaOne/NinjaOneAdapter.php
+++ b/app/SyncAdapters/NinjaOne/NinjaOneAdapter.php
@@ -3,7 +3,6 @@
namespace App\SyncAdapters\NinjaOne;
use App\Models\Asset;
-use App\Models\AssetExternalSource;
use App\SyncAdapters\HostInventoryRecord;
use App\SyncAdapters\PushableAdapter;
use App\SyncAdapters\Support\ConfigurableAdapter;
@@ -176,20 +175,7 @@ class NinjaOneAdapter extends ConfigurableAdapter implements PushableAdapter
*/
public function push(Asset $asset, array $changedFields = []): void
{
- $pushFields = $this->pushDirectedFields();
- if ($pushFields === []) {
- return;
- }
-
- if ($changedFields !== [] && array_intersect($changedFields, $pushFields) === []) {
- return;
- }
-
- $externalSource = AssetExternalSource::query()
- ->where('asset_id', $asset->id)
- ->where('source', $this->name())
- ->first();
-
+ $externalSource = $this->pushPrologue($asset, $changedFields);
if ($externalSource === null) {
return;
}
@@ -206,7 +192,7 @@ class NinjaOneAdapter extends ConfigurableAdapter implements PushableAdapter
}
$payload = [];
- foreach ($pushFields as $field) {
+ foreach ($this->pushDirectedFields() as $field) {
if ($field !== 'asset_tag') {
continue;
}
@@ -224,13 +210,9 @@ class NinjaOneAdapter extends ConfigurableAdapter implements PushableAdapter
// sets the notes-target field via the composed-notes fieldset
// override. Nothing default because Ninja has no built-in
// notes concept for us to guess.
- $template = $this->pushNotesTemplate();
- $notesTarget = $this->effectiveNotesTarget();
- if ($template !== '' && $notesTarget !== null) {
- $composed = \App\SyncAdapters\Support\NotesComposer::compose($asset, $template);
- if ($composed !== '') {
- $payload[$notesTarget] = $composed;
- }
+ $composed = $this->composeNotesForPush($asset);
+ if ($composed !== '') {
+ $payload[$this->effectiveNotesTarget()] = $composed;
}
if ($payload === []) {
diff --git a/app/SyncAdapters/Support/ConfigurableAdapter.php b/app/SyncAdapters/Support/ConfigurableAdapter.php
index 1649226875..e094b90d7b 100644
--- a/app/SyncAdapters/Support/ConfigurableAdapter.php
+++ b/app/SyncAdapters/Support/ConfigurableAdapter.php
@@ -193,19 +193,43 @@ abstract class ConfigurableAdapter implements HostInventoryAdapter
return $rules;
}
- /**
- * @SuppressWarnings("PHPMD.ElseExpression")
- */
public function saveConfig(Request $request): void
{
$slug = $this->instance->slug;
+ $this->persistUrl($request, $slug);
+ $this->persistCredentialsFromSchema($request, $slug);
+ $this->persistOperationalSettings($request, $slug);
+
+ if ($this->supportsGroupScoping()) {
+ $this->persistGroupMappings($request, $slug);
+ }
+
+ $validFields = $this->validMappingFields();
+ $this->persistFieldMappings($request, $slug, $validFields);
+ $this->persistFieldDirections($request, $slug, $validFields);
+
+ $this->afterSaveConfig();
+ }
+
+ /**
+ * URL is always overwritten from the form. Blank means "no URL
+ * configured yet" which the isEnabled() gate then treats as
+ * "instance not usable."
+ */
+ private function persistUrl(Request $request, string $slug): void
+ {
SyncAdapterConfig::put($this->instance->id, 'url', $request->input($slug.'_url'));
+ }
- // Blank input preserves the existing value so admins can update
- // the URL without re-entering every credential every time.
- // Secrets get encrypted at rest. plain-text fields (like OAuth
- // tenant / client IDs) get stored as-is.
+ /**
+ * Blank input preserves the existing value so admins can update the
+ * URL without re-entering every credential every time. Secrets get
+ * encrypted at rest. Plain-text fields (like OAuth tenant / client
+ * IDs) get stored as-is.
+ */
+ private function persistCredentialsFromSchema(Request $request, string $slug): void
+ {
foreach ($this->credentialSchema() as $field) {
$fieldName = $slug.'_'.$field['key'];
if (! $request->filled($fieldName)) {
@@ -218,7 +242,15 @@ abstract class ConfigurableAdapter implements HostInventoryAdapter
}
SyncAdapterConfig::put($this->instance->id, $field['key'], $value);
}
+ }
+ /**
+ * Non-credential operational toggles + defaults + push settings.
+ * Grouped here so saveConfig() reads as a list of intent rather
+ * than a wall of SyncAdapterConfig::put() calls.
+ */
+ private function persistOperationalSettings(Request $request, string $slug): void
+ {
SyncAdapterConfig::put(
$this->instance->id,
'log_heartbeats',
@@ -311,46 +343,72 @@ abstract class ConfigurableAdapter implements HostInventoryAdapter
'push_notes_target',
(string) $request->input($slug.'_push_notes_target', ''),
);
+ }
- // Per-vendor-group Snipe-IT company mappings. Form emits one
- // input per group (name = {slug}_group_mapping[{vendor_group_id}]).
- // Blank / "unassigned" values clear that group's mapping so
- // it falls back to the instance company_id at sync time.
- if ($this->supportsGroupScoping()) {
- foreach ((array) $request->input($slug.'_group_mapping', []) as $vendorGroupId => $companyId) {
- $key = 'group_mapping.'.$vendorGroupId;
- if ($companyId === null || $companyId === '') {
- SyncAdapterConfig::forget($this->instance->id, $key);
- } else {
- SyncAdapterConfig::put($this->instance->id, $key, (string) (int) $companyId);
- }
+ /**
+ * Per-vendor-group Snipe-IT company mappings. Form emits one input
+ * per group (name = {slug}_group_mapping[{vendor_group_id}]).
+ * Blank / "unassigned" values clear that group's mapping so it
+ * falls back to the instance company_id at sync time.
+ */
+ private function persistGroupMappings(Request $request, string $slug): void
+ {
+ foreach ((array) $request->input($slug.'_group_mapping', []) as $vendorGroupId => $companyId) {
+ $key = 'group_mapping.'.$vendorGroupId;
+
+ if ($companyId === null || $companyId === '') {
+ SyncAdapterConfig::forget($this->instance->id, $key);
+
+ continue;
}
+
+ SyncAdapterConfig::put($this->instance->id, $key, (string) (int) $companyId);
}
+ }
- // Standard fields have shipped defaults from MappingTargets.
- // Extras default to skip. Both share the same mapping.{key}
- // storage prefix because the two key namespaces don't collide
- // (standard = hostname/serial/etc, extras = adapter-prefixed).
- $validFields = array_merge(
+ /**
+ * Standard fields have shipped defaults from MappingTargets. Extras
+ * default to skip. Both share the same mapping.{key} storage prefix
+ * because the two key namespaces don't collide (standard =
+ * hostname/serial/etc, extras = adapter-prefixed).
+ *
+ * @return array<int, string>
+ */
+ private function validMappingFields(): array
+ {
+ return array_merge(
MappingTargets::FIELDS,
array_keys($this->extraFields()),
);
+ }
+ /**
+ * @param array<int, string> $validFields
+ */
+ private function persistFieldMappings(Request $request, string $slug, array $validFields): void
+ {
foreach ((array) $request->input($slug.'_mapping', []) as $field => $target) {
if (! in_array($field, $validFields, true)) {
continue;
}
SyncAdapterConfig::put($this->instance->id, 'mapping.'.$field, (string) $target);
}
+ }
- // Per-field direction (pull / push / skip). Orthogonal to the
- // target column stored above so admins can flip direction
- // without re-picking the target. Only meaningful for adapters
- // that implement PushableAdapter. For pull-only adapters the
- // form doesn't render the direction column and this loop is
- // a no-op. Value 'pull' is the default and doesn't need
- // storing, but writing it explicitly keeps the round-trip
- // behavior predictable for admins reading raw config.
+ /**
+ * Per-field direction (pull / push / skip). Orthogonal to the
+ * target column stored above so admins can flip direction without
+ * re-picking the target. Only meaningful for adapters that
+ * implement PushableAdapter. For pull-only adapters the form
+ * doesn't render the direction column and this loop is a no-op.
+ * Value 'pull' is the default and doesn't need storing, but writing
+ * it explicitly keeps the round-trip behavior predictable for
+ * admins reading raw config.
+ *
+ * @param array<int, string> $validFields
+ */
+ private function persistFieldDirections(Request $request, string $slug, array $validFields): void
+ {
foreach ((array) $request->input($slug.'_direction', []) as $field => $direction) {
if (! in_array($field, $validFields, true)) {
continue;
@@ -360,8 +418,6 @@ abstract class ConfigurableAdapter implements HostInventoryAdapter
}
SyncAdapterConfig::put($this->instance->id, 'direction.'.$field, (string) $direction);
}
-
- $this->afterSaveConfig();
}
/**
@@ -471,6 +527,63 @@ abstract class ConfigurableAdapter implements HostInventoryAdapter
return $out;
}
+ /**
+ * Shared prologue for every PushableAdapter::push() implementation.
+ * Runs the three identical guards each adapter's push() started with
+ * and returns the AssetExternalSource row when the push should
+ * proceed, or null when any guard rejects it. Callers early-return
+ * on null.
+ *
+ * The three guards, in order:
+ * 1. pushDirectedFields is empty AND no composed-notes template is
+ * configured — nothing to send, skip.
+ * 2. Caller-provided $changedFields is non-empty but doesn't
+ * intersect pushDirectedFields — the caller told us which
+ * fields changed and none of them are push-directed on this
+ * instance, so skip the vendor call.
+ * 3. asset_external_sources row missing — the asset was never
+ * synced from this instance, so we have no vendor device id to
+ * write against.
+ *
+ * @param array<int, string> $changedFields
+ */
+ public function pushPrologue(\App\Models\Asset $asset, array $changedFields): ?\App\Models\AssetExternalSource
+ {
+ $pushFields = $this->pushDirectedFields();
+ $notesConfigured = $this->pushNotesTemplate() !== '' && $this->effectiveNotesTarget() !== null;
+
+ if ($pushFields === [] && ! $notesConfigured) {
+ return null;
+ }
+
+ if ($pushFields !== [] && $changedFields !== []
+ && array_intersect($changedFields, $pushFields) === []) {
+ return null;
+ }
+
+ return \App\Models\AssetExternalSource::query()
+ ->where('asset_id', $asset->id)
+ ->where('source', $this->name())
+ ->first();
+ }
+
+ /**
+ * Render the composed-notes template against the given asset via
+ * NotesComposer, or return an empty string when the template or
+ * target isn't configured. Adapters call this and check for '' to
+ * decide whether to include composed notes in their push payload.
+ */
+ public function composeNotesForPush(\App\Models\Asset $asset): string
+ {
+ $template = $this->pushNotesTemplate();
+ $target = $this->effectiveNotesTarget();
+ if ($template === '' || $target === null) {
+ return '';
+ }
+
+ return \App\SyncAdapters\Support\NotesComposer::compose($asset, $template);
+ }
+
/**
* Currently-selected target for a field, or the shipped default
* when no per-instance override exists. Standard fields fall back
diff --git a/app/SyncAdapters/SyncHostFromAdapter.php b/app/SyncAdapters/SyncHostFromAdapter.php
index a595824e18..3d4cfa74e0 100644
--- a/app/SyncAdapters/SyncHostFromAdapter.php
+++ b/app/SyncAdapters/SyncHostFromAdapter.php
@@ -33,142 +33,19 @@ use RuntimeException;
*/
class SyncHostFromAdapter
{
- /**
- * @SuppressWarnings("PHPMD.ElseExpression")
- */
public static function run(HostInventoryRecord $record): Asset
{
return DB::transaction(function () use ($record) {
$instance = SyncAdapterInstance::query()->where('slug', $record->sourceKey)->first();
$mapping = self::loadMapping($instance);
- $existingSource = DB::table('asset_external_sources')
- ->where('source', $record->sourceKey)
- ->where('external_id', $record->sourceId)
- ->first();
-
- $asset = $existingSource ? Asset::find($existingSource->asset_id) : null;
- $isNew = $asset === null;
-
- if ($isNew) {
- $asset = self::createShellAsset($record, $instance);
-
- // Identity row created empty of inventory columns. the
- // mapping loop below fills them and the write goes out
- // through upsertExternalSource().
- DB::table('asset_external_sources')->insert([
- 'asset_id' => $asset->id,
- 'company_id' => $instance?->company_id,
- 'source' => $record->sourceKey,
- 'external_id' => $record->sourceId,
- // NULL for CLI / scheduled runs, admin id for
- // interactive Sync Now clicks.
- 'created_by' => auth()->id(),
- 'created_at' => now(),
- 'updated_at' => now(),
- ]);
- } else {
- // Update-sync path: if the vendor moved this device
- // to a different group and the new group maps to a
- // different Snipe-IT company, reassign. Same
- // "vendor is authoritative" model as native:asset_tag
- // for tags. Admins who want to preserve manual
- // company assignments turn off group scoping for
- // this adapter or delete the specific mapping.
- $resolvedCompanyId = self::resolveCompanyId($record, $instance);
- if ($resolvedCompanyId !== null && $resolvedCompanyId !== (int) $asset->company_id) {
- $asset->company_id = $resolvedCompanyId;
- }
- }
+ [$asset, $isNew] = self::provisionAsset($record, $instance);
- // Apply per-field mappings. Routes each normalized field to
- // native asset columns, external-source columns, custom
- // fields, or skips it, based on per-instance config. Fields
- // directed 'push' or 'skip' on this instance are excluded
- // from the pull path so the vendor's value can't overwrite
- // a Snipe-IT-authoritative field (asset_tag pushed to the
- // vendor shouldn't get pulled back from what the vendor
- // reports). 'both' direction still pulls (naive last-write-
- // wins) so both sides converge on whichever side ran most
- // recently.
- $adapterForDirection = $instance?->adapter();
$externalUpdates = [];
- foreach (MappingTargets::FIELDS as $field) {
- $target = $mapping[$field] ?? MappingTargets::defaultTarget($field);
- if ($target === 'skip') {
- continue;
- }
- if ($adapterForDirection instanceof ConfigurableAdapter
- && ! in_array($adapterForDirection->directionFor($field), ['pull', 'both'], true)) {
- continue;
- }
-
- $value = self::recordValueFor($record, $field);
- self::writeToTarget($asset, $externalUpdates, $target, $value, $instance);
- }
+ self::applyStandardFieldMappings($asset, $externalUpdates, $record, $instance, $mapping);
+ self::applyExtraFieldMappings($asset, $record, $instance, $mapping);
- // Apply extra-field mappings. Extras are vendor-specific
- // keys the adapter emits into HostInventoryRecord::$extra.
- // Valid targets for extras are custom fields OR a small
- // set of native asset columns (asset_tag, notes) for
- // admins who store per-device metadata in the vendor's
- // labels / blueprint / team field. Values get stringified
- // so array or object payloads (Fleet's labels list, etc.)
- // land as readable text regardless of the underlying
- // native / custom write path.
- if ($instance !== null) {
- $adapter = $instance->adapter();
- if ($adapter instanceof ConfigurableAdapter) {
- $extraFields = $adapter->extraFields();
- foreach (array_keys($extraFields) as $extraKey) {
- $target = $mapping[$extraKey] ?? 'skip';
- if ($target === 'skip') {
- continue;
- }
- $isCustom = str_starts_with($target, 'custom:');
- $isNative = str_starts_with($target, 'native:');
- if (! $isCustom && ! $isNative) {
- continue;
- }
-
- $raw = $record->extra[$extraKey] ?? null;
- $type = self::extraFieldType($extraFields, $extraKey);
-
- // Booleans render '0' when raw is false. other
- // types treat blank strings as null. Guard on
- // raw-is-null so we don't blank existing data
- // for partially populated payloads.
- if ($raw === null && $type !== 'boolean') {
- continue;
- }
-
- $value = self::stringifyExtra($raw, $type);
- if ($value === null) {
- continue;
- }
-
- if ($isCustom) {
- self::writeCustom($asset, (int) substr($target, 7), $value);
- } else {
- self::writeNative($asset, substr($target, 7), $value, $instance);
- }
- }
- }
- }
-
- // Snapshot the current external-source inventory columns
- // before the write so we can diff and log any real changes
- // to non-heartbeat fields (MAC / IP / OS / os_version) via
- // a manual Actionlog. AssetObserver only sees native-column
- // diffs via getDirty(), so external-source column changes
- // would otherwise go untracked in the asset history.
$previousExternal = $isNew ? [] : self::loadExternalSourceInventory($asset->id);
-
- // Push native and custom-field writes. Laravel skips the
- // UPDATE when $asset->isDirty() is false, so a sync that
- // only changed external-source columns is a no-op on the
- // asset row: no AssetObserver::updating fires (we handle
- // external-source logging separately below).
$wasDirty = $asset->isDirty();
$asset->saveOrFail();
@@ -186,43 +63,220 @@ class SyncHostFromAdapter
// silently after logging a warning.
self::assignUserIfMatched($asset, $record, $instance);
- // Diff external-source column changes and decide whether
- // to log + touch. Meaningful diff (MAC / IP / OS /
- // os_version) always logs. last_seen-only diff logs only
- // when the admin opted into heartbeat logging.
if (! $isNew) {
- $externalDiff = self::diffExternal($previousExternal, $externalUpdates);
- $meaningfulExternalChange = count(array_diff(array_keys($externalDiff), ['last_seen'])) > 0;
- $heartbeatOnly = $externalDiff !== [] && ! $meaningfulExternalChange;
-
- $logsHeartbeats = false;
- if ($instance !== null) {
- $adapter = $instance->adapter();
- if ($adapter instanceof ConfigurableAdapter) {
- $logsHeartbeats = $adapter->logsHeartbeats();
- }
- }
-
- if ($meaningfulExternalChange || ($heartbeatOnly && $logsHeartbeats)) {
- self::writeExternalSourceActionlog($asset, $externalDiff);
- // Bump updated_at so "recently updated" sorts
- // reflect the sync activity. Use saveQuietly so
- // AssetObserver::updating doesn't fire and log a
- // redundant `update` Actionlog on top of the
- // external-source row we just wrote. Skipped when
- // the asset was already dirty (native columns
- // changed) because the save above handles it.
- if (! $wasDirty) {
- $asset->updated_at = now();
- $asset->saveQuietly();
- }
- }
+ self::logExternalSourceChanges($asset, $previousExternal, $externalUpdates, $wasDirty, $instance);
}
return $asset->refresh();
});
}
+ /**
+ * Resolve the asset for this sync record. Either finds it by the
+ * existing (source, external_id) tuple in asset_external_sources
+ * or creates a fresh shell asset + identity row for first-sync
+ * cases. Also handles the update-sync group-reassignment case
+ * where a device moved to a different vendor group that maps to
+ * a different Snipe-IT company.
+ *
+ * @return array{0: Asset, 1: bool} Tuple of the resolved asset and an "isNew" flag.
+ */
+ private static function provisionAsset(HostInventoryRecord $record, ?SyncAdapterInstance $instance): array
+ {
+ $existingSource = DB::table('asset_external_sources')
+ ->where('source', $record->sourceKey)
+ ->where('external_id', $record->sourceId)
+ ->first();
+
+ $asset = $existingSource ? Asset::find($existingSource->asset_id) : null;
+
+ if ($asset !== null) {
+ // Update-sync path: if the vendor moved this device to a
+ // different group and the new group maps to a different
+ // Snipe-IT company, reassign. Same "vendor is
+ // authoritative" model as native:asset_tag for tags.
+ // Admins who want to preserve manual company assignments
+ // turn off group scoping for this adapter or delete the
+ // specific mapping.
+ $resolvedCompanyId = self::resolveCompanyId($record, $instance);
+ if ($resolvedCompanyId !== null && $resolvedCompanyId !== (int) $asset->company_id) {
+ $asset->company_id = $resolvedCompanyId;
+ }
+
+ return [$asset, false];
+ }
+
+ $asset = self::createShellAsset($record, $instance);
+
+ // Identity row created empty of inventory columns. the
+ // mapping loop below fills them and the write goes out
+ // through upsertExternalSource().
+ DB::table('asset_external_sources')->insert([
+ 'asset_id' => $asset->id,
+ 'company_id' => $instance?->company_id,
+ 'source' => $record->sourceKey,
+ 'external_id' => $record->sourceId,
+ // NULL for CLI / scheduled runs, admin id for
+ // interactive Sync Now clicks.
+ 'created_by' => auth()->id(),
+ 'created_at' => now(),
+ 'updated_at' => now(),
+ ]);
+
+ return [$asset, true];
+ }
+
+ /**
+ * Apply per-field mappings. Routes each normalized field to native
+ * asset columns, external-source columns, custom fields, or skips
+ * it, based on per-instance config. Fields directed 'push' or
+ * 'skip' on this instance are excluded from the pull path so the
+ * vendor's value can't overwrite a Snipe-IT-authoritative field
+ * (asset_tag pushed to the vendor shouldn't get pulled back from
+ * what the vendor reports). 'both' direction still pulls (naive
+ * last-write-wins) so both sides converge on whichever side ran
+ * most recently.
+ *
+ * @param array<string, mixed> $externalUpdates
+ * @param array<string, string> $mapping
+ */
+ private static function applyStandardFieldMappings(
+ Asset $asset,
+ array &$externalUpdates,
+ HostInventoryRecord $record,
+ ?SyncAdapterInstance $instance,
+ array $mapping,
+ ): void {
+ $adapterForDirection = $instance?->adapter();
+
+ foreach (MappingTargets::FIELDS as $field) {
+ $target = $mapping[$field] ?? MappingTargets::defaultTarget($field);
+ if ($target === 'skip') {
+ continue;
+ }
+ if ($adapterForDirection instanceof ConfigurableAdapter
+ && ! in_array($adapterForDirection->directionFor($field), ['pull', 'both'], true)) {
+ continue;
+ }
+
+ $value = self::recordValueFor($record, $field);
+ self::writeToTarget($asset, $externalUpdates, $target, $value, $instance);
+ }
+ }
+
+ /**
+ * Apply extra-field mappings. Extras are vendor-specific keys the
+ * adapter emits into HostInventoryRecord::$extra. Valid targets
+ * for extras are custom fields OR a small set of native asset
+ * columns (asset_tag, notes) for admins who store per-device
+ * metadata in the vendor's labels / blueprint / team field.
+ * Values get stringified so array or object payloads (Fleet's
+ * labels list, etc.) land as readable text regardless of the
+ * underlying native / custom write path.
+ *
+ * Sibling of applyStandardFieldMappings but doesn't take
+ * $externalUpdates because extras only route to native columns
+ * or custom fields, never to the asset_external_sources side
+ * table. writeToTarget (which is what feeds $externalUpdates) is
+ * not on the code path here.
+ *
+ * @param array<string, string> $mapping
+ */
+ private static function applyExtraFieldMappings(
+ Asset $asset,
+ HostInventoryRecord $record,
+ ?SyncAdapterInstance $instance,
+ array $mapping,
+ ): void {
+ if ($instance === null) {
+ return;
+ }
+ $adapter = $instance->adapter();
+ if (! $adapter instanceof ConfigurableAdapter) {
+ return;
+ }
+
+ $extraFields = $adapter->extraFields();
+ foreach (array_keys($extraFields) as $extraKey) {
+ $target = $mapping[$extraKey] ?? 'skip';
+ if ($target === 'skip') {
+ continue;
+ }
+ $isCustom = str_starts_with($target, 'custom:');
+ $isNative = str_starts_with($target, 'native:');
+ if (! $isCustom && ! $isNative) {
+ continue;
+ }
+
+ $raw = $record->extra[$extraKey] ?? null;
+ $type = self::extraFieldType($extraFields, $extraKey);
+
+ // Booleans render '0' when raw is false. other types
+ // treat blank strings as null. Guard on raw-is-null so
+ // we don't blank existing data for partially populated
+ // payloads.
+ if ($raw === null && $type !== 'boolean') {
+ continue;
+ }
+
+ $value = self::stringifyExtra($raw, $type);
+ if ($value === null) {
+ continue;
+ }
+
+ if ($isCustom) {
+ self::writeCustom($asset, (int) substr($target, 7), $value);
+
+ continue;
+ }
+ self::writeNative($asset, substr($target, 7), $value, $instance);
+ }
+ }
+
+ /**
+ * Diff external-source column writes against a pre-sync snapshot
+ * and log meaningful changes as an Actionlog. Skips heartbeat-only
+ * diffs unless the adapter has heartbeat logging turned on.
+ *
+ * @param array<string, mixed> $previousExternal
+ * @param array<string, mixed> $externalUpdates
+ */
+ private static function logExternalSourceChanges(
+ Asset $asset,
+ array $previousExternal,
+ array $externalUpdates,
+ bool $wasDirty,
+ ?SyncAdapterInstance $instance,
+ ): void {
+ $externalDiff = self::diffExternal($previousExternal, $externalUpdates);
+ $meaningfulExternalChange = count(array_diff(array_keys($externalDiff), ['last_seen'])) > 0;
+ $heartbeatOnly = $externalDiff !== [] && ! $meaningfulExternalChange;
+
+ $logsHeartbeats = false;
+ if ($instance !== null) {
+ $adapter = $instance->adapter();
+ if ($adapter instanceof ConfigurableAdapter) {
+ $logsHeartbeats = $adapter->logsHeartbeats();
+ }
+ }
+
+ if (! $meaningfulExternalChange && ! ($heartbeatOnly && $logsHeartbeats)) {
+ return;
+ }
+
+ self::writeExternalSourceActionlog($asset, $externalDiff);
+ // Bump updated_at so "recently updated" sorts reflect the
+ // sync activity. Use saveQuietly so AssetObserver::updating
+ // doesn't fire and log a redundant `update` Actionlog on top
+ // of the external-source row we just wrote. Skipped when the
+ // asset was already dirty (native columns changed) because
+ // the save above handles it.
+ if (! $wasDirty) {
+ $asset->updated_at = now();
+ $asset->saveQuietly();
+ }
+ }
+
/**
* Snapshot the current inventory columns from the
* asset_external_sources row for diffing. Returns an empty array
@@ -732,10 +786,39 @@ class SyncHostFromAdapter
return;
}
- // Build the ordered list of (field, value) attempts. Cascade
- // strategy tries username first (guaranteed unique in
- // Snipe-IT) then email as fallback. Explicit single-field
- // strategies produce one attempt.
+ $attempts = self::buildUserMatchAttempts($record, $strategy);
+
+ if ($attempts === []) {
+ if ($adapter->checksInOnNullUser()
+ && $asset->assigned_to !== null
+ && $asset->assigned_type === User::class) {
+ self::silentCheckinAsset($asset, $instance);
+ }
+
+ return;
+ }
+
+ $user = self::resolveUserFromAttempts($attempts, $instance, $strategy, $record->sourceId);
+ if ($user === null) {
+ return;
+ }
+
+ self::applyUserAssignment($asset, $user, $adapter, $instance);
+ }
+
+ /**
+ * Build the ordered list of (field, value) attempts for the user-
+ * match strategy. Cascade strategy tries username first (guaranteed
+ * unique in Snipe-IT) then email as fallback. Explicit single-field
+ * strategies produce one attempt. Attempts where the vendor gave us
+ * nothing to match on are filtered out so callers can distinguish
+ * "vendor reported no user at all" (opt-in checkin-on-null) from
+ * "vendor gave us a user we couldn't find" (warning log).
+ *
+ * @return array<int, array{0: string, 1: string}>
+ */
+ private static function buildUserMatchAttempts(HostInventoryRecord $record, string $strategy): array
+ {
$attempts = match ($strategy) {
'email' => [['email', $record->assignedUserEmail]],
'username' => [['username', $record->assignedUserName]],
@@ -746,85 +829,91 @@ class SyncHostFromAdapter
default => [],
};
- // Filter out attempts where the vendor gave us nothing to
- // match on so we can distinguish "vendor reported no user at
- // all" from "vendor gave us a user we couldn't find". The
- // first case may trigger the opt-in checkin-on-null path.
- // The second gets a warning log.
- $attempts = array_values(array_filter(
+ return array_values(array_filter(
$attempts,
fn (array $a) => is_string($a[1]) && $a[1] !== '',
));
+ }
- if ($attempts === []) {
- if ($adapter->checksInOnNullUser()
- && $asset->assigned_to !== null
- && $asset->assigned_type === User::class) {
- self::silentCheckinAsset($asset, $instance);
- }
-
- return;
- }
-
- $user = null;
- $matchedVia = null;
+ /**
+ * Walk the ordered attempts and return the first matching user.
+ * Emits an info log on success and a warning on complete miss so
+ * admins can see the strategy played out per-host. Returns null
+ * when no attempt matched.
+ *
+ * @param array<int, array{0: string, 1: string}> $attempts
+ */
+ private static function resolveUserFromAttempts(
+ array $attempts,
+ SyncAdapterInstance $instance,
+ string $strategy,
+ string $sourceId,
+ ): ?User {
foreach ($attempts as [$field, $value]) {
$candidate = User::query()->where($field, $value)->first();
if ($candidate !== null) {
- $user = $candidate;
- $matchedVia = sprintf('%s=%s', $field, $value);
- break;
+ Log::channel('sync-adapters')->info(sprintf(
+ '%s sync: matched user via %s=%s for host %s',
+ $instance->slug,
+ $field,
+ $value,
+ $sourceId,
+ ));
+
+ return $candidate;
}
}
- if ($user === null) {
- $tried = implode(', ', array_map(
- fn (array $a) => sprintf('%s=%s', $a[0], $a[1]),
- $attempts,
- ));
- Log::channel('sync-adapters')->warning(sprintf(
- '%s sync: no Snipe-IT user matched (strategy=%s, tried [%s]) for host %s',
- $instance->slug,
- $strategy,
- $tried,
- $record->sourceId,
- ));
-
- return;
- }
-
- Log::channel('sync-adapters')->info(sprintf(
- '%s sync: matched user via %s for host %s',
+ $tried = implode(', ', array_map(
+ fn (array $a) => sprintf('%s=%s', $a[0], $a[1]),
+ $attempts,
+ ));
+ Log::channel('sync-adapters')->warning(sprintf(
+ '%s sync: no Snipe-IT user matched (strategy=%s, tried [%s]) for host %s',
$instance->slug,
- $matchedVia,
- $record->sourceId,
+ $strategy,
+ $tried,
+ $sourceId,
));
- // Already assigned to the resolved user: no-op.
+ return null;
+ }
+
+ /**
+ * Commit the assignment. Suppress mode is always silent (direct
+ * assignment). Otherwise fall through to Asset::checkOut() which
+ * fires the CheckoutableCheckedOut event and its notification
+ * listener. The event constructor requires a non-null admin User.
+ * auth() is null for CLI-triggered sync runs, so silently fall
+ * back to direct assignment when there's no auth context to
+ * attach the event to. Skips when the asset is already assigned
+ * to the resolved user.
+ */
+ private static function applyUserAssignment(
+ Asset $asset,
+ User $user,
+ ConfigurableAdapter $adapter,
+ SyncAdapterInstance $instance,
+ ): void {
if ((int) $asset->assigned_to === (int) $user->id
&& $asset->assigned_type === User::class) {
return;
}
- // Suppress mode: always silent (direct assignment). Otherwise
- // fall through to Asset::checkOut() which fires the
- // CheckoutableCheckedOut event and its notification listener.
- // The event constructor requires a non-null admin User. auth()
- // is null for CLI-triggered sync runs, so silently fall back
- // to direct assignment when there's no auth context to attach
- // the event to.
$admin = auth()->user();
if ($adapter->suppressesNotifications() || $admin === null) {
self::silentAssignToUser($asset, $user);
- } else {
- $asset->checkOut(
- target: $user,
- admin: $admin,
- checkout_at: now()->toDateTimeString(),
- note: 'Assigned via sync from '.$instance->slug,
- name: $asset->name,
- );
+
+ return;
}
+
+ $asset->checkOut(
+ target: $user,
+ admin: $admin,
+ checkout_at: now()->toDateTimeString(),
+ note: 'Assigned via sync from '.$instance->slug,
+ name: $asset->name,
+ );
}
/**
diff --git a/app/SyncAdapters/WorkspaceOne/WorkspaceOneAdapter.php b/app/SyncAdapters/WorkspaceOne/WorkspaceOneAdapter.php
index 506c482cd8..5c47b9c034 100644
--- a/app/SyncAdapters/WorkspaceOne/WorkspaceOneAdapter.php
+++ b/app/SyncAdapters/WorkspaceOne/WorkspaceOneAdapter.php
@@ -3,7 +3,6 @@
namespace App\SyncAdapters\WorkspaceOne;
use App\Models\Asset;
-use App\Models\AssetExternalSource;
use App\SyncAdapters\HostInventoryRecord;
use App\SyncAdapters\PushableAdapter;
use App\SyncAdapters\Support\ConfigurableAdapter;
@@ -187,27 +186,13 @@ class WorkspaceOneAdapter extends ConfigurableAdapter implements PushableAdapter
*/
public function push(Asset $asset, array $changedFields = []): void
{
- // Don't early-exit on empty pushFields. Composed notes may
- // still be configured without any per-field direction=push.
- // Only skip when we have push fields AND the caller told us
- // none of them are in the changed set.
- $pushFields = $this->pushDirectedFields();
- if ($pushFields !== [] && $changedFields !== []
- && array_intersect($changedFields, $pushFields) === []) {
- return;
- }
-
- $externalSource = AssetExternalSource::query()
- ->where('asset_id', $asset->id)
- ->where('source', $this->name())
- ->first();
-
+ $externalSource = $this->pushPrologue($asset, $changedFields);
if ($externalSource === null) {
return;
}
$payload = [];
- foreach ($pushFields as $field) {
+ foreach ($this->pushDirectedFields() as $field) {
$mapped = self::sourceFieldToWs1Field($field);
if ($mapped === null) {
continue;
@@ -228,11 +213,8 @@ class WorkspaceOneAdapter extends ConfigurableAdapter implements PushableAdapter
// are configured. Admin sets the Custom Attribute name via
// the composed-notes fieldset override. Nothing default
// because WS1 has no built-in notes concept for us to guess.
- $notesTemplate = $this->pushNotesTemplate();
+ $composed = $this->composeNotesForPush($asset);
$notesTarget = $this->effectiveNotesTarget();
- $composed = ($notesTemplate !== '' && $notesTarget !== null)
- ? \App\SyncAdapters\Support\NotesComposer::compose($asset, $notesTemplate)
- : '';
if ($payload === [] && $composed === '') {
return;