A free open source IT asset/license management system
Small codacy refactors
snipe27ffde09a43e
diff --git a/app/Http/Controllers/SettingsController.php b/app/Http/Controllers/SettingsController.phpindex 98586dc7e0..0f3c2233da 100644--- a/app/Http/Controllers/SettingsController.php+++ b/app/Http/Controllers/SettingsController.php@@ -1231,39 +1231,92 @@ class SettingsController extends Controllerreturn null;}+ $candidate = self::pluckErrorCandidate($body);+ if (! is_string($candidate) || trim($candidate) === '') {+ return null;+ }++ $candidate = trim($candidate);++ return mb_strlen($candidate) > 200+ ? mb_substr($candidate, 0, 200).'…'+ : $candidate;+ }++ /**+ * Walk the shapes we know about in order (top-level scalar keys,+ * nested error object, errors array of strings, errors array of+ * objects). Returns the first string it lands on or null if none+ * of the paths yield anything.+ *+ * @param array<string, mixed> $body+ */+ private static function pluckErrorCandidate(array $body): ?string+ {$candidate = $body['message']?? $body['detail']?? $body['errorMessage']?? null;+ if (is_string($candidate)) {+ return $candidate;+ }- if (! is_string($candidate) && isset($body['error'])) {- $candidate = is_string($body['error'])- ? $body['error']- : ($body['error']['message'] ?? null);- }-- if (! is_string($candidate) && isset($body['errors']) && is_array($body['errors'])) {- $first = $body['errors'][0] ?? null;- if (is_string($first)) {- $candidate = $first;- } elseif (is_array($first)) {- $candidate = $first['description']- ?? $first['reason']- ?? $first['message']- ?? $first['detail']- ?? null;- }+ $candidate = self::pluckErrorFromErrorKey($body);+ if (is_string($candidate)) {+ return $candidate;}- if (! is_string($candidate) || trim($candidate) === '') {+ return self::pluckErrorFromErrorsArray($body);+ }++ /**+ * Extract from a top-level `error` key. Handles both the string+ * shape ({"error": "..."}) and the Microsoft Graph nested-object+ * shape ({"error": {"message": "..."}}).+ *+ * @param array<string, mixed> $body+ */+ private static function pluckErrorFromErrorKey(array $body): ?string+ {+ if (! isset($body['error'])) {return null;}+ if (is_string($body['error'])) {+ return $body['error'];+ }+ if (is_array($body['error']) && isset($body['error']['message']) && is_string($body['error']['message'])) {+ return $body['error']['message'];+ }- $candidate = trim($candidate);+ return null;+ }- return mb_strlen($candidate) > 200- ? mb_substr($candidate, 0, 200).'…'- : $candidate;+ /**+ * Extract from an `errors` array. First entry wins. Handles the+ * Meraki string-array shape and the Jamf / Fleet object-array+ * shape whose entries carry description / reason / message /+ * detail keys.+ *+ * @param array<string, mixed> $body+ */+ private static function pluckErrorFromErrorsArray(array $body): ?string+ {+ if (! isset($body['errors']) || ! is_array($body['errors'])) {+ return null;+ }+ $first = $body['errors'][0] ?? null;+ if (is_string($first)) {+ return $first;+ }+ if (! is_array($first)) {+ return null;+ }++ return $first['description']+ ?? $first['reason']+ ?? $first['message']+ ?? $first['detail']+ ?? null;}/**diff --git a/app/SyncAdapters/Intune/IntuneAdapter.php b/app/SyncAdapters/Intune/IntuneAdapter.phpindex e17fece00d..24b6a23bf1 100644--- a/app/SyncAdapters/Intune/IntuneAdapter.php+++ b/app/SyncAdapters/Intune/IntuneAdapter.php@@ -3,11 +3,9 @@namespace App\SyncAdapters\Intune;use App\Models\Asset;-use App\Models\AssetExternalSource;use App\SyncAdapters\HostInventoryRecord;use App\SyncAdapters\PushableAdapter;use App\SyncAdapters\Support\ConfigurableAdapter;-use App\SyncAdapters\Support\NotesComposer;use Carbon\Carbon;use Illuminate\Support\Arr;use Illuminate\Support\Facades\Log;@@ -180,27 +178,17 @@ class IntuneAdapter extends ConfigurableAdapter implements PushableAdapter*/public function push(Asset $asset, array $changedFields = []): void{- $template = $this->pushNotesTemplate();- $target = $this->effectiveNotesTarget();- if ($template === '' || $target === null) {- return;- }-- $externalSource = AssetExternalSource::query()- ->where('asset_id', $asset->id)- ->where('source', $this->name())- ->first();-+ $externalSource = $this->pushPrologue($asset, $changedFields);if ($externalSource === null) {return;}- $composed = NotesComposer::compose($asset, $template);+ $composed = $this->composeNotesForPush($asset);if ($composed === '') {return;}- $payload = [$target => $composed];+ $payload = [$this->effectiveNotesTarget() => $composed];if ($this->isPushDryRun()) {Log::channel('sync-adapters')->info(sprintf(@@ -227,7 +215,7 @@ class IntuneAdapter extends ConfigurableAdapter implements PushableAdapter'%s push: updated Intune managed device %s (%s)',$this->name(),$externalSource->external_id,- $target,+ $this->effectiveNotesTarget(),));}}diff --git a/app/SyncAdapters/Mosyle/MosyleAdapter.php b/app/SyncAdapters/Mosyle/MosyleAdapter.phpindex 6860d91890..094618b105 100644--- a/app/SyncAdapters/Mosyle/MosyleAdapter.php+++ b/app/SyncAdapters/Mosyle/MosyleAdapter.php@@ -153,8 +153,6 @@ class MosyleAdapter extends ConfigurableAdapter implements PushableAdapter* pull and is more stable across re-enrollment).** @param array<int, string> $changedFields- *- * @SuppressWarnings("PHPMD.ElseExpression")*/public function push(Asset $asset, array $changedFields = []): void{@@ -163,77 +161,99 @@ class MosyleAdapter extends ConfigurableAdapter implements PushableAdapterreturn;}- // Mosyle keys writes by serial number, not the UDID we- // stored as external_id. Fall back to the external_id if- // the asset has no serial (Mosyle Business uses serial ==- // external_id for some device types).$serial = $asset->serial;if ($serial === null || $serial === '') {+ // Mosyle keys writes by serial number, not the UDID we+ // stored as external_id. Fall back to external_id when+ // the asset has no serial (Mosyle Business uses+ // serial == external_id for some device types).$serial = $externalSource->external_id;}- $pushedFields = [];$client = null;+ $pushedFields = array_merge(+ $this->pushAssetTagField($asset, $serial, $client),+ $this->pushComposedNotesField($asset, $serial, $client),+ );- foreach ($this->pushDirectedFields() as $field) {- if ($field !== 'asset_tag') {- continue;- }-- $value = $this->assetValueForSourceField($asset, $field);- if ($value === null || $value === '') {- continue;- }-- if ($this->isPushDryRun()) {- Log::channel('sync-adapters')->info(sprintf(- '%s push [dry-run]: would set Mosyle device serial=%s asset_tag=%s',- $this->name(),- $serial,- $value,- ));- $pushedFields[] = $field;-- continue;- }-- $client ??= new MosyleClient(baseUrl: $this->url(), token: $this->credential('token'));- $client->updateDeviceAssetTagBySerial($serial, (string) $value);- $pushedFields[] = $field;+ if ($pushedFields === [] || $this->isPushDryRun()) {+ return;}- // 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.- $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';- }+ Log::channel('sync-adapters')->info(sprintf(+ '%s push: updated Mosyle device serial=%s fields [%s]',+ $this->name(),+ $serial,+ implode(', ', $pushedFields),+ ));+ }++ /**+ * Push the asset_tag field to Mosyle if it's in pushDirectedFields+ * and has a non-empty value. Handles both dry-run and real calls.+ * $client is passed by reference so the shared HTTP client gets+ * lazy-instantiated once across both push helpers.+ *+ * @return array<int, string> Names of the fields actually pushed.+ */+ private function pushAssetTagField(Asset $asset, string $serial, ?MosyleClient &$client): array+ {+ if (! in_array('asset_tag', $this->pushDirectedFields(), true)) {+ return [];}- if ($pushedFields === []) {- return;+ $value = $this->assetValueForSourceField($asset, 'asset_tag');+ if ($value === null || $value === '') {+ return [];+ }++ if ($this->isPushDryRun()) {+ Log::channel('sync-adapters')->info(sprintf(+ '%s push [dry-run]: would set Mosyle device serial=%s asset_tag=%s',+ $this->name(),+ $serial,+ $value,+ ));++ return ['asset_tag'];+ }++ $client ??= new MosyleClient(baseUrl: $this->url(), token: $this->credential('token'));+ $client->updateDeviceAssetTagBySerial($serial, (string) $value);++ return ['asset_tag'];+ }++ /**+ * Push composed notes to Mosyle if a template + target are+ * configured. 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.+ *+ * @return array<int, string> Names of the fields actually pushed.+ */+ private function pushComposedNotesField(Asset $asset, string $serial, ?MosyleClient &$client): array+ {+ $composed = $this->composeNotesForPush($asset);+ if ($composed === '') {+ return [];}- if (! $this->isPushDryRun()) {+ if ($this->isPushDryRun()) {Log::channel('sync-adapters')->info(sprintf(- '%s push: updated Mosyle device serial=%s fields [%s]',+ '%s push [dry-run]: would set Mosyle device serial=%s notes=%s',$this->name(),$serial,- implode(', ', $pushedFields),+ $composed,));++ return ['notes'];}++ $client ??= new MosyleClient(baseUrl: $this->url(), token: $this->credential('token'));+ $client->updateDeviceNotesBySerial($serial, $composed);++ return ['notes'];}private function assetValueForSourceField(Asset $asset, string $field): mixeddiff --git a/app/SyncAdapters/NinjaOne/NinjaOneAdapter.php b/app/SyncAdapters/NinjaOne/NinjaOneAdapter.phpindex c2dacdb4b0..81756709e8 100644--- a/app/SyncAdapters/NinjaOne/NinjaOneAdapter.php+++ b/app/SyncAdapters/NinjaOne/NinjaOneAdapter.php@@ -191,30 +191,7 @@ class NinjaOneAdapter extends ConfigurableAdapter implements PushableAdapterreturn;}- $payload = [];- foreach ($this->pushDirectedFields() as $field) {- if ($field !== 'asset_tag') {- continue;- }- $value = $this->assetValueForSourceField($asset, $field);- if ($value === null || $value === '') {- continue;- }- $payload[$customFieldName] = $value;- }-- // Composed notes go into a separate admin-named Custom Field- // via the same /custom-fields PATCH endpoint. Ninja accepts- // multiple field name / value pairs in one request, so we- // merge asset_tag + notes when both are configured. Admin- // 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.- $composed = $this->composeNotesForPush($asset);- if ($composed !== '') {- $payload[$this->effectiveNotesTarget()] = $composed;- }-+ $payload = $this->buildCustomFieldPayload($asset, $customFieldName);if ($payload === []) {return;}@@ -245,6 +222,35 @@ class NinjaOneAdapter extends ConfigurableAdapter implements PushableAdapter));}+ /**+ * Assemble the /custom-fields PATCH payload. Ninja accepts+ * multiple field name / value pairs in one request, so asset_tag+ * and the composed-notes target get merged when both are+ * configured. Admin sets the notes-target field via the composed-+ * notes fieldset override; nothing is defaulted because Ninja+ * has no built-in notes concept for us to guess.+ *+ * @return array<string, mixed>+ */+ private function buildCustomFieldPayload(Asset $asset, string $assetTagFieldName): array+ {+ $payload = [];++ $value = in_array('asset_tag', $this->pushDirectedFields(), true)+ ? $this->assetValueForSourceField($asset, 'asset_tag')+ : null;+ if ($value !== null && $value !== '') {+ $payload[$assetTagFieldName] = $value;+ }++ $composed = $this->composeNotesForPush($asset);+ if ($composed !== '') {+ $payload[$this->effectiveNotesTarget()] = $composed;+ }++ return $payload;+ }+private function assetValueForSourceField(Asset $asset, string $field): mixed{return match ($field) {diff --git a/app/SyncAdapters/SyncHostFromAdapter.php b/app/SyncAdapters/SyncHostFromAdapter.phpindex 34c03b5def..30ead0d290 100644--- a/app/SyncAdapters/SyncHostFromAdapter.php+++ b/app/SyncAdapters/SyncHostFromAdapter.php@@ -199,36 +199,38 @@ class SyncHostFromAdapter$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);+ $value = self::stringifyExtra(+ $record->extra[$extraKey] ?? null,+ self::extraFieldType($extraFields, $extraKey),+ );+ self::writeExtraValueToTarget($asset, $target, $value, $instance);+ }+ }- // 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;- }+ /**+ * Route one extra value to its configured target. Extras only+ * write to native:{column} or custom:{id} slots. Skip and any+ * other target shape are no-ops. Null values (missing from the+ * vendor payload or unstringifiable) pass through silently so+ * partially-populated payloads never blank existing data.+ */+ private static function writeExtraValueToTarget(+ Asset $asset,+ string $target,+ ?string $value,+ SyncAdapterInstance $instance,+ ): void {+ if ($target === 'skip' || $value === null) {+ return;+ }- $value = self::stringifyExtra($raw, $type);- if ($value === null) {- continue;- }+ if (str_starts_with($target, 'custom:')) {+ self::writeCustom($asset, (int) substr($target, 7), $value);- if ($isCustom) {- self::writeCustom($asset, (int) substr($target, 7), $value);+ return;+ }- continue;- }+ if (str_starts_with($target, 'native:')) {self::writeNative($asset, substr($target, 7), $value, $instance);}}diff --git a/app/SyncAdapters/WorkspaceOne/WorkspaceOneAdapter.php b/app/SyncAdapters/WorkspaceOne/WorkspaceOneAdapter.phpindex aa200aff8b..c1a6d64a63 100644--- a/app/SyncAdapters/WorkspaceOne/WorkspaceOneAdapter.php+++ b/app/SyncAdapters/WorkspaceOne/WorkspaceOneAdapter.php@@ -191,85 +191,120 @@ class WorkspaceOneAdapter extends ConfigurableAdapter implements PushableAdapterreturn;}+ $payload = $this->buildDevicePayload($asset);+ $composed = $this->composeNotesForPush($asset);++ if ($payload === [] && $composed === '') {+ return;+ }++ $client = $this->isPushDryRun() ? null : $this->buildClient();+ $this->pushDeviceFields($externalSource->external_id, $payload, $client);+ $this->pushCustomAttribute($externalSource->external_id, $composed, $client);+ }++ /**+ * Assemble the device-update payload from pushDirectedFields.+ * Fields the vendor doesn't accept map to null and get skipped.+ *+ * @return array<string, mixed>+ */+ private function buildDevicePayload(Asset $asset): array+ {$payload = [];foreach ($this->pushDirectedFields() as $field) {$mapped = self::sourceFieldToWs1Field($field);if ($mapped === null) {continue;}-$value = $this->assetValueForSourceField($asset, $field);if ($value === null) {continue;}-$payload[$mapped] = $value;}- // Composed notes go to a WS1 Custom Attribute via a separate- // endpoint from the top-level device fields (AssetNumber uses- // PUT /devices/{uuid}, Custom Attributes use POST- // /devices/{uuid}/customattributes). Two API calls when both- // 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.- $composed = $this->composeNotesForPush($asset);- $notesTarget = $this->effectiveNotesTarget();+ return $payload;+ }- if ($payload === [] && $composed === '') {+ /**+ * Push top-level device fields (AssetNumber, etc.) via PUT+ * /devices/{uuid}. Null $client means dry-run; log the payload+ * and skip the HTTP call.+ *+ * @param array<string, mixed> $payload+ */+ private function pushDeviceFields(string $uuid, array $payload, ?WorkspaceOneClient $client): void+ {+ if ($payload === []) {return;}- if ($this->isPushDryRun()) {- if ($payload !== []) {- Log::channel('sync-adapters')->info(sprintf(- '%s push [dry-run]: would PUT Workspace ONE device %s with %s',- $this->name(),- $externalSource->external_id,- json_encode($payload, JSON_UNESCAPED_SLASHES),- ));- }- if ($composed !== '') {- Log::channel('sync-adapters')->info(sprintf(- '%s push [dry-run]: would set Workspace ONE Custom Attribute %s=%s on device %s',- $this->name(),- $notesTarget,- $composed,- $externalSource->external_id,- ));- }+ if ($client === null) {+ Log::channel('sync-adapters')->info(sprintf(+ '%s push [dry-run]: would PUT Workspace ONE device %s with %s',+ $this->name(),+ $uuid,+ json_encode($payload, JSON_UNESCAPED_SLASHES),+ ));return;}- $apiBaseUrl = $this->url();- $client = new WorkspaceOneClient(- apiBaseUrl: $apiBaseUrl,- authBaseUrl: $this->deriveAuthBaseUrl($apiBaseUrl),- tenantCode: $this->credential('tenant_code'),- clientId: $this->credential('client_id'),- clientSecret: $this->credential('client_secret'),- );+ $client->updateDevice($uuid, $payload);+ Log::channel('sync-adapters')->info(sprintf(+ '%s push: updated Workspace ONE device %s with fields [%s]',+ $this->name(),+ $uuid,+ implode(', ', array_keys($payload)),+ ));+ }- if ($payload !== []) {- $client->updateDevice($externalSource->external_id, $payload);- Log::channel('sync-adapters')->info(sprintf(- '%s push: updated Workspace ONE device %s with fields [%s]',- $this->name(),- $externalSource->external_id,- implode(', ', array_keys($payload)),- ));+ /**+ * Push composed notes to a WS1 Custom Attribute via POST+ * /devices/{uuid}/customattributes. Separate endpoint from the+ * top-level device fields, so this fires independently.+ */+ private function pushCustomAttribute(string $uuid, string $composed, ?WorkspaceOneClient $client): void+ {+ if ($composed === '') {+ return;}- if ($composed !== '') {- $client->updateDeviceCustomAttribute($externalSource->external_id, $notesTarget, $composed);+ $notesTarget = $this->effectiveNotesTarget();++ if ($client === null) {Log::channel('sync-adapters')->info(sprintf(- '%s push: set Workspace ONE Custom Attribute "%s" on device %s',+ '%s push [dry-run]: would set Workspace ONE Custom Attribute %s=%s on device %s',$this->name(),$notesTarget,- $externalSource->external_id,+ $composed,+ $uuid,));++ return;}++ $client->updateDeviceCustomAttribute($uuid, $notesTarget, $composed);+ Log::channel('sync-adapters')->info(sprintf(+ '%s push: set Workspace ONE Custom Attribute "%s" on device %s',+ $this->name(),+ $notesTarget,+ $uuid,+ ));+ }++ private function buildClient(): WorkspaceOneClient+ {+ $apiBaseUrl = $this->url();++ return new WorkspaceOneClient(+ apiBaseUrl: $apiBaseUrl,+ authBaseUrl: $this->deriveAuthBaseUrl($apiBaseUrl),+ tenantCode: $this->credential('tenant_code'),+ clientId: $this->credential('client_id'),+ clientSecret: $this->credential('client_secret'),+ );}/**diff --git a/config/logging.php b/config/logging.phpindex cac5f4329e..bab78d3bf7 100644--- a/config/logging.php+++ b/config/logging.php@@ -132,7 +132,7 @@ $config = [// Fleet / Kandji / Intune / etc. sync without wading through// unrelated warnings. Same daily-rotation shape as `admin`.'sync-adapters' => [- 'driver' => 'daily',+ 'driver' => 'single','path' => storage_path('logs/sync-adapters.log'),'level' => env('LOG_LEVEL', 'info'),'days' => 30,diff --git a/tests/Feature/SyncAdapters/AppleBusinessManager/AppleBusinessManagerAdapterTest.php b/tests/Feature/SyncAdapters/AppleBusinessManager/AppleBusinessManagerAdapterTest.phpindex f7b5445a44..572d307288 100644--- a/tests/Feature/SyncAdapters/AppleBusinessManager/AppleBusinessManagerAdapterTest.php+++ b/tests/Feature/SyncAdapters/AppleBusinessManager/AppleBusinessManagerAdapterTest.php@@ -30,6 +30,7 @@ class AppleBusinessManagerAdapterTest extends TestCase'private_key_type' => OPENSSL_KEYTYPE_EC,'curve_name' => 'prime256v1',]);+ $pem = '';openssl_pkey_export($key, $pem);$this->privateKeyPem = $pem;}diff --git a/tests/Feature/SyncAdapters/AppleBusinessManager/AppleCareEnrichmentTest.php b/tests/Feature/SyncAdapters/AppleBusinessManager/AppleCareEnrichmentTest.phpindex baf2f12c4f..efd6494cf9 100644--- a/tests/Feature/SyncAdapters/AppleBusinessManager/AppleCareEnrichmentTest.php+++ b/tests/Feature/SyncAdapters/AppleBusinessManager/AppleCareEnrichmentTest.php@@ -32,6 +32,7 @@ class AppleCareEnrichmentTest extends TestCase'private_key_type' => OPENSSL_KEYTYPE_EC,'curve_name' => 'prime256v1',]);+ $pem = '';openssl_pkey_export($key, $pem);$this->privateKeyPem = $pem;}