diff --git a/.codespellrc b/.codespellrc new file mode 100644 index 000000000000..284607ac6dd8 --- /dev/null +++ b/.codespellrc @@ -0,0 +1,5 @@ +[codespell] +skip = ./phpmd.xml,./CONTRIBUTORS.md,./composer.lock,*.min.js,*.map,./resources/lang/*,./node_modules/*,./public/vendor/*,./sample_csvs/*,./database/migrations/*,./public/js/* +count = +quiet-level = 3 +ignore-words-list = checkin,Checkin,currentY,userA \ No newline at end of file diff --git a/.github/workflows/codespell.yml b/.github/workflows/codespell.yml new file mode 100644 index 000000000000..cdab5a6649a6 --- /dev/null +++ b/.github/workflows/codespell.yml @@ -0,0 +1,18 @@ +name: codespell + +on: + push: + branches: + - develop + pull_request: + +jobs: + codespell: + runs-on: ubuntu-latest + + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Run codespell + uses: codespell-project/actions-codespell@v2.0 diff --git a/.github/workflows/crowdin-upload.yml b/.github/workflows/crowdin-upload.yml deleted file mode 100644 index 7b9331c97d04..000000000000 --- a/.github/workflows/crowdin-upload.yml +++ /dev/null @@ -1,21 +0,0 @@ -name: Crowdin Action - -on: - push: - branches: [ develop ] - -jobs: - upload-sources-to-crowdin: - runs-on: ubuntu-latest - steps: - - name: Checkout - uses: actions/checkout@v4 - - - name: Crowdin push - uses: crowdin/github-action@v2 - with: - upload_sources: true - upload_translations: false - download_translations: false - project_id: ${{ secrets.CROWDIN_PROJECT_ID }} - token: ${{ secrets.CROWDIN_PERSONAL_TOKEN }} diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index df81e980957f..ee14f1d7d397 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -4,3 +4,17 @@ Please see the documentation on [contributing and developing for Snipe-IT](https Please note that this project is released with a [Contributor Code of Conduct](CODE_OF_CONDUCT.md). By participating in this project you agree to abide by its terms. + +### Useful tools + +Add codespell as a linter: +`pip install codespell` + +Add a precommit hook: +`cp contrib/hooks/pre-commit .git/hooks/` + +Add phpcs: +`curl -OL https://phars.phpcodesniffer.com/phpcs.phar` + +Check against PSR12: +`php phpcs.phar -n --standard=PSR12 app/` \ No newline at end of file diff --git a/README.md b/README.md index 34a5ee405c2c..30ec594e8ca5 100644 --- a/README.md +++ b/README.md @@ -1,141 +1,3 @@ -![snipe-it-by-grok](https://github.com/grokability/snipe-it/assets/197404/b515673b-c7c8-4d9a-80f5-9fa58829a602) - -[![Crowdin](https://d322cqt584bo4o.cloudfront.net/snipe-it/localized.svg)](https://crowdin.com/project/snipe-it) [![Docker Pulls](https://img.shields.io/docker/pulls/snipe/snipe-it.svg)](https://hub.docker.com/r/snipe/snipe-it/) [![Codacy Badge](https://app.codacy.com/project/badge/Grade/553ce52037fc43ea99149785afcfe641)](https://app.codacy.com/gh/snipe/snipe-it/dashboard?utm_source=gh&utm_medium=referral&utm_content=&utm_campaign=Badge_grade) [![Tests](https://github.com/grokability/snipe-it/actions/workflows/tests.yml/badge.svg)](https://github.com/grokability/snipe-it/actions/workflows/tests.yml) -[![All Contributors](https://img.shields.io/badge/all_contributors-331-orange.svg?style=flat-square)](#contributing) [![Discord](https://badgen.net/badge/icon/discord?icon=discord&label)](https://discord.gg/yZFtShAcKk) - ## Snipe-IT - Open Source Asset Management System -This is a FOSS project for asset management in IT Operations. Knowing who has which laptop, when it was purchased in order to depreciate it correctly, handling software licenses, etc. - -It is built on [Laravel 11](http://laravel.com). - -Snipe-IT is actively developed and we [release quite frequently](https://github.com/grokability/snipe-it/releases). ([Check out the live demo here](https://snipeitapp.com/demo/).) - -> [!TIP] -> __This is web-based software__. This means there is no executable file (aka no .exe files), and it must be run on a web server and accessed through a web browser. It runs on any Mac OSX, any flavor of Linux, as well as Windows, and we have a [Docker image](https://snipe-it.readme.io/docs/docker) available if that's what you're into. - ------ - -### Table of Contents -* [Installation](#installation) -* [User's Manual](#users-manual) -* [Bug Reports & Feature Requests](#bug-reports--feature-requests) -* [Security](#security) -* [Upgrading](#upgrading) -* [Translations!](#translations-) -* [Libraries, Modules & Related Projects](#libraries-modules--related-projects) -* [Join the Community!](#join-the-community) -* [Contributing](#contributing) -* [Announcement List](#announcement-list) - - ------ - -### Installation - -For instructions on installing and configuring Snipe-IT on your server, check out the [installation manual](https://snipe-it.readme.io/docs). (Please see the [requirements documentation](https://snipe-it.readme.io/docs/requirements) for full requirements.) - -If you're having trouble with the installation, please check the [Common Issues](https://snipe-it.readme.io/docs/common-issues) and [Getting Help](https://snipe-it.readme.io/docs/getting-help) documentation, and search this repository's open *and* closed issues for help. - ------ -### User's Manual -For help using Snipe-IT, check out the [user's manual](https://snipe-it.readme.io/docs/overview). - ------ -### Bug Reports & Feature Requests - -Feel free to check out the [GitHub Issues for this project](https://github.com/grokability/snipe-it/issues) to open a bug report or see what open issues you can help with. Please search through existing issues (open *and* closed) to see if your question has already been answered before opening a new issue. - -> [!IMPORTANT] -> **PLEASE see the [Getting Help Guidelines](https://snipe-it.readme.io/docs/getting-help) and [Common Issues](https://snipe-it.readme.io/docs/common-issues) before opening a ticket, and be sure to complete all of the questions in the Github Issue template to help us to help you as quickly as possible.** - ------ - -### Security - -> [!IMPORTANT] -> **To report a security vulnerability, please email security@snipeitapp.com instead of using the issue tracker.** ------ - - -### Upgrading - -Please see the [upgrading documentation](https://snipe-it.readme.io/docs/upgrading) for instructions on upgrading Snipe-IT. - ------- -### Translations! - -Please see the [translations documentation](https://snipe-it.readme.io/docs/translations) for information about available languages and how to add translations to Snipe-IT. - ------ - -### Libraries, Modules & Related Projects - -Since the release of the JSON REST API, several third-party developers have been developing modules and libraries to work with Snipe-IT. - -> [!NOTE] -> As these were created by third-parties, Snipe-IT cannot provide support for these project, and you should contact the developers directly if you need assistance. Additionally, Snipe-IT makes no guarantees as to the reliability, accuracy or maintainability of these libraries. Use at your own risk. :) - -#### Libraries & Modules - -- [SnipeSharp - .NET module in C#](https://github.com/barrycarey/SnipeSharp) by [@barrycarey](https://github.com/barrycarey) -- [SnipeitPS](https://github.com/snazy2000/SnipeitPS) by [@snazy2000](https://github.com/snazy2000) - Powershell API Wrapper for Snipe-it -- [jamf2snipe](https://github.com/grokability/jamf2snipe) - Python script to sync assets between a JAMFPro instance and a Snipe-IT instance -- [jamf-snipe-rename](https://macblog.org/jamf-snipe-rename/) - Python script to rename computers in Jamf from Snipe-IT -- [Snipe-IT plugin for Jira Service Desk](https://marketplace.atlassian.com/apps/1220964/snipe-it-for-jira) -- [Python 3 CSV importer](https://github.com/gastamper/snipeit-csvimporter) - allows importing assets into Snipe-IT based on Item Name rather than Asset Tag. -- [Snipe-IT Kubernetes Helm Chart](https://github.com/t3n/helm-charts/tree/master/snipeit) - For more information, [click here](https://hub.helm.sh/charts/t3n/snipeit). -- [Snipe-IT Bulk Edit](https://github.com/bricelabelle/snipe-it-bulkedit) - Google Script files to use Google Sheets as a bulk checkout/checkin/edit tool for Snipe-IT. -- [MosyleSnipeSync](https://github.com/RodneyLeeBrands/MosyleSnipeSync) by [@Karpadiem](https://github.com/Karpadiem) - Python script to synchronize information between Mosyle and Snipe-IT. -- [WWW::SnipeIT](https://github.com/SEDC/perl-www-snipeit) by [@SEDC](https://github.com/SEDC) - perl module for accessing the API -- [UniFi to Snipe-IT](https://www.edtechirl.com/p/snipe-it-and-azure-asset-management) originally by [@karpadiem](https://github.com/karpadiem) - Python script that synchronizes UniFi devices with Snipe-IT. -- [Kandji2Snipe](https://github.com/grokability/kandji2snipe) by [@briangoldstein](https://github.com/briangoldstein) - Python script that synchronizes Kandji with Snipe-IT. -- [SnipeAgent](https://github.com/ReticentRobot/SnipeAgent) by [@ReticentRobot](https://github.com/ReticentRobot) - Windows agent for Snipe-IT. -- [Gate Pass Generator](https://github.com/cha7uraAE/snipe-it-gate-pass-system) by [@cha7uraAE](https://github.com/cha7uraAE) - A Streamlit application for generating gate passes based on hardware data from a Snipe-IT API. -- [InQRy (archived)](https://github.com/Microsoft/InQRy) by [@Microsoft](https://github.com/Microsoft) -- [Marksman (archived)](https://github.com/Scope-IT/marksman) - A Windows agent for Snipe-IT -- [Python Module (archived)](https://github.com/jbloomer/SnipeIT-PythonAPI) by [@jbloomer](https://github.com/jbloomer) - -We also have a handful of [Google Apps scripts](https://github.com/grokability/google-apps-scripts-for-snipe-it) to help with various tasks. - -#### Mobile Apps - -We're currently working on our own mobile app, but in the meantime, check out these third-party apps that work with Snipe-IT: - -- [SnipeMate](https://snipemate.app/) (iOS, Google Play, Huawei AppGallery) by Mars Technology -- [Snipe-Scan](https://apps.apple.com/do/app/snipe-scan/id6744179400?uo=2) (iOS) by Nicolas Maton -- [Snipe-IT Assets Management](https://play.google.com/store/apps/details?id=com.diegogarciadev.assetsmanager.snipeit&hl=en&pli=1) (Google Play) by DiegoGarciaDEV -- [AssetX](https://apps.apple.com/my/app/assetx-for-snipe-it/id6741996196?uo=2) (iOS) for Snipe-IT by Rishi Gupta - ------ - -### Join the Community! - -- **[Join our Discord](https://discord.gg/yZFtShAcKk)!** It’s full of great people. We even wrote about it [here](https://grokstar.dev/culture/2024/06/the-unlikely-rise-of-discord-as-a-support-channel/)! -- **Follow us on Bluesky** at [@snipeitapp.com](https://bsky.app/profile/snipeitapp.com) -- **Follow us on Mastodon** at [hachyderm.io/@grokability](https://hachyderm.io/@grokability) -- **Follow our blog** at [Grokstar.Dev](https://grokstar.dev) -- **Subscribe here** on Github for notifications about new releases. (We recommend selecting "Releases" only for most users - this repo can get noisy.) - ------ - -### Contributing - -**Please refrain from submitting issues or pull requests generated by fully-automated tools. Maintainers reserve the right, at their sole discretion, to close such submissions and to block any account responsible for them.** - -Contributions should follow from a human-to-human discussion in the form of an issue for the best chances of being merged into the core project. (Sometimes we might already be working on that feature, sometimes we've decided against ) - -Please see the complete documentation on [contributing and developing for Snipe-IT](https://snipe-it.readme.io/docs/contributing-overview). - -This project is released with a [Contributor Code of Conduct](CODE_OF_CONDUCT.md). By participating in this project you agree to abide by its terms. - -The ERD is available [online here](https://drawsql.app/templates/snipe-it). - -Be sure to check out all of the [amazing people](CONTRIBUTORS.md) that have contributed to Snipe-IT over the years! - ------- -### Announcement List - -To be notified of important news (such as new releases, security advisories, etc), [sign up for our list](http://eepurl.com/XyZKz). We'll never sell or give away your info, and we'll only email you when it's important. - - +A hard fork of Snipe-IT diff --git a/SECURITY.md b/SECURITY.md deleted file mode 100644 index e7ea43159205..000000000000 --- a/SECURITY.md +++ /dev/null @@ -1,29 +0,0 @@ -# Security Policy - -We take security issues very seriously, and will always attempt to address any -vulnerabilities as quickly as possible. - -## Supported Versions - -We try to make a reasonable effort to support older versions of Snipe-IT, -however there are times when library dependencies and/or PHP/MySQL dependencies -make it impossible to backport security fixes on older versions. - -| Version | Supported | -|---------| ------------------ | -| 7.x | :white_check_mark: | -| 6.x | :x: | -| 5.1.x | :x: | -| 5.0.x | :x: | -| 4.0.x | :x: | -| < 4.0 | :x: | - -## Reporting a Vulnerability - -Security vulnerabilities should be sent to security@snipeitapp.com. You can typically expect a -response within two business days, and we typically have fixes out in under a week from the initial disclosure. - -This obviously varies based on the severity of the security issue and the difficulty in remediation, -but those have historically been the timelines we worm around. - -For a full breakdown of our security policies, please see https://snipeitapp.com/security. diff --git a/ansible/freebsd/vagrant_playbook.yml b/ansible/freebsd/vagrant_playbook.yml index 7e10ca0d8691..54a02fe7f899 100644 --- a/ansible/freebsd/vagrant_playbook.yml +++ b/ansible/freebsd/vagrant_playbook.yml @@ -45,9 +45,9 @@ become: true # - # Install php and php dependancies + # Install php and php dependencies # - - name: Install PHP dependancies + - name: Install PHP dependencies pkgng: name: "{{ item }}" state: present @@ -94,7 +94,7 @@ become: true # - # Install the lastest version of composer + # Install the latest version of composer # - name: Composer check stat: diff --git a/ansible/ubuntu/vagrant_playbook.yml b/ansible/ubuntu/vagrant_playbook.yml index 44b1a6ef00aa..10727b67a5b3 100755 --- a/ansible/ubuntu/vagrant_playbook.yml +++ b/ansible/ubuntu/vagrant_playbook.yml @@ -44,7 +44,7 @@ - unzip - python-pymysql # - # Install the lastest version of composer + # Install the latest version of composer # - name: Composer check stat: diff --git a/app.json b/app.json index 24d874114ace..980a4263d1c0 100644 --- a/app.json +++ b/app.json @@ -1,12 +1,12 @@ { "name": "Snipe-IT", - "description": "Open source asset management.", + "description": "A hard fork of snipe-it", "keywords": [ "asset management", "it asset" ], - "website": "https://snipeitapp.com/", - "repository": "https://github.com/grokability/snipe-it", + "website": "https://github.com/CloCkWeRX/snipe-it/", + "repository": "https://github.com/CloCkWeRX/snipe-it", "logo": "https://pbs.twimg.com/profile_images/976748875733020672/K-HnZCCK_400x400.jpg", "success_url": "/setup", "env": { diff --git a/app/Actions/CheckoutRequests/CancelCheckoutRequestAction.php b/app/Actions/CheckoutRequests/CancelCheckoutRequestAction.php index 2d6dd68a0837..196fbb7f52c6 100644 --- a/app/Actions/CheckoutRequests/CancelCheckoutRequestAction.php +++ b/app/Actions/CheckoutRequests/CancelCheckoutRequestAction.php @@ -44,5 +44,4 @@ public static function run(Asset $asset, User $user) return true; } - -} \ No newline at end of file +} diff --git a/app/Actions/CheckoutRequests/CreateCheckoutRequestAction.php b/app/Actions/CheckoutRequests/CreateCheckoutRequestAction.php index 6870cfba2d4f..058e644c651d 100644 --- a/app/Actions/CheckoutRequests/CreateCheckoutRequestAction.php +++ b/app/Actions/CheckoutRequests/CreateCheckoutRequestAction.php @@ -51,4 +51,4 @@ public static function run(Asset $asset, User $user): string return true; } -} \ No newline at end of file +} diff --git a/app/Console/Commands/LdapTroubleshooter.php b/app/Console/Commands/LdapTroubleshooter.php index 5bb3cdd366c2..5280b758c449 100644 --- a/app/Console/Commands/LdapTroubleshooter.php +++ b/app/Console/Commands/LdapTroubleshooter.php @@ -273,7 +273,7 @@ public function handle() $this->line("Trying TLS first for port $port"); $ldap_url = "ldaps://".$parsed['host'].":$port"; if($this->test_anonymous_bind($ldap_url)) { - $this->info("Anonymous bind succesful to $ldap_url!"); + $this->info("Anonymous bind successful to $ldap_url!"); $ldap_urls[] = [ $ldap_url, true, false ]; $pretty_ldap_urls[] = [ $ldap_url, "YES", "no" ]; continue; // TODO - lots of copypasta in these if(test_anonymous_bind()) routines... @@ -282,7 +282,7 @@ public function handle() } if($this->test_anonymous_bind($ldap_url, false)) { - $this->info("Anonymous bind succesful to $ldap_url with certifcate-checks disabled"); + $this->info("Anonymous bind successful to $ldap_url with certificate-checks disabled"); $ldap_urls[] = [ $ldap_url, false, false ]; $pretty_ldap_urls[] = [ $ldap_url, "no", "no" ]; continue; @@ -292,7 +292,7 @@ public function handle() $ldap_url = "ldap://".$parsed['host'].":$port"; if($this->test_anonymous_bind($ldap_url, true, true)) { - $this->info("Plain connection to $ldap_url with STARTTLS succesful!"); + $this->info("Plain connection to $ldap_url with STARTTLS successful!"); $ldap_urls[] = [ $ldap_url, true, true ]; $pretty_ldap_urls[] = [ $ldap_url, "YES", "YES" ]; continue; @@ -301,7 +301,7 @@ public function handle() } if($this->test_anonymous_bind($ldap_url)) { - $this->info("Plain connection to $ldap_url succesful!"); + $this->info("Plain connection to $ldap_url successful!"); $ldap_urls[] = [ $ldap_url, true, false ]; $pretty_ldap_urls[] = [ $ldap_url, "YES", "no" ]; continue; diff --git a/app/Console/Commands/Purge.php b/app/Console/Commands/Purge.php index 1dd2aaa51ddf..3723c4d8bbd7 100644 --- a/app/Console/Commands/Purge.php +++ b/app/Console/Commands/Purge.php @@ -60,12 +60,12 @@ public function handle() */ $assets = Asset::whereNotNull('deleted_at')->withTrashed()->get(); $assetcount = $assets->count(); - $this->info($assets->count().' assets purged.'); + $this->info($assets->count() . ' assets purged.'); $asset_assoc = 0; $asset_maintenances = 0; foreach ($assets as $asset) { - $this->info('- Asset "'.$asset->present()->name().'" deleted.'); + $this->info('- Asset "' . $asset->present()->name() . '" deleted.'); $asset_assoc += $asset->assetlog()->count(); $asset->assetlog()->forceDelete(); $asset_maintenances += $asset->assetmaintenances()->count(); @@ -73,83 +73,82 @@ public function handle() $asset->forceDelete(); } - $this->info($asset_assoc.' corresponding log records purged.'); - $this->info($asset_maintenances.' corresponding maintenance records purged.'); + $this->info($asset_assoc . ' corresponding log records purged.'); + $this->info($asset_maintenances . ' corresponding maintenance records purged.'); $locations = Location::whereNotNull('deleted_at')->withTrashed()->get(); - $this->info($locations->count().' locations purged.'); + $this->info($locations->count() . ' locations purged.'); foreach ($locations as $location) { - $this->info('- Location "'.$location->name.'" deleted.'); + $this->info('- Location "' . $location->name . '" deleted.'); $location->forceDelete(); } $accessories = Accessory::whereNotNull('deleted_at')->withTrashed()->get(); $accessory_assoc = 0; - $this->info($accessories->count().' accessories purged.'); + $this->info($accessories->count() . ' accessories purged.'); foreach ($accessories as $accessory) { - $this->info('- Accessory "'.$accessory->name.'" deleted.'); + $this->info('- Accessory "' . $accessory->name . '" deleted.'); $accessory_assoc += $accessory->assetlog()->count(); $accessory->assetlog()->forceDelete(); $accessory->forceDelete(); } - $this->info($accessory_assoc.' corresponding log records purged.'); + $this->info($accessory_assoc . ' corresponding log records purged.'); $consumables = Consumable::whereNotNull('deleted_at')->withTrashed()->get(); - $this->info($consumables->count().' consumables purged.'); + $this->info($consumables->count() . ' consumables purged.'); foreach ($consumables as $consumable) { - $this->info('- Consumable "'.$consumable->name.'" deleted.'); + $this->info('- Consumable "' . $consumable->name . '" deleted.'); $consumable->assetlog()->forceDelete(); $consumable->forceDelete(); } $components = Component::whereNotNull('deleted_at')->withTrashed()->get(); - $this->info($components->count().' components purged.'); + $this->info($components->count() . ' components purged.'); foreach ($components as $component) { - $this->info('- Component "'.$component->name.'" deleted.'); + $this->info('- Component "' . $component->name . '" deleted.'); $component->assetlog()->forceDelete(); $component->forceDelete(); } $licenses = License::whereNotNull('deleted_at')->withTrashed()->get(); - $this->info($licenses->count().' licenses purged.'); + $this->info($licenses->count() . ' licenses purged.'); foreach ($licenses as $license) { - $this->info('- License "'.$license->name.'" deleted.'); + $this->info('- License "' . $license->name . '" deleted.'); $license->assetlog()->forceDelete(); $license->licenseseats()->forceDelete(); $license->forceDelete(); } $models = AssetModel::whereNotNull('deleted_at')->withTrashed()->get(); - $this->info($models->count().' asset models purged.'); + $this->info($models->count() . ' asset models purged.'); foreach ($models as $model) { - $this->info('- Asset Model "'.$model->name.'" deleted.'); + $this->info('- Asset Model "' . $model->name . '" deleted.'); $model->forceDelete(); } $categories = Category::whereNotNull('deleted_at')->withTrashed()->get(); - $this->info($categories->count().' categories purged.'); + $this->info($categories->count() . ' categories purged.'); foreach ($categories as $category) { - $this->info('- Category "'.$category->name.'" deleted.'); + $this->info('- Category "' . $category->name . '" deleted.'); $category->forceDelete(); } $suppliers = Supplier::whereNotNull('deleted_at')->withTrashed()->get(); - $this->info($suppliers->count().' suppliers purged.'); + $this->info($suppliers->count() . ' suppliers purged.'); foreach ($suppliers as $supplier) { - $this->info('- Supplier "'.$supplier->name.'" deleted.'); + $this->info('- Supplier "' . $supplier->name . '" deleted.'); $supplier->forceDelete(); } $users = User::whereNotNull('deleted_at')->where('show_in_list', '!=', '0')->withTrashed()->get(); - $this->info($users->count().' users purged.'); + $this->info($users->count() . ' users purged.'); $user_assoc = 0; foreach ($users as $user) { - $rel_path = 'private_uploads/users'; $filenames = Actionlog::where('action_type', 'uploaded') ->where('item_id', $user->id) ->pluck('filename'); - foreach($filenames as $filename) { + foreach ($filenames as $filename) { try { if (Storage::exists($rel_path . '/' . $filename)) { Storage::delete($rel_path . '/' . $filename); @@ -158,24 +157,24 @@ public function handle() Log::info('An error occurred while deleting files: ' . $e->getMessage()); } } - $this->info('- User "'.$user->username.'" deleted.'); + $this->info('- User "' . $user->username . '" deleted.'); $user_assoc += $user->userlog()->count(); $user->userlog()->forceDelete(); $user->forceDelete(); } - $this->info($user_assoc.' corresponding user log records purged.'); + $this->info($user_assoc . ' corresponding user log records purged.'); $manufacturers = Manufacturer::whereNotNull('deleted_at')->withTrashed()->get(); - $this->info($manufacturers->count().' manufacturers purged.'); + $this->info($manufacturers->count() . ' manufacturers purged.'); foreach ($manufacturers as $manufacturer) { - $this->info('- Manufacturer "'.$manufacturer->name.'" deleted.'); + $this->info('- Manufacturer "' . $manufacturer->name . '" deleted.'); $manufacturer->forceDelete(); } $status_labels = Statuslabel::whereNotNull('deleted_at')->withTrashed()->get(); - $this->info($status_labels->count().' status labels purged.'); + $this->info($status_labels->count() . ' status labels purged.'); foreach ($status_labels as $status_label) { - $this->info('- Status Label "'.$status_label->name.'" deleted.'); + $this->info('- Status Label "' . $status_label->name . '" deleted.'); $status_label->forceDelete(); } } else { diff --git a/app/Console/Commands/RestoreFromBackup.php b/app/Console/Commands/RestoreFromBackup.php index 0bee8dcdcf96..bef89256897e 100644 --- a/app/Console/Commands/RestoreFromBackup.php +++ b/app/Console/Commands/RestoreFromBackup.php @@ -93,7 +93,7 @@ public static function guess_prefix($input):string $parser->should_guess = true; $parser->line_aware_piping(); // <----- THIS is doing the heavy lifting! - $check_tables = ['settings' => null, 'migrations' => null /* 'assets' => null */]; //TODO - move to statics? + $check_tables = ['settings' => null, 'migrations' => null /* 'assets' => null */]; //TODO - move to static? //can't use 'users' because the 'accessories_checkout' table? // can't use 'assets' because 'ver1_components_assets' foreach($check_tables as $check_table => $_ignore) { @@ -508,7 +508,7 @@ public function handle() $bar->finish(); $this->line(''); } else { - $this->info(count($interesting_files).' files were succesfully transferred'); + $this->info(count($interesting_files).' files were successfully transferred'); } if (count($unsafe_files) > 0) { foreach ($unsafe_files as $unsafe_file) { diff --git a/app/Console/Kernel.php b/app/Console/Kernel.php index 664c8edc628b..0c19ba546fca 100644 --- a/app/Console/Kernel.php +++ b/app/Console/Kernel.php @@ -19,7 +19,7 @@ class Kernel extends ConsoleKernel */ protected function schedule(Schedule $schedule) { - if(Setting::getSettings()->alerts_enabled === 1) { + if (Setting::getSettings()->alerts_enabled === 1) { $schedule->command('snipeit:inventory-alerts')->daily(); $schedule->command('snipeit:expiring-alerts')->daily(); $schedule->command('snipeit:expected-checkin')->daily(); @@ -38,6 +38,6 @@ protected function schedule(Schedule $schedule) protected function commands() { require base_path('routes/console.php'); - $this->load(__DIR__.'/Commands'); + $this->load(__DIR__ . '/Commands'); } } diff --git a/app/Events/CheckoutAccepted.php b/app/Events/CheckoutAccepted.php index cd5ee1977666..abcbed959cc3 100644 --- a/app/Events/CheckoutAccepted.php +++ b/app/Events/CheckoutAccepted.php @@ -9,7 +9,8 @@ class CheckoutAccepted { - use Dispatchable, SerializesModels; + use Dispatchable; + use SerializesModels; /** * Create a new event instance. diff --git a/app/Events/CheckoutDeclined.php b/app/Events/CheckoutDeclined.php index 01d84b30f371..0ea3855ed03e 100644 --- a/app/Events/CheckoutDeclined.php +++ b/app/Events/CheckoutDeclined.php @@ -9,7 +9,8 @@ class CheckoutDeclined { - use Dispatchable, SerializesModels; + use Dispatchable; + use SerializesModels; /** * Create a new event instance. diff --git a/app/Events/CheckoutableCheckedIn.php b/app/Events/CheckoutableCheckedIn.php index 48aed2a64d7e..5ccfc66d8e7b 100644 --- a/app/Events/CheckoutableCheckedIn.php +++ b/app/Events/CheckoutableCheckedIn.php @@ -8,13 +8,14 @@ class CheckoutableCheckedIn { - use Dispatchable, SerializesModels; + use Dispatchable; + use SerializesModels; public $checkoutable; public $checkedOutTo; public $checkedInBy; public $note; - public $action_date; // Date setted in the hardware.checkin view at the checkin_at input, for the action log + public $action_date; // Date set in the hardware.checkin view at the checkin_at input, for the action log public $originalValues; /** diff --git a/app/Events/CheckoutableCheckedOut.php b/app/Events/CheckoutableCheckedOut.php index 3f215bd3bce8..43e3fd60913e 100644 --- a/app/Events/CheckoutableCheckedOut.php +++ b/app/Events/CheckoutableCheckedOut.php @@ -8,7 +8,8 @@ class CheckoutableCheckedOut { - use Dispatchable, SerializesModels; + use Dispatchable; + use SerializesModels; public $checkoutable; public $checkedOutTo; diff --git a/app/Events/UserMerged.php b/app/Events/UserMerged.php index 3a7f4d6a2c38..a8e01b5f042d 100644 --- a/app/Events/UserMerged.php +++ b/app/Events/UserMerged.php @@ -8,7 +8,8 @@ class UserMerged { - use Dispatchable, SerializesModels; + use Dispatchable; + use SerializesModels; /** * Create a new event instance. diff --git a/app/Exceptions/Handler.php b/app/Exceptions/Handler.php index e340d70b097c..da2072291955 100644 --- a/app/Exceptions/Handler.php +++ b/app/Exceptions/Handler.php @@ -53,7 +53,7 @@ public function report(Throwable $exception) /** * Render an exception into an HTTP response. - * + * * @param \Illuminate\Http\Request $request * @param \Exception $e * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse|\Illuminate\Http\Response @@ -77,7 +77,7 @@ public function render($request, Throwable $e) if ($e instanceof SCIMException) { try { $e->report(); // logs as 'debug', so shouldn't get too noisy - } catch(\Exception $reportException) { + } catch (\Exception $reportException) { //do nothing } return $e->render($request); // ALL SCIMExceptions have the 'render()' method @@ -90,7 +90,6 @@ public function render($request, Throwable $e) // Handle API requests that fail if ($request->ajax() || $request->wantsJson()) { - // Handle API requests that fail because Carbon cannot parse the date on validation (when a submitted date value is definitely not a date) if ($e instanceof InvalidFormatException) { return response()->json(Helper::formatStandardApiResponse('error', null, trans('validation.date', ['attribute' => 'date'])), 200); @@ -104,19 +103,17 @@ public function render($request, Throwable $e) // Handle API requests that fail because of an HTTP status code and return a useful error message if ($this->isHttpException($e)) { - $statusCode = $e->getStatusCode(); switch ($e->getStatusCode()) { case '404': - return response()->json(Helper::formatStandardApiResponse('error', null, $statusCode . ' endpoint not found'), 404); + return response()->json(Helper::formatStandardApiResponse('error', null, $statusCode . ' endpoint not found'), 404); case '429': return response()->json(Helper::formatStandardApiResponse('error', null, 'Too many requests'), 429); - case '405': + case '405': return response()->json(Helper::formatStandardApiResponse('error', null, 'Method not allowed'), 405); default: return response()->json(Helper::formatStandardApiResponse('error', null, $statusCode), $statusCode); - } } } @@ -125,10 +122,9 @@ public function render($request, Throwable $e) // This is traaaaash but it handles models that are not found while using route model binding :( // The only alternative is to set that at *each* route, which is crazypants if ($e instanceof \Illuminate\Database\Eloquent\ModelNotFoundException) { - // This gets the MVC model name from the exception and formats in a way that's less fugly $model_name = strtolower(implode(" ", preg_split('/(?=[A-Z])/', last(explode('\\', $e->getModel()))))); - $route = str_plural(strtolower(last(explode('\\', $e->getModel())))).'.index'; + $route = str_plural(strtolower(last(explode('\\', $e->getModel())))) . '.index'; // Sigh. if ($route == 'assets.index') { @@ -154,11 +150,10 @@ public function render($request, Throwable $e) if ($this->isHttpException($e) && (isset($statusCode)) && ($statusCode == '404' )) { return response()->view('layouts/basic', [ 'content' => view('errors/404') - ],$statusCode); + ], $statusCode); } return parent::render($request, $e); - } /** @@ -183,7 +178,7 @@ protected function invalidJson($request, ValidationException $exception) } - /** + /** * A list of the inputs that are never flashed for validation exceptions. * * @var array diff --git a/app/Exceptions/UserDoestExistException.php b/app/Exceptions/UserDoestExistException.php index e14069dca4af..17f8888600c3 100644 --- a/app/Exceptions/UserDoestExistException.php +++ b/app/Exceptions/UserDoestExistException.php @@ -6,5 +6,4 @@ class UserDoestExistException extends Exception { - } diff --git a/app/Helpers/Helper.php b/app/Helpers/Helper.php index e899fb8781f3..33b95f2a4345 100644 --- a/app/Helpers/Helper.php +++ b/app/Helpers/Helper.php @@ -1,6 +1,7 @@ digit_separator=='1.234,56') { + if (Setting::getSettings()->digit_separator == '1.234,56') { return number_format($cost, 2, ',', '.'); } return number_format($cost, 2, '.', ','); @@ -416,17 +414,15 @@ public static function defaultChartColors(int $index = 0) $total_colors = count($colors); if ($index >= $total_colors) { - - Log::info('Status label count is '.$index.' and exceeds the allowed count of 266.'); + Log::info('Status label count is ' . $index . ' and exceeds the allowed count of 266.'); //patch fix for array key overflow (color count starts at 1, array starts at 0) $index = $index - $total_colors - 1; //constraints to keep result in 0-265 range. This should never be needed, but if something happens //to create this many status labels and it DOES happen, this will keep it from failing at least. - if($index < 0) { + if ($index < 0) { $index = 0; - } - elseif($index >($total_colors - 1)) { + } elseif ($index > ($total_colors - 1)) { $index = $total_colors - 1; } } @@ -447,7 +443,7 @@ public static function adjustBrightness($hexCode, $adjustPercent) $hexCode = ltrim($hexCode, '#'); if (strlen($hexCode) == 3) { - $hexCode = $hexCode[0].$hexCode[0].$hexCode[1].$hexCode[1].$hexCode[2].$hexCode[2]; + $hexCode = $hexCode[0] . $hexCode[0] . $hexCode[1] . $hexCode[1] . $hexCode[2] . $hexCode[2]; } $hexCode = array_map('hexdec', str_split($hexCode, 2)); @@ -459,7 +455,7 @@ public static function adjustBrightness($hexCode, $adjustPercent) $color = str_pad(dechex($color + $adjustAmount), 2, '0', STR_PAD_LEFT); } - return '#'.implode($hexCode); + return '#' . implode($hexCode); } /** @@ -499,17 +495,17 @@ public static function chartBackgroundColors() public static function ParseFloat($floatString) { /******* - * + * * WARNING: This does conversions based on *locale* - a Unix-ey-like thing. - * + * * Everything else in the system tends to convert based on the Snipe-IT settings - * + * * So it's very likely this is *not* what you want - instead look for the new - * + * * ParseCurrency($currencyString) - * + * * Which should be directly below here - * + * */ $LocaleInfo = localeconv(); $floatString = str_replace(',', '', $floatString); @@ -525,17 +521,18 @@ public static function ParseFloat($floatString) return floatval($floatString); } - + /** * Format currency using comma or period for thousands, and period or comma for decimal, based on settings. - * + * * @author [B. Wetherington] [] * @since [v5.2] * @return Float */ - public static function ParseCurrency($currencyString) { + public static function ParseCurrency($currencyString) + { $without_currency = str_replace(Setting::getSettings()->default_currency, '', $currencyString); //generally shouldn't come up, since we don't do this in fields, but just in case it does... - if(Setting::getSettings()->digit_separator=='1.234,56') { + if (Setting::getSettings()->digit_separator == '1.234,56') { //EU format $without_thousands = str_replace('.', '', $without_currency); $corrected_decimal = str_replace(',', '.', $without_thousands); @@ -623,7 +620,7 @@ public static function depreciationList() * @since [v2.5] * @return array */ - public static function categoryTypeList($selection=null) + public static function categoryTypeList($selection = null) { $category_types = [ '' => '', @@ -634,11 +631,11 @@ public static function categoryTypeList($selection=null) 'license' => trans('general.license'), ]; - if ($selection != null){ + if ($selection != null) { return $category_types[strtolower($selection)]; + } else { + return $category_types; } - else - return $category_types; } /** * Get the list of custom fields in an array to make a dropdown menu @@ -718,7 +715,8 @@ public static function generateRandomString($length = 10) * @since [v7.0.14] * @return array */ - public static function deprecationCheck() : array { + public static function deprecationCheck(): array + { // The check and message that the user is still using the deprecated version $deprecations = [ 'ms_teams_deprecated' => array( @@ -727,7 +725,7 @@ public static function deprecationCheck() : array { ]; // if item of concern is being used and its being used with the deprecated values return the notification array. - if(Setting::getSettings()->webhook_selected === 'microsoft' && $deprecations['ms_teams_deprecated']['check']) { + if (Setting::getSettings()->webhook_selected === 'microsoft' && $deprecations['ms_teams_deprecated']['check']) { return $deprecations; } return []; @@ -810,8 +808,7 @@ public static function checkLowInventory() } } - foreach ($asset_models as $asset_model){ - + foreach ($asset_models as $asset_model) { $asset = new Asset(); $total_owned = $asset->where('model_id', '=', $asset_model->id)->count(); $avail = $asset->where('model_id', '=', $asset_model->id)->whereNull('assigned_to')->count(); @@ -832,7 +829,7 @@ public static function checkLowInventory() } } - foreach ($licenses as $license){ + foreach ($licenses as $license) { $avail = $license->remaincount(); if ($avail < ($license->min_amt) + $alert_threshold) { if ($avail > 0) { @@ -849,7 +846,6 @@ public static function checkLowInventory() $items_array[$all_count]['min_amt'] = $license->min_amt; $all_count++; } - } return $items_array; @@ -902,15 +898,12 @@ public static function selectedPermissionsArray($permissions, $selected_arr = [] $permission_name = $permission[$x]['permission']; if ($permission[$x]['display'] === true) { - if (is_array($selected_arr)) { - if (array_key_exists($permission_name, $selected_arr)) { $permissions_arr[$permission_name] = $selected_arr[$permission_name]; } else { $permissions_arr[$permission_name] = '0'; } - } else { $permissions_arr[$permission_name] = '0'; } @@ -940,17 +933,17 @@ public static function checkIfRequired($class, $field) if ($rule_name == $field) { if (is_array($rule)) { if (in_array('required', $rule)) { - return true; + return true; } else { return false; } } else { if (strpos($rule, 'required') === false) { return false; - } else { - return true; - } + } else { + return true; } + } } } return false; @@ -992,14 +985,13 @@ public static function gracefulDecrypt(CustomField $field, $string) return Crypt::decrypt($string); } catch (DecryptException $e) { - return 'Error Decrypting: '.$e->getMessage(); - } + return 'Error Decrypting: ' . $e->getMessage(); } + } return $string; } public static function formatStandardApiResponse($status, $payload = null, $messages = null) - { $array['status'] = $status; $array['messages'] = $messages; @@ -1055,7 +1047,7 @@ public static function getFormattedDateObject($date, $type = 'datetime', $array if ($type == 'datetime') { $dt['datetime'] = $tmp_date->format('Y-m-d H:i:s'); - $dt['formatted'] = $tmp_date->format($settings->date_display_format.' '.$settings->time_display_format); + $dt['formatted'] = $tmp_date->format($settings->date_display_format . ' ' . $settings->time_display_format); } else { $dt['date'] = $tmp_date->format('Y-m-d'); $dt['formatted'] = $tmp_date->format($settings->date_display_format); @@ -1066,12 +1058,10 @@ public static function getFormattedDateObject($date, $type = 'datetime', $array } return $dt['formatted']; - } catch (\Exception $e) { Log::warning($e); - return $date.' (Invalid '.$type.' value.)'; + return $date . ' (Invalid ' . $type . ' value.)'; } - } // Nicked from Drupal :) @@ -1082,7 +1072,6 @@ public static function file_upload_max_size() static $max_size = -1; if ($max_size < 0) { - // Start with post_max_size. $post_max_size = self::parse_size(ini_get('post_max_size')); if ($post_max_size > 0) { @@ -1203,7 +1192,7 @@ public static function generateUnencryptedPassword(): string * @param string $save_path path to a folder where the image should be saved * @return string path to uploaded image or false if something went wrong */ - public static function processUploadedImage(String $image_data, String $save_path) + public static function processUploadedImage(string $image_data, string $save_path) { if ($image_data == null || $save_path == null) { return false; @@ -1217,7 +1206,7 @@ public static function processUploadedImage(String $image_data, String $save_pat // Start reading the image after the first comma, postceding the base64. $image = substr($image_data, strpos($image_data, ',') + 1); - $file_name = str_random(25).'.'.$extension; + $file_name = str_random(25) . '.' . $extension; $directory = public_path($save_path); // Check if the uploads directory exists. If not, try to create it. @@ -1225,7 +1214,7 @@ public static function processUploadedImage(String $image_data, String $save_pat mkdir($directory, 0755, true); } - $path = public_path($save_path.$file_name); + $path = public_path($save_path . $file_name); try { Image::make($image)->resize(500, 500, function ($constraint) { @@ -1250,28 +1239,17 @@ public static function processUploadedImage(String $image_data, String $save_pat */ public static function formatFilesizeUnits($bytes) { - if ($bytes >= 1073741824) - { + if ($bytes >= 1073741824) { $bytes = number_format($bytes / 1073741824, 2) . ' GB'; - } - elseif ($bytes >= 1048576) - { + } elseif ($bytes >= 1048576) { $bytes = number_format($bytes / 1048576, 2) . ' MB'; - } - elseif ($bytes >= 1024) - { + } elseif ($bytes >= 1024) { $bytes = number_format($bytes / 1024, 2) . ' KB'; - } - elseif ($bytes > 1) - { + } elseif ($bytes > 1) { $bytes = $bytes . ' bytes'; - } - elseif ($bytes == 1) - { + } elseif ($bytes == 1) { $bytes = $bytes . ' byte'; - } - else - { + } else { $bytes = '0 bytes'; } @@ -1286,11 +1264,12 @@ public static function formatFilesizeUnits($bytes) * * @return string[] */ - public static function SettingUrls(){ - $settings=['#','fields.index', 'statuslabels.index', 'models.index', 'categories.index', 'manufacturers.index', 'suppliers.index', 'departments.index', 'locations.index', 'companies.index', 'depreciations.index']; + public static function SettingUrls() + { + $settings = ['#','fields.index', 'statuslabels.index', 'models.index', 'categories.index', 'manufacturers.index', 'suppliers.index', 'departments.index', 'locations.index', 'companies.index', 'depreciations.index']; return $settings; - } + } /** @@ -1302,7 +1281,8 @@ public static function SettingUrls(){ * * @return string */ - public static function iconTypeByItem($item) { + public static function iconTypeByItem($item) + { switch ($item) { case 'asset': @@ -1327,7 +1307,6 @@ public static function iconTypeByItem($item) { return 'fas fa-user'; break; } - } @@ -1345,16 +1324,17 @@ public static function iconTypeByItem($item) { * } * @todo - use this everywhere else in the app where we have very long if/else config('app.lock_passwords') stuff */ - public static function isDemoMode() { + public static function isDemoMode() + { if (config('app.lock_passwords') === true) { return true; Log::debug('app locked!'); } - + return false; } - + /** * Conversion between units of measurement * @@ -1366,13 +1346,14 @@ public static function isDemoMode() { * @param int $round Round the result to decimals (Default false - No rounding) * @return float */ - public static function convertUnit($value, $srcUnit, $dstUnit, $round=false) { + public static function convertUnit($value, $srcUnit, $dstUnit, $round = false) + { $srcFactor = static::getUnitConversionFactor($srcUnit); $dstFactor = static::getUnitConversionFactor($dstUnit); $output = $value * $srcFactor / $dstFactor; return ($round !== false) ? round($output, $round) : $output; } - + /** * Get conversion factor from unit of measurement to mm * @@ -1381,7 +1362,8 @@ public static function convertUnit($value, $srcUnit, $dstUnit, $round=false) { * @param string $unit Unit of measurement * @return float */ - public static function getUnitConversionFactor($unit) { + public static function getUnitConversionFactor($unit) + { switch (strtolower($unit)) { case 'mm': return 1.0; @@ -1409,7 +1391,8 @@ public static function getUnitConversionFactor($unit) { * I know it's gauche to return a shitty HTML string, but this is just a helper and since it will be the same every single time, * it seemed pretty safe to do here. Don't you judge me. */ - public static function showDemoModeFieldWarning() { + public static function showDemoModeFieldWarning() + { if (Helper::isDemoMode()) { return "

" . trans('general.feature_disabled') . "

"; } @@ -1465,17 +1448,20 @@ public static function mapBackToLegacyLocale($new_locale = null) return $new_locale; // better that you have some weird locale that doesn't fit into our mappings anywhere than 'void' } - public static function determineLanguageDirection() { - return in_array(app()->getLocale(), + public static function determineLanguageDirection() + { + return in_array( + app()->getLocale(), [ 'ar-SA', 'fa-IR', 'he-IL' - ]) ? 'rtl' : 'ltr'; + ] + ) ? 'rtl' : 'ltr'; } - static public function getRedirectOption($request, $id, $table, $item_id = null) + public static function getRedirectOption($request, $id, $table, $item_id = null) { $redirect_option = Session::get('redirect_option'); @@ -1534,7 +1520,7 @@ static public function getRedirectOption($request, $id, $table, $item_id = null) /** * Check for inconsistencies before activating scoped locations with FullMultipleCompanySupport - * If there are locations with different companies than related objects unforseen problems could arise + * If there are locations with different companies than related objects unforeseen problems could arise * * @author T. Regnery * @since 7.0 @@ -1544,7 +1530,8 @@ static public function getRedirectOption($request, $id, $table, $item_id = null) * @param $new_company_id in case of updating a location, this is the newly requested company_id * @return string [] */ - static public function test_locations_fmcs($artisan, $location_id = null, $new_company_id = null) { + public static function test_locations_fmcs($artisan, $location_id = null, $new_company_id = null) + { $mismatched = []; if ($location_id) { @@ -1556,7 +1543,7 @@ static public function test_locations_fmcs($artisan, $location_id = null, $new_c $locations = Location::all(); } - foreach($locations as $location) { + foreach ($locations as $location) { // in case of an update of a single location, use the newly requested company_id if ($new_company_id) { $location_company = $new_company_id; @@ -1587,7 +1574,7 @@ static public function test_locations_fmcs($artisan, $location_id = null, $new_c } foreach ($keywords_relation as $relation => $keywords) { - foreach($keywords as $keyword) { + foreach ($keywords as $keyword) { if ($relation == 'many') { $items = $location->{$keyword}->all(); } else { @@ -1595,7 +1582,6 @@ static public function test_locations_fmcs($artisan, $location_id = null, $new_c } foreach ($items as $item) { - if ($item && $item->company_id != $location_company) { $mismatched[] = [ class_basename(get_class($item)), @@ -1612,12 +1598,11 @@ class_basename(get_class($item)), $item->location->company->name ?? null, $location_company ?? null, ]; - } } } } } return $mismatched; - } + } } diff --git a/app/Helpers/IconHelper.php b/app/Helpers/IconHelper.php index 7c8e2a74562a..8ea6ec96f028 100644 --- a/app/Helpers/IconHelper.php +++ b/app/Helpers/IconHelper.php @@ -4,8 +4,8 @@ class IconHelper { - - public static function icon($type) { + public static function icon($type) + { switch ($type) { case 'checkout': return 'fa-solid fa-rotate-left'; @@ -107,7 +107,7 @@ public static function icon($type) { case 'dashboard': return 'fas fa-tachometer-alt'; case 'info-circle': - return 'fas fa-info-circle'; + return 'fas fa-info-circle'; case 'caret-right': return 'fa fa-caret-right'; case 'caret-up': @@ -182,11 +182,11 @@ public static function icon($type) { return 'fas fa-crosshairs'; case 'oauth': return 'fas fa-user-secret'; - case 'employee_num' : + case 'employee_num': return 'fa-regular fa-id-card'; - case 'department' : + case 'department': return 'fa-solid fa-building-user'; - case 'home' : + case 'home': return 'fa-solid fa-house'; case 'note': case 'notes': diff --git a/app/Helpers/StorageHelper.php b/app/Helpers/StorageHelper.php index 47700f913ac5..8e68c55bd2f7 100644 --- a/app/Helpers/StorageHelper.php +++ b/app/Helpers/StorageHelper.php @@ -8,9 +8,10 @@ use Symfony\Component\HttpFoundation\BinaryFileResponse; use Symfony\Component\HttpFoundation\StreamedResponse; use Illuminate\Contracts\Filesystem\FileNotFoundException; + class StorageHelper { - public static function downloader($filename, $disk = 'default') : BinaryFileResponse | RedirectResponse | StreamedResponse + public static function downloader($filename, $disk = 'default'): BinaryFileResponse | RedirectResponse | StreamedResponse { if ($disk == 'default') { $disk = config('filesystems.default'); @@ -37,7 +38,8 @@ public static function downloader($filename, $disk = 'default') : BinaryFileResp * @param $file_with_path * @return bool */ - public static function allowSafeInline($file_with_path) { + public static function allowSafeInline($file_with_path) + { $allowed_inline = [ 'pdf', @@ -56,18 +58,17 @@ public static function allowSafeInline($file_with_path) { return true; } return false; - } /** * Decide whether to show the file inline or download it. */ - public static function showOrDownloadFile($file, $filename) { + public static function showOrDownloadFile($file, $filename) + { $headers = []; if (request('inline') == 'true') { - $headers = [ 'Content-Disposition' => 'inline', ]; @@ -84,6 +85,5 @@ public static function showOrDownloadFile($file, $filename) { } return Storage::download($file, $filename, $headers); - } } diff --git a/app/Http/Controllers/Api/CompaniesController.php b/app/Http/Controllers/Api/CompaniesController.php index fd7f57ddce30..337322431843 100644 --- a/app/Http/Controllers/Api/CompaniesController.php +++ b/app/Http/Controllers/Api/CompaniesController.php @@ -20,7 +20,7 @@ class CompaniesController extends Controller * @author [A. Gianotto] [] * @since [v4.0] */ - public function index(Request $request) : JsonResponse | array + public function index(Request $request): JsonResponse | array { $this->authorize('view', Company::class); @@ -53,7 +53,7 @@ public function index(Request $request) : JsonResponse | array $companies->where('name', '=', $request->input('name')); } - if ($request->filled('email')) { + if ($request->filled('email')) { $companies->where('email', '=', $request->input('email')); } @@ -81,8 +81,7 @@ public function index(Request $request) : JsonResponse | array $total = $companies->count(); $companies = $companies->skip($offset)->take($limit)->get(); - return (new CompaniesTransformer)->transformCompanies($companies, $total); - + return (new CompaniesTransformer())->transformCompanies($companies, $total); } @@ -93,15 +92,15 @@ public function index(Request $request) : JsonResponse | array * @since [v4.0] * @param \App\Http\Requests\ImageUploadRequest $request */ - public function store(ImageUploadRequest $request) : JsonResponse + public function store(ImageUploadRequest $request): JsonResponse { $this->authorize('create', Company::class); - $company = new Company; + $company = new Company(); $company->fill($request->all()); $company = $request->handleImages($company); - + if ($company->save()) { - return response()->json(Helper::formatStandardApiResponse('success', (new CompaniesTransformer)->transformCompany($company), trans('admin/companies/message.create.success'))); + return response()->json(Helper::formatStandardApiResponse('success', (new CompaniesTransformer())->transformCompany($company), trans('admin/companies/message.create.success'))); } return response() @@ -115,12 +114,11 @@ public function store(ImageUploadRequest $request) : JsonResponse * @since [v4.0] * @param int $id */ - public function show($id) : array + public function show($id): array { $this->authorize('view', Company::class); $company = Company::findOrFail($id); - return (new CompaniesTransformer)->transformCompany($company); - + return (new CompaniesTransformer())->transformCompany($company); } @@ -132,7 +130,7 @@ public function show($id) : array * @param \App\Http\Requests\ImageUploadRequest $request * @param int $id */ - public function update(ImageUploadRequest $request, $id) : JsonResponse + public function update(ImageUploadRequest $request, $id): JsonResponse { $this->authorize('update', Company::class); $company = Company::findOrFail($id); @@ -141,7 +139,7 @@ public function update(ImageUploadRequest $request, $id) : JsonResponse if ($company->save()) { return response() - ->json(Helper::formatStandardApiResponse('success', (new CompaniesTransformer)->transformCompany($company), trans('admin/companies/message.update.success'))); + ->json(Helper::formatStandardApiResponse('success', (new CompaniesTransformer())->transformCompany($company), trans('admin/companies/message.update.success'))); } return response() @@ -155,7 +153,7 @@ public function update(ImageUploadRequest $request, $id) : JsonResponse * @since [v4.0] * @param int $id */ - public function destroy($id) : JsonResponse + public function destroy($id): JsonResponse { $this->authorize('delete', Company::class); $company = Company::findOrFail($id); @@ -178,7 +176,7 @@ public function destroy($id) : JsonResponse * @since [v4.0.16] * @see \App\Http\Transformers\SelectlistTransformer */ - public function selectlist(Request $request) : array + public function selectlist(Request $request): array { $this->authorize('view.selectlists'); $companies = Company::select([ @@ -189,7 +187,7 @@ public function selectlist(Request $request) : array ]); if ($request->filled('search')) { - $companies = $companies->where('companies.name', 'LIKE', '%'.$request->get('search').'%'); + $companies = $companies->where('companies.name', 'LIKE', '%' . $request->get('search') . '%'); } $companies = $companies->orderBy('name', 'ASC')->paginate(50); @@ -198,9 +196,9 @@ public function selectlist(Request $request) : array // This lets us have more flexibility in special cases like assets, where // they may not have a ->name value but we want to display something anyway foreach ($companies as $company) { - $company->use_image = ($company->image) ? Storage::disk('public')->url('companies/'.$company->image, $company->image) : null; + $company->use_image = ($company->image) ? Storage::disk('public')->url('companies/' . $company->image, $company->image) : null; } - return (new SelectlistTransformer)->transformSelectlist($companies); + return (new SelectlistTransformer())->transformSelectlist($companies); } } diff --git a/app/Http/Controllers/Api/DepartmentsController.php b/app/Http/Controllers/Api/DepartmentsController.php index 167d5cbc2af2..d8b6ed609d29 100644 --- a/app/Http/Controllers/Api/DepartmentsController.php +++ b/app/Http/Controllers/Api/DepartmentsController.php @@ -20,7 +20,7 @@ class DepartmentsController extends Controller * @author [Godfrey Martinez] [] * @since [v4.0] */ - public function index(Request $request) : JsonResponse | array + public function index(Request $request): JsonResponse | array { $this->authorize('view', Department::class); $allowed_columns = ['id', 'name', 'image', 'users_count', 'notes']; @@ -83,8 +83,7 @@ public function index(Request $request) : JsonResponse | array $total = $departments->count(); $departments = $departments->skip($offset)->take($limit)->get(); - return (new DepartmentsTransformer)->transformDepartments($departments, $total); - + return (new DepartmentsTransformer())->transformDepartments($departments, $total); } /** @@ -94,10 +93,10 @@ public function index(Request $request) : JsonResponse | array * @since [v4.0] * @param \App\Http\Requests\ImageUploadRequest $request */ - public function store(ImageUploadRequest $request) : JsonResponse + public function store(ImageUploadRequest $request): JsonResponse { $this->authorize('create', Department::class); - $department = new Department; + $department = new Department(); $department->fill($request->all()); $department = $request->handleImages($department); @@ -108,7 +107,6 @@ public function store(ImageUploadRequest $request) : JsonResponse return response()->json(Helper::formatStandardApiResponse('success', $department, trans('admin/departments/message.create.success'))); } return response()->json(Helper::formatStandardApiResponse('error', null, $department->getErrors())); - } /** @@ -118,11 +116,11 @@ public function store(ImageUploadRequest $request) : JsonResponse * @since [v4.0] * @param int $id */ - public function show($id) : array + public function show($id): array { $this->authorize('view', Department::class); $department = Department::findOrFail($id); - return (new DepartmentsTransformer)->transformDepartment($department); + return (new DepartmentsTransformer())->transformDepartment($department); } /** @@ -133,7 +131,7 @@ public function show($id) : array * @param \App\Http\Requests\ImageUploadRequest $request * @param int $id */ - public function update(ImageUploadRequest $request, $id) : JsonResponse + public function update(ImageUploadRequest $request, $id): JsonResponse { $this->authorize('update', Department::class); $department = Department::findOrFail($id); @@ -155,7 +153,7 @@ public function update(ImageUploadRequest $request, $id) : JsonResponse * @param int $locationId * @since [v4.0] */ - public function destroy($id) : JsonResponse + public function destroy($id): JsonResponse { $department = Department::findOrFail($id); @@ -167,7 +165,6 @@ public function destroy($id) : JsonResponse $department->delete(); return response()->json(Helper::formatStandardApiResponse('success', null, trans('admin/departments/message.delete.success'))); - } /** @@ -177,7 +174,7 @@ public function destroy($id) : JsonResponse * @since [v4.0.16] * @see \App\Http\Transformers\SelectlistTransformer */ - public function selectlist(Request $request) : array + public function selectlist(Request $request): array { $this->authorize('view.selectlists'); @@ -188,7 +185,7 @@ public function selectlist(Request $request) : array ]); if ($request->filled('search')) { - $departments = $departments->where('name', 'LIKE', '%'.$request->get('search').'%'); + $departments = $departments->where('name', 'LIKE', '%' . $request->get('search') . '%'); } $departments = $departments->orderBy('name', 'ASC')->paginate(50); @@ -197,9 +194,9 @@ public function selectlist(Request $request) : array // This lets us have more flexibility in special cases like assets, where // they may not have a ->name value but we want to display something anyway foreach ($departments as $department) { - $department->use_image = ($department->image) ? Storage::disk('public')->url('departments/'.$department->image, $department->image) : null; + $department->use_image = ($department->image) ? Storage::disk('public')->url('departments/' . $department->image, $department->image) : null; } - return (new SelectlistTransformer)->transformSelectlist($departments); + return (new SelectlistTransformer())->transformSelectlist($departments); } } diff --git a/app/Http/Controllers/Api/LocationsController.php b/app/Http/Controllers/Api/LocationsController.php index 638765928b84..1529cfda14a9 100644 --- a/app/Http/Controllers/Api/LocationsController.php +++ b/app/Http/Controllers/Api/LocationsController.php @@ -57,7 +57,9 @@ public function index(Request $request) : JsonResponse | array 'users_count', 'zip', 'notes', - ]; + 'latitude', + 'longitude' + ]; $locations = Location::with('parent', 'manager', 'children')->select([ 'locations.id', @@ -79,6 +81,8 @@ public function index(Request $request) : JsonResponse | array 'locations.currency', 'locations.company_id', 'locations.notes', + 'locations.latitude', + 'locations.longitude' ]) ->withCount('assignedAssets as assigned_assets_count') ->withCount('assignedAssets as assigned_assets_count') @@ -122,6 +126,8 @@ public function index(Request $request) : JsonResponse | array $locations->where('locations.country', '=', $request->input('country')); } + // TBA: Should this API support basic lat/long filtering? + if ($request->filled('manager_id')) { $locations->where('locations.manager_id', '=', $request->input('manager_id')); } @@ -158,7 +164,7 @@ public function index(Request $request) : JsonResponse | array $total = $locations->count(); $locations = $locations->skip($offset)->take($limit)->get(); - return (new LocationsTransformer)->transformLocations($locations, $total); + return (new LocationsTransformer())->transformLocations($locations, $total); } @@ -172,7 +178,7 @@ public function index(Request $request) : JsonResponse | array public function store(ImageUploadRequest $request) : JsonResponse { $this->authorize('create', Location::class); - $location = new Location; + $location = new Location(); $location->fill($request->all()); $location = $request->handleImages($location); @@ -182,11 +188,11 @@ public function store(ImageUploadRequest $request) : JsonResponse // check if parent is set and has a different company if ($location->parent_id && Location::find($location->parent_id)->company_id != $location->company_id) { response()->json(Helper::formatStandardApiResponse('error', null, 'different company than parent')); - } + } } if ($location->save()) { - return response()->json(Helper::formatStandardApiResponse('success', (new LocationsTransformer)->transformLocation($location), trans('admin/locations/message.create.success'))); + return response()->json(Helper::formatStandardApiResponse('success', (new LocationsTransformer())->transformLocation($location), trans('admin/locations/message.create.success'))); } return response()->json(Helper::formatStandardApiResponse('error', null, $location->getErrors())); @@ -219,6 +225,8 @@ public function show($id) : JsonResponse | array 'locations.image', 'locations.currency', 'locations.notes', + 'locations.latitude', + 'locations.longitude' ]) ->withCount('assignedAssets as assigned_assets_count') ->withCount('assets as assets_count') @@ -226,7 +234,7 @@ public function show($id) : JsonResponse | array ->withCount('users as users_count') ->findOrFail($id); - return (new LocationsTransformer)->transformLocation($location); + return (new LocationsTransformer())->transformLocation($location); } @@ -253,19 +261,19 @@ public function update(ImageUploadRequest $request, $id) : JsonResponse // check if there are related objects with different company if (Helper::test_locations_fmcs(false, $id, $location->company_id)) { return response()->json(Helper::formatStandardApiResponse('error', null, 'error scoped locations')); - } + } } else { $location->company_id = $request->get('company_id'); } } if ($location->isValid()) { - $location->save(); + return response()->json( Helper::formatStandardApiResponse( 'success', - (new LocationsTransformer)->transformLocation($location), + (new LocationsTransformer())->transformLocation($location), trans('admin/locations/message.update.success') ) ); @@ -281,7 +289,7 @@ public function assets(Request $request, Location $location) : JsonResponse | ar $this->authorize('view', $location); $assets = Asset::where('location_id', '=', $location->id)->with('model', 'model.category', 'assetstatus', 'location', 'company', 'defaultLoc'); $assets = $assets->get(); - return (new AssetsTransformer)->transformAssets($assets, $assets->count(), $request); + return (new AssetsTransformer())->transformAssets($assets, $assets->count(), $request); } public function assignedAssets(Request $request, Location $location) : JsonResponse | array @@ -290,7 +298,7 @@ public function assignedAssets(Request $request, Location $location) : JsonRespo $this->authorize('view', $location); $assets = Asset::where('assigned_to', '=', $location->id)->where('assigned_type', '=', Location::class)->with('model', 'model.category', 'assetstatus', 'location', 'company', 'defaultLoc'); $assets = $assets->get(); - return (new AssetsTransformer)->transformAssets($assets, $assets->count(), $request); + return (new AssetsTransformer())->transformAssets($assets, $assets->count(), $request); } public function assignedAccessories(Request $request, Location $location) : JsonResponse | array @@ -304,7 +312,7 @@ public function assignedAccessories(Request $request, Location $location) : Json $total = $accessory_checkouts->count(); $accessory_checkouts = $accessory_checkouts->skip($offset)->take($limit)->get(); - return (new LocationsTransformer)->transformCheckedoutAccessories($accessory_checkouts, $total); + return (new LocationsTransformer())->transformCheckedoutAccessories($accessory_checkouts, $total); } /** @@ -390,7 +398,7 @@ public function selectlist(Request $request) : array } if ($request->filled('search')) { - $locations = $locations->where('locations.name', 'LIKE', '%'.$request->input('search').'%'); + $locations = $locations->where('locations.name', 'LIKE', '%' . $request->input('search') . '%'); } $locations = $locations->orderBy('name', 'ASC')->get(); @@ -413,6 +421,6 @@ public function selectlist(Request $request) : array $paginated_results = new LengthAwarePaginator($locations_formatted->forPage($page, 500), $locations_formatted->count(), 500, $page, []); - return (new SelectlistTransformer)->transformSelectlist($paginated_results); + return (new SelectlistTransformer())->transformSelectlist($paginated_results); } } diff --git a/app/Http/Controllers/Api/ManufacturersController.php b/app/Http/Controllers/Api/ManufacturersController.php index 652fad1cfc6b..782be3c80dc9 100644 --- a/app/Http/Controllers/Api/ManufacturersController.php +++ b/app/Http/Controllers/Api/ManufacturersController.php @@ -22,7 +22,7 @@ class ManufacturersController extends Controller * @since [v4.0] * @return \Illuminate\Http\Response */ - public function index(Request $request) : JsonResponse | array + public function index(Request $request): JsonResponse | array { $this->authorize('view', Manufacturer::class); $allowed_columns = [ @@ -116,7 +116,7 @@ public function index(Request $request) : JsonResponse | array $total = $manufacturers->count(); $manufacturers = $manufacturers->skip($offset)->take($limit)->get(); - return (new ManufacturersTransformer)->transformManufacturers($manufacturers, $total); + return (new ManufacturersTransformer())->transformManufacturers($manufacturers, $total); } /** @@ -126,10 +126,10 @@ public function index(Request $request) : JsonResponse | array * @since [v4.0] * @param \App\Http\Requests\ImageUploadRequest $request */ - public function store(ImageUploadRequest $request) : JsonResponse + public function store(ImageUploadRequest $request): JsonResponse { $this->authorize('create', Manufacturer::class); - $manufacturer = new Manufacturer; + $manufacturer = new Manufacturer(); $manufacturer->fill($request->all()); $manufacturer = $request->handleImages($manufacturer); @@ -137,7 +137,6 @@ public function store(ImageUploadRequest $request) : JsonResponse return response()->json(Helper::formatStandardApiResponse('success', $manufacturer, trans('admin/manufacturers/message.create.success'))); } return response()->json(Helper::formatStandardApiResponse('error', null, $manufacturer->getErrors())); - } /** @@ -147,12 +146,12 @@ public function store(ImageUploadRequest $request) : JsonResponse * @since [v4.0] * @param int $id */ - public function show($id) : JsonResponse | array + public function show($id): JsonResponse | array { $this->authorize('view', Manufacturer::class); $manufacturer = Manufacturer::withCount('assets as assets_count')->withCount('licenses as licenses_count')->withCount('consumables as consumables_count')->withCount('accessories as accessories_count')->findOrFail($id); - return (new ManufacturersTransformer)->transformManufacturer($manufacturer); + return (new ManufacturersTransformer())->transformManufacturer($manufacturer); } /** @@ -163,7 +162,7 @@ public function show($id) : JsonResponse | array * @param \App\Http\Requests\ImageUploadRequest $request * @param int $id */ - public function update(ImageUploadRequest $request, $id) : JsonResponse + public function update(ImageUploadRequest $request, $id): JsonResponse { $this->authorize('update', Manufacturer::class); $manufacturer = Manufacturer::findOrFail($id); @@ -184,7 +183,7 @@ public function update(ImageUploadRequest $request, $id) : JsonResponse * @since [v4.0] * @param int $id */ - public function destroy($id) : JsonResponse + public function destroy($id): JsonResponse { $this->authorize('delete', Manufacturer::class); $manufacturer = Manufacturer::findOrFail($id); @@ -192,11 +191,10 @@ public function destroy($id) : JsonResponse if ($manufacturer->isDeletable()) { $manufacturer->delete(); - return response()->json(Helper::formatStandardApiResponse('success', null, trans('admin/manufacturers/message.delete.success'))); + return response()->json(Helper::formatStandardApiResponse('success', null, trans('admin/manufacturers/message.delete.success'))); } - return response()->json(Helper::formatStandardApiResponse('error', null, trans('admin/manufacturers/message.assoc_users'))); - + return response()->json(Helper::formatStandardApiResponse('error', null, trans('admin/manufacturers/message.assoc_users'))); } /** @@ -207,18 +205,16 @@ public function destroy($id) : JsonResponse * @param int $id * @throws \Illuminate\Auth\Access\AuthorizationException */ - public function restore($id) : JsonResponse + public function restore($id): JsonResponse { $this->authorize('delete', Manufacturer::class); if ($manufacturer = Manufacturer::withTrashed()->find($id)) { - if ($manufacturer->deleted_at == '') { return response()->json(Helper::formatStandardApiResponse('error', trans('general.not_deleted', ['item_type' => trans('general.manufacturer')])), 200); } if ($manufacturer->restore()) { - $logaction = new Actionlog(); $logaction->item_type = Manufacturer::class; $logaction->item_id = $manufacturer->id; @@ -233,7 +229,7 @@ public function restore($id) : JsonResponse return response()->json(Helper::formatStandardApiResponse('error', trans('general.could_not_restore', ['item_type' => trans('general.manufacturer'), 'error' => $manufacturer->getErrors()->first()])), 200); } - return response()->json(Helper::formatStandardApiResponse('error', null, trans('admin/manufacturers/message.does_not_exist'))); + return response()->json(Helper::formatStandardApiResponse('error', null, trans('admin/manufacturers/message.does_not_exist'))); } /** @@ -243,7 +239,7 @@ public function restore($id) : JsonResponse * @since [v4.0.16] * @see \App\Http\Transformers\SelectlistTransformer */ - public function selectlist(Request $request) : array + public function selectlist(Request $request): array { $this->authorize('view.selectlists'); @@ -254,7 +250,7 @@ public function selectlist(Request $request) : array ]); if ($request->filled('search')) { - $manufacturers = $manufacturers->where('name', 'LIKE', '%'.$request->get('search').'%'); + $manufacturers = $manufacturers->where('name', 'LIKE', '%' . $request->get('search') . '%'); } $manufacturers = $manufacturers->orderBy('name', 'ASC')->paginate(50); @@ -264,9 +260,9 @@ public function selectlist(Request $request) : array // they may not have a ->name value but we want to display something anyway foreach ($manufacturers as $manufacturer) { $manufacturer->use_text = $manufacturer->name; - $manufacturer->use_image = ($manufacturer->image) ? Storage::disk('public')->url('manufacturers/'.$manufacturer->image, $manufacturer->image) : null; + $manufacturer->use_image = ($manufacturer->image) ? Storage::disk('public')->url('manufacturers/' . $manufacturer->image, $manufacturer->image) : null; } - return (new SelectlistTransformer)->transformSelectlist($manufacturers); + return (new SelectlistTransformer())->transformSelectlist($manufacturers); } } diff --git a/app/Http/Controllers/Api/PredefinedKitsController.php b/app/Http/Controllers/Api/PredefinedKitsController.php index 24f132018508..a9493c6cdf0d 100644 --- a/app/Http/Controllers/Api/PredefinedKitsController.php +++ b/app/Http/Controllers/Api/PredefinedKitsController.php @@ -121,7 +121,7 @@ public function destroy($id) : JsonResponse $this->authorize('delete', PredefinedKit::class); $kit = PredefinedKit::findOrFail($id); - // Delete childs + // Delete children $kit->models()->detach(); $kit->licenses()->detach(); $kit->consumables()->detach(); diff --git a/app/Http/Controllers/Api/SuppliersController.php b/app/Http/Controllers/Api/SuppliersController.php index f752f222411a..47efa7c75738 100644 --- a/app/Http/Controllers/Api/SuppliersController.php +++ b/app/Http/Controllers/Api/SuppliersController.php @@ -28,6 +28,7 @@ public function index(Request $request): array id', 'name', 'address', + 'address2', 'phone', 'contact', 'fax', @@ -39,15 +40,40 @@ public function index(Request $request): array 'components_count', 'consumables_count', 'url', + 'city', + 'state', + 'zip', + 'latitude', + 'longitude' ]; - - $suppliers = Supplier::select( - ['id', 'name', 'address', 'address2', 'city', 'state', 'country', 'fax', 'phone', 'email', 'contact', 'created_at', 'updated_at', 'deleted_at', 'image', 'notes', 'url']) - ->withCount('assets as assets_count') - ->withCount('licenses as licenses_count') - ->withCount('accessories as accessories_count') - ->withCount('components as components_count') - ->withCount('consumables as consumables_count'); + + $suppliers = Supplier::select([ + 'id', + 'name', + 'address', + 'address2', + 'city', + 'state', + 'country', + 'fax', + 'phone', + 'email', + 'contact', + 'created_at', + 'updated_at', + 'deleted_at', + 'image', + 'notes', + 'url', + 'zip', + 'latitude', + 'longitude' + ]) + ->withCount('assets as assets_count') + ->withCount('licenses as licenses_count') + ->withCount('accessories as accessories_count') + ->withCount('components as components_count') + ->withCount('consumables as consumables_count'); if ($request->filled('search')) { @@ -74,6 +100,8 @@ public function index(Request $request): array $suppliers->where('zip', '=', $request->input('zip')); } + // TBA: Should this API support basic lat/long filtering? + if ($request->filled('country')) { $suppliers->where('country', '=', $request->input('country')); } @@ -105,7 +133,7 @@ public function index(Request $request): array $total = $suppliers->count(); $suppliers = $suppliers->skip($offset)->take($limit)->get(); - return (new SuppliersTransformer)->transformSuppliers($suppliers, $total); + return (new SuppliersTransformer())->transformSuppliers($suppliers, $total); } @@ -116,10 +144,10 @@ public function index(Request $request): array * @since [v4.0] * @param \App\Http\Requests\ImageUploadRequest $request */ - public function store(ImageUploadRequest $request) : JsonResponse + public function store(ImageUploadRequest $request): JsonResponse { $this->authorize('create', Supplier::class); - $supplier = new Supplier; + $supplier = new Supplier(); $supplier->fill($request->all()); $supplier = $request->handleImages($supplier); @@ -127,7 +155,6 @@ public function store(ImageUploadRequest $request) : JsonResponse return response()->json(Helper::formatStandardApiResponse('success', $supplier, trans('admin/suppliers/message.create.success'))); } return response()->json(Helper::formatStandardApiResponse('error', null, $supplier->getErrors())); - } /** @@ -137,12 +164,12 @@ public function store(ImageUploadRequest $request) : JsonResponse * @since [v4.0] * @param int $id */ - public function show($id) : array + public function show($id): array { $this->authorize('view', Supplier::class); $supplier = Supplier::findOrFail($id); - return (new SuppliersTransformer)->transformSupplier($supplier); + return (new SuppliersTransformer())->transformSupplier($supplier); } @@ -154,7 +181,7 @@ public function show($id) : array * @param \App\Http\Requests\ImageUploadRequest $request * @param int $id */ - public function update(ImageUploadRequest $request, $id) : JsonResponse + public function update(ImageUploadRequest $request, $id): JsonResponse { $this->authorize('update', Supplier::class); $supplier = Supplier::findOrFail($id); @@ -175,7 +202,7 @@ public function update(ImageUploadRequest $request, $id) : JsonResponse * @since [v4.0] * @param int $id */ - public function destroy($id) : JsonResponse + public function destroy($id): JsonResponse { $this->authorize('delete', Supplier::class); $supplier = Supplier::with('asset_maintenances', 'assets', 'licenses')->withCount('asset_maintenances as asset_maintenances_count', 'assets as assets_count', 'licenses as licenses_count')->findOrFail($id); @@ -206,7 +233,7 @@ public function destroy($id) : JsonResponse * @since [v4.0.16] * @see \App\Http\Transformers\SelectlistTransformer */ - public function selectlist(Request $request) : array + public function selectlist(Request $request): array { $this->authorize('view.selectlists'); @@ -218,7 +245,7 @@ public function selectlist(Request $request) : array ]); if ($request->filled('search')) { - $suppliers = $suppliers->where('suppliers.name', 'LIKE', '%'.$request->get('search').'%'); + $suppliers = $suppliers->where('suppliers.name', 'LIKE', '%' . $request->get('search') . '%'); } $suppliers = $suppliers->orderBy('name', 'ASC')->paginate(50); @@ -228,9 +255,9 @@ public function selectlist(Request $request) : array // they may not have a ->name value but we want to display something anyway foreach ($suppliers as $supplier) { $supplier->use_text = $supplier->name; - $supplier->use_image = ($supplier->image) ? Storage::disk('public')->url('suppliers/'.$supplier->image, $supplier->image) : null; + $supplier->use_image = ($supplier->image) ? Storage::disk('public')->url('suppliers/' . $supplier->image, $supplier->image) : null; } - return (new SelectlistTransformer)->transformSelectlist($suppliers); + return (new SelectlistTransformer())->transformSelectlist($suppliers); } } diff --git a/app/Http/Controllers/AssetModelsController.php b/app/Http/Controllers/AssetModelsController.php index 079558877677..a3617d1d6bee 100755 --- a/app/Http/Controllers/AssetModelsController.php +++ b/app/Http/Controllers/AssetModelsController.php @@ -333,7 +333,7 @@ public function postBulkEdit(Request $request) : View | RedirectResponse /** - * Returns a view that allows the user to bulk edit model attrbutes + * Returns a view that allows the user to bulk edit model attributes * * @author [A. Gianotto] [] * @since [v1.7] diff --git a/app/Http/Controllers/Assets/BulkAssetsController.php b/app/Http/Controllers/Assets/BulkAssetsController.php index e433475d3955..376ddc11472b 100644 --- a/app/Http/Controllers/Assets/BulkAssetsController.php +++ b/app/Http/Controllers/Assets/BulkAssetsController.php @@ -604,7 +604,7 @@ public function storeCheckout(AssetCheckoutRequest $request) : RedirectResponse } $errors = []; - DB::transaction(function () use ($target, $admin, $checkout_at, $expected_checkin, &$errors, $assets, $request) { //NOTE: $errors is passsed by reference! + DB::transaction(function () use ($target, $admin, $checkout_at, $expected_checkin, &$errors, $assets, $request) { //NOTE: $errors is passed by reference! foreach ($assets as $asset) { $this->authorize('checkout', $asset); diff --git a/app/Http/Controllers/Auth/ResetPasswordController.php b/app/Http/Controllers/Auth/ResetPasswordController.php index 805b829180d9..d35b5584f168 100644 --- a/app/Http/Controllers/Auth/ResetPasswordController.php +++ b/app/Http/Controllers/Auth/ResetPasswordController.php @@ -99,7 +99,7 @@ public function reset(Request $request) if (strpos(Setting::passwordComplexityRulesSaving('store'), 'disallow_same_pwd_as_user_fields') !== false) { $request->validate( [ - 'password' => 'required|notIn:["'.$user->email.'","'.$user->username.'","'.$user->first_name.'","'.$user->last_name.'"', + 'password' => 'required|notIn:["'.$user->email.'","'.$user->username.'","'.$user->first_name.'","'.$user->last_name.'"', // codespell:ignore ], $messages); } diff --git a/app/Http/Controllers/BulkAssetModelsController.php b/app/Http/Controllers/BulkAssetModelsController.php index 5f64ea083868..875920ec9a6a 100644 --- a/app/Http/Controllers/BulkAssetModelsController.php +++ b/app/Http/Controllers/BulkAssetModelsController.php @@ -11,7 +11,7 @@ class BulkAssetModelsController extends Controller { /** - * Returns a view that allows the user to bulk edit model attrbutes + * Returns a view that allows the user to bulk edit model attributes * * @author [A. Gianotto] [] * @since [v1.7] @@ -55,7 +55,7 @@ public function edit(Request $request) : View | RedirectResponse } /** - * Returns a view that allows the user to bulk edit model attrbutes + * Returns a view that allows the user to bulk edit model attributes * * @author [A. Gianotto] [] * @since [v1.7] diff --git a/app/Http/Controllers/Components/ComponentsController.php b/app/Http/Controllers/Components/ComponentsController.php index 74594d312bc9..ef03e91475b0 100644 --- a/app/Http/Controllers/Components/ComponentsController.php +++ b/app/Http/Controllers/Components/ComponentsController.php @@ -53,7 +53,7 @@ public function create() $this->authorize('create', Component::class); return view('components/edit')->with('category_type', 'component') - ->with('item', new Component); + ->with('item', new Component()); } /** @@ -190,7 +190,7 @@ public function destroy($componentId) // Remove the image if one exists if ($component->image && Storage::disk('public')->exists('components/' . $component->image)) { try { - Storage::disk('public')->delete('components/'.$component->image); + Storage::disk('public')->delete('components/' . $component->image); } catch (\Exception $e) { Log::debug($e); } diff --git a/app/Http/Controllers/Controller.php b/app/Http/Controllers/Controller.php index 74fff19a3733..edd1313aa8d0 100644 --- a/app/Http/Controllers/Controller.php +++ b/app/Http/Controllers/Controller.php @@ -1,4 +1,5 @@ route('kits.index')->with('error', trans('admin/kits/general.kit_not_found')); } - // Delete childs + // Delete children $kit->models()->detach(); $kit->licenses()->detach(); $kit->consumables()->detach(); @@ -217,7 +217,7 @@ public function detachModel($kit_id, $model_id) return redirect()->route('kits.index')->with('error', trans('admin/kits/general.kit_none')); } - // Delete childs + // Delete children $kit->models()->detach($model_id); // Redirect to the kit management page @@ -250,7 +250,7 @@ public function editLicense($kit_id, $license_id) } /** - * Update attached licese + * Update attached license * * @author [D. Minaev] [] * @param int $kit_id @@ -296,7 +296,7 @@ public function detachLicense($kit_id, $license_id) return redirect()->route('kits.index')->with('error', trans('admin/kits/general.kit_none')); } - // Delete childs + // Delete children $kit->licenses()->detach($license_id); // Redirect to the kit management page @@ -374,7 +374,7 @@ public function detachAccessory($kit_id, $accessory_id) return redirect()->route('kits.index')->with('error', trans('admin/kits/general.kit_none')); } - // Delete childs + // Delete children $kit->accessories()->detach($accessory_id); // Redirect to the kit management page @@ -452,7 +452,7 @@ public function detachConsumable($kit_id, $consumable_id) return redirect()->route('kits.index')->with('error', trans('admin/kits/general.kit_none')); } - // Delete childs + // Delete children $kit->consumables()->detach($consumable_id); // Redirect to the kit management page diff --git a/app/Http/Controllers/LocationsController.php b/app/Http/Controllers/LocationsController.php index da4e6a7e4447..c444cf1d4036 100755 --- a/app/Http/Controllers/LocationsController.php +++ b/app/Http/Controllers/LocationsController.php @@ -14,7 +14,8 @@ use Illuminate\Http\Request; use Illuminate\Support\Facades\Log; use Illuminate\Http\RedirectResponse; -use \Illuminate\Contracts\View\View; +use Illuminate\Contracts\View\View; + /** * This controller handles all actions related to Locations for * the Snipe-IT Asset Management application. @@ -51,7 +52,7 @@ public function create() : View $this->authorize('create', Location::class); return view('locations/edit') - ->with('item', new Location); + ->with('item', new Location()); } /** @@ -66,7 +67,7 @@ public function create() : View public function store(ImageUploadRequest $request) : RedirectResponse { $this->authorize('create', Location::class); - + $location = new Location(); $location->name = $request->input('name'); $location->parent_id = $request->input('parent_id', null); @@ -77,6 +78,8 @@ public function store(ImageUploadRequest $request) : RedirectResponse $location->state = $request->input('state'); $location->country = $request->input('country'); $location->zip = $request->input('zip'); + $location->latitude = $request->input('latitude'); + $location->longitude = $request->input('longitude'); $location->ldap_ou = $request->input('ldap_ou'); $location->manager_id = $request->input('manager_id'); $location->created_by = auth()->id(); @@ -91,7 +94,7 @@ public function store(ImageUploadRequest $request) : RedirectResponse // check if parent is set and has a different company if ($location->parent_id && Location::find($location->parent_id)->company_id != $location->company_id) { return redirect()->back()->withInput()->withInput()->with('error', 'different company than parent'); - } + } } else { $location->company_id = $request->input('company_id'); } @@ -141,6 +144,8 @@ public function update(ImageUploadRequest $request, Location $location) : Redire $location->state = $request->input('state'); $location->country = $request->input('country'); $location->zip = $request->input('zip'); + $location->latitude = $request->input('latitude'); + $location->longitude = $request->input('longitude'); $location->phone = request('phone'); $location->fax = request('fax'); $location->ldap_ou = $request->input('ldap_ou'); @@ -153,7 +158,7 @@ public function update(ImageUploadRequest $request, Location $location) : Redire // check if there are related objects with different company if (Helper::test_locations_fmcs(false, $location->id, $location->company_id)) { return redirect()->back()->withInput()->withInput()->with('error', 'error scoped locations'); - } + } } else { $location->company_id = $request->input('company_id'); } @@ -194,7 +199,7 @@ public function destroy($locationId) : RedirectResponse if ($location->image) { try { - Storage::disk('public')->delete('locations/'.$location->image); + Storage::disk('public')->delete('locations/' . $location->image); } catch (\Exception $e) { Log::error($e); } @@ -243,7 +248,7 @@ public function print_assigned($id) : View | RedirectResponse $assets = Asset::where('assigned_to', $id)->where('assigned_type', Location::class)->with('model', 'model.category')->get(); return view('locations/print') ->with('assets', $assets) - ->with('users',$users) + ->with('users', $users) ->with('location', $location) ->with('parent', $parent) ->with('manager', $manager) @@ -294,7 +299,6 @@ public function postRestore($id) : RedirectResponse $this->authorize('create', Location::class); if ($location = Location::withTrashed()->find($id)) { - if ($location->deleted_at == '') { return redirect()->back()->with('error', trans('general.not_deleted', ['item_type' => trans('general.location')])); } @@ -315,8 +319,8 @@ public function postRestore($id) : RedirectResponse } return redirect()->back()->with('error', trans('admin/models/message.does_not_exist')); - } + public function print_all_assigned($id) : View | RedirectResponse { $this->authorize('view', Location::class); @@ -328,7 +332,7 @@ public function print_all_assigned($id) : View | RedirectResponse $assets = Asset::where('location_id', $id)->with('model', 'model.category')->get(); return view('locations/print') ->with('assets', $assets) - ->with('users',$users) + ->with('users', $users) ->with('location', $location) ->with('parent', $parent) ->with('manager', $manager) @@ -359,13 +363,13 @@ public function postBulkDelete(Request $request) : View | RedirectResponse ->withCount('children as children_count') ->withCount('users as users_count')->get(); - $valid_count = 0; - foreach ($locations as $location) { - if ($location->isDeletable()) { - $valid_count++; - } + $valid_count = 0; + foreach ($locations as $location) { + if ($location->isDeletable()) { + $valid_count++; } - return view('locations/bulk-delete', compact('locations'))->with('valid_count', $valid_count); + } + return view('locations/bulk-delete', compact('locations'))->with('valid_count', $valid_count); } return redirect()->route('models.index') @@ -397,7 +401,6 @@ public function postBulkDeleteStore(Request $request) : RedirectResponse $error_count = 0; foreach ($locations as $location) { - // Can we delete this location? if ($location->isDeletable()) { $location->delete(); @@ -407,8 +410,8 @@ public function postBulkDeleteStore(Request $request) : RedirectResponse } } - Log::debug('Success count: '.$success_count); - Log::debug('Error count: '.$error_count); + Log::debug('Success count: ' . $success_count); + Log::debug('Error count: ' . $error_count); // Complete success if ($success_count == count($locations_raw_array)) { return redirect() @@ -422,19 +425,19 @@ public function postBulkDeleteStore(Request $request) : RedirectResponse if ($error_count > 0) { return redirect() ->route('locations.index') - ->with('warning', trans('general.bulk.delete.partial', - ['success' => $success_count, 'error' => $error_count, 'object_type' => trans('general.locations')] - )); - } + ->with( + 'warning', + trans( + 'general.bulk.delete.partial', + ['success' => $success_count, 'error' => $error_count, 'object_type' => trans('general.locations')] + ) + ); } - + } // Nothing was selected - return to the index return redirect() ->route('locations.index') - ->with('error', trans('general.bulk.nothing_selected', - ['object_type' => trans('general.locations')] - )); - + ->with('error', trans('general.bulk.nothing_selected', ['object_type' => trans('general.locations')])); } } diff --git a/app/Http/Controllers/SuppliersController.php b/app/Http/Controllers/SuppliersController.php index d96031a9aa49..25bfb08bfa86 100755 --- a/app/Http/Controllers/SuppliersController.php +++ b/app/Http/Controllers/SuppliersController.php @@ -6,7 +6,7 @@ use App\Models\Supplier; use Illuminate\Support\Facades\Auth; use Illuminate\Http\RedirectResponse; -use \Illuminate\Contracts\View\View; +use Illuminate\Contracts\View\View; /** * This controller handles all actions related to Suppliers for @@ -35,7 +35,7 @@ public function index() : View public function create() : View { $this->authorize('create', Supplier::class); - return view('suppliers/edit')->with('item', new Supplier); + return view('suppliers/edit')->with('item', new Supplier()); } /** @@ -47,7 +47,7 @@ public function store(ImageUploadRequest $request) : RedirectResponse { $this->authorize('create', Supplier::class); // Create a new supplier - $supplier = new Supplier; + $supplier = new Supplier(); // Save the location data $supplier->name = request('name'); $supplier->address = request('address'); @@ -56,6 +56,8 @@ public function store(ImageUploadRequest $request) : RedirectResponse $supplier->state = request('state'); $supplier->country = request('country'); $supplier->zip = request('zip'); + $supplier->latitude = request('latitude'); + $supplier->longitude = request('longitude'); $supplier->contact = request('contact'); $supplier->phone = request('phone'); $supplier->fax = request('fax'); @@ -80,7 +82,7 @@ public function store(ImageUploadRequest $request) : RedirectResponse public function edit(Supplier $supplier) : View | RedirectResponse { $this->authorize('update', Supplier::class); - return view('suppliers/edit')->with('item', $supplier); + return view('suppliers/edit')->with('item', $supplier); } /** @@ -99,6 +101,8 @@ public function update(ImageUploadRequest $request, Supplier $supplier) : Redire $supplier->state = request('state'); $supplier->country = request('country'); $supplier->zip = request('zip'); + $supplier->latitude = request('latitude'); + $supplier->longitude = request('longitude'); $supplier->contact = request('contact'); $supplier->phone = request('phone'); $supplier->fax = request('fax'); @@ -140,7 +144,8 @@ public function destroy($supplierId) : RedirectResponse $supplier->delete(); - return redirect()->route('suppliers.index')->with('success', + return redirect()->route('suppliers.index')->with( + 'success', trans('admin/suppliers/message.delete.success') ); } @@ -155,6 +160,5 @@ public function show(Supplier $supplier) : View | RedirectResponse { $this->authorize('view', Supplier::class); return view('suppliers/view', compact('supplier')); - } } diff --git a/app/Http/Controllers/ViewAssetsController.php b/app/Http/Controllers/ViewAssetsController.php index bbff6ba4f77e..2ab303b232d1 100755 --- a/app/Http/Controllers/ViewAssetsController.php +++ b/app/Http/Controllers/ViewAssetsController.php @@ -60,7 +60,7 @@ public function getIndex() : View | RedirectResponse } - // Since some models may re-use the same fieldsets/fields, let's make the array unique so we don't repeat columns + // Since some models may reuse the same fieldsets/fields, let's make the array unique so we don't repeat columns array_unique($field_array); if (isset($user->id)) { diff --git a/app/Http/Requests/DeleteUserRequest.php b/app/Http/Requests/DeleteUserRequest.php index 6d387917c633..7ab60ee34af5 100644 --- a/app/Http/Requests/DeleteUserRequest.php +++ b/app/Http/Requests/DeleteUserRequest.php @@ -48,7 +48,7 @@ public function prepareForValidation(): void public function rules(): array { return [ - 'user' => Rule::notIn([auth()->id()]), + 'user' => Rule::notIn([auth()->id()]), // codespell:ignore 'managed_users' => Rule::in([0]), 'managed_locations' => Rule::in([0]), 'assigned_assets' => Rule::in([0]), diff --git a/app/Http/Requests/SettingsSamlRequest.php b/app/Http/Requests/SettingsSamlRequest.php index 2ab876141a73..6175d59c8372 100644 --- a/app/Http/Requests/SettingsSamlRequest.php +++ b/app/Http/Requests/SettingsSamlRequest.php @@ -96,7 +96,7 @@ public function withValidator($validator) $x509 = openssl_x509_read($custom_x509cert); $pkey = openssl_pkey_get_private($custom_privateKey); } elseif ($this->input('saml_sp_regenerate_keypair') == '1' || ! $this->has('saml_sp_x509cert') || $was_custom_x509cert) { - // key regeneration requested, no certificate defined yet or previous custom certicate was removed + // key regeneration requested, no certificate defined yet or previous custom certificate was removed error_log('regen'); $cert_updated = true; $dn = [ diff --git a/app/Http/Transformers/AccessoriesTransformer.php b/app/Http/Transformers/AccessoriesTransformer.php index bc3fe1172d8c..67b1c175363f 100644 --- a/app/Http/Transformers/AccessoriesTransformer.php +++ b/app/Http/Transformers/AccessoriesTransformer.php @@ -17,7 +17,7 @@ public function transformAccessories(Collection $accessories, $total) $array[] = self::transformAccessory($accessory); } - return (new DatatablesTransformer)->transformDatatables($array, $total); + return (new DatatablesTransformer())->transformDatatables($array, $total); } public function transformAccessory(Accessory $accessory) @@ -25,13 +25,13 @@ public function transformAccessory(Accessory $accessory) $array = [ 'id' => $accessory->id, 'name' => e($accessory->name), - 'image' => ($accessory->image) ? Storage::disk('public')->url('accessories/'.e($accessory->image)) : null, - 'company' => ($accessory->company) ? ['id' => $accessory->company->id, 'name'=> e($accessory->company->name)] : null, - 'manufacturer' => ($accessory->manufacturer) ? ['id' => $accessory->manufacturer->id, 'name'=> e($accessory->manufacturer->name)] : null, - 'supplier' => ($accessory->supplier) ? ['id' => $accessory->supplier->id, 'name'=> e($accessory->supplier->name)] : null, + 'image' => ($accessory->image) ? Storage::disk('public')->url('accessories/' . e($accessory->image)) : null, + 'company' => ($accessory->company) ? ['id' => $accessory->company->id, 'name' => e($accessory->company->name)] : null, + 'manufacturer' => ($accessory->manufacturer) ? ['id' => $accessory->manufacturer->id, 'name' => e($accessory->manufacturer->name)] : null, + 'supplier' => ($accessory->supplier) ? ['id' => $accessory->supplier->id, 'name' => e($accessory->supplier->name)] : null, 'model_number' => ($accessory->model_number) ? e($accessory->model_number) : null, - 'category' => ($accessory->category) ? ['id' => $accessory->category->id, 'name'=> e($accessory->category->name)] : null, - 'location' => ($accessory->location) ? ['id' => $accessory->location->id, 'name'=> e($accessory->location->name)] : null, + 'category' => ($accessory->category) ? ['id' => $accessory->category->id, 'name' => e($accessory->category->name)] : null, + 'location' => ($accessory->location) ? ['id' => $accessory->location->id, 'name' => e($accessory->location->name)] : null, 'notes' => ($accessory->notes) ? Helper::parseEscapedMarkedownInline($accessory->notes) : null, 'qty' => ($accessory->qty) ? (int) $accessory->qty : null, 'purchase_date' => ($accessory->purchase_date) ? Helper::getFormattedDateObject($accessory->purchase_date, 'date') : null, @@ -44,7 +44,7 @@ public function transformAccessory(Accessory $accessory) 'checkouts_count' => $accessory->checkouts_count, 'created_by' => ($accessory->adminuser) ? [ 'id' => (int) $accessory->adminuser->id, - 'name'=> e($accessory->adminuser->present()->fullName()), + 'name' => e($accessory->adminuser->present()->fullName()), ] : null, 'created_at' => Helper::getFormattedDateObject($accessory->created_at, 'datetime'), 'updated_at' => Helper::getFormattedDateObject($accessory->updated_at, 'datetime'), @@ -57,7 +57,7 @@ public function transformAccessory(Accessory $accessory) 'update' => Gate::allows('update', Accessory::class), 'delete' => Gate::allows('delete', Accessory::class), 'clone' => Gate::allows('create', Accessory::class), - + ]; $permissions_array['user_can_checkout'] = false; @@ -82,20 +82,20 @@ public function transformCheckedoutAccessory($accessory_checkouts, $total) 'note' => $checkout->note ? e($checkout->note) : null, 'created_by' => $checkout->adminuser ? [ 'id' => (int) $checkout->adminuser->id, - 'name'=> e($checkout->adminuser->present()->fullName), - ]: null, + 'name' => e($checkout->adminuser->present()->fullName), + ] : null, 'created_at' => Helper::getFormattedDateObject($checkout->created_at, 'datetime'), 'available_actions' => Gate::allows('checkout', Accessory::class) ? ['checkin' => true] : ['checkin' => false], ]; } - return (new DatatablesTransformer)->transformDatatables($array, $total); + return (new DatatablesTransformer())->transformDatatables($array, $total); } public function transformAssignedTo($accessoryCheckout) { if ($accessoryCheckout->checkedOutToUser()) { - return (new UsersTransformer)->transformUserCompact($accessoryCheckout->assigned); + return (new UsersTransformer())->transformUserCompact($accessoryCheckout->assigned); } elseif ($accessoryCheckout->checkedOutToLocation()) { return (new LocationsTransformer())->transformLocationCompact($accessoryCheckout->assigned); } elseif ($accessoryCheckout->checkedOutToAsset()) { diff --git a/app/Http/Transformers/ActionlogsTransformer.php b/app/Http/Transformers/ActionlogsTransformer.php index 702ea123d8f2..b32616181aad 100644 --- a/app/Http/Transformers/ActionlogsTransformer.php +++ b/app/Http/Transformers/ActionlogsTransformer.php @@ -1,4 +1,5 @@ transformDatatables($array, $total); + return (new DatatablesTransformer())->transformDatatables($array, $total); } private function clean_field($value) @@ -40,13 +40,13 @@ private function clean_field($value) // {"_snipeit_right_sized_fault_tolerant_localareanetwo_1": // {"old":null,"new":{"value":"1579490695972","_snipeit_new_field_2":2,"_snipeit_new_field_3":"Monday, 20 January 2020 2:24:55 PM"}} // so we have to walk down that next level - if(is_object($value) && isset($value->value)) { + if (is_object($value) && isset($value->value)) { return $this->clean_field($value->value); } return is_scalar($value) || is_null($value) ? e($value) : e(json_encode($value)); } - public function transformActionlog (Actionlog $actionlog, $settings = null) + public function transformActionlog(Actionlog $actionlog, $settings = null) { $icon = $actionlog->present()->icon(); @@ -56,32 +56,26 @@ public function transformActionlog (Actionlog $actionlog, $settings = null) $custom_fields = CustomField::all(); } - if ($actionlog->filename!='') { + if ($actionlog->filename != '') { $icon = Helper::filetype_icon($actionlog->filename); } // This is necessary since we can't escape special characters within a JSON object - if (($actionlog->log_meta) && ($actionlog->log_meta!='')) { + if (($actionlog->log_meta) && ($actionlog->log_meta != '')) { $meta_array = json_decode($actionlog->log_meta); $clean_meta = []; if ($meta_array) { - foreach ($meta_array as $fieldname => $fieldata) { - $clean_meta[$fieldname]['old'] = $this->clean_field($fieldata->old); $clean_meta[$fieldname]['new'] = $this->clean_field($fieldata->new); // this is a custom field if (str_starts_with($fieldname, '_snipeit_')) { - foreach ($custom_fields as $custom_field) { - if ($custom_field->db_column == $fieldname) { - - if ($custom_field->field_encrypted == '1') { - + if ($custom_field->field_encrypted == '1') { // Unset these fields. We need to decrypt them, since even if the decrypted value // didn't change, their value in the DB will, so we have to compare the unencrypted version // to see if the values actually did change @@ -91,7 +85,7 @@ public function transformActionlog (Actionlog $actionlog, $settings = null) $enc_old = ''; $enc_new = ''; - if ($this->clean_field($fieldata->old!='')) { + if ($this->clean_field($fieldata->old != '')) { try { $enc_old = Crypt::decryptString($this->clean_field($fieldata->old)); } catch (\Exception $e) { @@ -99,7 +93,7 @@ public function transformActionlog (Actionlog $actionlog, $settings = null) } } - if ($this->clean_field($fieldata->new!='')) { + if ($this->clean_field($fieldata->new != '')) { try { $enc_new = Crypt::decryptString($this->clean_field($fieldata->new)); } catch (\Exception $e) { @@ -113,28 +107,21 @@ public function transformActionlog (Actionlog $actionlog, $settings = null) // Display the changes if the user is an admin or superadmin if (Gate::allows('admin')) { - $clean_meta[$fieldname]['old'] = ($enc_old) ? unserialize($enc_old): ''; - $clean_meta[$fieldname]['new'] = ($enc_new) ? unserialize($enc_new): ''; + $clean_meta[$fieldname]['old'] = ($enc_old) ? unserialize($enc_old) : ''; + $clean_meta[$fieldname]['new'] = ($enc_new) ? unserialize($enc_new) : ''; } - } - - } - } - } } - } - } - $clean_meta= $this->changedInfo($clean_meta); + $clean_meta = $this->changedInfo($clean_meta); } $file_url = ''; - if($actionlog->filename!='') { + if ($actionlog->filename != '') { if ($actionlog->action_type == 'accepted') { $file_url = route('log.storedeula.download', ['filename' => $actionlog->filename]); } else { @@ -155,7 +142,7 @@ public function transformActionlog (Actionlog $actionlog, $settings = null) $array = [ 'id' => (int) $actionlog->id, 'icon' => $icon, - 'file' => ($actionlog->filename!='') + 'file' => ($actionlog->filename != '') ? [ 'url' => $file_url, @@ -164,9 +151,9 @@ public function transformActionlog (Actionlog $actionlog, $settings = null) 'item' => ($actionlog->item) ? [ 'id' => (int) $actionlog->item->id, - 'name' => ($actionlog->itemType()=='user') ? e($actionlog->item->getFullNameAttribute()) : e($actionlog->item->getDisplayNameAttribute()), + 'name' => ($actionlog->itemType() == 'user') ? e($actionlog->item->getFullNameAttribute()) : e($actionlog->item->getDisplayNameAttribute()), 'type' => e($actionlog->itemType()), - 'serial' =>e($actionlog->item->serial) ? e($actionlog->item->serial) : null + 'serial' => e($actionlog->item->serial) ? e($actionlog->item->serial) : null ] : null, 'location' => ($actionlog->location) ? [ 'id' => (int) $actionlog->location->id, @@ -174,34 +161,34 @@ public function transformActionlog (Actionlog $actionlog, $settings = null) ] : null, 'created_at' => Helper::getFormattedDateObject($actionlog->created_at, 'datetime'), 'updated_at' => Helper::getFormattedDateObject($actionlog->updated_at, 'datetime'), - 'next_audit_date' => ($actionlog->itemType()=='asset') ? Helper::getFormattedDateObject($actionlog->calcNextAuditDate(null, $actionlog->item), 'date'): null, + 'next_audit_date' => ($actionlog->itemType() == 'asset') ? Helper::getFormattedDateObject($actionlog->calcNextAuditDate(null, $actionlog->item), 'date') : null, 'days_to_next_audit' => $actionlog->daysUntilNextAudit($settings->audit_interval, $actionlog->item), 'action_type' => $actionlog->present()->actionType(), 'admin' => ($actionlog->adminuser) ? [ 'id' => (int) $actionlog->adminuser->id, 'name' => e($actionlog->adminuser->getFullNameAttribute()), - 'first_name'=> e($actionlog->adminuser->first_name), - 'last_name'=> e($actionlog->adminuser->last_name) + 'first_name' => e($actionlog->adminuser->first_name), + 'last_name' => e($actionlog->adminuser->last_name) ] : null, 'created_by' => ($actionlog->adminuser) ? [ 'id' => (int) $actionlog->adminuser->id, 'name' => e($actionlog->adminuser->getFullNameAttribute()), - 'first_name'=> e($actionlog->adminuser->first_name), - 'last_name'=> e($actionlog->adminuser->last_name) + 'first_name' => e($actionlog->adminuser->first_name), + 'last_name' => e($actionlog->adminuser->last_name) ] : null, 'target' => ($actionlog->target) ? [ 'id' => (int) $actionlog->target->id, - 'name' => ($actionlog->targetType()=='user') ? e($actionlog->target->getFullNameAttribute()) : e($actionlog->target->getDisplayNameAttribute()), + 'name' => ($actionlog->targetType() == 'user') ? e($actionlog->target->getFullNameAttribute()) : e($actionlog->target->getDisplayNameAttribute()), 'type' => e($actionlog->targetType()), ] : null, - 'note' => ($actionlog->note) ? Helper::parseEscapedMarkedownInline($actionlog->note): null, + 'note' => ($actionlog->note) ? Helper::parseEscapedMarkedownInline($actionlog->note) : null, 'signature_file' => ($actionlog->accept_signature) ? route('log.signature.view', ['filename' => $actionlog->accept_signature ]) : null, - 'log_meta' => ((isset($clean_meta)) && (is_array($clean_meta))) ? $clean_meta: null, + 'log_meta' => ((isset($clean_meta)) && (is_array($clean_meta))) ? $clean_meta : null, 'remote_ip' => ($actionlog->remote_ip) ?? null, 'user_agent' => ($actionlog->user_agent) ?? null, 'action_source' => ($actionlog->action_source) ?? null, - 'action_date' => ($actionlog->action_date) ? Helper::getFormattedDateObject($actionlog->action_date, 'datetime'): Helper::getFormattedDateObject($actionlog->created_at, 'datetime'), + 'action_date' => ($actionlog->action_date) ? Helper::getFormattedDateObject($actionlog->action_date, 'datetime') : Helper::getFormattedDateObject($actionlog->created_at, 'datetime'), ]; // Log::info("Clean Meta is: ".print_r($clean_meta,true)); @@ -210,24 +197,22 @@ public function transformActionlog (Actionlog $actionlog, $settings = null) return $array; } - - - public function transformCheckedoutActionlog (Collection $accessories_checkout, $total) + public function transformCheckedoutActionlog(Collection $accessories_checkout, $total) { $array = array(); foreach ($accessories_checkout as $user) { - $array[] = (new UsersTransformer)->transformUser($user); + $array[] = (new UsersTransformer())->transformUser($user); } - return (new DatatablesTransformer)->transformDatatables($array, $total); + return (new DatatablesTransformer())->transformDatatables($array, $total); } + /** * This takes the ids of the changed attributes and returns the names instead for the history view of an Asset * * @param array $clean_meta * @return array */ - public function changedInfo(array $clean_meta) { static $location = false; @@ -253,23 +238,21 @@ public function changedInfo(array $clean_meta) $company = Company::select('id', 'name')->get(); } - if(array_key_exists('rtd_location_id',$clean_meta)) { - + if (array_key_exists('rtd_location_id', $clean_meta)) { $oldRtd = $location->find($clean_meta['rtd_location_id']['old']); $oldRtdName = $oldRtd ? e($oldRtd->name) : trans('general.deleted'); $newRtd = $location->find($clean_meta['rtd_location_id']['new']); $newRtdName = $newRtd ? e($newRtd->name) : trans('general.deleted'); - $clean_meta['rtd_location_id']['old'] = $clean_meta['rtd_location_id']['old'] ? "[id: ".$clean_meta['rtd_location_id']['old']."] ". $oldRtdName : ''; - $clean_meta['rtd_location_id']['new'] = $clean_meta['rtd_location_id']['new'] ? "[id: ".$clean_meta['rtd_location_id']['new']."] ". $newRtdName : ''; + $clean_meta['rtd_location_id']['old'] = $clean_meta['rtd_location_id']['old'] ? "[id: " . $clean_meta['rtd_location_id']['old'] . "] " . $oldRtdName : ''; + $clean_meta['rtd_location_id']['new'] = $clean_meta['rtd_location_id']['new'] ? "[id: " . $clean_meta['rtd_location_id']['new'] . "] " . $newRtdName : ''; $clean_meta[trans('admin/hardware/form.default_location')] = $clean_meta['rtd_location_id']; unset($clean_meta['rtd_location_id']); } if (array_key_exists('location_id', $clean_meta)) { - $oldLocation = $location->find($clean_meta['location_id']['old']); $oldLocationName = $oldLocation ? e($oldLocation->name) : trans('general.deleted'); @@ -277,74 +260,69 @@ public function changedInfo(array $clean_meta) $newLocationName = $newLocation ? e($newLocation->name) : trans('general.deleted'); - $clean_meta['location_id']['old'] = $clean_meta['location_id']['old'] ? "[id: ".$clean_meta['location_id']['old']."] ". $oldLocationName : ''; - $clean_meta['location_id']['new'] = $clean_meta['location_id']['new'] ? "[id: ".$clean_meta['location_id']['new']."] ". $newLocationName : ''; + $clean_meta['location_id']['old'] = $clean_meta['location_id']['old'] ? "[id: " . $clean_meta['location_id']['old'] . "] " . $oldLocationName : ''; + $clean_meta['location_id']['new'] = $clean_meta['location_id']['new'] ? "[id: " . $clean_meta['location_id']['new'] . "] " . $newLocationName : ''; $clean_meta[trans('admin/locations/message.current_location')] = $clean_meta['location_id']; unset($clean_meta['location_id']); } - if(array_key_exists('model_id', $clean_meta)) { - + if (array_key_exists('model_id', $clean_meta)) { $oldModel = $model->find($clean_meta['model_id']['old']); $oldModelName = $oldModel ? e($oldModel->name) : trans('admin/models/message.deleted'); $newModel = $model->find($clean_meta['model_id']['new']); $newModelName = $newModel ? e($newModel->name) : trans('admin/models/message.deleted'); - $clean_meta['model_id']['old'] = "[id: ".$clean_meta['model_id']['old']."] ".$oldModelName; - $clean_meta['model_id']['new'] = "[id: ".$clean_meta['model_id']['new']."] ".$newModelName; /** model is required at asset creation */ + $clean_meta['model_id']['old'] = "[id: " . $clean_meta['model_id']['old'] . "] " . $oldModelName; + $clean_meta['model_id']['new'] = "[id: " . $clean_meta['model_id']['new'] . "] " . $newModelName; /** model is required at asset creation */ $clean_meta[trans('admin/hardware/form.model')] = $clean_meta['model_id']; unset($clean_meta['model_id']); } - if(array_key_exists('company_id', $clean_meta)) { + if (array_key_exists('company_id', $clean_meta)) { $oldCompany = $company->find($clean_meta['company_id']['old']); $oldCompanyName = $oldCompany ? e($oldCompany->name) : trans('admin/company/message.deleted'); $newCompany = $company->find($clean_meta['company_id']['new']); $newCompanyName = $newCompany ? e($newCompany->name) : trans('admin/company/message.deleted'); - $clean_meta['company_id']['old'] = $clean_meta['company_id']['old'] ? "[id: ".$clean_meta['company_id']['old']."] ". $oldCompanyName : trans('general.unassigned'); - $clean_meta['company_id']['new'] = $clean_meta['company_id']['new'] ? "[id: ".$clean_meta['company_id']['new']."] ". $newCompanyName : trans('general.unassigned'); + $clean_meta['company_id']['old'] = $clean_meta['company_id']['old'] ? "[id: " . $clean_meta['company_id']['old'] . "] " . $oldCompanyName : trans('general.unassigned'); + $clean_meta['company_id']['new'] = $clean_meta['company_id']['new'] ? "[id: " . $clean_meta['company_id']['new'] . "] " . $newCompanyName : trans('general.unassigned'); $clean_meta[trans('general.company')] = $clean_meta['company_id']; unset($clean_meta['company_id']); } - if(array_key_exists('supplier_id', $clean_meta)) { + if (array_key_exists('supplier_id', $clean_meta)) { $oldSupplier = $supplier->find($clean_meta['supplier_id']['old']); $oldSupplierName = $oldSupplier ? e($oldSupplier->name) : trans('admin/suppliers/message.deleted'); $newSupplier = $supplier->find($clean_meta['supplier_id']['new']); $newSupplierName = $newSupplier ? e($newSupplier->name) : trans('admin/suppliers/message.deleted'); - $clean_meta['supplier_id']['old'] = $clean_meta['supplier_id']['old'] ? "[id: ".$clean_meta['supplier_id']['old']."] ". $oldSupplierName : trans('general.unassigned'); - $clean_meta['supplier_id']['new'] = $clean_meta['supplier_id']['new'] ? "[id: ".$clean_meta['supplier_id']['new']."] ". $newSupplierName : trans('general.unassigned'); + $clean_meta['supplier_id']['old'] = $clean_meta['supplier_id']['old'] ? "[id: " . $clean_meta['supplier_id']['old'] . "] " . $oldSupplierName : trans('general.unassigned'); + $clean_meta['supplier_id']['new'] = $clean_meta['supplier_id']['new'] ? "[id: " . $clean_meta['supplier_id']['new'] . "] " . $newSupplierName : trans('general.unassigned'); $clean_meta[trans('general.supplier')] = $clean_meta['supplier_id']; unset($clean_meta['supplier_id']); } - if(array_key_exists('status_id', $clean_meta)) { + if (array_key_exists('status_id', $clean_meta)) { $oldStatus = $status->find($clean_meta['status_id']['old']); $oldStatusName = $oldStatus ? e($oldStatus->name) : trans('admin/statuslabels/message.deleted_label'); $newStatus = $status->find($clean_meta['status_id']['new']); $newStatusName = $newStatus ? e($newStatus->name) : trans('admin/statuslabels/message.deleted_label'); - $clean_meta['status_id']['old'] = $clean_meta['status_id']['old'] ? "[id: ".$clean_meta['status_id']['old']."] ". $oldStatusName : trans('general.unassigned'); - $clean_meta['status_id']['new'] = $clean_meta['status_id']['new'] ? "[id: ".$clean_meta['status_id']['new']."] ". $newStatusName : trans('general.unassigned'); + $clean_meta['status_id']['old'] = $clean_meta['status_id']['old'] ? "[id: " . $clean_meta['status_id']['old'] . "] " . $oldStatusName : trans('general.unassigned'); + $clean_meta['status_id']['new'] = $clean_meta['status_id']['new'] ? "[id: " . $clean_meta['status_id']['new'] . "] " . $newStatusName : trans('general.unassigned'); $clean_meta[trans('general.status_label')] = $clean_meta['status_id']; unset($clean_meta['status_id']); } - if(array_key_exists('asset_eol_date', $clean_meta)) { + if (array_key_exists('asset_eol_date', $clean_meta)) { $clean_meta[trans('admin/hardware/form.eol_date')] = $clean_meta['asset_eol_date']; unset($clean_meta['asset_eol_date']); } return $clean_meta; - } - - - } diff --git a/app/Http/Transformers/AssetMaintenancesTransformer.php b/app/Http/Transformers/AssetMaintenancesTransformer.php index ab044260f782..ee96fc8e1a7f 100644 --- a/app/Http/Transformers/AssetMaintenancesTransformer.php +++ b/app/Http/Transformers/AssetMaintenancesTransformer.php @@ -17,7 +17,7 @@ public function transformAssetMaintenances(Collection $assetmaintenances, $total $array[] = self::transformAssetMaintenance($assetmaintenance); } - return (new DatatablesTransformer)->transformDatatables($array, $total); + return (new DatatablesTransformer())->transformDatatables($array, $total); } public function transformAssetMaintenance(AssetMaintenance $assetmaintenance) @@ -26,40 +26,40 @@ public function transformAssetMaintenance(AssetMaintenance $assetmaintenance) 'id' => (int) $assetmaintenance->id, 'asset' => ($assetmaintenance->asset) ? [ 'id' => (int) $assetmaintenance->asset->id, - 'name'=> ($assetmaintenance->asset->name) ? e($assetmaintenance->asset->name) : null, - 'asset_tag'=> e($assetmaintenance->asset->asset_tag), - 'serial'=> e($assetmaintenance->asset->serial), - 'deleted_at'=> Helper::getFormattedDateObject($assetmaintenance->asset->deleted_at, 'datetime'), + 'name' => ($assetmaintenance->asset->name) ? e($assetmaintenance->asset->name) : null, + 'asset_tag' => e($assetmaintenance->asset->asset_tag), + 'serial' => e($assetmaintenance->asset->serial), + 'deleted_at' => Helper::getFormattedDateObject($assetmaintenance->asset->deleted_at, 'datetime'), 'created_at' => Helper::getFormattedDateObject($assetmaintenance->asset->created_at, 'datetime'), 'updated_at' => Helper::getFormattedDateObject($assetmaintenance->asset->updated_at, 'datetime'), ] : null, 'model' => (($assetmaintenance->asset) && ($assetmaintenance->asset->model)) ? [ 'id' => (int) $assetmaintenance->asset->model->id, - 'name'=> ($assetmaintenance->asset->model->name) ? e($assetmaintenance->asset->model->name).' '.e($assetmaintenance->asset->model->model_number) : null, + 'name' => ($assetmaintenance->asset->model->name) ? e($assetmaintenance->asset->model->name) . ' ' . e($assetmaintenance->asset->model->model_number) : null, ] : null, 'status_label' => (($assetmaintenance->asset) && ($assetmaintenance->asset->assetstatus)) ? [ 'id' => (int) $assetmaintenance->asset->assetstatus->id, - 'name'=> e($assetmaintenance->asset->assetstatus->name), - 'status_type'=> e($assetmaintenance->asset->assetstatus->getStatuslabelType()), + 'name' => e($assetmaintenance->asset->assetstatus->name), + 'status_type' => e($assetmaintenance->asset->assetstatus->getStatuslabelType()), 'status_meta' => e($assetmaintenance->asset->present()->statusMeta), ] : null, 'company' => (($assetmaintenance->asset) && ($assetmaintenance->asset->company)) ? [ 'id' => (int) $assetmaintenance->asset->company->id, - 'name'=> ($assetmaintenance->asset->company->name) ? e($assetmaintenance->asset->company->name) : null, + 'name' => ($assetmaintenance->asset->company->name) ? e($assetmaintenance->asset->company->name) : null, ] : null, 'title' => ($assetmaintenance->title) ? e($assetmaintenance->title) : null, 'location' => (($assetmaintenance->asset) && ($assetmaintenance->asset->location)) ? [ 'id' => (int) $assetmaintenance->asset->location->id, - 'name'=> e($assetmaintenance->asset->location->name), + 'name' => e($assetmaintenance->asset->location->name), ] : null, 'rtd_location' => (($assetmaintenance->asset) && ($assetmaintenance->asset->defaultLoc)) ? [ 'id' => (int) $assetmaintenance->asset->defaultLoc->id, - 'name'=> e($assetmaintenance->asset->defaultLoc->name), + 'name' => e($assetmaintenance->asset->defaultLoc->name), ] : null, 'notes' => ($assetmaintenance->notes) ? Helper::parseEscapedMarkedownInline($assetmaintenance->notes) : null, - 'supplier' => ($assetmaintenance->supplier) ? ['id' => $assetmaintenance->supplier->id, 'name'=> e($assetmaintenance->supplier->name)] : null, + 'supplier' => ($assetmaintenance->supplier) ? ['id' => $assetmaintenance->supplier->id, 'name' => e($assetmaintenance->supplier->name)] : null, 'cost' => Helper::formatCurrencyOutput($assetmaintenance->cost), 'asset_maintenance_type' => e($assetmaintenance->asset_maintenance_type), 'start_date' => Helper::getFormattedDateObject($assetmaintenance->start_date, 'date'), @@ -67,20 +67,20 @@ public function transformAssetMaintenance(AssetMaintenance $assetmaintenance) 'completion_date' => Helper::getFormattedDateObject($assetmaintenance->completion_date, 'date'), 'user_id' => ($assetmaintenance->adminuser) ? [ 'id' => $assetmaintenance->adminuser->id, - 'name'=> e($assetmaintenance->adminuser->present()->fullName()) + 'name' => e($assetmaintenance->adminuser->present()->fullName()) ] : null, // legacy to not change the shape of the API 'created_by' => ($assetmaintenance->adminuser) ? [ 'id' => (int) $assetmaintenance->adminuser->id, - 'name'=> e($assetmaintenance->adminuser->present()->fullName()), + 'name' => e($assetmaintenance->adminuser->present()->fullName()), ] : null, 'created_at' => Helper::getFormattedDateObject($assetmaintenance->created_at, 'datetime'), 'updated_at' => Helper::getFormattedDateObject($assetmaintenance->updated_at, 'datetime'), - 'is_warranty'=> $assetmaintenance->is_warranty, + 'is_warranty' => $assetmaintenance->is_warranty, ]; $permissions_array['available_actions'] = [ - 'update' => (Gate::allows('update', Asset::class) && ((($assetmaintenance->asset) && $assetmaintenance->asset->deleted_at==''))) ? true : false, + 'update' => (Gate::allows('update', Asset::class) && ((($assetmaintenance->asset) && $assetmaintenance->asset->deleted_at == ''))) ? true : false, 'delete' => Gate::allows('delete', Asset::class), ]; diff --git a/app/Http/Transformers/AssetModelsTransformer.php b/app/Http/Transformers/AssetModelsTransformer.php index d1b79000319c..c04e13e0b632 100644 --- a/app/Http/Transformers/AssetModelsTransformer.php +++ b/app/Http/Transformers/AssetModelsTransformer.php @@ -17,7 +17,7 @@ public function transformAssetModels(Collection $assetmodels, $total) $array[] = self::transformAssetModel($assetmodel); } - return (new DatatablesTransformer)->transformDatatables($array, $total); + return (new DatatablesTransformer())->transformDatatables($array, $total); } public function transformAssetModel(AssetModel $assetmodel) @@ -27,7 +27,7 @@ public function transformAssetModel(AssetModel $assetmodel) // Reach into the custom fields and models_custom_fields pivot table to find the default values for this model if ($assetmodel->fieldset) { - foreach($assetmodel->fieldset->fields AS $field) { + foreach ($assetmodel->fieldset->fields as $field) { $default_field_values[] = [ 'name' => e($field->name), 'db_column_name' => e($field->db_column_name()), @@ -43,32 +43,32 @@ public function transformAssetModel(AssetModel $assetmodel) 'name' => e($assetmodel->name), 'manufacturer' => ($assetmodel->manufacturer) ? [ 'id' => (int) $assetmodel->manufacturer->id, - 'name'=> e($assetmodel->manufacturer->name), + 'name' => e($assetmodel->manufacturer->name), ] : null, - 'image' => ($assetmodel->image != '') ? Storage::disk('public')->url('models/'.e($assetmodel->image)) : null, - 'model_number' => ($assetmodel->model_number ? e($assetmodel->model_number): null), + 'image' => ($assetmodel->image != '') ? Storage::disk('public')->url('models/' . e($assetmodel->image)) : null, + 'model_number' => ($assetmodel->model_number ? e($assetmodel->model_number) : null), 'min_amt' => ($assetmodel->min_amt) ? (int) $assetmodel->min_amt : null, 'remaining' => (int) ($assetmodel->assets_count - $assetmodel->min_amt), 'depreciation' => ($assetmodel->depreciation) ? [ 'id' => (int) $assetmodel->depreciation->id, - 'name'=> e($assetmodel->depreciation->name), + 'name' => e($assetmodel->depreciation->name), ] : null, 'assets_count' => (int) $assetmodel->assets_count, 'category' => ($assetmodel->category) ? [ 'id' => (int) $assetmodel->category->id, - 'name'=> e($assetmodel->category->name), + 'name' => e($assetmodel->category->name), ] : null, 'fieldset' => ($assetmodel->fieldset) ? [ 'id' => (int) $assetmodel->fieldset->id, - 'name'=> e($assetmodel->fieldset->name), + 'name' => e($assetmodel->fieldset->name), ] : null, 'default_fieldset_values' => $default_field_values, - 'eol' => ($assetmodel->eol > 0) ? $assetmodel->eol.' months' : 'None', + 'eol' => ($assetmodel->eol > 0) ? $assetmodel->eol . ' months' : 'None', 'requestable' => ($assetmodel->requestable == '1') ? true : false, 'notes' => Helper::parseEscapedMarkedownInline($assetmodel->notes), 'created_by' => ($assetmodel->adminuser) ? [ 'id' => (int) $assetmodel->adminuser->id, - 'name'=> e($assetmodel->adminuser->present()->fullName()), + 'name' => e($assetmodel->adminuser->present()->fullName()), ] : null, 'created_at' => Helper::getFormattedDateObject($assetmodel->created_at, 'datetime'), 'updated_at' => Helper::getFormattedDateObject($assetmodel->updated_at, 'datetime'), @@ -96,7 +96,7 @@ public function transformAssetModelFiles($assetmodel, $total) $array[] = self::transformAssetModelFile($file, $assetmodel); } - return (new DatatablesTransformer)->transformDatatables($array, $total); + return (new DatatablesTransformer())->transformDatatables($array, $total); } public function transformAssetModelFile($file, $assetmodel) @@ -105,10 +105,11 @@ public function transformAssetModelFile($file, $assetmodel) $array = [ 'id' => (int) $file->id, 'filename' => e($file->filename), + 'note' => $file->note, 'url' => route('show/modelfile', [$assetmodel->id, $file->id]), 'created_by' => ($file->adminuser) ? [ 'id' => (int) $file->adminuser->id, - 'name'=> e($file->adminuser->present()->fullName), + 'name' => e($file->adminuser->present()->fullName), ] : null, 'created_at' => Helper::getFormattedDateObject($file->created_at, 'datetime'), 'updated_at' => Helper::getFormattedDateObject($file->updated_at, 'datetime'), @@ -125,6 +126,6 @@ public function transformAssetModelFile($file, $assetmodel) public function transformAssetModelsDatatable($assetmodels) { - return (new DatatablesTransformer)->transformDatatables($assetmodels); + return (new DatatablesTransformer())->transformDatatables($assetmodels); } } diff --git a/app/Http/Transformers/AssetsTransformer.php b/app/Http/Transformers/AssetsTransformer.php index 8b16a9a7265d..1c1e0a2fb2a5 100644 --- a/app/Http/Transformers/AssetsTransformer.php +++ b/app/Http/Transformers/AssetsTransformer.php @@ -21,7 +21,7 @@ public function transformAssets(Collection $assets, $total) $array[] = self::transformAsset($asset); } - return (new DatatablesTransformer)->transformDatatables($array, $total); + return (new DatatablesTransformer())->transformDatatables($array, $total); } public function transformAsset(Asset $asset) @@ -36,7 +36,7 @@ public function transformAsset(Asset $asset) 'serial' => e($asset->serial), 'model' => ($asset->model) ? [ 'id' => (int) $asset->model->id, - 'name'=> e($asset->model->name), + 'name' => e($asset->model->name), ] : null, 'byod' => ($asset->byod ? true : false), 'requestable' => ($asset->requestable ? true : false), @@ -46,45 +46,45 @@ public function transformAsset(Asset $asset) 'asset_eol_date' => ($asset->asset_eol_date != '') ? Helper::getFormattedDateObject($asset->asset_eol_date, 'date') : null, 'status_label' => ($asset->assetstatus) ? [ 'id' => (int) $asset->assetstatus->id, - 'name'=> e($asset->assetstatus->name), - 'status_type'=> e($asset->assetstatus->getStatuslabelType()), + 'name' => e($asset->assetstatus->name), + 'status_type' => e($asset->assetstatus->getStatuslabelType()), 'status_meta' => e($asset->present()->statusMeta), ] : null, 'category' => (($asset->model) && ($asset->model->category)) ? [ 'id' => (int) $asset->model->category->id, - 'name'=> e($asset->model->category->name), + 'name' => e($asset->model->category->name), ] : null, 'manufacturer' => (($asset->model) && ($asset->model->manufacturer)) ? [ 'id' => (int) $asset->model->manufacturer->id, - 'name'=> e($asset->model->manufacturer->name), + 'name' => e($asset->model->manufacturer->name), ] : null, 'supplier' => ($asset->supplier) ? [ 'id' => (int) $asset->supplier->id, - 'name'=> e($asset->supplier->name), + 'name' => e($asset->supplier->name), ] : null, 'notes' => ($asset->notes) ? Helper::parseEscapedMarkedownInline($asset->notes) : null, 'order_number' => ($asset->order_number) ? e($asset->order_number) : null, 'company' => ($asset->company) ? [ 'id' => (int) $asset->company->id, - 'name'=> e($asset->company->name), + 'name' => e($asset->company->name), ] : null, 'location' => ($asset->location) ? [ 'id' => (int) $asset->location->id, - 'name'=> e($asset->location->name), + 'name' => e($asset->location->name), ] : null, 'rtd_location' => ($asset->defaultLoc) ? [ 'id' => (int) $asset->defaultLoc->id, - 'name'=> e($asset->defaultLoc->name), + 'name' => e($asset->defaultLoc->name), ] : null, 'image' => ($asset->getImageUrl()) ? $asset->getImageUrl() : null, - 'qr' => ($setting->qr_code=='1') ? config('app.url').'/uploads/barcodes/qr-'.str_slug($asset->asset_tag).'-'.str_slug($asset->id).'.png' : null, - 'alt_barcode' => ($setting->alt_barcode_enabled=='1') ? config('app.url').'/uploads/barcodes/'.str_slug($setting->alt_barcode).'-'.str_slug($asset->asset_tag).'.png' : null, + 'qr' => ($setting->qr_code == '1') ? config('app.url') . '/uploads/barcodes/qr-' . str_slug($asset->asset_tag) . '-' . str_slug($asset->id) . '.png' : null, + 'alt_barcode' => ($setting->alt_barcode_enabled == '1') ? config('app.url') . '/uploads/barcodes/' . str_slug($setting->alt_barcode) . '-' . str_slug($asset->asset_tag) . '.png' : null, 'assigned_to' => $this->transformAssignedTo($asset), - 'warranty_months' => ($asset->warranty_months > 0) ? e($asset->warranty_months.' '.trans('admin/hardware/form.months')) : null, + 'warranty_months' => ($asset->warranty_months > 0) ? e($asset->warranty_months . ' ' . trans('admin/hardware/form.months')) : null, 'warranty_expires' => ($asset->warranty_months > 0) ? Helper::getFormattedDateObject($asset->warranty_expires, 'date') : null, 'created_by' => ($asset->adminuser) ? [ 'id' => (int) $asset->adminuser->id, - 'name'=> e($asset->adminuser->present()->fullName()), + 'name' => e($asset->adminuser->present()->fullName()), ] : null, 'created_at' => Helper::getFormattedDateObject($asset->created_at, 'datetime'), 'updated_at' => Helper::getFormattedDateObject($asset->updated_at, 'datetime'), @@ -113,11 +113,11 @@ public function transformAsset(Asset $asset) $decrypted = Helper::gracefulDecrypt($field, $asset->{$field->db_column}); $value = (Gate::allows('assets.view.encrypted_custom_fields')) ? $decrypted : strtoupper(trans('admin/custom_fields/general.encrypted')); - if ($field->format == 'DATE'){ - if (Gate::allows('assets.view.encrypted_custom_fields')){ + if ($field->format == 'DATE') { + if (Gate::allows('assets.view.encrypted_custom_fields')) { $value = Helper::getFormattedDateObject($value, 'date', false); } else { - $value = strtoupper(trans('admin/custom_fields/general.encrypted')); + $value = strtoupper(trans('admin/custom_fields/general.encrypted')); } } @@ -127,14 +127,13 @@ public function transformAsset(Asset $asset) 'field_format' => $field->format, 'element' => $field->element, ]; - } else { $value = $asset->{$field->db_column}; - if (($field->format == 'DATE') && (!is_null($value)) && ($value!='')){ + if (($field->format == 'DATE') && (!is_null($value)) && ($value != '')) { $value = Helper::getFormattedDateObject($value, 'date', false); } - + $fields_array[$field->name] = [ 'field' => e($field->db_column), 'value' => e($value), @@ -146,27 +145,26 @@ public function transformAsset(Asset $asset) $array['custom_fields'] = $fields_array; } } else { - $array['custom_fields'] = new \stdClass; // HACK to force generation of empty object instead of empty list + $array['custom_fields'] = new \stdClass(); // HACK to force generation of empty object instead of empty list } $permissions_array['available_actions'] = [ - 'checkout' => ($asset->deleted_at=='' && Gate::allows('checkout', Asset::class)) ? true : false, - 'checkin' => ($asset->deleted_at=='' && Gate::allows('checkin', Asset::class)) ? true : false, + 'checkout' => ($asset->deleted_at == '' && Gate::allows('checkout', Asset::class)) ? true : false, + 'checkin' => ($asset->deleted_at == '' && Gate::allows('checkin', Asset::class)) ? true : false, 'clone' => Gate::allows('create', Asset::class) ? true : false, - 'restore' => ($asset->deleted_at!='' && Gate::allows('create', Asset::class)) ? true : false, - 'update' => ($asset->deleted_at=='' && Gate::allows('update', Asset::class)) ? true : false, - 'delete' => ($asset->deleted_at=='' && $asset->assigned_to =='' && Gate::allows('delete', Asset::class) && ($asset->deleted_at == '')) ? true : false, - ]; + 'restore' => ($asset->deleted_at != '' && Gate::allows('create', Asset::class)) ? true : false, + 'update' => ($asset->deleted_at == '' && Gate::allows('update', Asset::class)) ? true : false, + 'delete' => ($asset->deleted_at == '' && $asset->assigned_to == '' && Gate::allows('delete', Asset::class) && ($asset->deleted_at == '')) ? true : false, + ]; - if (request('components')=='true') { - + if (request('components') == 'true') { if ($asset->components) { $array['components'] = []; - + foreach ($asset->components as $component) { $array['components'][] = [ - + 'id' => $component->id, 'pivot_id' => $component->pivot->id, 'name' => e($component->name), @@ -174,13 +172,12 @@ public function transformAsset(Asset $asset) 'price_cost' => $component->purchase_cost, 'purchase_total' => $component->purchase_cost * $component->pivot->assigned_qty, 'checkout_date' => Helper::getFormattedDateObject($component->pivot->created_at, 'datetime') , - + ]; } } - } - + $array += $permissions_array; return $array; @@ -188,7 +185,7 @@ public function transformAsset(Asset $asset) public function transformAssetsDatatable($assets) { - return (new DatatablesTransformer)->transformDatatables($assets); + return (new DatatablesTransformer())->transformDatatables($assets); } public function transformAssignedTo($asset) @@ -198,9 +195,9 @@ public function transformAssignedTo($asset) 'id' => (int) $asset->assigned->id, 'username' => e($asset->assigned->username), 'name' => e($asset->assigned->getFullNameAttribute()), - 'first_name'=> e($asset->assigned->first_name), - 'last_name'=> ($asset->assigned->last_name) ? e($asset->assigned->last_name) : null, - 'email'=> ($asset->assigned->email) ? e($asset->assigned->email) : null, + 'first_name' => e($asset->assigned->first_name), + 'last_name' => ($asset->assigned->last_name) ? e($asset->assigned->last_name) : null, + 'email' => ($asset->assigned->email) ? e($asset->assigned->email) : null, 'employee_number' => ($asset->assigned->employee_num) ? e($asset->assigned->employee_num) : null, 'type' => 'user', ] : null; @@ -221,7 +218,7 @@ public function transformRequestedAssets(Collection $assets, $total) $array[] = self::transformRequestedAsset($asset); } - return (new DatatablesTransformer)->transformDatatables($array, $total); + return (new DatatablesTransformer())->transformDatatables($array, $total); } public function transformRequestedAsset(Asset $asset) @@ -244,10 +241,8 @@ public function transformRequestedAsset(Asset $asset) $fields_array = []; foreach ($asset->model->fieldset->fields as $field) { - // Only display this if it's allowed via the custom field setting if (($field->field_encrypted == '0') && ($field->show_in_requestable_list == '1')) { - $value = $asset->{$field->db_column}; if (($field->format == 'DATE') && (!is_null($value)) && ($value != '')) { $value = Helper::getFormattedDateObject($value, 'date', false); @@ -259,7 +254,7 @@ public function transformRequestedAsset(Asset $asset) $array['custom_fields'] = $fields_array; } } else { - $array['custom_fields'] = new \stdClass; // HACK to force generation of empty object instead of empty list + $array['custom_fields'] = new \stdClass(); // HACK to force generation of empty object instead of empty list } @@ -296,7 +291,7 @@ public function transformCheckedoutAccessories($accessory_checkouts, $total) $array[] = self::transformCheckedoutAccessory($checkout); } - return (new DatatablesTransformer)->transformDatatables($array, $total); + return (new DatatablesTransformer())->transformDatatables($array, $total); } @@ -329,5 +324,4 @@ public function transformCheckedoutAccessory(AccessoryCheckout $accessory_checko return $array; } } - } diff --git a/app/Http/Transformers/CategoriesTransformer.php b/app/Http/Transformers/CategoriesTransformer.php index 0d1834649da5..ab17e6a8f421 100644 --- a/app/Http/Transformers/CategoriesTransformer.php +++ b/app/Http/Transformers/CategoriesTransformer.php @@ -17,7 +17,7 @@ public function transformCategories(Collection $categorys, $total) $array[] = self::transformCategory($category); } - return (new DatatablesTransformer)->transformDatatables($array, $total); + return (new DatatablesTransformer())->transformDatatables($array, $total); } public function transformCategory(Category $category = null) @@ -49,10 +49,10 @@ public function transformCategory(Category $category = null) $array = [ 'id' => (int) $category->id, 'name' => e($category->name), - 'image' => ($category->image) ? Storage::disk('public')->url('categories/'.e($category->image)) : null, + 'image' => ($category->image) ? Storage::disk('public')->url('categories/' . e($category->image)) : null, 'category_type' => Helper::categoryTypeList($category->category_type), 'has_eula' => ($category->getEula() ? true : false), - 'use_default_eula' => ($category->use_default_eula=='1' ? true : false), + 'use_default_eula' => ($category->use_default_eula == '1' ? true : false), 'eula' => ($category->getEula()), 'checkin_email' => ($category->checkin_email == '1'), 'require_acceptance' => ($category->require_acceptance == '1'), @@ -64,7 +64,7 @@ public function transformCategory(Category $category = null) 'licenses_count' => (int) $category->licenses_count, 'created_by' => ($category->adminuser) ? [ 'id' => (int) $category->adminuser->id, - 'name'=> e($category->adminuser->present()->fullName()), + 'name' => e($category->adminuser->present()->fullName()), ] : null, 'notes' => Helper::parseEscapedMarkedownInline($category->notes), 'created_at' => Helper::getFormattedDateObject($category->created_at, 'datetime'), diff --git a/app/Http/Transformers/CompaniesTransformer.php b/app/Http/Transformers/CompaniesTransformer.php index 8ca5344de6be..e1e705bcb6e7 100644 --- a/app/Http/Transformers/CompaniesTransformer.php +++ b/app/Http/Transformers/CompaniesTransformer.php @@ -17,7 +17,7 @@ public function transformCompanies(Collection $companies, $total) $array[] = self::transformCompany($company); } - return (new DatatablesTransformer)->transformDatatables($array, $total); + return (new DatatablesTransformer())->transformDatatables($array, $total); } public function transformCompany(Company $company = null) @@ -26,10 +26,10 @@ public function transformCompany(Company $company = null) $array = [ 'id' => (int) $company->id, 'name' => e($company->name), - 'phone' => ($company->phone!='') ? e($company->phone): null, - 'fax' => ($company->fax!='') ? e($company->fax): null, - 'email' => ($company->email!='') ? e($company->email): null, - 'image' => ($company->image) ? Storage::disk('public')->url('companies/'.e($company->image)) : null, + 'phone' => ($company->phone != '') ? e($company->phone) : null, + 'fax' => ($company->fax != '') ? e($company->fax) : null, + 'email' => ($company->email != '') ? e($company->email) : null, + 'image' => ($company->image) ? Storage::disk('public')->url('companies/' . e($company->image)) : null, 'assets_count' => (int) $company->assets_count, 'licenses_count' => (int) $company->licenses_count, 'accessories_count' => (int) $company->accessories_count, @@ -38,7 +38,7 @@ public function transformCompany(Company $company = null) 'users_count' => (int) $company->users_count, 'created_by' => ($company->adminuser) ? [ 'id' => (int) $company->adminuser->id, - 'name'=> e($company->adminuser->present()->fullName()), + 'name' => e($company->adminuser->present()->fullName()), ] : null, 'notes' => Helper::parseEscapedMarkedownInline($company->notes), 'created_at' => Helper::getFormattedDateObject($company->created_at, 'datetime'), diff --git a/app/Http/Transformers/ComponentsAssetsTransformer.php b/app/Http/Transformers/ComponentsAssetsTransformer.php index 437d00ca2204..5a5209cf69a8 100644 --- a/app/Http/Transformers/ComponentsAssetsTransformer.php +++ b/app/Http/Transformers/ComponentsAssetsTransformer.php @@ -15,7 +15,7 @@ public function transformAssets(Collection $assets, $total) $array[] = self::transformAsset($asset); } - return (new DatatablesTransformer)->transformDatatables($array, $total); + return (new DatatablesTransformer())->transformDatatables($array, $total); } public function transformAsset(Asset $asset) @@ -50,6 +50,6 @@ public function transformAsset(Asset $asset) public function transformAssetsDatatable($assets) { - return (new DatatablesTransformer)->transformDatatables($assets); + return (new DatatablesTransformer())->transformDatatables($assets); } } diff --git a/app/Http/Transformers/ComponentsTransformer.php b/app/Http/Transformers/ComponentsTransformer.php index 90d10ba9a504..ed69fe482881 100644 --- a/app/Http/Transformers/ComponentsTransformer.php +++ b/app/Http/Transformers/ComponentsTransformer.php @@ -17,7 +17,7 @@ public function transformComponents(Collection $components, $total) $array[] = self::transformComponent($component); } - return (new DatatablesTransformer)->transformDatatables($array, $total); + return (new DatatablesTransformer())->transformDatatables($array, $total); } public function transformComponent(Component $component) @@ -25,7 +25,7 @@ public function transformComponent(Component $component) $array = [ 'id' => (int) $component->id, 'name' => e($component->name), - 'image' => ($component->image) ? Storage::disk('public')->url('components/'.e($component->image)) : null, + 'image' => ($component->image) ? Storage::disk('public')->url('components/' . e($component->image)) : null, 'serial' => ($component->serial) ? e($component->serial) : null, 'location' => ($component->location) ? [ 'id' => (int) $component->location->id, @@ -37,8 +37,8 @@ public function transformComponent(Component $component) 'id' => (int) $component->category->id, 'name' => e($component->category->name), ] : null, - 'supplier' => ($component->supplier) ? ['id' => $component->supplier->id, 'name'=> e($component->supplier->name)] : null, - 'manufacturer' => ($component->manufacturer) ? ['id' => $component->manufacturer->id, 'name'=> e($component->manufacturer->name)] : null, + 'supplier' => ($component->supplier) ? ['id' => $component->supplier->id, 'name' => e($component->supplier->name)] : null, + 'manufacturer' => ($component->manufacturer) ? ['id' => $component->manufacturer->id, 'name' => e($component->manufacturer->name)] : null, 'model_number' => ($component->model_number) ? e($component->model_number) : null, 'order_number' => e($component->order_number), 'purchase_date' => Helper::getFormattedDateObject($component->purchase_date, 'date'), @@ -51,7 +51,7 @@ public function transformComponent(Component $component) 'notes' => ($component->notes) ? Helper::parseEscapedMarkedownInline($component->notes) : null, 'created_by' => ($component->adminuser) ? [ 'id' => (int) $component->adminuser->id, - 'name'=> e($component->adminuser->present()->fullName()), + 'name' => e($component->adminuser->present()->fullName()), ] : null, 'created_at' => Helper::getFormattedDateObject($component->created_at, 'datetime'), 'updated_at' => Helper::getFormattedDateObject($component->updated_at, 'datetime'), @@ -76,7 +76,7 @@ public function transformCheckedoutComponents(Collection $components_assets, $to $array[] = [ 'assigned_pivot_id' => $asset->pivot->id, 'id' => (int) $asset->id, - 'name' => e($asset->model->present()->name).' '.e($asset->present()->name), + 'name' => e($asset->model->present()->name) . ' ' . e($asset->present()->name), 'qty' => $asset->pivot->assigned_qty, 'note' => $asset->pivot->note, 'type' => 'asset', @@ -85,6 +85,6 @@ public function transformCheckedoutComponents(Collection $components_assets, $to ]; } - return (new DatatablesTransformer)->transformDatatables($array, $total); + return (new DatatablesTransformer())->transformDatatables($array, $total); } } diff --git a/app/Http/Transformers/ConsumablesTransformer.php b/app/Http/Transformers/ConsumablesTransformer.php index b31e31ac96d8..66287702fd4a 100644 --- a/app/Http/Transformers/ConsumablesTransformer.php +++ b/app/Http/Transformers/ConsumablesTransformer.php @@ -17,7 +17,7 @@ public function transformConsumables(Collection $consumables, $total) $array[] = self::transformConsumable($consumable); } - return (new DatatablesTransformer)->transformDatatables($array, $total); + return (new DatatablesTransformer())->transformDatatables($array, $total); } public function transformConsumable(Consumable $consumable) @@ -25,13 +25,13 @@ public function transformConsumable(Consumable $consumable) $array = [ 'id' => (int) $consumable->id, 'name' => e($consumable->name), - 'image' => ($consumable->image) ? Storage::disk('public')->url('consumables/'.e($consumable->image)) : null, + 'image' => ($consumable->image) ? Storage::disk('public')->url('consumables/' . e($consumable->image)) : null, 'category' => ($consumable->category) ? ['id' => $consumable->category->id, 'name' => e($consumable->category->name)] : null, 'company' => ($consumable->company) ? ['id' => (int) $consumable->company->id, 'name' => e($consumable->company->name)] : null, 'item_no' => e($consumable->item_no), 'location' => ($consumable->location) ? ['id' => (int) $consumable->location->id, 'name' => e($consumable->location->name)] : null, 'manufacturer' => ($consumable->manufacturer) ? ['id' => (int) $consumable->manufacturer->id, 'name' => e($consumable->manufacturer->name)] : null, - 'supplier' => ($consumable->supplier) ? ['id' => $consumable->supplier->id, 'name'=> e($consumable->supplier->name)] : null, + 'supplier' => ($consumable->supplier) ? ['id' => $consumable->supplier->id, 'name' => e($consumable->supplier->name)] : null, 'min_amt' => (int) $consumable->min_amt, 'model_number' => ($consumable->model_number != '') ? e($consumable->model_number) : null, 'remaining' => $consumable->numRemaining(), @@ -42,7 +42,7 @@ public function transformConsumable(Consumable $consumable) 'notes' => ($consumable->notes) ? Helper::parseEscapedMarkedownInline($consumable->notes) : null, 'created_by' => ($consumable->adminuser) ? [ 'id' => (int) $consumable->adminuser->id, - 'name'=> e($consumable->adminuser->present()->fullName()), + 'name' => e($consumable->adminuser->present()->fullName()), ] : null, 'created_at' => Helper::getFormattedDateObject($consumable->created_at, 'datetime'), 'updated_at' => Helper::getFormattedDateObject($consumable->updated_at, 'datetime'), @@ -70,9 +70,9 @@ public function transformCheckedoutConsumables(Collection $consumables_users, $t { $array = []; foreach ($consumables_users as $user) { - $array[] = (new UsersTransformer)->transformUser($user); + $array[] = (new UsersTransformer())->transformUser($user); } - return (new DatatablesTransformer)->transformDatatables($array, $total); + return (new DatatablesTransformer())->transformDatatables($array, $total); } } diff --git a/app/Http/Transformers/CustomFieldsTransformer.php b/app/Http/Transformers/CustomFieldsTransformer.php index 501d264b5572..f80885e02d86 100644 --- a/app/Http/Transformers/CustomFieldsTransformer.php +++ b/app/Http/Transformers/CustomFieldsTransformer.php @@ -15,7 +15,7 @@ public function transformCustomFields(Collection $fields, $total) $array[] = self::transformCustomField($field); } - return (new DatatablesTransformer)->transformDatatables($array, $total); + return (new DatatablesTransformer())->transformDatatables($array, $total); } /** @@ -33,7 +33,7 @@ public function transformCustomFieldsWithDefaultValues(Collection $fields, $mode $array[] = self::transformCustomFieldWithDefaultValue($field, $modelId); } - return (new DatatablesTransformer)->transformDatatables($array, $total); + return (new DatatablesTransformer())->transformDatatables($array, $total); } public function transformCustomField(CustomField $field) @@ -46,8 +46,8 @@ public function transformCustomField(CustomField $field) 'field_values' => ($field->field_values) ? e($field->field_values) : null, 'field_values_array' => ($field->field_values) ? explode("\r\n", e($field->field_values)) : null, 'type' => e($field->element), - 'required' => (($field->pivot) && ($field->pivot->required=='1')) ? true : false, - 'display_in_user_view' => ($field->display_in_user_view =='1') ? true : false, + 'required' => (($field->pivot) && ($field->pivot->required == '1')) ? true : false, + 'display_in_user_view' => ($field->display_in_user_view == '1') ? true : false, 'auto_add_to_fieldsets' => ($field->auto_add_to_fieldsets == '1') ? true : false, 'show_in_listview' => ($field->show_in_listview == '1') ? true : false, 'display_checkin' => ($field->display_checkin == '1') ? true : false, diff --git a/app/Http/Transformers/CustomFieldsetsTransformer.php b/app/Http/Transformers/CustomFieldsetsTransformer.php index 61e42486ab43..b3ac88737e5b 100644 --- a/app/Http/Transformers/CustomFieldsetsTransformer.php +++ b/app/Http/Transformers/CustomFieldsetsTransformer.php @@ -15,7 +15,7 @@ public function transformCustomFieldsets(Collection $fieldsets, $total) $array[] = self::transformCustomFieldset($fieldset); } - return (new DatatablesTransformer)->transformDatatables($array, $total); + return (new DatatablesTransformer())->transformDatatables($array, $total); } public function transformCustomFieldset(CustomFieldset $fieldset) @@ -34,8 +34,8 @@ public function transformCustomFieldset(CustomFieldset $fieldset) $array = [ 'id' => (int) $fieldset->id, 'name' => e($fieldset->name), - 'fields' => (new CustomFieldsTransformer)->transformCustomFields($fields, $fieldset->fields_count), - 'models' => (new DatatablesTransformer)->transformDatatables($modelsArray, $fieldset->models_count), + 'fields' => (new CustomFieldsTransformer())->transformCustomFields($fields, $fieldset->fields_count), + 'models' => (new DatatablesTransformer())->transformDatatables($modelsArray, $fieldset->models_count), 'created_at' => Helper::getFormattedDateObject($fieldset->created_at, 'datetime'), 'updated_at' => Helper::getFormattedDateObject($fieldset->updated_at, 'datetime'), ]; diff --git a/app/Http/Transformers/DepartmentsTransformer.php b/app/Http/Transformers/DepartmentsTransformer.php index 3d1e4c6f90c4..d0dec6c37d34 100644 --- a/app/Http/Transformers/DepartmentsTransformer.php +++ b/app/Http/Transformers/DepartmentsTransformer.php @@ -17,7 +17,7 @@ public function transformDepartments(Collection $departments, $total) $array[] = self::transformDepartment($department); } - return (new DatatablesTransformer)->transformDatatables($array, $total); + return (new DatatablesTransformer())->transformDatatables($array, $total); } public function transformDepartment(Department $department = null) @@ -26,18 +26,18 @@ public function transformDepartment(Department $department = null) $array = [ 'id' => (int) $department->id, 'name' => e($department->name), - 'phone' => ($department->phone!='') ? e($department->phone): null, - 'fax' => ($department->fax!='') ? e($department->fax): null, - 'image' => ($department->image) ? Storage::disk('public')->url(app('departments_upload_url').e($department->image)) : null, + 'phone' => ($department->phone != '') ? e($department->phone) : null, + 'fax' => ($department->fax != '') ? e($department->fax) : null, + 'image' => ($department->image) ? Storage::disk('public')->url(app('departments_upload_url') . e($department->image)) : null, 'company' => ($department->company) ? [ 'id' => (int) $department->company->id, - 'name'=> e($department->company->name), + 'name' => e($department->company->name), ] : null, 'manager' => ($department->manager) ? [ 'id' => (int) $department->manager->id, 'name' => e($department->manager->getFullNameAttribute()), - 'first_name'=> e($department->manager->first_name), - 'last_name'=> e($department->manager->last_name), + 'first_name' => e($department->manager->first_name), + 'last_name' => e($department->manager->last_name), ] : null, 'location' => ($department->location) ? [ 'id' => (int) $department->location->id, diff --git a/app/Http/Transformers/DepreciationReportTransformer.php b/app/Http/Transformers/DepreciationReportTransformer.php index 00eb984fa51b..5b211ba5a573 100644 --- a/app/Http/Transformers/DepreciationReportTransformer.php +++ b/app/Http/Transformers/DepreciationReportTransformer.php @@ -1,4 +1,5 @@ ] * @since [v5.2.0] */ @@ -23,7 +24,7 @@ public function transformAssets(Collection $assets, $total) foreach ($assets as $asset) { $array[] = self::transformAsset($asset); } - return (new DatatablesTransformer)->transformDatatables($array, $total); + return (new DatatablesTransformer())->transformDatatables($array, $total); } @@ -50,23 +51,22 @@ public function transformAsset(Asset $asset) /** * If there is a NOT an empty purchase cost (meaning not null or '' but it *could* be zero), - * format the purchase cost. We coould do this inline in the transformer, but we need that value + * format the purchase cost. We coould do this inline in the transformer, but we need that value * for the other calculations that come after, like diff, etc. */ - if ($asset->purchase_cost!='') { + if ($asset->purchase_cost != '') { $purchase_cost = $asset->purchase_cost; } - + /** * Override the previously set null values if there is a valid model and associated depreciation */ if (($asset->model) && ($asset->model->depreciation) && ($asset->model->depreciation->months !== 0)) { $depreciated_value = Helper::formatCurrencyOutput($asset->getDepreciatedValue()); - $monthly_depreciation =Helper::formatCurrencyOutput($asset->purchase_cost / $asset->model->depreciation->months); + $monthly_depreciation = Helper::formatCurrencyOutput($asset->purchase_cost / $asset->model->depreciation->months); $diff = Helper::formatCurrencyOutput(($asset->purchase_cost - $asset->getDepreciatedValue())); - } - else if($asset->model->eol !== null) { + } elseif ($asset->model->eol !== null) { $monthly_depreciation = Helper::formatCurrencyOutput(($asset->model->eol > 0 ? ($asset->purchase_cost / $asset->model->eol) : 0)); } @@ -74,19 +74,18 @@ public function transformAsset(Asset $asset) $checkout_target = $asset->assigned->name; if ($asset->checkedOutToUser()) { $checkout_target = $asset->assigned->getFullNameAttribute(); - } - + } } - + $array = [ - + 'company' => ($asset->company) ? e($asset->company->name) : null, 'name' => e($asset->name), 'asset_tag' => e($asset->asset_tag), 'serial' => e($asset->serial), 'model' => ($asset->model) ? e($asset->model->name) : null, 'model_number' => (($asset->model) && ($asset->model->model_number)) ? e($asset->model->model_number) : null, - 'eol' => ($asset->purchase_date!='') ? Helper::getFormattedDateObject($asset->present()->eol_date(), 'date') : null , + 'eol' => ($asset->purchase_date != '') ? Helper::getFormattedDateObject($asset->present()->eol_date(), 'date') : null , 'status_label' => ($asset->assetstatus) ? e($asset->assetstatus->name) : null, 'status' => ($asset->assetstatus) ? e($asset->present()->statusMeta) : null, 'category' => (($asset->model) && ($asset->model->category)) ? e($asset->model->category->name) : null, @@ -105,9 +104,9 @@ public function transformAsset(Asset $asset) 'diff' => Helper::formatCurrencyOutput($diff), 'number_of_months' => ($asset->model && $asset->model->depreciation) ? e($asset->model->depreciation->months) : null, 'depreciation' => (($asset->model) && ($asset->model->depreciation)) ? e($asset->model->depreciation->name) : null, - - + + ]; return $array; @@ -115,9 +114,6 @@ public function transformAsset(Asset $asset) public function transformAssetsDatatable($assets) { - return (new DatatablesTransformer)->transformDatatables($assets); + return (new DatatablesTransformer())->transformDatatables($assets); } - - - } diff --git a/app/Http/Transformers/DepreciationsTransformer.php b/app/Http/Transformers/DepreciationsTransformer.php index 64d4c88f7edc..a0483acd6d72 100644 --- a/app/Http/Transformers/DepreciationsTransformer.php +++ b/app/Http/Transformers/DepreciationsTransformer.php @@ -18,7 +18,7 @@ public function transformDepreciations(Collection $depreciations, $total) $array[] = self::transformDepreciation($depreciation); } - return (new DatatablesTransformer)->transformDatatables($array, $total); + return (new DatatablesTransformer())->transformDatatables($array, $total); } public function transformDepreciation(Depreciation $depreciation) @@ -26,14 +26,14 @@ public function transformDepreciation(Depreciation $depreciation) $array = [ 'id' => (int) $depreciation->id, 'name' => e($depreciation->name), - 'months' => $depreciation->months.' '.trans('general.months'), - 'depreciation_min' => $depreciation->depreciation_type === 'percent' ? $depreciation->depreciation_min.'%' : $depreciation->depreciation_min, + 'months' => $depreciation->months . ' ' . trans('general.months'), + 'depreciation_min' => $depreciation->depreciation_type === 'percent' ? $depreciation->depreciation_min . '%' : $depreciation->depreciation_min, 'assets_count' => $depreciation->assets_count, 'models_count' => $depreciation->models_count, 'licenses_count' => $depreciation->licenses_count, 'created_by' => ($depreciation->adminuser) ? [ 'id' => (int) $depreciation->adminuser->id, - 'name'=> e($depreciation->adminuser->present()->fullName()), + 'name' => e($depreciation->adminuser->present()->fullName()), ] : null, 'created_at' => Helper::getFormattedDateObject($depreciation->created_at, 'datetime'), 'updated_at' => Helper::getFormattedDateObject($depreciation->updated_at, 'datetime') @@ -48,4 +48,4 @@ public function transformDepreciation(Depreciation $depreciation) return $array; } -} \ No newline at end of file +} diff --git a/app/Http/Transformers/GroupsTransformer.php b/app/Http/Transformers/GroupsTransformer.php index 920c856b1a49..59f9b716295c 100644 --- a/app/Http/Transformers/GroupsTransformer.php +++ b/app/Http/Transformers/GroupsTransformer.php @@ -9,14 +9,14 @@ class GroupsTransformer { - public function transformGroups (Collection $groups, $total = null) + public function transformGroups(Collection $groups, $total = null) { $array = []; foreach ($groups as $group) { $array[] = self::transformGroup($group); } - return (new DatatablesTransformer)->transformDatatables($array, $total); + return (new DatatablesTransformer())->transformDatatables($array, $total); } public function transformGroup(Group $group) @@ -29,7 +29,7 @@ public function transformGroup(Group $group) 'notes' => Helper::parseEscapedMarkedownInline($group->notes), 'created_by' => ($group->adminuser) ? [ 'id' => (int) $group->adminuser->id, - 'name'=> e($group->adminuser->present()->fullName()), + 'name' => e($group->adminuser->present()->fullName()), ] : null, 'created_at' => Helper::getFormattedDateObject($group->created_at, 'datetime'), 'updated_at' => Helper::getFormattedDateObject($group->updated_at, 'datetime'), diff --git a/app/Http/Transformers/ImportsTransformer.php b/app/Http/Transformers/ImportsTransformer.php index 486c18f28cba..bdf8bcf9138c 100644 --- a/app/Http/Transformers/ImportsTransformer.php +++ b/app/Http/Transformers/ImportsTransformer.php @@ -36,6 +36,6 @@ public function transformImport(Import $import) public function transformImportsDatatable($imports) { - return (new DatatablesTransformer)->transformDatatables($imports); + return (new DatatablesTransformer())->transformDatatables($imports); } } diff --git a/app/Http/Transformers/LabelsTransformer.php b/app/Http/Transformers/LabelsTransformer.php index 0ed5a09686fc..f399b8d2c4e6 100644 --- a/app/Http/Transformers/LabelsTransformer.php +++ b/app/Http/Transformers/LabelsTransformer.php @@ -17,7 +17,7 @@ public function transformLabels(Collection $labels, $total) $array[] = self::transformLabel($label); } - return (new DatatablesTransformer)->transformDatatables($array, $total); + return (new DatatablesTransformer())->transformDatatables($array, $total); } public function transformLabel(Label $label) diff --git a/app/Http/Transformers/LicenseSeatsTransformer.php b/app/Http/Transformers/LicenseSeatsTransformer.php index 7ae68e9e449c..21045694403b 100644 --- a/app/Http/Transformers/LicenseSeatsTransformer.php +++ b/app/Http/Transformers/LicenseSeatsTransformer.php @@ -18,7 +18,7 @@ public function transformLicenseSeats(Collection $seats, $total) $array[] = self::transformLicenseSeat($seat, $seat_count); } - return (new DatatablesTransformer)->transformDatatables($array, $total); + return (new DatatablesTransformer())->transformDatatables($array, $total); } public function transformLicenseSeat(LicenseSeat $seat, $seat_count = 0) @@ -28,9 +28,9 @@ public function transformLicenseSeat(LicenseSeat $seat, $seat_count = 0) 'license_id' => (int) $seat->license->id, 'assigned_user' => ($seat->user) ? [ 'id' => (int) $seat->user->id, - 'name'=> e($seat->user->present()->fullName), + 'name' => e($seat->user->present()->fullName), 'email' => e($seat->user->email), - 'department'=> ($seat->user->department) ? + 'department' => ($seat->user->department) ? [ 'id' => (int) $seat->user->department->id, 'name' => e($seat->user->department->name), @@ -39,11 +39,11 @@ public function transformLicenseSeat(LicenseSeat $seat, $seat_count = 0) ] : null, 'assigned_asset' => ($seat->asset) ? [ 'id' => (int) $seat->asset->id, - 'name'=> e($seat->asset->present()->fullName), + 'name' => e($seat->asset->present()->fullName), ] : null, 'location' => ($seat->location()) ? [ 'id' => (int) $seat->location()->id, - 'name'=> e($seat->location()->name), + 'name' => e($seat->location()->name), ] : null, 'reassignable' => (bool) $seat->license->reassignable, 'notes' => e($seat->notes), diff --git a/app/Http/Transformers/LicensesTransformer.php b/app/Http/Transformers/LicensesTransformer.php index b63a5725a461..4538aa4a3e88 100644 --- a/app/Http/Transformers/LicensesTransformer.php +++ b/app/Http/Transformers/LicensesTransformer.php @@ -16,7 +16,7 @@ public function transformLicenses(Collection $licenses, $total) $array[] = self::transformLicense($license); } - return (new DatatablesTransformer)->transformDatatables($array, $total); + return (new DatatablesTransformer())->transformDatatables($array, $total); } public function transformLicense(License $license) @@ -24,14 +24,14 @@ public function transformLicense(License $license) $array = [ 'id' => (int) $license->id, 'name' => e($license->name), - 'company' => ($license->company) ? ['id' => (int) $license->company->id, 'name'=> e($license->company->name)] : null, - 'manufacturer' => ($license->manufacturer) ? ['id' => (int) $license->manufacturer->id, 'name'=> e($license->manufacturer->name)] : null, + 'company' => ($license->company) ? ['id' => (int) $license->company->id, 'name' => e($license->company->name)] : null, + 'manufacturer' => ($license->manufacturer) ? ['id' => (int) $license->manufacturer->id, 'name' => e($license->manufacturer->name)] : null, 'product_key' => (Gate::allows('viewKeys', License::class)) ? e($license->serial) : '------------', 'order_number' => ($license->order_number) ? e($license->order_number) : null, 'purchase_order' => ($license->purchase_order) ? e($license->purchase_order) : null, 'purchase_date' => Helper::getFormattedDateObject($license->purchase_date, 'date'), 'termination_date' => Helper::getFormattedDateObject($license->termination_date, 'date'), - 'depreciation' => ($license->depreciation) ? ['id' => (int) $license->depreciation->id,'name'=> e($license->depreciation->name)] : null, + 'depreciation' => ($license->depreciation) ? ['id' => (int) $license->depreciation->id,'name' => e($license->depreciation->name)] : null, 'purchase_cost' => Helper::formatCurrencyOutput($license->purchase_cost), 'purchase_cost_numeric' => $license->purchase_cost, 'notes' => Helper::parseEscapedMarkedownInline($license->notes), @@ -44,11 +44,11 @@ public function transformLicense(License $license) 'license_email' => ($license->license_email) ? e($license->license_email) : null, 'reassignable' => ($license->reassignable == 1) ? true : false, 'maintained' => ($license->maintained == 1) ? true : false, - 'supplier' => ($license->supplier) ? ['id' => (int) $license->supplier->id, 'name'=> e($license->supplier->name)] : null, - 'category' => ($license->category) ? ['id' => (int) $license->category->id, 'name'=> e($license->category->name)] : null, + 'supplier' => ($license->supplier) ? ['id' => (int) $license->supplier->id, 'name' => e($license->supplier->name)] : null, + 'category' => ($license->category) ? ['id' => (int) $license->category->id, 'name' => e($license->category->name)] : null, 'created_by' => ($license->adminuser) ? [ 'id' => (int) $license->adminuser->id, - 'name'=> e($license->adminuser->present()->fullName()), + 'name' => e($license->adminuser->present()->fullName()), ] : null, 'created_at' => Helper::getFormattedDateObject($license->created_at, 'datetime'), 'updated_at' => Helper::getFormattedDateObject($license->updated_at, 'datetime'), @@ -72,9 +72,6 @@ public function transformLicense(License $license) public function transformAssetsDatatable($licenses) { - return (new DatatablesTransformer)->transformDatatables($licenses); + return (new DatatablesTransformer())->transformDatatables($licenses); } - - - } diff --git a/app/Http/Transformers/LocationsTransformer.php b/app/Http/Transformers/LocationsTransformer.php index b1553c69f47c..e5758763968f 100644 --- a/app/Http/Transformers/LocationsTransformer.php +++ b/app/Http/Transformers/LocationsTransformer.php @@ -19,7 +19,7 @@ public function transformLocations(Collection $locations, $total) $array[] = self::transformLocation($location); } - return (new DatatablesTransformer)->transformDatatables($array, $total); + return (new DatatablesTransformer())->transformDatatables($array, $total); } public function transformLocation(Location $location = null) @@ -38,15 +38,17 @@ public function transformLocation(Location $location = null) $array = [ 'id' => (int) $location->id, 'name' => e($location->name), - 'image' => ($location->image) ? Storage::disk('public')->url('locations/'.e($location->image)) : null, + 'image' => ($location->image) ? Storage::disk('public')->url('locations/' . e($location->image)) : null, 'address' => ($location->address) ? e($location->address) : null, 'address2' => ($location->address2) ? e($location->address2) : null, 'city' => ($location->city) ? e($location->city) : null, 'state' => ($location->state) ? e($location->state) : null, 'country' => ($location->country) ? e($location->country) : null, 'zip' => ($location->zip) ? e($location->zip) : null, - 'phone' => ($location->phone!='') ? e($location->phone): null, - 'fax' => ($location->fax!='') ? e($location->fax): null, + 'latitude' => ($location->latitude) ? e($location->latitude) : null, + 'longitude' => ($location->longitude) ? e($location->longitude) : null, + 'phone' => ($location->phone != '') ? e($location->phone) : null, + 'fax' => ($location->fax != '') ? e($location->fax) : null, 'accessories_count' => (int) $location->accessories_count, 'assigned_accessories_count' => (int) $location->assigned_accessories_count, 'assigned_assets_count' => (int) $location->assigned_assets_count, @@ -60,12 +62,12 @@ public function transformLocation(Location $location = null) 'updated_at' => Helper::getFormattedDateObject($location->updated_at, 'datetime'), 'parent' => ($location->parent) ? [ 'id' => (int) $location->parent->id, - 'name'=> e($location->parent->name), + 'name' => e($location->parent->name), ] : null, - 'manager' => ($location->manager) ? (new UsersTransformer)->transformUser($location->manager) : null, + 'manager' => ($location->manager) ? (new UsersTransformer())->transformUser($location->manager) : null, 'company' => ($location->company) ? [ 'id' => (int) $location->company->id, - 'name'=> e($location->company->name) + 'name' => e($location->company->name) ] : null, 'children' => $children_arr, @@ -95,7 +97,7 @@ public function transformCheckedoutAccessories($accessory_checkouts, $total) $array[] = self::transformCheckedoutAccessory($checkout); } - return (new DatatablesTransformer)->transformDatatables($array, $total); + return (new DatatablesTransformer())->transformDatatables($array, $total); } @@ -110,8 +112,8 @@ public function transformCheckedoutAccessory(AccessoryCheckout $accessory_checko 'note' => $accessory_checkout->note ? e($accessory_checkout->note) : null, 'created_by' => $accessory_checkout->adminuser ? [ 'id' => (int) $accessory_checkout->adminuser->id, - 'name'=> e($accessory_checkout->adminuser->present()->fullName), - ]: null, + 'name' => e($accessory_checkout->adminuser->present()->fullName), + ] : null, 'created_at' => Helper::getFormattedDateObject($accessory_checkout->created_at, 'datetime'), ]; @@ -121,7 +123,7 @@ public function transformCheckedoutAccessory(AccessoryCheckout $accessory_checko ]; $array += $permissions_array; - return $array; + return $array; } @@ -138,16 +140,15 @@ public function transformCheckedoutAccessory(AccessoryCheckout $accessory_checko public function transformLocationCompact(Location $location = null) { if ($location) { - $array = [ 'id' => (int) $location->id, - 'image' => ($location->image) ? Storage::disk('public')->url('locations/'.e($location->image)) : null, + 'image' => ($location->image) ? Storage::disk('public')->url('locations/' . e($location->image)) : null, 'type' => "location", 'name' => e($location->name), 'created_by' => $location->adminuser ? [ 'id' => (int) $location->adminuser->id, - 'name'=> e($location->adminuser->present()->fullName), - ]: null, + 'name' => e($location->adminuser->present()->fullName), + ] : null, 'created_at' => Helper::getFormattedDateObject($location->created_at, 'datetime'), ]; diff --git a/app/Http/Transformers/LoginAttemptsTransformer.php b/app/Http/Transformers/LoginAttemptsTransformer.php index cc1c512fbb67..b3e1a12dad0a 100644 --- a/app/Http/Transformers/LoginAttemptsTransformer.php +++ b/app/Http/Transformers/LoginAttemptsTransformer.php @@ -13,7 +13,7 @@ public function transformLoginAttempts($login_attempts, $total) $array[] = self::transformLoginAttempt($login_attempt); } - return (new DatatablesTransformer)->transformDatatables($array, $total); + return (new DatatablesTransformer())->transformDatatables($array, $total); } public function transformLoginAttempt($login_attempt) diff --git a/app/Http/Transformers/ManufacturersTransformer.php b/app/Http/Transformers/ManufacturersTransformer.php index cf17eb77646a..e607738149f8 100644 --- a/app/Http/Transformers/ManufacturersTransformer.php +++ b/app/Http/Transformers/ManufacturersTransformer.php @@ -17,7 +17,7 @@ public function transformManufacturers(Collection $manufacturers, $total) $array[] = self::transformManufacturer($manufacturer); } - return (new DatatablesTransformer)->transformDatatables($array, $total); + return (new DatatablesTransformer())->transformDatatables($array, $total); } public function transformManufacturer(Manufacturer $manufacturer = null) @@ -27,7 +27,7 @@ public function transformManufacturer(Manufacturer $manufacturer = null) 'id' => (int) $manufacturer->id, 'name' => e($manufacturer->name), 'url' => e($manufacturer->url), - 'image' => ($manufacturer->image) ? Storage::disk('public')->url('manufacturers/'.e($manufacturer->image)) : null, + 'image' => ($manufacturer->image) ? Storage::disk('public')->url('manufacturers/' . e($manufacturer->image)) : null, 'support_url' => e($manufacturer->support_url), 'warranty_lookup_url' => e($manufacturer->warranty_lookup_url), 'support_phone' => e($manufacturer->support_phone), @@ -40,7 +40,7 @@ public function transformManufacturer(Manufacturer $manufacturer = null) 'notes' => Helper::parseEscapedMarkedownInline($manufacturer->notes), 'created_by' => ($manufacturer->adminuser) ? [ 'id' => (int) $manufacturer->adminuser->id, - 'name'=> e($manufacturer->adminuser->present()->fullName()), + 'name' => e($manufacturer->adminuser->present()->fullName()), ] : null, 'created_at' => Helper::getFormattedDateObject($manufacturer->created_at, 'datetime'), 'updated_at' => Helper::getFormattedDateObject($manufacturer->updated_at, 'datetime'), diff --git a/app/Http/Transformers/PieChartTransformer.php b/app/Http/Transformers/PieChartTransformer.php index e5f48644a582..a125f6eeeb5f 100644 --- a/app/Http/Transformers/PieChartTransformer.php +++ b/app/Http/Transformers/PieChartTransformer.php @@ -2,8 +2,8 @@ namespace App\Http\Transformers; - use App\Helpers\Helper; + /** * Class PieChartTransformer * @@ -25,10 +25,8 @@ public function transformPieChartDate($totals) $colors_array = []; foreach ($totals as $total) { - if ($total['count'] > 0) { - - $labels[] = $total['label']." (".$total['count'].")"; + $labels[] = $total['label'] . " (" . $total['count'] . ")"; $counts[] = $total['count']; if (isset($total['color'])) { diff --git a/app/Http/Transformers/PredefinedKitsTransformer.php b/app/Http/Transformers/PredefinedKitsTransformer.php index 61c9e476a99d..afb5a35662b8 100644 --- a/app/Http/Transformers/PredefinedKitsTransformer.php +++ b/app/Http/Transformers/PredefinedKitsTransformer.php @@ -24,7 +24,7 @@ public function transformPredefinedKits(Collection $kits, $total) $array[] = self::transformPredefinedKit($kit); } - return (new DatatablesTransformer)->transformDatatables($array, $total); + return (new DatatablesTransformer())->transformDatatables($array, $total); } public function transformPredefinedKit(PredefinedKit $kit) @@ -34,7 +34,7 @@ public function transformPredefinedKit(PredefinedKit $kit) 'name' => e($kit->name), 'created_by' => ($kit->adminuser) ? [ 'id' => (int) $kit->adminuser->id, - 'name'=> e($kit->adminuser->present()->fullName()), + 'name' => e($kit->adminuser->present()->fullName()), ] : null, 'created_at' => Helper::getFormattedDateObject($kit->created_at, 'datetime'), 'updated_at' => Helper::getFormattedDateObject($kit->updated_at, 'datetime'), @@ -54,7 +54,7 @@ public function transformPredefinedKit(PredefinedKit $kit) } /** - * transform collection of any elemets attached to kit + * transform collection of any elements attached to kit * @return array */ public function transformElements(Collection $elements, $total) @@ -64,7 +64,7 @@ public function transformElements(Collection $elements, $total) $array[] = self::transformElement($element); } - return (new DatatablesTransformer)->transformDatatables($array, $total); + return (new DatatablesTransformer())->transformDatatables($array, $total); } public function transformElement(SnipeModel $element) @@ -89,6 +89,6 @@ public function transformElement(SnipeModel $element) public function transformPredefinedKitsDatatable($kits) { - return (new DatatablesTransformer)->transformDatatables($kits); + return (new DatatablesTransformer())->transformDatatables($kits); } } diff --git a/app/Http/Transformers/StatuslabelsTransformer.php b/app/Http/Transformers/StatuslabelsTransformer.php index 751edb7016b1..98d2b393ee6f 100644 --- a/app/Http/Transformers/StatuslabelsTransformer.php +++ b/app/Http/Transformers/StatuslabelsTransformer.php @@ -16,7 +16,7 @@ public function transformStatuslabels(Collection $statuslabels, $total) $array[] = self::transformStatuslabel($statuslabel); } - return (new DatatablesTransformer)->transformDatatables($array, $total); + return (new DatatablesTransformer())->transformDatatables($array, $total); } public function transformStatuslabel(Statuslabel $statuslabel) @@ -32,7 +32,7 @@ public function transformStatuslabel(Statuslabel $statuslabel) 'notes' => e($statuslabel->notes), 'created_by' => ($statuslabel->adminuser) ? [ 'id' => (int) $statuslabel->adminuser->id, - 'name'=> e($statuslabel->adminuser->present()->fullName()), + 'name' => e($statuslabel->adminuser->present()->fullName()), ] : null, 'created_at' => Helper::getFormattedDateObject($statuslabel->created_at, 'datetime'), 'updated_at' => Helper::getFormattedDateObject($statuslabel->updated_at, 'datetime'), diff --git a/app/Http/Transformers/SuppliersTransformer.php b/app/Http/Transformers/SuppliersTransformer.php index 1fdc93c193b8..cde9f1436a38 100644 --- a/app/Http/Transformers/SuppliersTransformer.php +++ b/app/Http/Transformers/SuppliersTransformer.php @@ -17,7 +17,7 @@ public function transformSuppliers(Collection $suppliers, $total) $array[] = self::transformSupplier($supplier); } - return (new DatatablesTransformer)->transformDatatables($array, $total); + return (new DatatablesTransformer())->transformDatatables($array, $total); } public function transformSupplier(Supplier $supplier = null) @@ -26,7 +26,7 @@ public function transformSupplier(Supplier $supplier = null) $array = [ 'id' => (int) $supplier->id, 'name' => e($supplier->name), - 'image' => ($supplier->image) ? Storage::disk('public')->url('suppliers/'.e($supplier->image)) : null, + 'image' => ($supplier->image) ? Storage::disk('public')->url('suppliers/' . e($supplier->image)) : null, 'url' => e($supplier->url), 'address' => e($supplier->address), 'address2' => e($supplier->address2), @@ -34,6 +34,8 @@ public function transformSupplier(Supplier $supplier = null) 'state' => e($supplier->state), 'country' => e($supplier->country), 'zip' => e($supplier->zip), + 'latitude' => e($supplier->latitude), + 'longitude' => e($supplier->longitude), 'fax' => e($supplier->fax), 'phone' => e($supplier->phone), 'email' => e($supplier->email), diff --git a/app/Http/Transformers/UploadedFilesTransformer.php b/app/Http/Transformers/UploadedFilesTransformer.php index a18c9f9b65e5..d4f5ebd57d22 100644 --- a/app/Http/Transformers/UploadedFilesTransformer.php +++ b/app/Http/Transformers/UploadedFilesTransformer.php @@ -18,7 +18,7 @@ public function transformFiles(Collection $files, $total) $array[] = self::transformFile($file); } - return (new DatatablesTransformer)->transformDatatables($array, $total); + return (new DatatablesTransformer())->transformDatatables($array, $total); } @@ -38,7 +38,7 @@ public function transformFile(Actionlog $file) 'url' => $file_url, 'created_by' => ($file->adminuser) ? [ 'id' => (int) $file->adminuser->id, - 'name'=> e($file->adminuser->present()->fullName), + 'name' => e($file->adminuser->present()->fullName), ] : null, 'created_at' => Helper::getFormattedDateObject($file->created_at, 'datetime'), 'updated_at' => Helper::getFormattedDateObject($file->updated_at, 'datetime'), @@ -52,5 +52,4 @@ public function transformFile(Actionlog $file) $array += $permissions_array; return $array; } - } diff --git a/app/Http/Transformers/UsersTransformer.php b/app/Http/Transformers/UsersTransformer.php index 3bf3ee970265..f8b92344ad19 100644 --- a/app/Http/Transformers/UsersTransformer.php +++ b/app/Http/Transformers/UsersTransformer.php @@ -16,7 +16,7 @@ public function transformUsers(Collection $users, $total) $array[] = self::transformUser($user); } - return (new DatatablesTransformer)->transformDatatables($array, $total); + return (new DatatablesTransformer())->transformDatatables($array, $total); } public function transformUser(User $user) @@ -34,7 +34,7 @@ public function transformUser(User $user) 'employee_num' => ($user->employee_num) ? e($user->employee_num) : null, 'manager' => ($user->manager) ? [ 'id' => (int) $user->manager->id, - 'name'=> e($user->manager->first_name).' '.e($user->manager->last_name), + 'name' => e($user->manager->first_name) . ' ' . e($user->manager->last_name), ] : null, 'jobtitle' => ($user->jobtitle) ? e($user->jobtitle) : null, 'vip' => ($user->vip == '1') ? true : false, @@ -48,13 +48,13 @@ public function transformUser(User $user) 'email' => ($user->email) ? e($user->email) : null, 'department' => ($user->department) ? [ 'id' => (int) $user->department->id, - 'name'=> e($user->department->name), + 'name' => e($user->department->name), ] : null, 'location' => ($user->userloc) ? [ 'id' => (int) $user->userloc->id, - 'name'=> e($user->userloc->name), + 'name' => e($user->userloc->name), ] : null, - 'notes'=> Helper::parseEscapedMarkedownInline($user->notes), + 'notes' => Helper::parseEscapedMarkedownInline($user->notes), 'permissions' => $user->decodePermissions(), 'activated' => ($user->activated == '1') ? true : false, 'autoassign_licenses' => ($user->autoassign_licenses == '1') ? true : false, @@ -67,10 +67,10 @@ public function transformUser(User $user) 'consumables_count' => (int) $user->consumables_count, 'manages_users_count' => (int) $user->manages_users_count, 'manages_locations_count' => (int) $user->manages_locations_count, - 'company' => ($user->company) ? ['id' => (int) $user->company->id, 'name'=> e($user->company->name)] : null, + 'company' => ($user->company) ? ['id' => (int) $user->company->id, 'name' => e($user->company->name)] : null, 'created_by' => ($user->createdBy) ? [ 'id' => (int) $user->createdBy->id, - 'name'=> e($user->createdBy->present()->fullName), + 'name' => e($user->createdBy->present()->fullName), ] : null, 'created_at' => Helper::getFormattedDateObject($user->created_at, 'datetime'), 'updated_at' => Helper::getFormattedDateObject($user->updated_at, 'datetime'), @@ -115,7 +115,7 @@ public function transformUser(User $user) * @return array * @throws \Exception */ - public function transformUserCompact(User $user) : array + public function transformUserCompact(User $user): array { $array = [ @@ -128,8 +128,8 @@ public function transformUserCompact(User $user) : array 'username' => e($user->username), 'created_by' => $user->adminuser ? [ 'id' => (int) $user->adminuser->id, - 'name'=> e($user->adminuser->present()->fullName), - ]: null, + 'name' => e($user->adminuser->present()->fullName), + ] : null, 'created_at' => Helper::getFormattedDateObject($user->created_at, 'datetime'), 'deleted_at' => ($user->deleted_at) ? Helper::getFormattedDateObject($user->deleted_at, 'datetime') : null, ]; @@ -139,6 +139,6 @@ public function transformUserCompact(User $user) : array public function transformUsersDatatable($users) { - return (new DatatablesTransformer)->transformDatatables($users); + return (new DatatablesTransformer())->transformDatatables($users); } } diff --git a/app/Importer/AccessoryImporter.php b/app/Importer/AccessoryImporter.php index bc9c1909ff42..44019487d516 100644 --- a/app/Importer/AccessoryImporter.php +++ b/app/Importer/AccessoryImporter.php @@ -28,7 +28,7 @@ public function createAccessoryIfNotExists($row) $accessory = Accessory::where('name', $this->item['name'])->first(); if ($accessory) { if (! $this->updating) { - $this->log('A matching Accessory '.$this->item['name'].' already exists. '); + $this->log('A matching Accessory ' . $this->item['name'] . ' already exists. '); return; } @@ -50,7 +50,7 @@ public function createAccessoryIfNotExists($row) // This sets an attribute on the Loggable trait for the action log $accessory->setImported(true); if ($accessory->save()) { - $this->log('Accessory '.$this->item['name'].' was created'); + $this->log('Accessory ' . $this->item['name'] . ' was created'); return; } diff --git a/app/Importer/AssetImporter.php b/app/Importer/AssetImporter.php index ad690280553e..3d54aca1cdc3 100644 --- a/app/Importer/AssetImporter.php +++ b/app/Importer/AssetImporter.php @@ -47,10 +47,10 @@ protected function handle($row) if ($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)); + $this->log('Custom Field ' . $customField->name . ': ' . Crypt::encrypt($customFieldValue)); } else { $this->item['custom_fields'][$customField->db_column_name()] = $customFieldValue; - $this->log('Custom Field '.$customField->name.': '.$customFieldValue); + $this->log('Custom Field ' . $customField->name . ': ' . $customFieldValue); } } else { // Clear out previous data. @@ -76,11 +76,11 @@ public function createAssetIfNotExists(array $row) $editingAsset = false; $asset_tag = $this->findCsvMatch($row, 'asset_tag'); - if (empty($asset_tag)){ + if (empty($asset_tag)) { $asset_tag = Asset::autoincrement_asset(); } - $asset = Asset::where(['asset_tag'=> (string) $asset_tag])->first(); + $asset = Asset::where(['asset_tag' => (string) $asset_tag])->first(); if ($asset) { if (! $this->updating) { $exists_error = trans('general.import_asset_tag_exists', ['asset_tag' => $asset_tag]); @@ -93,7 +93,7 @@ public function createAssetIfNotExists(array $row) $editingAsset = true; } else { $this->log('No Matching Asset, Creating a new one'); - $asset = new Asset; + $asset = new Asset(); } // If no status ID is found @@ -137,7 +137,7 @@ public function createAssetIfNotExists(array $row) * 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']; } @@ -146,24 +146,24 @@ public function createAssetIfNotExists(array $row) * 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'); } @@ -185,26 +185,23 @@ public function createAssetIfNotExists(array $row) $asset->setImported(true); if ($asset->save()) { - - $this->log('Asset '.$this->item['name'].' with serial number '.$this->item['serial'].' was created'); + $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). 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, User::find($asset->assigned_to), 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'].'"'); + $this->logError($asset, 'Asset "' . $this->item['name'] . '"'); } - - } diff --git a/app/Importer/AssetModelImporter.php b/app/Importer/AssetModelImporter.php index 7cfd8a530dbb..dbac3c36495a 100644 --- a/app/Importer/AssetModelImporter.php +++ b/app/Importer/AssetModelImporter.php @@ -44,7 +44,7 @@ public function createAssetModelIfNotExists(array $row) if ($assetModel) { if (! $this->updating) { - $this->log('A matching Model '.$this->item['name'].' already exists'); + $this->log('A matching Model ' . $this->item['name'] . ' already exists'); return; } @@ -104,15 +104,13 @@ public function createAssetModelIfNotExists(array $row) } if ($assetModel->save()) { - $this->log('AssetModel '.$assetModel->name.' created or updated from CSV import'); + $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(); } - } @@ -127,12 +125,11 @@ public function createAssetModelIfNotExists(array $row) * @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'); + $this->log('A matching Depreciation ' . $depreciation_name . ' already exists'); return $depreciation->id; } } @@ -148,13 +145,13 @@ public function fetchDepreciation($depreciation_name) : ?int * @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'); + $this->log('A matching fieldset ' . $fieldset_name . ' already exists'); return $fieldset->id; } @@ -162,7 +159,7 @@ public function createOrFetchCustomFieldset($fieldset_name) : ?int $fieldset->name = $fieldset_name; if ($fieldset->save()) { - $this->log('Fieldset '.$fieldset_name.' was created'); + $this->log('Fieldset ' . $fieldset_name . ' was created'); return $fieldset->id; } @@ -171,4 +168,4 @@ public function createOrFetchCustomFieldset($fieldset_name) : ?int return null; } -} \ No newline at end of file +} diff --git a/app/Importer/ComponentImporter.php b/app/Importer/ComponentImporter.php index 3979ba499d29..4b239928e4e0 100644 --- a/app/Importer/ComponentImporter.php +++ b/app/Importer/ComponentImporter.php @@ -22,7 +22,7 @@ protected function handle($row) * Create a component if a duplicate does not exist * * @author Daniel Melzter - * @since 3.0 + * @since 3.0 */ public function createComponentIfNotExists() { @@ -33,7 +33,7 @@ public function createComponentIfNotExists() ->first(); if ($component) { - $this->log('A matching Component '.$this->item['name'].' with serial '.$this->item['serial'].' already exists. '); + $this->log('A matching Component ' . $this->item['name'] . ' with serial ' . $this->item['serial'] . ' already exists. '); if (! $this->updating) { $this->log('Skipping Component'); @@ -46,14 +46,14 @@ public function createComponentIfNotExists() return; } $this->log('No matching component, creating one'); - $component = new Component; + $component = new Component(); $component->created_by = auth()->id(); $component->fill($this->sanitizeItemForStoring($component)); // This sets an attribute on the Loggable trait for the action log $component->setImported(true); if ($component->save()) { - $this->log('Component '.$this->item['name'].' was created'); + $this->log('Component ' . $this->item['name'] . ' was created'); // If we have an asset tag, checkout to that asset. if (isset($this->item['asset_tag']) && ($asset = Asset::where('asset_tag', $this->item['asset_tag'])->first())) { diff --git a/app/Importer/ConsumableImporter.php b/app/Importer/ConsumableImporter.php index 40c597e89664..92dd6a6cf1a3 100644 --- a/app/Importer/ConsumableImporter.php +++ b/app/Importer/ConsumableImporter.php @@ -28,9 +28,8 @@ public function createConsumableIfNotExists($row) { $consumable = Consumable::where('name', trim($this->item['name']))->first(); if ($consumable) { - if (! $this->updating) { - $this->log('A matching Consumable '.$this->item['name'].' already exists. '); + $this->log('A matching Consumable ' . $this->item['name'] . ' already exists. '); return; } $this->log('Updating Consumable'); @@ -48,7 +47,7 @@ public function createConsumableIfNotExists($row) // This sets an attribute on the Loggable trait for the action log $consumable->setImported(true); if ($consumable->save()) { - $this->log('Consumable '.$this->item['name'].' was created'); + $this->log('Consumable ' . $this->item['name'] . ' was created'); return; } diff --git a/app/Importer/Importer.php b/app/Importer/Importer.php index 0d4b8d493290..ffd2b99760c3 100644 --- a/app/Importer/Importer.php +++ b/app/Importer/Importer.php @@ -170,7 +170,7 @@ public function import() $this->log('------------- Action Summary ----------------'); } - Model::reguard(); + Model::reguard(); # codespell:ignore }); } @@ -272,7 +272,7 @@ protected function logError($item, $field) } } - 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]]); @@ -299,8 +299,8 @@ protected function createOrFetchUser($row, $type = 'user') 'first_name' => $this->findCsvMatch($row, 'first_name'), 'last_name' => $this->findCsvMatch($row, 'last_name'), 'email' => $this->findCsvMatch($row, 'email'), - 'manager_id'=> '', - 'department_id' => '', + 'manager_id' => '', + 'department_id' => '', 'username' => $this->findCsvMatch($row, 'username'), 'activated' => $this->fetchHumanBoolean($this->findCsvMatch($row, 'activated')), 'remote' => $this->fetchHumanBoolean(($this->findCsvMatch($row, 'remote'))), @@ -314,7 +314,7 @@ protected function createOrFetchUser($row, $type = 'user') // Maybe we're lucky and the username was passed and it already exists. if (!empty($user_array['username'])) { if ($user = User::where('username', $user_array['username'])->first()) { - $this->log('User '.$user_array['username'].' already exists'); + $this->log('User ' . $user_array['username'] . ' already exists'); return $user; } } @@ -352,7 +352,7 @@ protected function createOrFetchUser($row, $type = 'user') // 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'); + $this->log('User ' . $user_array['username'] . ' already exists'); return $user; } } @@ -363,7 +363,7 @@ protected function createOrFetchUser($row, $type = 'user') } // No luck finding a user on username or first name, let's create one. - $user = new User; + $user = new User(); $user->first_name = $user_array['first_name']; $user->last_name = $user_array['last_name']; @@ -374,14 +374,14 @@ protected function createOrFetchUser($row, $type = 'user') $user->activated = 1; $user->password = $this->tempPassword; - Log::debug('Creating a user with the following attributes: '.print_r($user_array, true)); + Log::debug('Creating a user with the following attributes: ' . print_r($user_array, true)); if ($user->save()) { - $this->log('User '.$user_array['username'].' created'); + $this->log('User ' . $user_array['username'] . ' created'); return $user; } - $this->logError($user, 'User "'.$user_array['username'].'" was not able to be created.'); + $this->logError($user, 'User "' . $user_array['username'] . '" was not able to be created.'); return false; } @@ -395,7 +395,7 @@ protected function findUserByNumber($user_name) { // A number was given instead of a name if (is_numeric($user_name)) { - $this->log('User '.$user_name.' is a number - lets see if it matches a user id'); + $this->log('User ' . $user_name . ' is a number - lets see if it matches a user id'); return User::find($user_name); } @@ -521,7 +521,7 @@ public function createOrFetchDepartment($user_department_name) $department = Department::where('name', '=', $user_department_name)->first(); if ($department) { - $this->log('A matching Department '.$user_department_name.' already exists'); + $this->log('A matching Department ' . $user_department_name . ' already exists'); return $department->id; } @@ -530,7 +530,7 @@ public function createOrFetchDepartment($user_department_name) $department->name = $user_department_name; if ($department->save()) { - $this->log('Department '.$user_department_name.' was created'); + $this->log('Department ' . $user_department_name . ' was created'); return $department->id; } @@ -554,11 +554,11 @@ public function fetchManager($user_manager_first_name, $user_manager_last_name) $manager = User::where('first_name', '=', $user_manager_first_name) ->where('last_name', '=', $user_manager_last_name)->first(); if ($manager) { - $this->log('A matching Manager '.$user_manager_first_name.' '.$user_manager_last_name.' already exists'); + $this->log('A matching Manager ' . $user_manager_first_name . ' ' . $user_manager_last_name . ' already exists'); return $manager->id; } - $this->log('No matching Manager '.$user_manager_first_name.' '.$user_manager_last_name.' found. If their user account is being created through this import, you should re-process this file again. '); + $this->log('No matching Manager ' . $user_manager_first_name . ' ' . $user_manager_last_name . ' found. If their user account is being created through this import, you should re-process this file again. '); return null; } @@ -573,8 +573,8 @@ public function fetchManager($user_manager_first_name, $user_manager_last_name) * @return string|null */ - public function parseOrNullDate($field, $format = 'date') { - + public function parseOrNullDate($field, $format = 'date') + { $date_format = 'Y-m-d'; if ($format == 'datetime') { @@ -582,7 +582,6 @@ public function parseOrNullDate($field, $format = 'date') { } if (array_key_exists($field, $this->item) && $this->item[$field] != '') { - try { $value = CarbonImmutable::parse($this->item[$field])->format($date_format); return $value; diff --git a/app/Importer/ItemImporter.php b/app/Importer/ItemImporter.php index dfcd644c9d0f..b43b6f11ca76 100644 --- a/app/Importer/ItemImporter.php +++ b/app/Importer/ItemImporter.php @@ -114,7 +114,7 @@ protected function determineCheckout($row) 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'))); } @@ -221,7 +221,6 @@ public function createOrFetchAssetModel(array $row) $asset_model = $asset_model->first(); if ($asset_model) { - if (! $this->updating) { $this->log('A matching model already exists, returning it.'); return $asset_model->id; @@ -232,16 +231,15 @@ public function createOrFetchAssetModel(array $row) $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; + return $asset_model->id; } $this->log('No Matching Model, Creating a new one'); @@ -257,12 +255,12 @@ public function createOrFetchAssetModel(array $row) $item = null; if ($asset_model->save()) { - $this->log('Asset Model '.$asset_model_name.' with model number '.$asset_modelNumber.' was created'); + $this->log('Asset Model ' . $asset_model_name . ' with model number ' . $asset_modelNumber . ' was created'); return $asset_model->id; } - $this->log('Asset Model Errors: '.$asset_model->getErrors()); - $this->logError($asset_model, 'Asset Model "'.$asset_model_name.'"'); + $this->log('Asset Model Errors: ' . $asset_model->getErrors()); + $this->logError($asset_model, 'Asset Model "' . $asset_model_name . '"'); return null; } @@ -296,7 +294,7 @@ public function createOrFetchCategory($asset_category) if ($category) { - $this->log('A matching category: '.$category->name.' already exists'); + $this->log('A matching category: ' . $category->name . ' already exists'); return $category->id; } @@ -306,11 +304,11 @@ public function createOrFetchCategory($asset_category) $category->category_type = $item_type; if ($category->save()) { - $this->log('Category '.$asset_category.' was created'); + $this->log('Category ' . $asset_category . ' was created'); return $category->id; } - $this->logError($category, 'Category "'. $asset_category. '"'); + $this->logError($category, 'Category "' . $asset_category . '"'); return null; } @@ -327,7 +325,7 @@ public function createOrFetchCompany($asset_company_name) { $company = Company::where(['name' => $asset_company_name])->first(); if ($company) { - $this->log('A matching Company '.$asset_company_name.' already exists'); + $this->log('A matching Company ' . $asset_company_name . ' already exists'); return $company->id; } @@ -336,7 +334,7 @@ public function createOrFetchCompany($asset_company_name) $company->name = $asset_company_name; if ($company->save()) { - $this->log('Company '.$asset_company_name.' was created'); + $this->log('Company ' . $asset_company_name . ' was created'); return $company->id; } @@ -358,11 +356,11 @@ public function fetchManager($user_manager_first_name, $user_manager_last_name) $manager = User::where('first_name', '=', $user_manager_first_name) ->where('last_name', '=', $user_manager_last_name)->first(); if ($manager) { - $this->log('A matching Manager '.$user_manager_first_name.' '.$user_manager_last_name.' already exists'); + $this->log('A matching Manager ' . $user_manager_first_name . ' ' . $user_manager_last_name . ' already exists'); return $manager->id; } - $this->log('No matching Manager '.$user_manager_first_name.' '.$user_manager_last_name.' found. If their user account is being created through this import, you should re-process this file again. '); + $this->log('No matching Manager ' . $user_manager_first_name . ' ' . $user_manager_last_name . ' found. If their user account is being created through this import, you should re-process this file again. '); return null; } @@ -380,10 +378,10 @@ public function createOrFetchStatusLabel($asset_statuslabel_name) 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'); + $this->log('A matching Status ' . $asset_statuslabel_name . ' already exists'); return $status->id; } @@ -397,11 +395,11 @@ public function createOrFetchStatusLabel($asset_statuslabel_name) $status->archived = 0; if ($status->save()) { - $this->log('Status '.$asset_statuslabel_name.' was created'); + $this->log('Status ' . $asset_statuslabel_name . ' was created'); return $status->id; } - $this->logError($status, 'Status "'.$asset_statuslabel_name.'"'); + $this->logError($status, 'Status "' . $asset_statuslabel_name . '"'); return null; } @@ -418,10 +416,10 @@ public function createOrFetchManufacturer($item_manufacturer) 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'); + $this->log('Manufacturer ' . $item_manufacturer . ' already exists'); return $manufacturer->id; } @@ -432,11 +430,11 @@ public function createOrFetchManufacturer($item_manufacturer) $manufacturer->created_by = auth()->id(); if ($manufacturer->save()) { - $this->log('Manufacturer '.$manufacturer->name.' was created'); + $this->log('Manufacturer ' . $manufacturer->name . ' was created'); return $manufacturer->id; } - $this->logError($manufacturer, 'Manufacturer "'.$manufacturer->name.'"'); + $this->logError($manufacturer, 'Manufacturer "' . $manufacturer->name . '"'); return null; } @@ -459,7 +457,7 @@ public function createOrFetchLocation($asset_location) $location = Location::where(['name' => $asset_location])->first(); if ($location) { - $this->log('Location '.$asset_location.' already exists'); + $this->log('Location ' . $asset_location . ' already exists'); return $location->id; } // No matching locations in the collection, create a new one. @@ -472,7 +470,7 @@ public function createOrFetchLocation($asset_location) $location->created_by = auth()->id(); if ($location->save()) { - $this->log('Location '.$asset_location.' was created'); + $this->log('Location ' . $asset_location . ' was created'); return $location->id; } @@ -498,7 +496,7 @@ public function createOrFetchSupplier($item_supplier) $supplier = Supplier::where(['name' => $item_supplier])->first(); if ($supplier) { - $this->log('Supplier '.$item_supplier.' already exists'); + $this->log('Supplier ' . $item_supplier . ' already exists'); return $supplier->id; } @@ -508,12 +506,11 @@ public function createOrFetchSupplier($item_supplier) $supplier->created_by = auth()->id(); if ($supplier->save()) { - $this->log('Supplier '.$item_supplier.' was created'); + $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 d5df4aba3c59..dc76d21a031f 100644 --- a/app/Importer/LicenseImporter.php +++ b/app/Importer/LicenseImporter.php @@ -29,7 +29,6 @@ protected function handle($row) * @return License|mixed|null * updated @author Jes Vinsmoke * @since 6.1 - * */ public function createLicenseIfNotExists(array $row) { @@ -37,12 +36,10 @@ public function createLicenseIfNotExists(array $row) $license = License::where('serial', $this->item['serial'])->where('name', $this->item['name']) ->first(); if ($license) { - if (! $this->updating) { - - if($this->item['serial'] != "") { + if (!$this->updating) { + if ($this->item['serial'] != "") { $this->log('A matching License ' . $this->item['name'] . ' with serial ' . $this->item['serial'] . ' already exists'); - } - else { + } else { $this->log('A matching License ' . $this->item['name'] . ' with no serial number already exists'); } @@ -53,12 +50,12 @@ public function createLicenseIfNotExists(array $row) $editingLicense = true; } else { $this->log('No Matching License, Creating a new one'); - $license = new License; + $license = new License(); } $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")!='') { + 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')); @@ -70,14 +67,13 @@ public function createLicenseIfNotExists(array $row) $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")!='') { + if ($this->findCsvMatch($row, "termination_date") != '') { $this->item["termination_date"] = date("Y-m-d 00:00:01", strtotime($this->findCsvMatch($row, "termination_date"))); } @@ -91,7 +87,7 @@ public function createLicenseIfNotExists(array $row) // This sets an attribute on the Loggable trait for the action log $license->setImported(true); if ($license->save()) { - $this->log('License '.$this->item['name'].' with serial number '.$this->item['serial'].' was created'); + $this->log('License ' . $this->item['name'] . ' with serial number ' . $this->item['serial'] . ' was created'); // Lets try to checkout seats if the fields exist and we have seats. if ($license->seats > 0) { @@ -99,7 +95,7 @@ public function createLicenseIfNotExists(array $row) $asset = Asset::where('asset_tag', $asset_tag)->first(); $targetLicense = $license->freeSeat(); - if (is_null($targetLicense)){ + if (is_null($targetLicense)) { return; } @@ -119,6 +115,6 @@ public function createLicenseIfNotExists(array $row) return; } - $this->logError($license, 'License "'.$this->item['name'].'"'); + $this->logError($license, 'License "' . $this->item['name'] . '"'); } } diff --git a/app/Importer/LocationImporter.php b/app/Importer/LocationImporter.php index 1fcef6625d42..49125b17be87 100644 --- a/app/Importer/LocationImporter.php +++ b/app/Importer/LocationImporter.php @@ -41,16 +41,16 @@ public function createLocationIfNotExists(array $row) $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')); + \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'); + $this->log('A matching Location ' . $this->item['name'] . ' already exists'); return; } @@ -58,7 +58,7 @@ public function createLocationIfNotExists(array $row) $editingLocation = true; } else { $this->log('No Matching Location, Create a new one'); - $location = new Location; + $location = new Location(); $location->created_by = auth()->id(); } @@ -70,6 +70,8 @@ public function createLocationIfNotExists(array $row) $this->item['state'] = trim($this->findCsvMatch($row, 'state')); $this->item['country'] = trim($this->findCsvMatch($row, 'country')); $this->item['zip'] = trim($this->findCsvMatch($row, 'zip')); + $this->item['latitude'] = trim($this->findCsvMatch($row, 'latitude')); + $this->item['longitude'] = trim($this->findCsvMatch($row, 'longitude')); $this->item['currency'] = trim($this->findCsvMatch($row, 'currency')); $this->item['ldap_ou'] = trim($this->findCsvMatch($row, 'ldap_ou')); $this->item['manager'] = trim($this->findCsvMatch($row, 'manager')); @@ -100,15 +102,12 @@ public function createLocationIfNotExists(array $row) } if ($location->save()) { - $this->log('Location '.$location->name.' created or updated from CSV import'); + $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'].'"'); + $this->logError($location, 'Location "' . $this->item['name'] . '"'); return $location->errors; } - - } -} \ No newline at end of file +} diff --git a/app/Importer/UserImporter.php b/app/Importer/UserImporter.php index 77317b3d09db..2227f7c72a0b 100644 --- a/app/Importer/UserImporter.php +++ b/app/Importer/UserImporter.php @@ -64,8 +64,8 @@ public function createUserIfNotExists(array $row) $this->item['department_id'] = trim($this->createOrFetchDepartment(trim($this->findCsvMatch($row, 'department')))); $this->item['manager_id'] = $this->fetchManager(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['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(); @@ -81,16 +81,15 @@ public function createUserIfNotExists(array $row) } // 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(); } if ($user) { - if (! $this->updating) { - Log::debug('A matching User '.$this->item['name'].' already exists. '); + Log::debug('A matching User ' . $this->item['name'] . ' already exists. '); return; } $this->log('Updating User'); @@ -101,7 +100,7 @@ public function createUserIfNotExists(array $row) 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; } @@ -118,7 +117,7 @@ public function createUserIfNotExists(array $row) $user->fill($this->sanitizeItemForStoring($user)); if ($user->save()) { - $this->log('User '.$this->item['name'].' was created'); + $this->log('User ' . $this->item['name'] . ' was created'); if (($user->email) && ($user->activated == '1')) { $data = [ @@ -153,7 +152,7 @@ public function createUserIfNotExists(array $row) */ public function createOrFetchDepartment($department_name) { - if (is_null($department_name) || $department_name == ''){ + if (is_null($department_name) || $department_name == '') { return null; } @@ -176,7 +175,7 @@ public function createOrFetchDepartment($department_name) $this->logError($department, 'Department'); return null; } - + public function sendWelcome($send = true) { $this->send_welcome = $send; diff --git a/app/Jobs/Job.php b/app/Jobs/Job.php index 55ece29acb3d..19aae400b403 100644 --- a/app/Jobs/Job.php +++ b/app/Jobs/Job.php @@ -16,6 +16,5 @@ abstract class Job | provides access to the "onQueue" and "delay" queue helper methods. | */ - use Queueable; } diff --git a/app/Listeners/LogListener.php b/app/Listeners/LogListener.php index d7973e2103e7..8f0e84ea3375 100644 --- a/app/Listeners/LogListener.php +++ b/app/Listeners/LogListener.php @@ -105,7 +105,7 @@ public function onUserMerged(UserMerged $event) ]; // Add a record to the users being merged FROM - Log::debug('Users merged: '.$event->merged_from->id .' ('.$event->merged_from->username.') merged into '. $event->merged_to->id. ' ('.$event->merged_to->username.')'); + Log::debug('Users merged: ' . $event->merged_from->id . ' (' . $event->merged_from->username . ') merged into ' . $event->merged_to->id . ' (' . $event->merged_to->username . ')'); $logaction = new Actionlog(); $logaction->item_id = $event->merged_from->id; $logaction->item_type = User::class; @@ -126,8 +126,6 @@ public function onUserMerged(UserMerged $event) $logaction->note = trans('general.merged_log_this_user_into', $to_from_array); $logaction->created_by = $event->admin->id ?? null; $logaction->save(); - - } /** @@ -148,11 +146,9 @@ public function subscribe($events) foreach ($list as $event) { $events->listen( - 'App\Events\\'.$event, - 'App\Listeners\LogListener@on'.$event + 'App\Events\\' . $event, + 'App\Listeners\LogListener@on' . $event ); } } - - } diff --git a/app/Listeners/LogSuccessfulLogin.php b/app/Listeners/LogSuccessfulLogin.php index d6d9c618f28b..38d4a44db3c6 100644 --- a/app/Listeners/LogSuccessfulLogin.php +++ b/app/Listeners/LogSuccessfulLogin.php @@ -6,6 +6,7 @@ use Illuminate\Support\Facades\DB; use Illuminate\Auth\Events\Login; use Illuminate\Support\Facades\Log; + class LogSuccessfulLogin { /** diff --git a/app/Mail/CheckinAccessoryMail.php b/app/Mail/CheckinAccessoryMail.php index 311ee87a254c..dbab92431990 100644 --- a/app/Mail/CheckinAccessoryMail.php +++ b/app/Mail/CheckinAccessoryMail.php @@ -15,7 +15,8 @@ class CheckinAccessoryMail extends Mailable { - use Queueable, SerializesModels; + use Queueable; + use SerializesModels; /** * Create a new message instance. diff --git a/app/Mail/CheckinAssetMail.php b/app/Mail/CheckinAssetMail.php index 355c2f9f1343..2dde72ac1dae 100644 --- a/app/Mail/CheckinAssetMail.php +++ b/app/Mail/CheckinAssetMail.php @@ -17,7 +17,8 @@ class CheckinAssetMail extends Mailable { - use Queueable, SerializesModels; + use Queueable; + use SerializesModels; /** * Create a new message instance. @@ -33,8 +34,11 @@ public function __construct(Asset $asset, $checkedOutTo, User $checkedInBy, $not $this->expected_checkin = ''; if ($this->item->expected_checkin) { - $this->expected_checkin = Helper::getFormattedDateObject($this->item->expected_checkin, 'date', - false); + $this->expected_checkin = Helper::getFormattedDateObject( + $this->item->expected_checkin, + 'date', + false + ); } } diff --git a/app/Mail/CheckinLicenseMail.php b/app/Mail/CheckinLicenseMail.php index 6895fb9695aa..a354c94c312d 100644 --- a/app/Mail/CheckinLicenseMail.php +++ b/app/Mail/CheckinLicenseMail.php @@ -15,7 +15,8 @@ class CheckinLicenseMail extends Mailable { - use Queueable, SerializesModels; + use Queueable; + use SerializesModels; /** * Create a new message instance. diff --git a/app/Mail/CheckoutAccessoryMail.php b/app/Mail/CheckoutAccessoryMail.php index 64c02e31ed1c..2b15e064d3bc 100644 --- a/app/Mail/CheckoutAccessoryMail.php +++ b/app/Mail/CheckoutAccessoryMail.php @@ -16,7 +16,8 @@ class CheckoutAccessoryMail extends Mailable { - use Queueable, SerializesModels; + use Queueable; + use SerializesModels; /** * Create a new message instance. diff --git a/app/Mail/CheckoutAssetMail.php b/app/Mail/CheckoutAssetMail.php index 7ac20861edcf..671db8030b0e 100644 --- a/app/Mail/CheckoutAssetMail.php +++ b/app/Mail/CheckoutAssetMail.php @@ -18,7 +18,8 @@ class CheckoutAssetMail extends Mailable { - use Queueable, SerializesModels; + use Queueable; + use SerializesModels; private bool $firstTimeSending; @@ -41,13 +42,19 @@ public function __construct(Asset $asset, $checkedOutTo, User $checkedOutBy, $ac $this->firstTimeSending = $firstTimeSending; if ($this->item->last_checkout) { - $this->last_checkout = Helper::getFormattedDateObject($this->item->last_checkout, 'date', - false); + $this->last_checkout = Helper::getFormattedDateObject( + $this->item->last_checkout, + 'date', + false + ); } if ($this->item->expected_checkin) { - $this->expected_checkin = Helper::getFormattedDateObject($this->item->expected_checkin, 'date', - false); + $this->expected_checkin = Helper::getFormattedDateObject( + $this->item->expected_checkin, + 'date', + false + ); } } diff --git a/app/Mail/CheckoutConsumableMail.php b/app/Mail/CheckoutConsumableMail.php index 6a3d80679033..3d97403a4567 100644 --- a/app/Mail/CheckoutConsumableMail.php +++ b/app/Mail/CheckoutConsumableMail.php @@ -16,7 +16,8 @@ class CheckoutConsumableMail extends Mailable { - use Queueable, SerializesModels; + use Queueable; + use SerializesModels; /** * Create a new message instance. diff --git a/app/Mail/CheckoutLicenseMail.php b/app/Mail/CheckoutLicenseMail.php index 9462c6c332c4..d20ba0740556 100644 --- a/app/Mail/CheckoutLicenseMail.php +++ b/app/Mail/CheckoutLicenseMail.php @@ -15,7 +15,8 @@ class CheckoutLicenseMail extends Mailable { - use Queueable, SerializesModels; + use Queueable; + use SerializesModels; /** * Create a new message instance. diff --git a/app/Mail/ExpiringAssetsMail.php b/app/Mail/ExpiringAssetsMail.php index 13d322f060c5..c2d97945b17b 100644 --- a/app/Mail/ExpiringAssetsMail.php +++ b/app/Mail/ExpiringAssetsMail.php @@ -12,7 +12,8 @@ class ExpiringAssetsMail extends Mailable { - use Queueable, SerializesModels; + use Queueable; + use SerializesModels; /** * Create a new message instance. diff --git a/app/Mail/ExpiringLicenseMail.php b/app/Mail/ExpiringLicenseMail.php index 77d94df63793..97bd0d7268ec 100644 --- a/app/Mail/ExpiringLicenseMail.php +++ b/app/Mail/ExpiringLicenseMail.php @@ -12,7 +12,8 @@ class ExpiringLicenseMail extends Mailable { - use Queueable, SerializesModels; + use Queueable; + use SerializesModels; /** * Create a new message instance. diff --git a/app/Mail/SendUpcomingAuditMail.php b/app/Mail/SendUpcomingAuditMail.php index 03faa081ebaf..3904f2222151 100644 --- a/app/Mail/SendUpcomingAuditMail.php +++ b/app/Mail/SendUpcomingAuditMail.php @@ -12,7 +12,8 @@ class SendUpcomingAuditMail extends Mailable { - use Queueable, SerializesModels; + use Queueable; + use SerializesModels; /** * Create a new message instance. @@ -44,7 +45,6 @@ public function content(): Content return new Content( - markdown: 'notifications.markdown.upcoming-audits', with: [ 'assets' => $this->assets, diff --git a/app/Mail/UnacceptedAssetReminderMail.php b/app/Mail/UnacceptedAssetReminderMail.php index 0e4473aaadf2..766db467fd28 100644 --- a/app/Mail/UnacceptedAssetReminderMail.php +++ b/app/Mail/UnacceptedAssetReminderMail.php @@ -12,7 +12,8 @@ class UnacceptedAssetReminderMail extends Mailable { - use Queueable, SerializesModels; + use Queueable; + use SerializesModels; /** * Create a new message instance. diff --git a/app/Models/Accessory.php b/app/Models/Accessory.php index 039f8692f6b4..5b4cf71db5c4 100755 --- a/app/Models/Accessory.php +++ b/app/Models/Accessory.php @@ -22,7 +22,8 @@ class Accessory extends SnipeModel protected $presenter = \App\Presenters\AccessoryPresenter::class; use CompanyableTrait; - use Loggable, Presentable; + use Loggable; + use Presentable; use SoftDeletes; protected $table = 'accessories'; @@ -32,17 +33,17 @@ class Accessory extends SnipeModel use Searchable; use Acceptable; - + /** * The attributes that should be included when searching the model. - * + * * @var array */ protected $searchableAttributes = ['name', 'model_number', 'order_number', 'purchase_date', 'notes']; /** * The relations and their attributes that should be included when searching the model. - * + * * @var array */ protected $searchableRelations = [ @@ -198,7 +199,7 @@ public function assetlog() /** * Get the LAST checkout for this accessory. - * + * * This is kinda gross, but is necessary for how the accessory * pivot stuff works for now. * @@ -241,10 +242,9 @@ public function lastCheckout() public function getImageUrl() { if ($this->image) { - return Storage::disk('public')->url(app('accessories_upload_path').$this->image); + return Storage::disk('public')->url(app('accessories_upload_path') . $this->image); } return false; - } /** @@ -299,7 +299,7 @@ public function manufacturer() } /** - * Determins whether or not an email should be sent for checkin/checkout of this + * Determines whether or not an email should be sent for checkin/checkout of this * accessory based on the category it belongs to. * * @author [A. Gianotto] [] @@ -380,7 +380,7 @@ public function numRemaining() /** * Run after the checkout acceptance was declined by the user - * + * * @param User $acceptedBy * @param string $signature */ diff --git a/app/Models/AccessoryCheckout.php b/app/Models/AccessoryCheckout.php index 61ffcd08e5d8..4b83ef38de31 100755 --- a/app/Models/AccessoryCheckout.php +++ b/app/Models/AccessoryCheckout.php @@ -31,7 +31,7 @@ class AccessoryCheckout extends Model protected $presenter = \App\Presenters\AccessoryPresenter::class; protected $table = 'accessories_checkout'; - + /** * Establishes the accessory checkout -> accessory relationship * @@ -159,13 +159,13 @@ public function advancedTextSearch(Builder $query, array $terms) $query->where(function ($query) use ($userQuery) { $query->where('assigned_type', User::class) ->whereIn('assigned_to', $userQuery); - })->orWhere(function($query) use ($locationQuery) { + })->orWhere(function ($query) use ($locationQuery) { $query->where('assigned_type', Location::class) ->whereIn('assigned_to', $locationQuery); - })->orWhere(function($query) use ($assetQuery) { + })->orWhere(function ($query) use ($assetQuery) { $query->where('assigned_type', Asset::class) ->whereIn('assigned_to', $assetQuery); - })->orWhere(function($query) use ($terms) { + })->orWhere(function ($query) use ($terms) { foreach ($terms as $term) { $search_str = '%' . $term . '%'; $query->where('note', 'like', $search_str); @@ -174,6 +174,4 @@ public function advancedTextSearch(Builder $query, array $terms) return $query; } - - } diff --git a/app/Models/Company.php b/app/Models/Company.php index 43fd396069e0..8afc0f395168 100644 --- a/app/Models/Company.php +++ b/app/Models/Company.php @@ -10,6 +10,7 @@ use Watson\Validating\ValidatingTrait; use Illuminate\Support\Facades\Log; use Illuminate\Support\Facades\Schema; + /** * Model for Companies. * @@ -26,7 +27,7 @@ final class Company extends SnipeModel 'name' => 'required|min:1|max:255|unique:companies,name', 'fax' => 'min:7|max:35|nullable', 'phone' => 'min:7|max:35|nullable', - 'email' => 'email|max:150|nullable', + 'email' => 'email|max:150|nullable', ]; protected $presenter = \App\Presenters\CompanyPresenter::class; @@ -42,20 +43,20 @@ final class Company extends SnipeModel protected $injectUniqueIdentifier = true; use ValidatingTrait; use Searchable; - + /** * The attributes that should be included when searching the model. - * + * * @var array */ protected $searchableAttributes = ['name', 'phone', 'fax', 'email', 'created_at', 'updated_at']; /** * The relations and their attributes that should be included when searching the model. - * + * * @var array */ - protected $searchableRelations = []; + protected $searchableRelations = []; /** * The attributes that are mass assignable. @@ -152,7 +153,6 @@ public static function isCurrentUserHasAccess($companyable) if (!$companyable instanceof Company && !Schema::hasColumn($company_table, 'company_id')) { return true; } - } catch (\Exception $e) { Log::warning($e); } @@ -160,12 +160,11 @@ public static function isCurrentUserHasAccess($companyable) if (auth()->user()) { - Log::warning('Companyable is '.$companyable); + Log::warning('Companyable is ' . $companyable); $current_user_company_id = auth()->user()->company_id; $companyable_company_id = $companyable->company_id; return $current_user_company_id == null || $current_user_company_id == $companyable_company_id || auth()->user()->isSuperUser(); } - } public static function isCurrentUserAuthorized() @@ -250,7 +249,7 @@ public function components() /** * Scoping table queries, determining if a logged in user is part of a company, and only allows the user to access items associated with that company if FMCS is enabled. * - * This method is the one that the CompanyableTrait uses to contrain queries automatically, however that trait CANNOT be + * This method is the one that the CompanyableTrait uses to constrain queries automatically, however that trait CANNOT be * applied to the user's model, since it causes an infinite loop against the authenticated user. * * @todo - refactor that trait to handle the user's model as well. @@ -290,13 +289,11 @@ private static function scopeCompanyablesDirectly($query, $column = 'company_id' // If the column exists in the table, use it to scope the query if ((($query) && ($query->getModel()) && (Schema::hasColumn($query->getModel()->getTable(), $column)))) { - // Dynamically get the table name if it's not passed in, based on the model we're querying against - $table = ($table_name) ? $table_name."." : $query->getModel()->getTable()."."; + $table = ($table_name) ? $table_name . "." : $query->getModel()->getTable() . "."; - return $query->where($table.$column, '=', $company_id); + return $query->where($table . $column, '=', $company_id); } - } public function adminuser() @@ -348,5 +345,4 @@ public function scopeOrderByCreatedBy($query, $order) { return $query->leftJoin('users as admin_sort', 'companies.created_by', '=', 'admin_sort.id')->select('companies.*')->orderBy('admin_sort.first_name', $order)->orderBy('admin_sort.last_name', $order); } - } diff --git a/app/Models/CustomField.php b/app/Models/CustomField.php index 4954e2f17b08..0cdd7c95b93a 100644 --- a/app/Models/CustomField.php +++ b/app/Models/CustomField.php @@ -16,7 +16,7 @@ class CustomField extends Model UniqueUndeletedTrait; /** - * Custom field predfined formats + * Custom field predefined formats * * @var array */ diff --git a/app/Models/Department.php b/app/Models/Department.php index 592fd840b1b6..dbad4ea123b5 100644 --- a/app/Models/Department.php +++ b/app/Models/Department.php @@ -21,7 +21,8 @@ class Department extends SnipeModel */ protected $injectUniqueIdentifier = true; - use ValidatingTrait, UniqueUndeletedTrait; + use ValidatingTrait; + use UniqueUndeletedTrait; protected $casts = [ 'manager_id' => 'integer', diff --git a/app/Models/Depreciable.php b/app/Models/Depreciable.php index 0c513a3d3341..9d4fbf05db16 100644 --- a/app/Models/Depreciable.php +++ b/app/Models/Depreciable.php @@ -49,15 +49,15 @@ public function getDepreciatedValue() $setting = Setting::getSettings(); switch ($setting->depreciation_method) { case 'half_1': - $depreciation = $this->getHalfYearDepreciatedValue(true); - break; + $depreciation = $this->getHalfYearDepreciatedValue(true); + break; case 'half_2': - $depreciation = $this->getHalfYearDepreciatedValue(false); - break; + $depreciation = $this->getHalfYearDepreciatedValue(false); + break; default: - $depreciation = $this->getLinearDepreciatedValue(); + $depreciation = $this->getLinearDepreciatedValue(); } return $depreciation; @@ -69,34 +69,30 @@ public function getDepreciatedValue() public function getLinearDepreciatedValue() // TODO - for testing it might be nice to have an optional $relative_to param here, defaulted to 'now' { if (($this->get_depreciation()) && ($this->purchase_date)) { - $months_passed = ($this->purchase_date->diff(now())->m)+($this->purchase_date->diff(now())->y*12); + $months_passed = ($this->purchase_date->diff(now())->m) + ($this->purchase_date->diff(now())->y * 12); } else { return null; } - if ($months_passed >= $this->get_depreciation()->months){ + if ($months_passed >= $this->get_depreciation()->months) { //if there is a floor use it - if($this->get_depreciation()->depreciation_min) { - + if ($this->get_depreciation()->depreciation_min) { $current_value = $this->calculateDepreciation(); - - }else{ + } else { $current_value = 0; } - } - else { + } else { // The equation here is (Purchase_Cost-Floor_min)*(Months_passed/Months_til_depreciated) - $current_value = round(($this->purchase_cost-($this->purchase_cost - ($this->calculateDepreciation())) * ($months_passed / $this->get_depreciation()->months)), 2); - + $current_value = round(($this->purchase_cost - ($this->purchase_cost - ($this->calculateDepreciation())) * ($months_passed / $this->get_depreciation()->months)), 2); } return $current_value; } - public function getMonthlyDepreciation(){ - - return ($this->purchase_cost-$this->calculateDepreciation())/$this->get_depreciation()->months; + public function getMonthlyDepreciation() + { + return ($this->purchase_cost - $this->calculateDepreciation()) / $this->get_depreciation()->months; } /** @@ -179,11 +175,10 @@ public function depreciated_date() if (($this->purchase_date) && ($this->get_depreciation())) { $date = date_create($this->purchase_date); - return date_add($date, date_interval_create_from_date_string($this->get_depreciation()->months.' months'));//date_format($date, 'Y-m-d'); //don't bake-in format, for internationalization + return date_add($date, date_interval_create_from_date_string($this->get_depreciation()->months . ' months'));//date_format($date, 'Y-m-d'); //don't bake-in format, for internationalization } return null; - } // it's necessary for unit tests @@ -194,9 +189,9 @@ protected function getDateTime($time = null) private function calculateDepreciation() { - if($this->get_depreciation()->depreciation_type === 'percent') { - $depreciation_percent= $this->get_depreciation()->depreciation_min / 100; - $depreciation_min= $this->purchase_cost * $depreciation_percent; + if ($this->get_depreciation()->depreciation_type === 'percent') { + $depreciation_percent = $this->get_depreciation()->depreciation_min / 100; + $depreciation_min = $this->purchase_cost * $depreciation_percent; return $depreciation_min; } diff --git a/app/Models/Labels/Field.php b/app/Models/Labels/Field.php index c023f541755b..2401c352a9e8 100644 --- a/app/Models/Labels/Field.php +++ b/app/Models/Labels/Field.php @@ -17,7 +17,7 @@ public function setOptions($options) { public function toArray(Asset $asset) { return Field::makeArray($this, $asset); } - /* Statics */ + /* Static functions */ public static function makeArray(Field $field, Asset $asset) { return $field->getOptions() diff --git a/app/Models/Labels/FieldOption.php b/app/Models/Labels/FieldOption.php index 94394eda237f..230214a1852f 100644 --- a/app/Models/Labels/FieldOption.php +++ b/app/Models/Labels/FieldOption.php @@ -42,7 +42,7 @@ public function getValue(Asset $asset) { public function toArray(Asset $asset=null) { return FieldOption::makeArray($this, $asset); } public function toString() { return FieldOption::makeString($this); } - /* Statics */ + /* Static functions */ public static function makeArray(FieldOption $option, Asset $asset=null) { return [ diff --git a/app/Models/Ldap.php b/app/Models/Ldap.php index f71f926a9349..620275be980b 100644 --- a/app/Models/Ldap.php +++ b/app/Models/Ldap.php @@ -126,11 +126,11 @@ public static function findAndBindUserLdap($username, $password) * TODO PLEASE: * * this isn't very clear, so it's important to note: the $ldapbind value is never correctly returned - we never 'return true' from self::bindAdminToLdap() (the function - * just "falls off the end" without ever explictly returning 'true') + * just "falls off the end" without ever explicitly returning 'true') * * but it *does* have an interesting side-effect of checking for the LDAP password being incorrectly encrypted with the wrong APP_KEY, so I'm leaving it in for now. * - * If it *did* correctly return 'true' on a succesful bind, it would _probably_ allow users to log in with an incorrect password. Which would be horrible! + * If it *did* correctly return 'true' on a successful bind, it would _probably_ allow users to log in with an incorrect password. Which would be horrible! * * Let's definitely fix this at the next refactor!!!! * diff --git a/app/Models/License.php b/app/Models/License.php index 0997c1e57b99..bae4a64ca298 100755 --- a/app/Models/License.php +++ b/app/Models/License.php @@ -553,7 +553,7 @@ public function getAvailSeatsCountAttribute() } /** - * Retuns the number of assigned seats for this asset + * Returns the number of assigned seats for this asset * * @author A. Gianotto * @since [v3.0] diff --git a/app/Models/Location.php b/app/Models/Location.php index 69c79cfaebb2..083c37aae342 100755 --- a/app/Models/Location.php +++ b/app/Models/Location.php @@ -20,10 +20,13 @@ class Location extends SnipeModel { use HasFactory; use CompanyableTrait; - - protected $presenter = \App\Presenters\LocationPresenter::class; use Presentable; use SoftDeletes; + use ValidatingTrait; + use UniqueUndeletedTrait; + use Searchable; + + protected $presenter = \App\Presenters\LocationPresenter::class; protected $table = 'locations'; protected $rules = [ @@ -37,6 +40,8 @@ class Location extends SnipeModel 'manager_id' => 'exists:users,id|nullable', 'parent_id' => 'nullable|exists:locations,id|non_circular:locations,id', 'company_id' => 'integer|nullable|exists:companies,id', + 'latitude' => 'numeric|nullable|min:-90|max:90', + 'longitude' => 'numeric|nullable|min:-180|max:180' ]; protected $casts = [ @@ -53,8 +58,6 @@ class Location extends SnipeModel * @var bool */ protected $injectUniqueIdentifier = true; - use ValidatingTrait; - use UniqueUndeletedTrait; /** * The attributes that are mass assignable. @@ -78,11 +81,11 @@ class Location extends SnipeModel 'image', 'company_id', 'notes', + 'latitude', + 'longitude' ]; protected $hidden = ['user_id']; - use Searchable; - /** * The attributes that should be included when searching the model. * @@ -305,12 +308,12 @@ public static function indenter($locations_with_children, $parent_id = null, $pr } foreach ($locations_with_children[$parent_id] as $location) { - $location->use_text = $prefix.' '.$location->name; - $location->use_image = ($location->image) ? config('app.url').'/uploads/locations/'.$location->image : null; + $location->use_text = $prefix . ' ' . $location->name; + $location->use_image = ($location->image) ? config('app.url') . '/uploads/locations/' . $location->image : null; $results[] = $location; //now append the children. (if we have any) if (array_key_exists($location->id, $locations_with_children)) { - $results = array_merge($results, self::indenter($locations_with_children, $location->id, $prefix.'--')); + $results = array_merge($results, self::indenter($locations_with_children, $location->id, $prefix . '--')); } } diff --git a/app/Models/Recipients/AdminRecipient.php b/app/Models/Recipients/AdminRecipient.php index 90e39d4ee53e..f5113e6f8485 100644 --- a/app/Models/Recipients/AdminRecipient.php +++ b/app/Models/Recipients/AdminRecipient.php @@ -6,15 +6,15 @@ class AdminRecipient extends Recipient { - protected $email; public function __construct() { $settings = Setting::getSettings(); $this->email = trim($settings->admin_cc_email); } - - public function getEmail(){ + + public function getEmail() + { return $this->email; } } diff --git a/app/Models/Setting.php b/app/Models/Setting.php index 199aee33dcc3..797b7aa68c34 100755 --- a/app/Models/Setting.php +++ b/app/Models/Setting.php @@ -53,7 +53,9 @@ class Setting extends Model protected $rules = [ 'brand' => 'required|min:1|numeric', 'thumbnail_max_h' => 'numeric|max:500|min:25', - 'google_client_id' => 'nullable|ends_with:apps.googleusercontent.com' + 'google_client_id' => 'nullable|ends_with:apps.googleusercontent.com', + 'next_auto_tag_base' => 'integer|nullable|min:1', + 'zerofill_count' => 'integer|nullable|min:0' ]; protected $fillable = [ @@ -143,7 +145,7 @@ public static function getDefaultEula(): ?string } /** - * Check wether to show in model dropdowns. + * Check whether to show in model dropdowns. * * @param string $element * diff --git a/app/Models/Supplier.php b/app/Models/Supplier.php index e198d10c10bf..69f16e2fe372 100755 --- a/app/Models/Supplier.php +++ b/app/Models/Supplier.php @@ -12,6 +12,9 @@ class Supplier extends SnipeModel { use HasFactory; use SoftDeletes; + use ValidatingTrait; + use UniqueUndeletedTrait; + use Searchable; protected $table = 'suppliers'; @@ -29,6 +32,8 @@ class Supplier extends SnipeModel 'country' => 'min:2|max:191|nullable', 'zip' => 'max:10|nullable', 'url' => 'sometimes|nullable|string|max:250', + 'latitude' => 'numeric|nullable|min:-90|max:90', + 'longitude' => 'numeric|nullable|min:-180|max:180' ]; /** @@ -39,9 +44,6 @@ class Supplier extends SnipeModel * @var bool */ protected $injectUniqueIdentifier = true; - use ValidatingTrait; - use UniqueUndeletedTrait; - use Searchable; /** * The attributes that should be included when searching the model. @@ -62,7 +64,23 @@ class Supplier extends SnipeModel * * @var array */ - protected $fillable = ['name', 'address', 'address2', 'city', 'state', 'country', 'zip', 'phone', 'fax', 'email', 'contact', 'url', 'notes']; + protected $fillable = [ + 'name', + 'address', + 'address2', + 'city', + 'state', + 'country', + 'zip', + 'phone', + 'fax', + 'email', + 'contact', + 'url', + 'notes', + 'latitude', + 'longitude' + ]; /** * Eager load counts @@ -78,7 +96,7 @@ public function assetsRelation() { return $this->hasMany(Asset::class)->whereNull('deleted_at')->selectRaw('supplier_id, count(*) as count')->groupBy('supplier_id'); } - + /** * Establishes the supplier -> assets relationship @@ -191,8 +209,8 @@ public function num_licenses() */ public function addhttp($url) { - if (($url!='') && (! preg_match('~^(?:f|ht)tps?://~i', $url))) { - $url = 'http://'.$url; + if (($url != '') && (! preg_match('~^(?:f|ht)tps?://~i', $url))) { + $url = 'http://' . $url; } return $url; diff --git a/app/Models/Traits/Acceptable.php b/app/Models/Traits/Acceptable.php index f0d1442ed3a1..17947e44e315 100644 --- a/app/Models/Traits/Acceptable.php +++ b/app/Models/Traits/Acceptable.php @@ -4,6 +4,7 @@ use App\Models\User; use Illuminate\Support\Facades\Log; + /** * This trait allows models to have a callback after their checkout gets accepted or declined. * diff --git a/app/Models/Traits/Searchable.php b/app/Models/Traits/Searchable.php index 1430ce649a32..4a23121c336e 100644 --- a/app/Models/Traits/Searchable.php +++ b/app/Models/Traits/Searchable.php @@ -90,13 +90,13 @@ private function searchAttributes(Builder $query, array $terms) * @todo This does the job, but is inelegant and fragile */ if (! $firstConditionAdded) { - $query = $query->where($table.'.'.$column, 'LIKE', '%'.$term.'%'); + $query = $query->where($table . '.' . $column, 'LIKE', '%' . $term . '%'); $firstConditionAdded = true; continue; } - $query = $query->orWhere($table.'.'.$column, 'LIKE', '%'.$term.'%'); + $query = $query->orWhere($table . '.' . $column, 'LIKE', '%' . $term . '%'); } } @@ -124,7 +124,7 @@ private function searchCustomFields(Builder $query, array $terms) foreach ($customFields as $field) { foreach ($terms as $term) { - $query->orWhere($this->getTable().'.'.$field->db_column_name(), 'LIKE', '%'.$term.'%'); + $query->orWhere($this->getTable() . '.' . $field->db_column_name(), 'LIKE', '%' . $term . '%'); } } @@ -155,23 +155,23 @@ private function searchRelations(Builder $query, array $terms) foreach ($columns as $column) { foreach ($terms as $term) { if (! $firstConditionAdded) { - $query->where($table.'.'.$column, 'LIKE', '%'.$term.'%'); + $query->where($table . '.' . $column, 'LIKE', '%' . $term . '%'); $firstConditionAdded = true; continue; } - $query->orWhere($table.'.'.$column, 'LIKE', '%'.$term.'%'); + $query->orWhere($table . '.' . $column, 'LIKE', '%' . $term . '%'); } } // I put this here because I only want to add the concat one time in the end of the user relation search - if($relation == 'user') { + if ($relation == 'user') { $query->orWhereRaw( - $this->buildMultipleColumnSearch([ + $this->buildMultipleColumnSearch([ 'users.first_name', 'users.last_name', ]), - ["%{$term}%"] - ); + ["%{$term}%"] + ); } }); } diff --git a/app/Models/User.php b/app/Models/User.php index cdf5b55ff501..5998fc747dcb 100644 --- a/app/Models/User.php +++ b/app/Models/User.php @@ -28,8 +28,12 @@ class User extends SnipeModel implements AuthenticatableContract, AuthorizableCo use CompanyableTrait; protected $presenter = \App\Presenters\UserPresenter::class; - use SoftDeletes, ValidatingTrait; - use Authenticatable, Authorizable, CanResetPassword, HasApiTokens; + use SoftDeletes; + use ValidatingTrait; + use Authenticatable; + use Authorizable; + use CanResetPassword; + use HasApiTokens; use UniqueUndeletedTrait; use Notifiable; use Presentable; @@ -129,7 +133,7 @@ class User extends SnipeModel implements AuthenticatableContract, AuthorizableCo /** * The relations and their attributes that should be included when searching the model. - * + * * @var array */ protected $searchableRelations = [ @@ -157,7 +161,7 @@ protected static function boot() { parent::boot(); - static::retrieved(function($user){ + static::retrieved(function ($user) { $user->name = $user->getFullNameAttribute(); }); } @@ -172,7 +176,6 @@ protected function checkPermissionSection($section) { $user_groups = $this->groups; if (($this->permissions == '') && (count($user_groups) == 0)) { - return false; } @@ -238,7 +241,8 @@ public function isSuperUser() * @since [v6.3.4] * @return bool */ - public function canEditProfile() : bool { + public function canEditProfile(): bool + { $setting = Setting::getSettings(); if ($setting->profile_edit == 1) { @@ -315,10 +319,10 @@ public function getFullNameAttribute() { $setting = Setting::getSettings(); - if ($setting->name_display_format=='last_first') { - return ($this->last_name) ? $this->last_name.' '.$this->first_name : $this->first_name; + if ($setting->name_display_format == 'last_first') { + return ($this->last_name) ? $this->last_name . ' ' . $this->first_name : $this->first_name; } - return $this->last_name ? $this->first_name.' '.$this->last_name : $this->first_name; + return $this->last_name ? $this->first_name . ' ' . $this->last_name : $this->first_name; } @@ -372,7 +376,7 @@ public function accessories() */ public function consumables() { - return $this->belongsToMany(\App\Models\Consumable::class, 'consumables_users', 'assigned_to', 'consumable_id')->withPivot('id','created_at','note')->withTrashed(); + return $this->belongsToMany(\App\Models\Consumable::class, 'consumables_users', 'assigned_to', 'consumable_id')->withPivot('id', 'created_at', 'note')->withTrashed(); } /** @@ -403,16 +407,17 @@ public function reportTemplates(): HasMany * @since [v6.1] * @return \Illuminate\Database\Eloquent\Relations\Relation */ - Public function allAssignedCount() { + public function allAssignedCount() + { $assetsCount = $this->assets()->count(); $licensesCount = $this->licenses()->count(); $accessoriesCount = $this->accessories()->count(); $consumablesCount = $this->consumables()->count(); - + $totalCount = $assetsCount + $licensesCount + $accessoriesCount + $consumablesCount; - + return (int) $totalCount; - } + } /** * Establishes the user -> actionlogs relationship @@ -608,7 +613,7 @@ public function scopeMatchEmailOrUsername($query, $user_username, $user_email) /** * Generate email from full name - * + * * @author A. Gianotto * @since [v2.0] * @@ -619,7 +624,7 @@ public static function generateEmailFromFullName($name) { $username = self::generateFormattedNameFromFullName($name, Setting::getSettings()->email_format); - return $username['username'].'@'.Setting::getSettings()->email_domain; + return $username['username'] . '@' . Setting::getSettings()->email_domain; } public static function generateFormattedNameFromFullName($users_name, $format = 'filastname') @@ -631,36 +636,35 @@ public static function generateFormattedNameFromFullName($users_name, $format = $last_name = ''; $username = $users_name; } else { - list($first_name, $last_name) = explode(' ', $users_name, 2); // Assume filastname by default - $username = str_slug(substr($first_name, 0, 1).$last_name); + $username = str_slug(substr($first_name, 0, 1) . $last_name); - if ($format=='firstname.lastname') { + if ($format == 'firstname.lastname') { $username = str_slug($first_name) . '.' . str_slug($last_name); } elseif ($format == 'lastnamefirstinitial') { - $username = str_slug($last_name.substr($first_name, 0, 1)); + $username = str_slug($last_name . substr($first_name, 0, 1)); } elseif ($format == 'firstintial.lastname') { - $username = substr($first_name, 0, 1).'.'.str_slug($last_name); + $username = substr($first_name, 0, 1) . '.' . str_slug($last_name); } elseif ($format == 'firstname_lastname') { - $username = str_slug($first_name).'_'.str_slug($last_name); + $username = str_slug($first_name) . '_' . str_slug($last_name); } elseif ($format == 'firstname') { $username = str_slug($first_name); } elseif ($format == 'lastname') { $username = str_slug($last_name); } elseif ($format == 'firstinitial.lastname') { - $username = str_slug(substr($first_name, 0, 1).'.'.str_slug($last_name)); + $username = str_slug(substr($first_name, 0, 1) . '.' . str_slug($last_name)); } elseif ($format == 'lastname_firstinitial') { - $username = str_slug($last_name).'_'.str_slug(substr($first_name, 0, 1)); + $username = str_slug($last_name) . '_' . str_slug(substr($first_name, 0, 1)); } elseif ($format == 'lastname.firstinitial') { - $username = str_slug($last_name).'.'.str_slug(substr($first_name, 0, 1)); + $username = str_slug($last_name) . '.' . str_slug(substr($first_name, 0, 1)); } elseif ($format == 'firstnamelastname') { - $username = str_slug($first_name).str_slug($last_name); + $username = str_slug($first_name) . str_slug($last_name); } elseif ($format == 'firstnamelastinitial') { - $username = str_slug(($first_name.substr($last_name, 0, 1))); + $username = str_slug(($first_name . substr($last_name, 0, 1))); } elseif ($format == 'lastname.firstname') { - $username = str_slug($last_name).'.'.str_slug($first_name); + $username = str_slug($last_name) . '.' . str_slug($first_name); } } @@ -725,7 +729,6 @@ public function two_factor_active_and_enrolled() return true; } return false; - } /** @@ -773,8 +776,9 @@ public function scopeSimpleNameSearch($query, $search) * @param array $terms The search terms * @return \Illuminate\Database\Eloquent\Builder */ - public function advancedTextSearch(Builder $query, array $terms) { - foreach($terms as $term) { + public function advancedTextSearch(Builder $query, array $terms) + { + foreach ($terms as $term) { $query->orWhereMultipleColumns([ 'users.first_name', 'users.last_name', @@ -885,19 +889,20 @@ public function preferredLocale(): string return $this->locale ?? Setting::getSettings()->locale ?? config('app.locale'); } - public function getUserTotalCost(){ - $asset_cost= 0; - $license_cost= 0; - $accessory_cost= 0; - foreach ($this->assets as $asset){ + public function getUserTotalCost() + { + $asset_cost = 0; + $license_cost = 0; + $accessory_cost = 0; + foreach ($this->assets as $asset) { $asset_cost += $asset->purchase_cost; $this->asset_cost = $asset_cost; } - foreach ($this->licenses as $license){ + foreach ($this->licenses as $license) { $license_cost += $license->purchase_cost; $this->license_cost = $license_cost; } - foreach ($this->accessories as $accessory){ + foreach ($this->accessories as $accessory) { $accessory_cost += $accessory->purchase_cost; $this->accessory_cost = $accessory_cost; } @@ -907,10 +912,11 @@ public function getUserTotalCost(){ return $this; } - public function scopeUserLocation($query, $location, $search){ + public function scopeUserLocation($query, $location, $search) + { - return $query->where('location_id','=', $location) + return $query->where('location_id', '=', $location) ->where('users.first_name', 'LIKE', '%' . $search . '%') ->orWhere('users.email', 'LIKE', '%' . $search . '%') ->orWhere('users.last_name', 'LIKE', '%' . $search . '%') @@ -920,10 +926,6 @@ public function scopeUserLocation($query, $location, $search){ ->orWhere('users.jobtitle', 'LIKE', '%' . $search . '%') ->orWhere('users.employee_num', 'LIKE', '%' . $search . '%') ->orWhere('users.username', 'LIKE', '%' . $search . '%') - ->orwhereRaw('CONCAT(users.first_name," ",users.last_name) LIKE \''.$search.'%\''); - - - - + ->orwhereRaw('CONCAT(users.first_name," ",users.last_name) LIKE \'' . $search . '%\''); } } diff --git a/app/Observers/ComponentObserver.php b/app/Observers/ComponentObserver.php index cd2c58c3674e..fa500cda5fe2 100644 --- a/app/Observers/ComponentObserver.php +++ b/app/Observers/ComponentObserver.php @@ -38,7 +38,7 @@ public function created(Component $component) $logAction->item_id = $component->id; $logAction->created_at = date('Y-m-d H:i:s'); $logAction->created_by = auth()->id(); - if($component->imported) { + if ($component->imported) { $logAction->setActionSource('importer'); } $logAction->logaction('create'); diff --git a/app/Observers/LicenseObserver.php b/app/Observers/LicenseObserver.php index 4e355bf639d8..a8ff5913185a 100644 --- a/app/Observers/LicenseObserver.php +++ b/app/Observers/LicenseObserver.php @@ -38,7 +38,7 @@ public function created(License $license) $logAction->item_id = $license->id; $logAction->created_at = date('Y-m-d H:i:s'); $logAction->created_by = auth()->id(); - if($license->imported) { + if ($license->imported) { $logAction->setActionSource('importer'); } $logAction->logaction('create'); diff --git a/app/Observers/UserObserver.php b/app/Observers/UserObserver.php index acde9ceaede0..df6b9d84f4bd 100644 --- a/app/Observers/UserObserver.php +++ b/app/Observers/UserObserver.php @@ -51,17 +51,14 @@ public function updating(User $user) 'vip', 'password' ]; - + $changed = []; foreach ($user->getRawOriginal() as $key => $value) { - // Make sure the info is in the allow fields array if (in_array($key, $allowed_fields)) { - // Check and see if the value changed if ($user->getRawOriginal()[$key] != $user->getAttributes()[$key]) { - $changed[$key]['old'] = $user->getRawOriginal()[$key]; $changed[$key]['new'] = $user->getAttributes()[$key]; @@ -70,10 +67,8 @@ public function updating(User $user) $changed['password']['old'] = '*************'; $changed['password']['new'] = '*************'; } - } } - } if (count($changed) > 0) { @@ -87,8 +82,6 @@ public function updating(User $user) $logAction->log_meta = json_encode($changed); $logAction->logaction('update'); } - - } /** @@ -144,6 +137,4 @@ public function restoring(User $user) $logAction->created_by = auth()->id(); $logAction->logaction('restore'); } - - } diff --git a/app/Policies/CheckoutablePermissionsPolicy.php b/app/Policies/CheckoutablePermissionsPolicy.php index bcd0e0f39ae5..8dc1a4630efe 100644 --- a/app/Policies/CheckoutablePermissionsPolicy.php +++ b/app/Policies/CheckoutablePermissionsPolicy.php @@ -14,7 +14,7 @@ abstract class CheckoutablePermissionsPolicy extends SnipePermissionsPolicy */ public function checkout(User $user, $item = null) { - return $user->hasAccess($this->columnName().'.checkout'); + return $user->hasAccess($this->columnName() . '.checkout'); } /** @@ -25,7 +25,7 @@ public function checkout(User $user, $item = null) */ public function checkin(User $user, $item = null) { - return $user->hasAccess($this->columnName().'.checkin'); + return $user->hasAccess($this->columnName() . '.checkin'); } /** @@ -36,8 +36,8 @@ public function checkin(User $user, $item = null) */ public function manage(User $user, $item = null) { - return $user->hasAccess($this->columnName().'.checkin') - || $user->hasAccess($this->columnName().'.edit') - || $user->hasAccess($this->columnName().'.checkout'); + return $user->hasAccess($this->columnName() . '.checkin') + || $user->hasAccess($this->columnName() . '.edit') + || $user->hasAccess($this->columnName() . '.checkout'); } } diff --git a/app/Policies/LicensePolicy.php b/app/Policies/LicensePolicy.php index 38f5700ad175..758d9de11824 100644 --- a/app/Policies/LicensePolicy.php +++ b/app/Policies/LicensePolicy.php @@ -44,10 +44,9 @@ public function viewKeys(User $user, License $license = null) */ public function files(User $user, $license = null) { - if ($user->hasAccess('licenses.files')) { + if ($user->hasAccess('licenses.files')) { return true; } return false; - } } diff --git a/app/Policies/SnipePermissionsPolicy.php b/app/Policies/SnipePermissionsPolicy.php index 96c94cd77605..02a3e42e5083 100644 --- a/app/Policies/SnipePermissionsPolicy.php +++ b/app/Policies/SnipePermissionsPolicy.php @@ -57,7 +57,7 @@ public function before(User $user, $ability, $item) * via $this→authorize('something', Model::class) then calling Company:: isCurrentUserHasAccess($item) gets weird. * Bail out here by returning "nothing" and allow the relevant method lower in this class to be called and handle authorization. */ - if (!$item instanceof Model){ + if (!$item instanceof Model) { return; } @@ -69,7 +69,6 @@ public function before(User $user, $ability, $item) if (!Company::isCurrentUserHasAccess($item)) { return false; } - } @@ -81,7 +80,7 @@ public function before(User $user, $ability, $item) */ public function index(User $user) { - return $user->hasAccess($this->columnName().'.view'); + return $user->hasAccess($this->columnName() . '.view'); } /** @@ -92,12 +91,12 @@ public function index(User $user) */ public function view(User $user, $item = null) { - return $user->hasAccess($this->columnName().'.view'); + return $user->hasAccess($this->columnName() . '.view'); } public function files(User $user, $item = null) { - return $user->hasAccess($this->columnName().'.files'); + return $user->hasAccess($this->columnName() . '.files'); } /** @@ -108,7 +107,7 @@ public function files(User $user, $item = null) */ public function create(User $user) { - return $user->hasAccess($this->columnName().'.create'); + return $user->hasAccess($this->columnName() . '.create'); } /** @@ -119,7 +118,7 @@ public function create(User $user) */ public function update(User $user, $item = null) { - return $user->hasAccess($this->columnName().'.edit'); + return $user->hasAccess($this->columnName() . '.edit'); } @@ -131,7 +130,7 @@ public function update(User $user, $item = null) */ public function checkout(User $user, $item = null) { - return $user->hasAccess($this->columnName().'.checkout'); + return $user->hasAccess($this->columnName() . '.checkout'); } /** @@ -147,7 +146,7 @@ public function delete(User $user, $item = null) $itemConditional = empty($item->deleted_at); } - return $itemConditional && $user->hasAccess($this->columnName().'.delete'); + return $itemConditional && $user->hasAccess($this->columnName() . '.delete'); } /** @@ -158,6 +157,6 @@ public function delete(User $user, $item = null) */ public function manage(User $user, $item = null) { - return $user->hasAccess($this->columnName().'.edit'); + return $user->hasAccess($this->columnName() . '.edit'); } } diff --git a/app/Presenters/ActionlogPresenter.php b/app/Presenters/ActionlogPresenter.php index 4b7aefc87a8e..a58446ca3dd7 100644 --- a/app/Presenters/ActionlogPresenter.php +++ b/app/Presenters/ActionlogPresenter.php @@ -14,7 +14,7 @@ public function adminuser() return $user->present()->nameUrl(); } // The user was deleted - return ''.$user->getFullNameAttribute().' (deleted)'; + return '' . $user->getFullNameAttribute() . ' (deleted)'; } return ''; @@ -30,7 +30,7 @@ public function item() return $this->model->item->present()->nameUrl(); } // The item was deleted - return ''.$item->name.' (deleted)'; + return '' . $item->name . ' (deleted)'; } return ''; @@ -41,7 +41,6 @@ public function icon() // User related icons if ($this->itemType() == 'user') { - if ($this->action_type == '2fa reset') { return 'fa-solid fa-mobile-screen'; } @@ -107,12 +106,11 @@ public function icon() } return 'fa-solid fa-rotate-right'; - } public function actionType() { - return mb_strtolower(trans('general.'.str_replace(' ', '_', $this->action_type))); + return mb_strtolower(trans('general.' . str_replace(' ', '_', $this->action_type))); } public function target() @@ -141,7 +139,7 @@ public function target() return $target->present()->nameUrl(); } - return ''.$target->present()->name().''; + return '' . $target->present()->name() . ''; } return ''; diff --git a/app/Presenters/AssetAuditPresenter.php b/app/Presenters/AssetAuditPresenter.php index a4d208fc0ecf..629fa74122d5 100644 --- a/app/Presenters/AssetAuditPresenter.php +++ b/app/Presenters/AssetAuditPresenter.php @@ -29,7 +29,7 @@ public static function dataTableLayout() 'switchable' => true, 'title' => trans('general.id'), 'visible' => false, - ], [ + ], [ 'field' => 'company', 'searchable' => true, 'sortable' => true, @@ -37,14 +37,14 @@ public static function dataTableLayout() 'title' => trans('general.company'), 'visible' => false, 'formatter' => 'assetCompanyObjFilterFormatter', - ], [ + ], [ 'field' => 'name', 'searchable' => true, 'sortable' => true, 'title' => trans('admin/hardware/form.name'), 'visible' => true, 'formatter' => 'hardwareLinkFormatter', - ], [ + ], [ 'field' => 'file', 'searchable' => false, 'sortable' => true, @@ -52,83 +52,83 @@ public static function dataTableLayout() 'title' => trans('admin/hardware/table.image'), 'visible' => false, 'formatter' => 'auditImageFormatter', - ], [ + ], [ 'field' => 'asset_tag', 'searchable' => true, 'sortable' => true, 'title' => trans('admin/hardware/table.asset_tag'), 'visible' => true, 'formatter' => 'hardwareLinkFormatter', - ], [ + ], [ 'field' => 'serial', 'searchable' => true, 'sortable' => true, 'title' => trans('admin/hardware/form.serial'), 'visible' => true, 'formatter' => 'hardwareLinkFormatter', - ], [ + ], [ 'field' => 'model', 'searchable' => true, 'sortable' => true, 'title' => trans('admin/hardware/form.model'), 'visible' => true, 'formatter' => 'modelsLinkObjFormatter', - ], [ + ], [ 'field' => 'model_number', 'searchable' => true, 'sortable' => true, 'title' => trans('admin/models/table.modelnumber'), 'visible' => false, - ], [ + ], [ 'field' => 'category', 'searchable' => true, 'sortable' => true, 'title' => trans('general.category'), 'visible' => false, 'formatter' => 'categoriesLinkObjFormatter', - ], [ + ], [ 'field' => 'status_label', 'searchable' => true, 'sortable' => true, 'title' => trans('admin/hardware/table.status'), 'visible' => true, 'formatter' => 'statuslabelsLinkObjFormatter', - ], [ + ], [ 'field' => 'assigned_to', 'searchable' => true, 'sortable' => true, 'title' => trans('admin/hardware/form.checkedout_to'), 'visible' => true, 'formatter' => 'polymorphicItemFormatter', - ], [ + ], [ 'field' => 'location', 'searchable' => true, 'sortable' => true, 'title' => trans('admin/hardware/table.location'), 'visible' => true, 'formatter' => 'deployedLocationFormatter', - ], [ + ], [ 'field' => 'rtd_location', 'searchable' => true, 'sortable' => true, 'title' => trans('admin/hardware/form.default_location'), 'visible' => false, 'formatter' => 'deployedLocationFormatter', - ], [ + ], [ 'field' => 'manufacturer', 'searchable' => true, 'sortable' => true, 'title' => trans('general.manufacturer'), 'visible' => false, 'formatter' => 'manufacturersLinkObjFormatter', - ], [ + ], [ 'field' => 'purchase_date', 'searchable' => true, 'sortable' => true, 'visible' => false, 'title' => trans('general.purchase_date'), 'formatter' => 'dateDisplayFormatter', - ], [ + ], [ 'field' => 'purchase_cost', 'searchable' => true, 'sortable' => true, @@ -136,104 +136,104 @@ public static function dataTableLayout() 'title' => trans('general.purchase_cost'), 'footerFormatter' => 'sumFormatter', 'class' => 'text-right', - ], [ + ], [ 'field' => 'order_number', 'searchable' => true, 'sortable' => true, 'visible' => false, 'title' => trans('general.order_number'), 'formatter' => 'orderNumberObjFilterFormatter', - ], [ + ], [ 'field' => 'eol', 'searchable' => false, 'sortable' => false, 'visible' => false, 'title' => trans('general.eol'), 'formatter' => 'dateDisplayFormatter', - ], [ + ], [ 'field' => 'warranty_months', 'searchable' => true, 'sortable' => true, 'visible' => false, 'title' => trans('admin/hardware/form.warranty'), - ], [ + ], [ 'field' => 'warranty_expires', 'searchable' => false, 'sortable' => false, 'visible' => false, 'title' => trans('admin/hardware/form.warranty_expires'), 'formatter' => 'dateDisplayFormatter', - ], [ + ], [ 'field' => 'notes', 'searchable' => true, 'sortable' => true, 'visible' => false, 'title' => trans('general.notes'), - ], [ + ], [ 'field' => 'checkout_counter', 'searchable' => false, 'sortable' => true, 'visible' => false, 'title' => trans('general.checkouts_count'), - ], [ + ], [ 'field' => 'checkin_counter', 'searchable' => false, 'sortable' => true, 'visible' => false, 'title' => trans('general.checkins_count'), - ], [ + ], [ 'field' => 'requests_counter', 'searchable' => false, 'sortable' => true, 'visible' => false, 'title' => trans('general.user_requests_count'), - ], [ + ], [ 'field' => 'created_at', 'searchable' => false, 'sortable' => true, 'visible' => false, 'title' => trans('general.created_at'), 'formatter' => 'dateDisplayFormatter', - ], [ + ], [ 'field' => 'updated_at', 'searchable' => false, 'sortable' => true, 'visible' => false, 'title' => trans('general.updated_at'), 'formatter' => 'dateDisplayFormatter', - ], [ + ], [ 'field' => 'last_checkout', 'searchable' => false, 'sortable' => true, 'visible' => false, 'title' => trans('admin/hardware/table.checkout_date'), 'formatter' => 'dateDisplayFormatter', - ], [ + ], [ 'field' => 'expected_checkin', 'searchable' => false, 'sortable' => true, 'visible' => false, 'title' => trans('admin/hardware/form.expected_checkin'), 'formatter' => 'dateDisplayFormatter', - ], [ + ], [ 'field' => 'last_audit_date', 'searchable' => false, 'sortable' => true, 'visible' => true, 'title' => trans('general.last_audit'), 'formatter' => 'dateDisplayFormatter', - ], [ + ], [ 'field' => 'next_audit_date', 'searchable' => false, 'sortable' => true, 'visible' => true, 'title' => trans('general.next_audit_date'), 'formatter' => 'dateDisplayFormatter', - ], + ], ]; // This looks complicated, but we have to confirm that the custom fields exist in custom fieldsets @@ -249,12 +249,12 @@ public static function dataTableLayout() foreach ($fields as $field) { $layout[] = [ - 'field' => 'custom_fields.'.$field->db_column, + 'field' => 'custom_fields.' . $field->db_column, 'searchable' => true, 'sortable' => true, 'visible' => false, 'switchable' => true, - 'title' => ($field->field_encrypted == '1') ? ' '.e($field->name) : e($field->name), + 'title' => ($field->field_encrypted == '1') ? ' ' . e($field->name) : e($field->name), 'formatter' => 'customFieldsFormatter', ]; } diff --git a/app/Presenters/AssetModelPresenter.php b/app/Presenters/AssetModelPresenter.php index 2ed019eaea4f..6aa676a3298d 100644 --- a/app/Presenters/AssetModelPresenter.php +++ b/app/Presenters/AssetModelPresenter.php @@ -204,7 +204,7 @@ public function note() public function eolText() { if ($this->eol) { - return $this->eol.' '.trans('general.months'); + return $this->eol . ' ' . trans('general.months'); } return ''; @@ -218,12 +218,12 @@ public function modelName() { $name = ''; if ($this->model->manufacturer) { - $name .= $this->model->manufacturer->name.' '; + $name .= $this->model->manufacturer->name . ' '; } $name .= $this->name; if ($this->model_number) { - $name .= ' (#'.$this->model_number.')'; + $name .= ' (#' . $this->model_number . ')'; } return $name; @@ -245,7 +245,7 @@ public function nameUrl() public function imageUrl() { if (! empty($this->image)) { - return ''.$this->name.''; + return '' . $this->name . ''; } return ''; @@ -258,7 +258,7 @@ public function imageUrl() public function imageSrc() { if (! empty($this->image)) { - return config('app.url').'/uploads/models/'.$this->image; + return config('app.url') . '/uploads/models/' . $this->image; } return ''; diff --git a/app/Presenters/AssetPresenter.php b/app/Presenters/AssetPresenter.php index 2a4d09d1316b..6f5679cde2d0 100644 --- a/app/Presenters/AssetPresenter.php +++ b/app/Presenters/AssetPresenter.php @@ -319,12 +319,12 @@ public static function dataTableLayout() // name can break the listings page. - snipe foreach ($fields as $field) { $layout[] = [ - 'field' => 'custom_fields.'.$field->db_column, + 'field' => 'custom_fields.' . $field->db_column, 'searchable' => true, 'sortable' => true, 'switchable' => true, 'title' => $field->name, - 'formatter'=> 'customFieldsFormatter', + 'formatter' => 'customFieldsFormatter', 'escape' => true, 'class' => ($field->field_encrypted == '1') ? 'css-padlock' : '', 'visible' => ($field->show_in_listview == '1') ? true : false, @@ -336,7 +336,7 @@ public static function dataTableLayout() 'searchable' => false, 'sortable' => false, 'switchable' => false, - 'title' => trans('general.checkin').'/'.trans('general.checkout'), + 'title' => trans('general.checkin') . '/' . trans('general.checkout'), 'visible' => true, 'formatter' => 'hardwareInOutFormatter', ]; @@ -455,7 +455,7 @@ public function imageUrl() } $url = config('app.url'); if (! empty($imagePath)) { - $imagePath = ''.$imageAlt.''; + $imagePath = '' . $imageAlt . ''; } return $imagePath; @@ -474,7 +474,7 @@ public function imageSrc() $imagePath = $this->model->image; } if (! empty($imagePath)) { - return config('app.url').'/uploads/assets/'.$imagePath; + return config('app.url') . '/uploads/assets/' . $imagePath; } return $imagePath; @@ -507,12 +507,12 @@ public function fullName() // Asset tag if ($this->asset_tag) { - $str .= ' ('.$this->model->asset_tag.')'; + $str .= ' (' . $this->model->asset_tag . ')'; } // Asset Model name if ($this->model->model) { - $str .= ' - '.$this->model->model->name; + $str .= ' - ' . $this->model->model->name; } return $str; @@ -594,13 +594,11 @@ public function fullStatusText() { // Make sure the status is valid if ($this->assetstatus) { - // If the status is assigned to someone or something... if ($this->model->assigned) { - // If it's assigned and not set to the default "ready to deploy" status if ($this->assetstatus->name != trans('general.ready_to_deploy')) { - return trans('general.deployed').' ('.$this->model->assetstatus->name.')'; + return trans('general.deployed') . ' (' . $this->model->assetstatus->name . ')'; } // If it's assigned to the default "ready to deploy" status, just @@ -626,7 +624,7 @@ public function warranty_expires() { if (($this->purchase_date) && ($this->warranty_months)) { $date = date_create($this->purchase_date); - date_add($date, date_interval_create_from_date_string($this->warranty_months.' months')); + date_add($date, date_interval_create_from_date_string($this->warranty_months . ' months')); return date_format($date, 'Y-m-d'); } @@ -640,7 +638,7 @@ public function warranty_expires() */ public function dynamicUrl($dynamic_url) { - $url = (str_replace('{LOCALE}',\App\Models\Setting::getSettings()->locale, $dynamic_url)); + $url = (str_replace('{LOCALE}', \App\Models\Setting::getSettings()->locale, $dynamic_url)); $url = (str_replace('{SERIAL}', urlencode($this->model->serial), $url)); $url = (str_replace('{MODEL_NAME}', urlencode($this->model->model->name), $url)); $url = (str_replace('{MODEL_NUMBER}', urlencode($this->model->model->model_number), $url)); diff --git a/app/Presenters/CategoryPresenter.php b/app/Presenters/CategoryPresenter.php index d4a9f01a0526..b8da2bea6530 100644 --- a/app/Presenters/CategoryPresenter.php +++ b/app/Presenters/CategoryPresenter.php @@ -112,7 +112,7 @@ public static function dataTableLayout() 'sortable' => false, 'switchable' => false, 'title' => trans('table.actions'), - 'formatter' => 'categoriesActionsFormatter', + 'formatter' => 'categoriesActionsFormatter', ], ]; diff --git a/app/Presenters/CompanyPresenter.php b/app/Presenters/CompanyPresenter.php index fb8616609234..58541a99878d 100644 --- a/app/Presenters/CompanyPresenter.php +++ b/app/Presenters/CompanyPresenter.php @@ -52,7 +52,7 @@ public static function dataTableLayout() 'switchable' => true, 'title' => trans('admin/suppliers/table.email'), 'visible' => true, - 'formatter' => 'emailFormatter', + 'formatter' => 'emailFormatter', ], [ 'field' => 'image', 'searchable' => false, diff --git a/app/Presenters/ComponentPresenter.php b/app/Presenters/ComponentPresenter.php index 61f7a0ef4be3..e5fb668758b2 100644 --- a/app/Presenters/ComponentPresenter.php +++ b/app/Presenters/ComponentPresenter.php @@ -166,7 +166,7 @@ public static function dataTableLayout() 'searchable' => false, 'sortable' => false, 'switchable' => false, - 'title' => trans('general.checkin').'/'.trans('general.checkout'), + 'title' => trans('general.checkin') . '/' . trans('general.checkout'), 'visible' => true, 'formatter' => 'componentsInOutFormatter', ]; diff --git a/app/Presenters/DepreciationReportPresenter.php b/app/Presenters/DepreciationReportPresenter.php index 1d4c459614a7..8585438bf51e 100644 --- a/app/Presenters/DepreciationReportPresenter.php +++ b/app/Presenters/DepreciationReportPresenter.php @@ -1,4 +1,5 @@ false, "title" => trans('admin/hardware/form.warranty_expires'), "formatter" => "dateDisplayFormatter" - ], + ], ]; return json_encode($layout); @@ -207,7 +207,7 @@ public function imageUrl() } $url = config('app.url'); if (!empty($imagePath)) { - $imagePath = ''.$imageAlt.''; + $imagePath = '' . $imageAlt . ''; } return $imagePath; } @@ -225,7 +225,7 @@ public function imageSrc() $imagePath = $this->model->image; } if (!empty($imagePath)) { - return config('app.url').'/uploads/assets/'.$imagePath; + return config('app.url') . '/uploads/assets/' . $imagePath; } return $imagePath; } @@ -257,12 +257,12 @@ public function fullName() // Asset tag if ($this->asset_tag) { - $str .= ' ('.$this->model->asset_tag.')'; + $str .= ' (' . $this->model->asset_tag . ')'; } // Asset Model name if ($this->model->model) { - $str .= ' - '.$this->model->model->name; + $str .= ' - ' . $this->model->model->name; } return $str; } @@ -273,12 +273,11 @@ public function fullName() public function eol_date() { - if (( $this->purchase_date ) && ( $this->model->model ) && ($this->model->model->eol) ) { + if (( $this->purchase_date ) && ( $this->model->model ) && ($this->model->model->eol)) { $date = date_create($this->purchase_date); date_add($date, date_interval_create_from_date_string($this->model->model->eol . ' months')); return date_format($date, 'Y-m-d'); } - } /** @@ -341,16 +340,15 @@ public function statusText() * (if not deployed:) * Another Status Label */ - public function fullStatusText() { + public function fullStatusText() + { // Make sure the status is valid if ($this->assetstatus) { - // If the status is assigned to someone or something... if ($this->model->assigned) { - // If it's assigned and not set to the default "ready to deploy" status if ($this->assetstatus->name != trans('general.ready_to_deploy')) { - return trans('general.deployed'). ' (' . $this->model->assetstatus->name.')'; + return trans('general.deployed') . ' (' . $this->model->assetstatus->name . ')'; } // If it's assigned to the default "ready to deploy" status, just @@ -369,7 +367,7 @@ public function fullStatusText() { } /** - * Date the warantee expires. + * Date the warranty expires. * @return false|string */ public function warranty_expires() diff --git a/app/Presenters/LicensePresenter.php b/app/Presenters/LicensePresenter.php index 351a9acea41b..ca8960f9afe3 100644 --- a/app/Presenters/LicensePresenter.php +++ b/app/Presenters/LicensePresenter.php @@ -199,7 +199,7 @@ public static function dataTableLayout() 'searchable' => false, 'sortable' => false, 'switchable' => false, - 'title' => trans('general.checkin').'/'.trans('general.checkout'), + 'title' => trans('general.checkin') . '/' . trans('general.checkout'), 'visible' => true, 'formatter' => 'licensesInOutFormatter', ]; @@ -230,8 +230,8 @@ public static function dataTableLayoutSeats() 'switchable' => true, 'title' => trans('general.id'), 'visible' => false, - ], - [ + ], + [ 'field' => 'name', 'searchable' => false, 'sortable' => false, @@ -293,7 +293,7 @@ public static function dataTableLayoutSeats() 'searchable' => false, 'sortable' => false, 'switchable' => false, - 'title' => trans('general.checkin').'/'.trans('general.checkout'), + 'title' => trans('general.checkin') . '/' . trans('general.checkout'), 'visible' => true, 'formatter' => 'licenseSeatInOutFormatter', ], @@ -326,7 +326,7 @@ public function fullName() */ public function serialUrl() { - return (string) link_to('/licenses/'.$this->id, mb_strimwidth($this->serial, 0, 50, '...')); + return (string) link_to('/licenses/' . $this->id, mb_strimwidth($this->serial, 0, 50, '...')); } /** diff --git a/app/Presenters/PredefinedKitPresenter.php b/app/Presenters/PredefinedKitPresenter.php index 7ce7d8c23ddf..07d506e0549c 100644 --- a/app/Presenters/PredefinedKitPresenter.php +++ b/app/Presenters/PredefinedKitPresenter.php @@ -58,7 +58,7 @@ public static function dataTableLayout() 'searchable' => false, 'sortable' => false, 'switchable' => true, - 'title' => trans('general.checkin').'/'.trans('general.checkout'), + 'title' => trans('general.checkin') . '/' . trans('general.checkout'), 'visible' => true, 'formatter' => 'kitsInOutFormatter', ]; diff --git a/app/Presenters/StatusLabelPresenter.php b/app/Presenters/StatusLabelPresenter.php index 5bc4bd88316f..2c119bd9c79b 100644 --- a/app/Presenters/StatusLabelPresenter.php +++ b/app/Presenters/StatusLabelPresenter.php @@ -110,6 +110,4 @@ public static function dataTableLayout() return json_encode($layout); } - - } diff --git a/app/Presenters/UserPresenter.php b/app/Presenters/UserPresenter.php index ff81814818b2..510c29edd3c0 100644 --- a/app/Presenters/UserPresenter.php +++ b/app/Presenters/UserPresenter.php @@ -415,7 +415,7 @@ public static function dataTableLayout() public function emailLink() { if ($this->email) { - return ''.$this->email.''; + return '' . $this->email . ''; } return ''; @@ -429,7 +429,7 @@ public function emailLink() */ public function fullName() { - return html_entity_decode($this->first_name.' '.$this->last_name, ENT_QUOTES | ENT_XML1, 'UTF-8'); + return html_entity_decode($this->first_name . ' ' . $this->last_name, ENT_QUOTES | ENT_XML1, 'UTF-8'); } /** @@ -452,14 +452,13 @@ public function gravatar() // User's specific avatar if ($this->avatar) { - // Check if it's a google avatar or some external avatar if (Str::startsWith($this->avatar, ['http://', 'https://'])) { return $this->avatar; } // Otherwise assume it's an uploaded image - return Storage::disk('public')->url('avatars/'.e($this->avatar)); + return Storage::disk('public')->url('avatars/' . e($this->avatar)); } @@ -470,19 +469,17 @@ public function gravatar() // If there is a custom default avatar if (Setting::getSettings()->default_avatar != '') { - return Storage::disk('public')->url('avatars/'.e(Setting::getSettings()->default_avatar)); + return Storage::disk('public')->url('avatars/' . e(Setting::getSettings()->default_avatar)); } // If there is no default and no custom avatar, check for gravatar if ((Setting::getSettings()->load_remote == '1') && (Setting::getSettings()->default_avatar == '')) { - if ($this->model->gravatar != '') { $gravatar = md5(strtolower(trim($this->model->gravatar))); - return '//gravatar.com/avatar/'.$gravatar; - + return '//gravatar.com/avatar/' . $gravatar; } elseif ($this->email != '') { $gravatar = md5(strtolower(trim($this->email))); - return '//gravatar.com/avatar/'.$gravatar; + return '//gravatar.com/avatar/' . $gravatar; } } diff --git a/app/Providers/ValidationServiceProvider.php b/app/Providers/ValidationServiceProvider.php index a08a035fbbf0..d7f3f282003b 100644 --- a/app/Providers/ValidationServiceProvider.php +++ b/app/Providers/ValidationServiceProvider.php @@ -199,7 +199,7 @@ public function boot() $test_string = 'My hovercraft is full of eels'; - // We have to stip out the regex: part here to check with preg_match + // We have to strip out the regex: part here to check with preg_match $test_pattern = str_replace('regex:', '', $value); try { diff --git a/app/Rules/AssetCannotBeCheckedOutToNondeployableStatus.php b/app/Rules/AssetCannotBeCheckedOutToNondeployableStatus.php index c2c451b82b94..c96dbc4beda6 100644 --- a/app/Rules/AssetCannotBeCheckedOutToNondeployableStatus.php +++ b/app/Rules/AssetCannotBeCheckedOutToNondeployableStatus.php @@ -7,10 +7,8 @@ use Illuminate\Contracts\Validation\ValidationRule; use Illuminate\Contracts\Validation\DataAwareRule; - class AssetCannotBeCheckedOutToNondeployableStatus implements DataAwareRule, ValidationRule { - /** * All of the data under validation. * @@ -39,13 +37,9 @@ public function validate(string $attribute, mixed $value, Closure $fail): void { // Check to see if any of the assign-ish fields are set if ((isset($this->data['assigned_to'])) || (isset($this->data['assigned_user'])) || (isset($this->data['assigned_location'])) || (isset($this->data['assigned_asset'])) || (isset($this->data['assigned_type']))) { - - if (($value) && ($label = Statuslabel::find($value)) && ($label->getStatuslabelType()!='deployable')) { + if (($value) && ($label = Statuslabel::find($value)) && ($label->getStatuslabelType() != 'deployable')) { $fail(trans('admin/hardware/form.asset_not_deployable')); } - } - - } } diff --git a/app/Rules/UserCannotSwitchCompaniesIfItemsAssigned.php b/app/Rules/UserCannotSwitchCompaniesIfItemsAssigned.php index a433ee9a28e4..eb18c36d9136 100644 --- a/app/Rules/UserCannotSwitchCompaniesIfItemsAssigned.php +++ b/app/Rules/UserCannotSwitchCompaniesIfItemsAssigned.php @@ -1,6 +1,7 @@ route('user')->id); - if (($value) && ($user->allAssignedCount() > 0) && (Setting::getSettings()->full_multiple_companies_support=='1')) { - + if (($value) && ($user->allAssignedCount() > 0) && (Setting::getSettings()->full_multiple_companies_support == '1')) { // Check for assets with a different company_id than the selected company_id $user_assets = $user->assets()->where('assets.company_id', '!=', $value)->count(); if ($user_assets > 0) { diff --git a/app/Services/PredefinedKitCheckoutService.php b/app/Services/PredefinedKitCheckoutService.php index 2cf4593687f1..a20aea6a23ae 100644 --- a/app/Services/PredefinedKitCheckoutService.php +++ b/app/Services/PredefinedKitCheckoutService.php @@ -27,7 +27,6 @@ class PredefinedKitCheckoutService public function checkout(Request $request, PredefinedKit $kit, User $user) { try { - // Check if the user exists if (is_null($user)) { return ['errors' => trans('admin/users/message.user_not_found')]; @@ -93,7 +92,7 @@ protected function getAssetsToAdd($kit, $user, &$errors) } } if ($quantity > 0) { - $errors[] = trans('admin/kits/general.none_models', ['model'=> $model->name, 'qty' => $model->pivot->quantity]); + $errors[] = trans('admin/kits/general.none_models', ['model' => $model->name, 'qty' => $model->pivot->quantity]); } } @@ -109,7 +108,7 @@ protected function getLicenseSeatsToAdd($kit, &$errors) foreach ($licenses as $license) { $quantity = $license->pivot->quantity; if ($quantity > count($license->freeSeats)) { - $errors[] = trans('admin/kits/general.none_licenses', ['license'=> $license->name, 'qty' => $license->pivot->quantity]); + $errors[] = trans('admin/kits/general.none_licenses', ['license' => $license->name, 'qty' => $license->pivot->quantity]); } for ($i = 0; $i < $quantity; $i++) { $seats_to_add[] = $license->freeSeats[$i]; @@ -124,7 +123,7 @@ protected function getConsumablesToAdd($kit, &$errors) $consumables = $kit->consumables()->with('users')->get(); foreach ($consumables as $consumable) { if ($consumable->numRemaining() < $consumable->pivot->quantity) { - $errors[] = trans('admin/kits/general.none_consumables', ['consumable'=> $consumable->name, 'qty' => $consumable->pivot->quantity]); + $errors[] = trans('admin/kits/general.none_consumables', ['consumable' => $consumable->name, 'qty' => $consumable->pivot->quantity]); } } @@ -136,7 +135,7 @@ protected function getAccessoriesToAdd($kit, &$errors) $accessories = $kit->accessories()->with('users')->get(); foreach ($accessories as $accessory) { if ($accessory->numRemaining() < $accessory->pivot->quantity) { - $errors[] = trans('admin/kits/general.none_accessory', ['accessory'=> $accessory->name, 'qty' => $accessory->pivot->quantity]); + $errors[] = trans('admin/kits/general.none_accessory', ['accessory' => $accessory->name, 'qty' => $accessory->pivot->quantity]); } } diff --git a/app/Services/Saml.php b/app/Services/Saml.php index 222c2c2ea327..fbee90c59c02 100644 --- a/app/Services/Saml.php +++ b/app/Services/Saml.php @@ -134,8 +134,8 @@ public function __construct() try { $this->_auth = new OneLogin_Saml2_Auth($this->_settings); } catch (Exception $e) { - if ( $this->isEnabled() ) { // $this->loadSettings() initializes this to true if SAML is enabled by settings. - Log::warning('Trying OneLogin_Saml2_Auth failed. Setting SAML enabled to false. OneLogin_Saml2_Auth error message is: '. $e->getMessage()); + if ($this->isEnabled()) { // $this->loadSettings() initializes this to true if SAML is enabled by settings. + Log::warning('Trying OneLogin_Saml2_Auth failed. Setting SAML enabled to false. OneLogin_Saml2_Auth error message is: ' . $e->getMessage()); } $this->_enabled = false; } diff --git a/app/Services/SnipeTranslator.php b/app/Services/SnipeTranslator.php index eb7a9eb044ce..140f461814ea 100644 --- a/app/Services/SnipeTranslator.php +++ b/app/Services/SnipeTranslator.php @@ -16,8 +16,8 @@ * * This method is called by the trans_choice() helper, which we *do* use a lot. ***************************************************************/ -class SnipeTranslator extends Translator { - +class SnipeTranslator extends Translator +{ static $legacy_translation_namespaces = [ "backup::" //Spatie backup uses 'legacy' locale names ]; @@ -26,7 +26,9 @@ class SnipeTranslator extends Translator { public function choice($key, $number, array $replace = [], $locale = null) { $line = $this->get( - $key, [], $locale = $this->localeForChoice($key, $locale) + $key, + [], + $locale = $this->localeForChoice($key, $locale) ); // If the given "number" is actually an array or countable we will simply count the @@ -40,9 +42,10 @@ public function choice($key, $number, array $replace = [], $locale = null) $replace['count'] = $number; } - $underscored_locale = str_replace("-","_",$locale); // OUR CHANGE. + $underscored_locale = str_replace("-", "_", $locale); // OUR CHANGE. return $this->makeReplacements( // BELOW - that $underscored_locale is the *ONLY* modified part - $this->getSelector()->choose($line, $number, $underscored_locale), $replace + $this->getSelector()->choose($line, $number, $underscored_locale), + $replace ); } @@ -68,6 +71,4 @@ public function get($key, array $replace = [], $locale = null, $fallback = true) } return $result; } - - -} \ No newline at end of file +} diff --git a/app/View/Label.php b/app/View/Label.php index 6dbad39a349f..a2799e959d6a 100644 --- a/app/View/Label.php +++ b/app/View/Label.php @@ -14,7 +14,9 @@ class Label implements View { - use Macroable { __call as macroCall; } + use Macroable { + __call as macroCall; + } protected const NAME = 'label'; @@ -25,7 +27,8 @@ class Label implements View */ protected $data; - public function __construct() { + public function __construct() + { $this->data = new Collection(); } @@ -96,15 +99,14 @@ public function render(callable $callback = null) } if ($template->getSupportLogo()) { - $logo = null; // Should we use the assets assigned company logo? (A.K.A. "Is `Labels > Use Asset Logo` enabled?"), and do we have a company logo? - if ($settings->label2_asset_logo && $asset->company && $asset->company->image!='') { - $logo = Storage::disk('public')->path('companies/'.e($asset->company->image)); + if ($settings->label2_asset_logo && $asset->company && $asset->company->image != '') { + $logo = Storage::disk('public')->path('companies/' . e($asset->company->image)); } elseif (!empty($settings->label_logo)) { // Use the general site label logo, if available - $logo = Storage::disk('public')->path('/'.e($settings->label_logo)); + $logo = Storage::disk('public')->path('/' . e($settings->label_logo)); } if (!empty($logo)) { @@ -113,31 +115,31 @@ public function render(callable $callback = null) } - if ($template->getSupport1DBarcode()) { - $barcode1DType = $settings->label2_1d_type; - if ($barcode1DType != 'none') { - $assetData->put('barcode1d', (object)[ - 'type' => $barcode1DType, - 'content' => $asset->asset_tag, - ]); - } + if ($template->getSupport1DBarcode()) { + $barcode1DType = $settings->label2_1d_type; + if ($barcode1DType != 'none') { + $assetData->put('barcode1d', (object)[ + 'type' => $barcode1DType, + 'content' => $asset->asset_tag, + ]); } - - if ($template->getSupport2DBarcode()) { + } + + if ($template->getSupport2DBarcode()) { $barcode2DType = $settings->label2_2d_type; - if (($barcode2DType != 'none') && (!is_null($barcode2DType))) { + if (($barcode2DType != 'none') && (!is_null($barcode2DType))) { switch ($settings->label2_2d_target) { - case 'ht_tag': - $barcode2DTarget = route('ht/assetTag', $asset->asset_tag); + case 'ht_tag': + $barcode2DTarget = route('ht/assetTag', $asset->asset_tag); break; - case 'plain_asset_id': - $barcode2DTarget = (string) $asset->id; + case 'plain_asset_id': + $barcode2DTarget = (string) $asset->id; break; - case 'plain_asset_tag': - $barcode2DTarget = $asset->asset_tag; + case 'plain_asset_tag': + $barcode2DTarget = $asset->asset_tag; break; - case 'plain_serial_number': - $barcode2DTarget = $asset->serial; + case 'plain_serial_number': + $barcode2DTarget = $asset->serial; break; case 'location': $barcode2DTarget = route('locations.show', $asset->location_id); @@ -146,18 +148,18 @@ public function render(callable $callback = null) default: $barcode2DTarget = route('hardware.show', $asset); break; - } + } $assetData->put('barcode2d', (object)[ 'type' => $barcode2DType, 'content' => $barcode2DTarget, ]); - } } + } $fields = $fieldDefinitions ->map(fn($field) => $field->toArray($asset)) ->filter(fn($field) => $field != null) - ->reduce(function($myFields, $field) { + ->reduce(function ($myFields, $field) { // Remove Duplicates $toAdd = $field ->filter(fn($o) => !$myFields->contains('dataSource', $o['dataSource'])) @@ -195,13 +197,13 @@ public function render(callable $callback = null) return $assetData; }); - + if ($template instanceof Sheet) { $template->setLabelIndexOffset($offset ?? 0); } $template->writeAll($pdf, $data); - $filename = $assets->count() > 1 ? 'assets.pdf' : $assets->first()->asset_tag.'.pdf'; + $filename = $assets->count() > 1 ? 'assets.pdf' : $assets->first()->asset_tag . '.pdf'; $pdf->Output($filename, 'I'); } @@ -217,7 +219,7 @@ public function with($key, $value = null) $this->data->put($key, $value); return $this; } - + /** * Get the array of view data. * @@ -247,5 +249,4 @@ public function getName() { return self::NAME; } - } diff --git a/config/app.php b/config/app.php index 9de088089f0c..bdd8d86bdc82 100755 --- a/config/app.php +++ b/config/app.php @@ -162,7 +162,7 @@ | ENABLE HTTP Strict Transport Security (HSTS) |-------------------------------------------------------------------------- | - | This is set to default false for backwards compatibilty but should be + | This is set to default false for backwards compatibility but should be | set to true if the hosting environment allows it. | | See https://scotthelme.co.uk/hsts-the-missing-link-in-tls/ @@ -421,7 +421,7 @@ | Escape Excel formulas in CSV exports |-------------------------------------------------------------------------- | - | This determins whether or not we should escape Excel formulas in CSV exports. + | This determines whether or not we should escape Excel formulas in CSV exports. | This can be UNSAFE in untrusted environments, and therefore defaults to true | so that Excel forumals WILL be escaped in CSV exports, however if your workflow | is designed around using formulas in your fields, you diff --git a/config/dompdf.php b/config/dompdf.php index 22f5f6c27e32..2b22cec87b9c 100644 --- a/config/dompdf.php +++ b/config/dompdf.php @@ -124,7 +124,7 @@ * * @link http://www.pdflib.com * - * If pdflib present in web server and auto or selected explicitely above, + * If pdflib present in web server and auto or selected explicitly above, * a real license code must exist! */ //"DOMPDF_PDFLIB_LICENSE" => "your license key here", @@ -162,7 +162,7 @@ * Image DPI setting * * This setting determines the default DPI setting for images and fonts. The - * DPI may be overridden for inline images by explictly setting the + * DPI may be overridden for inline images by explicitly setting the * image's width & height style attributes (i.e. if the image's native * width is 600 pixels and you specify the image's width as 72 points, * the image will have a DPI of 600 in the rendered PDF. The DPI of diff --git a/contrib/hooks/pre-commit b/contrib/hooks/pre-commit new file mode 100755 index 000000000000..5fdd1bc2fde1 --- /dev/null +++ b/contrib/hooks/pre-commit @@ -0,0 +1,7 @@ +#!/usr/bin/env sh + +FILES=$(git diff --cached --name-only --diff-filter=ACMR | grep ".php") + +if ! [ -z "${FILES}" ]; then + codespell $FILES +fi \ No newline at end of file diff --git a/database/factories/AssetFactory.php b/database/factories/AssetFactory.php index ca85c2358442..13f79da21f52 100644 --- a/database/factories/AssetFactory.php +++ b/database/factories/AssetFactory.php @@ -57,7 +57,7 @@ public function definition() public function configure() { return $this->afterMaking(function (Asset $asset) { - // calculates the EOL date most of the time, but sometimes sets a random date so we have some explicits + // calculates the EOL date most of the time, but sometimes sets a random date // the explicit boolean gets set in the saving() method on the observer $asset->asset_eol_date = $this->faker->boolean(5) ? CarbonImmutable::parse($asset->purchase_date)->addMonths(rand(0, 20))->format('Y-m-d') diff --git a/database/factories/ConsumableFactory.php b/database/factories/ConsumableFactory.php index 4a4b3ef872d3..72aad6fa9998 100644 --- a/database/factories/ConsumableFactory.php +++ b/database/factories/ConsumableFactory.php @@ -63,7 +63,7 @@ public function paper() { return $this->state(function () { return [ - 'name' => 'Laserjet Paper (Ream)', + 'name' => 'Laserjet Paper (Ream)', // codespell:ignore 'category_id' => function () { return Category::where('name', 'Printer Paper')->first() ?? Category::factory()->consumablePaperCategory(); }, diff --git a/database/factories/LocationFactory.php b/database/factories/LocationFactory.php index 3d0b444f70e1..74004df60446 100644 --- a/database/factories/LocationFactory.php +++ b/database/factories/LocationFactory.php @@ -27,7 +27,7 @@ public function definition() ]; } - // one of these can eventuall go away - left temporarily for conflict resolution + // one of these can eventually go away - left temporarily for conflict resolution public function deleted(): self { return $this->state(['deleted_at' => $this->faker->dateTime()]); diff --git a/database/migrations/2025_04_18_095839_add_geocode_to_locations.php b/database/migrations/2025_04_18_095839_add_geocode_to_locations.php new file mode 100644 index 000000000000..a1214bd0733f --- /dev/null +++ b/database/migrations/2025_04_18_095839_add_geocode_to_locations.php @@ -0,0 +1,30 @@ +float('latitude', 5)->nullable(); + $table->float('longitude', 5)->nullable(); + }); + } + + /** + * Reverse the migrations. + */ + public function down(): void + { + Schema::table('locations', function (Blueprint $table) { + $table->dropColumn('latitude'); + $table->dropColumn('longitude'); + }); + } +}; diff --git a/database/migrations/2025_04_18_100651_add_geocode_to_suppliers.php b/database/migrations/2025_04_18_100651_add_geocode_to_suppliers.php new file mode 100644 index 000000000000..2293846f04f5 --- /dev/null +++ b/database/migrations/2025_04_18_100651_add_geocode_to_suppliers.php @@ -0,0 +1,30 @@ +float('latitude', 5)->nullable(); + $table->float('longitude', 5)->nullable(); + }); + } + + /** + * Reverse the migrations. + */ + public function down(): void + { + Schema::table('suppliers', function (Blueprint $table) { + $table->dropColumn('latitude'); + $table->dropColumn('longitude'); + }); + } +}; diff --git a/database/seeders/DatabaseSeeder.php b/database/seeders/DatabaseSeeder.php index 5e26a9a25738..8bfe945d24e3 100644 --- a/database/seeders/DatabaseSeeder.php +++ b/database/seeders/DatabaseSeeder.php @@ -50,7 +50,7 @@ public function run() $output = Artisan::output(); Log::info($output); - Model::reguard(); + Model::reguard(); // codespell:ignore DB::table('imports')->truncate(); DB::table('asset_maintenances')->truncate(); diff --git a/docker/001-default-ssl.conf b/docker/001-default-ssl.conf index ab8a6931ef94..e0b5c2b95c3b 100644 --- a/docker/001-default-ssl.conf +++ b/docker/001-default-ssl.conf @@ -48,7 +48,7 @@ # certificate chain for the server certificate. Alternatively # the referenced file can be the same as SSLCertificateFile # when the CA certificates are directly appended to the server - # certificate for convinience. + # certificate for convenience. #SSLCertificateChainFile /etc/apache2/ssl.crt/server-ca.crt SSLCertificateChainFile /var/lib/snipeit/ssl/snipeit-ssl.crt diff --git a/install.sh b/install.sh index 601816ea5a9a..a87196b9b657 100755 --- a/install.sh +++ b/install.sh @@ -1,6 +1,6 @@ # ensure running as root if [ "$(id -u)" != "0" ]; then - #Debian doesnt have sudo if root has a password. + # Debian doesn't have sudo if root has a password. if ! hash sudo 2>/dev/null; then exec su -c "$0" "$@" else diff --git a/public/.htaccess b/public/.htaccess index f2c92b30051d..8e48fff2a6c2 100644 --- a/public/.htaccess +++ b/public/.htaccess @@ -12,7 +12,8 @@ # RewriteCond %{HTTPS} off # RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L] - + # https://www.w3.org/TR/change-password-url/ + Redirect /.well-known/change-password /account/password # Redirect Trailing Slashes If Not A Folder... RewriteCond %{REQUEST_FILENAME} !-d diff --git a/resources/assets/js/bootstrap-table-reorder-columns.js b/resources/assets/js/bootstrap-table-reorder-columns.js index a9b29d4a94a3..98c60485c1c1 100644 --- a/resources/assets/js/bootstrap-table-reorder-columns.js +++ b/resources/assets/js/bootstrap-table-reorder-columns.js @@ -2063,31 +2063,31 @@ if (_this.options.cookie) { _this.persistReorderColumnsState(_this); } - var ths = []; + var table_headers = []; var formatters = []; var columns = []; var columnsHidden = []; var columnIndex = -1; var optionsColumns = []; _this.$header.find('th:not(.detail)').each(function (i, el) { - ths.push($$6(el).data('field')); + table_headers.push($$6(el).data('field')); formatters.push($$6(el).data('formatter')); }); // Exist columns not shown - if (ths.length < _this.columns.length) { + if (table_headers.length < _this.columns.length) { columnsHidden = _this.columns.filter(function (column) { return !column.visible; }); for (var i = 0; i < columnsHidden.length; i++) { - ths.push(columnsHidden[i].field); + table_headers.push(columnsHidden[i].field); formatters.push(columnsHidden[i].formatter); } } - for (var _i2 = 0; _i2 < ths.length; _i2++) { - columnIndex = _this.fieldsColumnsIndex[ths[_i2]]; + for (var _i2 = 0; _i2 < table_headers.length; _i2++) { + columnIndex = _this.fieldsColumnsIndex[table_headers[_i2]]; if (columnIndex !== -1) { - _this.fieldsColumnsIndex[ths[_i2]] = _i2; + _this.fieldsColumnsIndex[table_headers[_i2]] = _i2; _this.columns[columnIndex].fieldIndex = _i2; columns.push(_this.columns[columnIndex]); } @@ -2107,14 +2107,14 @@ }); }); _this.options.columns[0] = optionsColumns; - _this.header.fields = ths; + _this.header.fields = table_headers; _this.header.formatters = formatters; _this.initHeader(); _this.initToolbar(); _this.initSearchText(); _this.initBody(); _this.resetView(); - _this.trigger('reorder-column', ths); + _this.trigger('reorder-column', table_headers); } }); } diff --git a/resources/assets/js/bootstrap.js b/resources/assets/js/bootstrap.js index 0edde3675043..7f51144aa6d3 100755 --- a/resources/assets/js/bootstrap.js +++ b/resources/assets/js/bootstrap.js @@ -8,14 +8,14 @@ window._ = require('lodash'); //window.$ = window.jQuery = require('jquery'); /** - * jQuery UI is loaded here and then the tooltip is assigned another funtion name + * jQuery UI is loaded here and then the tooltip is assigned another function name * This resolves the issue of jquery-ui & bootstrap tooltip conflict */ require('jquery-ui'); jQuery.fn.uitooltip = jQuery.fn.tooltip; /** - * Load boostrap + * Load bootstrap */ require('bootstrap-less'); diff --git a/resources/assets/js/dragtable.js b/resources/assets/js/dragtable.js index 55ec7fe27d42..26383c808c6f 100644 --- a/resources/assets/js/dragtable.js +++ b/resources/assets/js/dragtable.js @@ -8,7 +8,7 @@ * and GPL (GPL-LICENSE.txt) licenses. * * Inspired by the the dragtable from Dan Vanderkam (danvk.org/dragtable/) - * Thanks to the jquery and jqueryui comitters + * Thanks to the jquery and jqueryui committers * * Any comment, bug report, feature-request is welcome * Feel free to contact me. @@ -49,7 +49,7 @@ * beforeStop: beforeStop */ /* - * Special thx to all pull requests comitters + * Special thx to all pull requests committers */ (function($) { @@ -65,7 +65,7 @@ restoreState: null, // JSON-Object or function: some kind of experimental aka Quick-Hack TODO: do it better exact: true, // removes pixels, so that the overlay table width fits exactly the original table width clickDelay: 10, // ms to wait before rendering sortable list and delegating click event - containment: null, // @see http://api.jqueryui.com/sortable/#option-containment, use it if you want to move in 2 dimesnions (together with axis: null) + containment: null, // @see http://api.jqueryui.com/sortable/#option-containment, use it if you want to move in 2 dimensions (together with axis: null) cursor: 'move', // @see http://api.jqueryui.com/sortable/#option-cursor cursorAt: false, // @see http://api.jqueryui.com/sortable/#option-cursorAt distance: 0, // @see http://api.jqueryui.com/sortable/#option-distance, for immediate feedback use "0" @@ -395,9 +395,9 @@ } function swapNodes(a, b) { - var aparent = a.parentNode; + var aparent = a.parentNode; // codespell:ignore var asibling = a.nextSibling === b ? a : a.nextSibling; b.parentNode.insertBefore(a, b); - aparent.insertBefore(b, asibling); + aparent.insertBefore(b, asibling); // codespell:ignore } })(jQuery); \ No newline at end of file diff --git a/resources/assets/js/snipeit.js b/resources/assets/js/snipeit.js index 7c06ac623373..abb4d3a79ebf 100755 --- a/resources/assets/js/snipeit.js +++ b/resources/assets/js/snipeit.js @@ -346,7 +346,7 @@ $(function () { var inner_div = $("
"); /****************************************************************** * - * We are specifically chosing empty alt-text below, because this + * We are specifically choosing empty alt-text below, because this * image conveys no additional information, relative to the text * that will *always* be there in any select2 list that is in use * in Snipe-IT. If that changes, we would probably want to change diff --git a/resources/assets/js/snipeit_modals.js b/resources/assets/js/snipeit_modals.js index cea79e1141bc..ab932938d5b9 100644 --- a/resources/assets/js/snipeit_modals.js +++ b/resources/assets/js/snipeit_modals.js @@ -178,7 +178,7 @@ function formatDatalistSafe(datalist) { var inner_div = $("
"); /****************************************************************** * - * We are specifically chosing empty alt-text below, because this + * We are specifically choosing empty alt-text below, because this * image conveys no additional information, relative to the text * that will *always* be there in any select2 list that is in use * in Snipe-IT. If that changes, we would probably want to change diff --git a/resources/assets/less/mixins.less b/resources/assets/less/mixins.less index ff801d415ecd..7e2747719ea3 100755 --- a/resources/assets/less/mixins.less +++ b/resources/assets/less/mixins.less @@ -42,7 +42,7 @@ } } -//Box solid color variantion creator +//Box solid color variation creator .box-solid-variant(@color; @text-color: #fff) { border: 1px solid @color; > .box-header { diff --git a/resources/lang/en-US/admin/settings/general.php b/resources/lang/en-US/admin/settings/general.php index d7d5447b3f76..f313e4c659e3 100644 --- a/resources/lang/en-US/admin/settings/general.php +++ b/resources/lang/en-US/admin/settings/general.php @@ -50,6 +50,7 @@ 'dashboard_message_help' => 'This text will appear on the dashboard for anyone with permission to view the dashboard.', 'default_currency' => 'Default Currency', 'default_eula_text' => 'Default EULA', + 'default_eula_text_placeholder' => 'Add your default EULA text', 'default_language' => 'Default Language', 'default_eula_help_text' => 'You can also associate custom EULAs to specific asset categories.', 'acceptance_note' => 'Add a note for your decision (Optional)', diff --git a/resources/lang/en-US/general.php b/resources/lang/en-US/general.php index 3a84d2412fac..0156e9e9d066 100644 --- a/resources/lang/en-US/general.php +++ b/resources/lang/en-US/general.php @@ -82,6 +82,7 @@ 'consumable' => 'Consumable', 'consumables' => 'Consumables', 'country' => 'Country', + 'coordinates' => 'Coordinates', 'could_not_restore' => 'Error restoring :item_type: :error', 'not_deleted' => 'The :item_type was not deleted and therefore cannot be restored', 'create' => 'Create New', @@ -199,6 +200,7 @@ 'model_no' => 'Model No.', 'months' => 'months', 'moreinfo' => 'More Info', + 'my_location' => 'Get from My Location', 'name' => 'Name', 'new_password' => 'New Password', 'next' => 'Next', diff --git a/resources/views/account/profile.blade.php b/resources/views/account/profile.blade.php index 7a6ad69da108..725205a0b0aa 100755 --- a/resources/views/account/profile.blade.php +++ b/resources/views/account/profile.blade.php @@ -84,7 +84,7 @@
- + {!! $errors->first('website', '') !!}
@@ -113,7 +113,7 @@ (Private)
- + {!! $errors->first('gravatar', '') !!}

{{ $user->present()->fullName() }} avatar image diff --git a/resources/views/companies/edit.blade.php b/resources/views/companies/edit.blade.php index d6b9cf9afdac..4a18c3b4b7a1 100644 --- a/resources/views/companies/edit.blade.php +++ b/resources/views/companies/edit.blade.php @@ -13,21 +13,6 @@ @include ('partials.forms.edit.fax') @include ('partials.forms.edit.email') @include ('partials.forms.edit.image-upload', ['image_path' => app('companies_upload_path')]) - -

- -
- - - -
-
+@include ('partials.forms.edit.notes') @stop diff --git a/resources/views/companies/index.blade.php b/resources/views/companies/index.blade.php index 001d03bcdfd8..e07cb8c1717e 100644 --- a/resources/views/companies/index.blade.php +++ b/resources/views/companies/index.blade.php @@ -13,7 +13,7 @@ {{-- Page content --}} @section('content')
-
+
- -
-

{{ trans('admin/companies/general.about_companies') }}

+
+

{{ trans('admin/companies/general.about_companies') }}

{{ trans('admin/companies/general.about_companies_description') }}

+
- @stop @section('moar_scripts') diff --git a/resources/views/departments/edit.blade.php b/resources/views/departments/edit.blade.php index 05d9b49e4ce9..24d47cc8b7f0 100644 --- a/resources/views/departments/edit.blade.php +++ b/resources/views/departments/edit.blade.php @@ -26,20 +26,7 @@ @include ('partials.forms.edit.location-select', ['translated_name' => trans('general.location'), 'fieldname' => 'location_id']) @include ('partials.forms.edit.image-upload', ['image_path' => app('departments_upload_path')]) -
- -
- - {!! $errors->first('notes', '') !!} -
-
+ @include ('partials.forms.edit.notes') @stop diff --git a/resources/views/depreciations/index.blade.php b/resources/views/depreciations/index.blade.php index 77732e826311..4cf4658d355b 100755 --- a/resources/views/depreciations/index.blade.php +++ b/resources/views/depreciations/index.blade.php @@ -16,7 +16,7 @@ @section('content')
-
+
- - + - -
-

{{ trans('admin/depreciations/general.about_asset_depreciations') }}

+
+

{{ trans('admin/depreciations/general.about_asset_depreciations') }}

{{ trans('admin/depreciations/general.about_depreciations') }}

-
- @stop @section('moar_scripts') diff --git a/resources/views/hardware/edit.blade.php b/resources/views/hardware/edit.blade.php index fa2c008c9ac8..7e339f26435a 100755 --- a/resources/views/hardware/edit.blade.php +++ b/resources/views/hardware/edit.blade.php @@ -122,7 +122,7 @@
- +
diff --git a/resources/views/manufacturers/edit.blade.php b/resources/views/manufacturers/edit.blade.php index 1c9b80777608..d36db1290e24 100755 --- a/resources/views/manufacturers/edit.blade.php +++ b/resources/views/manufacturers/edit.blade.php @@ -10,15 +10,7 @@ {{-- Page content --}} @section('inputFields') @include ('partials.forms.edit.name', ['translated_name' => trans('admin/manufacturers/table.name')]) - -
- -
- - {!! $errors->first('url', '') !!} -
-
+@include ('partials.forms.edit.url')
@@ -63,20 +55,7 @@ @include ('partials.forms.edit.image-upload', ['image_path' => app('manufacturers_upload_path')]) -
- -
- - {!! $errors->first('notes', '') !!} -
-
+@include ('partials.forms.edit.notes') diff --git a/resources/views/models/custom_fields_form.blade.php b/resources/views/models/custom_fields_form.blade.php index 2346218a385b..aa08090a766a 100644 --- a/resources/views/models/custom_fields_form.blade.php +++ b/resources/views/models/custom_fields_form.blade.php @@ -59,7 +59,7 @@ class="format form-control"
- pivot->required=='1') ? ' required' : '' }}> + pivot->required=='1') ? ' required' : '' }}>
diff --git a/resources/views/models/custom_fields_form_bulk_edit.blade.php b/resources/views/models/custom_fields_form_bulk_edit.blade.php index cea495ccd2e3..0027c55a5150 100644 --- a/resources/views/models/custom_fields_form_bulk_edit.blade.php +++ b/resources/views/models/custom_fields_form_bulk_edit.blade.php @@ -66,7 +66,7 @@ class="format form-control"
- +
diff --git a/resources/views/partials/bootstrap-table.blade.php b/resources/views/partials/bootstrap-table.blade.php index 1e3264e0d531..6f0d17624ccb 100644 --- a/resources/views/partials/bootstrap-table.blade.php +++ b/resources/views/partials/bootstrap-table.blade.php @@ -109,8 +109,8 @@ classes: 'table table-responsive table-no-bordered', onPostHeader: function () { var lookup = {}; var lookup_initialized = false; - var ths = $('th'); - ths.each(function (index, element) { + var table_headers = $('th'); + table_headers.each(function (index, element) { th = $(element); //only populate the lookup table once; don't need to keep doing it. if (!lookup_initialized) { diff --git a/resources/views/partials/forms/edit/address.blade.php b/resources/views/partials/forms/edit/address.blade.php index 12214b956b26..7686c2e1162a 100644 --- a/resources/views/partials/forms/edit/address.blade.php +++ b/resources/views/partials/forms/edit/address.blade.php @@ -47,3 +47,31 @@ {!! $errors->first('zip', '') !!}
+ +
+ +
+ + {!! $errors->first('latitude', '') !!} +
+
+ + {!! $errors->first('longitude', '') !!} +
+
+ +
+
+ + diff --git a/resources/views/partials/forms/edit/datepicker.blade.php b/resources/views/partials/forms/edit/datepicker.blade.php index d91659134e07..069e087d72f8 100644 --- a/resources/views/partials/forms/edit/datepicker.blade.php +++ b/resources/views/partials/forms/edit/datepicker.blade.php @@ -3,7 +3,7 @@
- +
{!! $errors->first($fieldname, '') !!} diff --git a/resources/views/partials/forms/edit/email.blade.php b/resources/views/partials/forms/edit/email.blade.php index edaea9921682..1703a74f4616 100644 --- a/resources/views/partials/forms/edit/email.blade.php +++ b/resources/views/partials/forms/edit/email.blade.php @@ -1,7 +1,7 @@
- + {!! $errors->first('email', '') !!}
diff --git a/resources/views/partials/forms/edit/eol_date.blade.php b/resources/views/partials/forms/edit/eol_date.blade.php index 5efba06a85e3..7ab06437d861 100644 --- a/resources/views/partials/forms/edit/eol_date.blade.php +++ b/resources/views/partials/forms/edit/eol_date.blade.php @@ -3,7 +3,7 @@
- +
{!! $errors->first('asset_eol_date', '') !!} diff --git a/resources/views/partials/forms/edit/fax.blade.php b/resources/views/partials/forms/edit/fax.blade.php index 19cf6ecef29f..b14da7d8ca40 100644 --- a/resources/views/partials/forms/edit/fax.blade.php +++ b/resources/views/partials/forms/edit/fax.blade.php @@ -1,7 +1,7 @@
- + {!! $errors->first('fax', '') !!}
diff --git a/resources/views/partials/forms/edit/notes.blade.php b/resources/views/partials/forms/edit/notes.blade.php index 5f82616c2cf7..818b4f8b6651 100644 --- a/resources/views/partials/forms/edit/notes.blade.php +++ b/resources/views/partials/forms/edit/notes.blade.php @@ -2,7 +2,7 @@
- + {!! $errors->first('notes', '') !!}
diff --git a/resources/views/partials/forms/edit/phone.blade.php b/resources/views/partials/forms/edit/phone.blade.php index af6ad8388e48..2e888e82047a 100644 --- a/resources/views/partials/forms/edit/phone.blade.php +++ b/resources/views/partials/forms/edit/phone.blade.php @@ -1,7 +1,7 @@
- + {!! $errors->first('phone', '') !!}
diff --git a/resources/views/partials/forms/edit/purchase_date.blade.php b/resources/views/partials/forms/edit/purchase_date.blade.php index f07387c3093c..97e753f5794c 100644 --- a/resources/views/partials/forms/edit/purchase_date.blade.php +++ b/resources/views/partials/forms/edit/purchase_date.blade.php @@ -3,7 +3,7 @@
- +
{!! $errors->first('purchase_date', '') !!} diff --git a/resources/views/partials/forms/edit/url.blade.php b/resources/views/partials/forms/edit/url.blade.php new file mode 100644 index 000000000000..b2073d4d55b2 --- /dev/null +++ b/resources/views/partials/forms/edit/url.blade.php @@ -0,0 +1,7 @@ +
+ +
+ + {!! $errors->first('url', '') !!} +
+
diff --git a/resources/views/settings/alerts.blade.php b/resources/views/settings/alerts.blade.php index 04554bcf3554..75e121c39289 100644 --- a/resources/views/settings/alerts.blade.php +++ b/resources/views/settings/alerts.blade.php @@ -69,7 +69,7 @@
- + {!! $errors->first('alert_email', '
') !!}

{{ trans('admin/settings/general.alert_email_help') }}

@@ -83,7 +83,7 @@
- + {!! $errors->first('admin_cc_email', '
') !!}

{{ trans('admin/settings/general.admin_cc_email_help') }}

@@ -98,7 +98,7 @@
- + {!! $errors->first('alert_interval', '') !!}
@@ -109,19 +109,19 @@
- + {!! $errors->first('alert_threshold', '') !!}
- +
- + {{ trans('general.months') }}
@@ -130,13 +130,13 @@
- +
- + {{ trans('general.days') }}
@@ -151,7 +151,7 @@
- + {{ trans('general.days') }}
diff --git a/resources/views/settings/asset_tags.blade.php b/resources/views/settings/asset_tags.blade.php index 4ac001b96b59..ec71d9686413 100644 --- a/resources/views/settings/asset_tags.blade.php +++ b/resources/views/settings/asset_tags.blade.php @@ -58,7 +58,7 @@
- + {!! $errors->first('next_auto_tag_base', '') !!}
@@ -85,7 +85,7 @@
- + {!! $errors->first('zerofill_count', '') !!}
diff --git a/resources/views/settings/general.blade.php b/resources/views/settings/general.blade.php index b4fa3cc5c31a..fa1e3e383838 100644 --- a/resources/views/settings/general.blade.php +++ b/resources/views/settings/general.blade.php @@ -228,7 +228,7 @@ {!! $errors->first('default_eula_text', '') !!}

{{ trans('admin/settings/general.default_eula_help_text') }}

@@ -304,7 +304,7 @@
@if (config('app.lock_passwords')) - + {!! $errors->first('dashboard_message', '') !!}

{{ trans('general.feature_disabled') }}

@else diff --git a/resources/views/settings/security.blade.php b/resources/views/settings/security.blade.php index 366beccee73c..9283eec7c4df 100644 --- a/resources/views/settings/security.blade.php +++ b/resources/views/settings/security.blade.php @@ -62,7 +62,7 @@
- + {!! $errors->first('pwd_secure_min', '') !!}

diff --git a/resources/views/setup/index.blade.php b/resources/views/setup/index.blade.php index 2eef58aa8961..f756ec507b54 100644 --- a/resources/views/setup/index.blade.php +++ b/resources/views/setup/index.blade.php @@ -126,7 +126,7 @@ @if (!$start_settings['owner_is_admin']) Your app files are owned by {{ $start_settings['owner'] }}. That doesn't look like a default root/admin account. Nice! @else - It looks like your files are owned by {{ $start_settings['owner'] }}, which might be a root/admin account. It's never a good idea to run a website with escalated priveliges. + It looks like your files are owned by {{ $start_settings['owner'] }}, which might be a root/admin account. It's never a good idea to run a website with escalated privileges. @endif diff --git a/resources/views/suppliers/edit.blade.php b/resources/views/suppliers/edit.blade.php index 9fc21a37f8e3..046ee2a69e8f 100755 --- a/resources/views/suppliers/edit.blade.php +++ b/resources/views/suppliers/edit.blade.php @@ -24,15 +24,7 @@ @include ('partials.forms.edit.phone') @include ('partials.forms.edit.fax') @include ('partials.forms.edit.email') - -

- -
- - {!! $errors->first('url', '') !!} -
-
- +@include ('partials.forms.edit.url') @include ('partials.forms.edit.notes') @include ('partials.forms.edit.image-upload', ['image_path' => app('suppliers_upload_path')]) diff --git a/routes/web.php b/routes/web.php index 14326f160c8d..a7458f4ca2a3 100644 --- a/routes/web.php +++ b/routes/web.php @@ -128,7 +128,7 @@ /* | |-------------------------------------------------------------------------- -| Re-Usable Modal Dialog routes. +| Reusable Modal Dialog routes. |-------------------------------------------------------------------------- | | Routes for various modal dialogs to interstitially create various things @@ -338,7 +338,7 @@ /** * This breadcrumb is repeated for groups in the BreadcrumbServiceProvider, since groups uses resource routes - * and that servcie provider cannot see the breadcrumbs defined below + * and that service provider cannot see the breadcrumbs defined below */ Route::get('/', [SettingsController::class, 'index']) ->name('settings.index') diff --git a/snipeit.sh b/snipeit.sh index e4b50c8e94e4..bd30be643788 100755 --- a/snipeit.sh +++ b/snipeit.sh @@ -73,7 +73,7 @@ fi # ensure running as root if [ "$(id -u)" != "0" ]; then - #Debian doesnt have sudo if root has a password. + # Debian doesn't have sudo if root has a password. if ! hash sudo 2>/dev/null; then exec su -c "$0" "$@" else @@ -394,8 +394,8 @@ set_fqdn () { } set_dbpass () { - ans=default - until [[ $ans == "yes" ]] || [[ $ans == "no" ]]; do + answer=default + until [[ $answer == "yes" ]] || [[ $answer == "no" ]]; do echo -n " Q. Do you want to automatically create the SnipeIT database user password? (y/n) " read -r setpw @@ -403,13 +403,13 @@ set_dbpass () { [yY] | [yY][Ee][Ss] ) mysqluserpw="$(< /dev/urandom tr -dc _A-Z-a-z-0-9 | head -c16; echo)" echo "" - ans="yes" + answer="yes" ;; [nN] | [n|N][O|o] ) echo -n " Q. What do you want your snipeit user password to be?" read -rs mysqluserpw echo "" - ans="no" + answer="no" ;; *) echo " Invalid answer. Please type y or n" ;; diff --git a/tests/CreatesApplication.php b/tests/CreatesApplication.php index 8d8a77e99df8..ab9240255084 100644 --- a/tests/CreatesApplication.php +++ b/tests/CreatesApplication.php @@ -13,10 +13,10 @@ trait CreatesApplication */ public function createApplication() { - $app = require __DIR__.'/../bootstrap/app.php'; + $app = require __DIR__ . '/../bootstrap/app.php'; $app->make(Kernel::class)->bootstrap(); return $app; } -} \ No newline at end of file +} diff --git a/tests/Feature/Accessories/Api/ShowAccessoryTest.php b/tests/Feature/Accessories/Api/ShowAccessoryTest.php index 117d72500739..489c983dd4e5 100644 --- a/tests/Feature/Accessories/Api/ShowAccessoryTest.php +++ b/tests/Feature/Accessories/Api/ShowAccessoryTest.php @@ -56,6 +56,5 @@ public function testCanGetSingleAccessory() 'name' => 'My Accessory', 'checkouts_count' => 1, ]); - } } diff --git a/tests/Feature/Accessories/Ui/AccessoriesIndexTest.php b/tests/Feature/Accessories/Ui/AccessoriesIndexTest.php index 7ab7f130a9c4..39acada6e92c 100644 --- a/tests/Feature/Accessories/Ui/AccessoriesIndexTest.php +++ b/tests/Feature/Accessories/Ui/AccessoriesIndexTest.php @@ -23,7 +23,7 @@ public function testRendersAccessoriesIndexPage() ->assertOk() ->assertViewIs('accessories.index'); } - + public function testPageRenders() { $this->actingAs(User::factory()->superuser()->create()) diff --git a/tests/Feature/Accessories/Ui/ShowAccessoryTest.php b/tests/Feature/Accessories/Ui/ShowAccessoryTest.php index 288ec9a50c3b..d72842570ccc 100644 --- a/tests/Feature/Accessories/Ui/ShowAccessoryTest.php +++ b/tests/Feature/Accessories/Ui/ShowAccessoryTest.php @@ -39,12 +39,11 @@ public function testCanViewAccessory() ->assertViewIs('accessories.view') ->assertViewHas(['accessory' => $accessory]); } - + public function testPageRenders() { $this->actingAs(User::factory()->superuser()->create()) ->get(route('accessories.show', Accessory::factory()->create())) ->assertOk(); - } } diff --git a/tests/Feature/AssetMaintenances/Ui/EditAssetMaintenanceTest.php b/tests/Feature/AssetMaintenances/Ui/EditAssetMaintenanceTest.php index 0e0f5b81c355..d1d28ccdf5f9 100644 --- a/tests/Feature/AssetMaintenances/Ui/EditAssetMaintenanceTest.php +++ b/tests/Feature/AssetMaintenances/Ui/EditAssetMaintenanceTest.php @@ -54,5 +54,4 @@ public function testCanUpdateAssetMaintenance() 'cost' => '100.00', ]); } - } diff --git a/tests/Feature/AssetModels/Api/AssetModelFilesTest.php b/tests/Feature/AssetModels/Api/AssetModelFilesTest.php index 8df441f2ab25..d29ea4f002ee 100644 --- a/tests/Feature/AssetModels/Api/AssetModelFilesTest.php +++ b/tests/Feature/AssetModels/Api/AssetModelFilesTest.php @@ -59,11 +59,24 @@ public function testAssetModelApiDownloadsFile() // Create a superuser to run this as $user = User::factory()->superuser()->create(); - //Upload a file + // Upload a file $this->actingAsForApi($user) ->post( route('api.models.files.store', ['model_id' => $model[0]["id"]]), [ - 'file' => [UploadedFile::fake()->create("test.jpg", 100)] + 'file' => [UploadedFile::fake()->create("test.jpg", 100)], + ]) + ->assertOk() + ->assertJsonStructure([ + 'status', + 'messages', + ]); + + // Upload a file with notes + $this->actingAsForApi($user) + ->post( + route('api.models.files.store', ['model_id' => $model[0]["id"]]), [ + 'file' => [UploadedFile::fake()->create("test.jpg", 100)], + 'notes' => 'manual' ]) ->assertOk() ->assertJsonStructure([ @@ -75,7 +88,26 @@ public function testAssetModelApiDownloadsFile() $result = $this->actingAsForApi($user) ->getJson( route('api.models.files.index', ['model_id' => $model[0]["id"]])) - ->assertOk(); + ->assertOk() + ->assertJsonStructure([ + 'total', + 'rows'=>[ + '*' => [ + 'id', + 'filename', + 'url', + 'created_by', + 'created_at', + 'updated_at', + 'deleted_at', + 'note', + 'available_actions' + ] + ] + ]) + ->assertJsonPath('rows.0.note','') + ->assertJsonPath('rows.1.note','manual'); + // Get the file diff --git a/tests/Feature/AssetModels/Api/CreateAssetModelsTest.php b/tests/Feature/AssetModels/Api/CreateAssetModelsTest.php index 2928d926f626..f4815dd8be06 100644 --- a/tests/Feature/AssetModels/Api/CreateAssetModelsTest.php +++ b/tests/Feature/AssetModels/Api/CreateAssetModelsTest.php @@ -10,8 +10,6 @@ class CreateAssetModelsTest extends TestCase { - - public function testRequiresPermissionToCreateAssetModel() { $this->actingAsForApi(User::factory()->create()) @@ -54,12 +52,11 @@ public function testCannotCreateAssetModelWithoutCategory() ->json(); $this->assertFalse(AssetModel::where('name', 'Test AssetModel')->exists()); - } public function testUniquenessAcrossModelNameAndModelNumber() { - AssetModel::factory()->create(['name' => 'Test Model', 'model_number'=>'1234']); + AssetModel::factory()->create(['name' => 'Test Model', 'model_number' => '1234']); $this->actingAsForApi(User::factory()->superuser()->create()) ->postJson(route('api.models.store'), [ @@ -77,7 +74,6 @@ public function testUniquenessAcrossModelNameAndModelNumber() ], ]) ->json(); - } public function testUniquenessAcrossModelNameAndModelNumberWithBlankModelNumber() @@ -98,7 +94,5 @@ public function testUniquenessAcrossModelNameAndModelNumberWithBlankModelNumber( ], ]) ->json(); - } - } diff --git a/tests/Feature/AssetModels/Api/IndexAssetModelsTest.php b/tests/Feature/AssetModels/Api/IndexAssetModelsTest.php index 26e4dd75b1c0..0428606e1bd4 100644 --- a/tests/Feature/AssetModels/Api/IndexAssetModelsTest.php +++ b/tests/Feature/AssetModels/Api/IndexAssetModelsTest.php @@ -33,7 +33,8 @@ public function testAssetModelIndexReturnsExpectedAssetModels() 'order' => 'asc', 'offset' => '0', 'limit' => '20', - ])) + ]) + ) ->assertOk() ->assertJsonStructure([ 'total', @@ -55,7 +56,8 @@ public function testAssetModelIndexSearchReturnsExpectedAssetModels() 'order' => 'asc', 'offset' => '0', 'limit' => '20', - ])) + ]) + ) ->assertOk() ->assertJsonStructure([ 'total', @@ -63,5 +65,4 @@ public function testAssetModelIndexSearchReturnsExpectedAssetModels() ]) ->assertJson(fn(AssertableJson $json) => $json->has('rows', 1)->etc()); } - } diff --git a/tests/Feature/AssetModels/Api/UpdateAssetModelsTest.php b/tests/Feature/AssetModels/Api/UpdateAssetModelsTest.php index c5ec2126508f..45c4106b1e95 100644 --- a/tests/Feature/AssetModels/Api/UpdateAssetModelsTest.php +++ b/tests/Feature/AssetModels/Api/UpdateAssetModelsTest.php @@ -9,7 +9,6 @@ class UpdateAssetModelsTest extends TestCase { - public function testRequiresPermissionToEditAssetModel() { $model = AssetModel::factory()->create(); @@ -34,7 +33,6 @@ public function testCanUpdateAssetModelViaPatch() $model->refresh(); $this->assertEquals('Test Model', $model->name, 'Name was not updated'); - } public function testCannotUpdateAssetModelViaPatchWithAccessoryCategory() @@ -116,5 +114,4 @@ public function testCannotUpdateAssetModelViaPatchWithComponentCategory() $this->assertNotEquals('Test Model', $model->name, 'Name was not updated'); $this->assertNotEquals('category_id', $category->id, 'Category ID was not updated'); } - } diff --git a/tests/Feature/AssetModels/Ui/CreateAssetModelsTest.php b/tests/Feature/AssetModels/Ui/CreateAssetModelsTest.php index 20772253a80b..2971ca577c75 100644 --- a/tests/Feature/AssetModels/Ui/CreateAssetModelsTest.php +++ b/tests/Feature/AssetModels/Ui/CreateAssetModelsTest.php @@ -56,13 +56,12 @@ public function testUserCannotUseAccessoryCategoryTypeAsAssetModelCategoryType() $response->assertSessionHasErrors(['category_type']); $this->followRedirects($response)->assertSee(trans('general.error')); $this->assertFalse(AssetModel::where('name', 'Test Invalid Model Category')->exists()); - } public function testUniquenessAcrossModelNameAndModelNumber() { - AssetModel::factory()->create(['name' => 'Test Model', 'model_number'=>'1234']); + AssetModel::factory()->create(['name' => 'Test Model', 'model_number' => '1234']); $response = $this->actingAs(User::factory()->superuser()->create()) ->from(route('models.create')) @@ -77,13 +76,12 @@ public function testUniquenessAcrossModelNameAndModelNumber() ->assertInvalid(['name','model_number']); $this->followRedirects($response)->assertSee(trans('general.error')); - } public function testUniquenessAcrossModelNameAndModelNumberWithoutModelNumber() { - AssetModel::factory()->create(['name' => 'Test Model', 'model_number'=> null]); + AssetModel::factory()->create(['name' => 'Test Model', 'model_number' => null]); $response = $this->actingAs(User::factory()->superuser()->create()) ->from(route('models.create')) @@ -98,7 +96,5 @@ public function testUniquenessAcrossModelNameAndModelNumberWithoutModelNumber() ->assertInvalid(['name']); $this->followRedirects($response)->assertSee(trans('general.error')); - } - } diff --git a/tests/Feature/AssetModels/Ui/UpdateAssetModelsTest.php b/tests/Feature/AssetModels/Ui/UpdateAssetModelsTest.php index 6fdd1bbcfce6..c1b16277aaf9 100644 --- a/tests/Feature/AssetModels/Ui/UpdateAssetModelsTest.php +++ b/tests/Feature/AssetModels/Ui/UpdateAssetModelsTest.php @@ -45,7 +45,6 @@ public function testUserCanEditAssetModels() $this->followRedirects($response)->assertSee('Success'); $this->assertTrue(AssetModel::where('name', 'Test Model Edited')->exists()); - } public function testUserCannotChangeAssetModelCategoryType() @@ -67,7 +66,6 @@ public function testUserCannotChangeAssetModelCategoryType() $this->followRedirects($response)->assertSee(trans('general.error')); $this->assertFalse(AssetModel::where('name', 'Test Model Edited')->exists()); - } public function test_default_values_remain_unchanged_after_validation_error_occurs() diff --git a/tests/Feature/Assets/Api/AssetIndexTest.php b/tests/Feature/Assets/Api/AssetIndexTest.php index c4a362d28b71..f988993c0cca 100644 --- a/tests/Feature/Assets/Api/AssetIndexTest.php +++ b/tests/Feature/Assets/Api/AssetIndexTest.php @@ -22,7 +22,8 @@ public function testAssetApiIndexReturnsExpectedAssets() 'order' => 'asc', 'offset' => '0', 'limit' => '20', - ])) + ]) + ) ->assertOk() ->assertJsonStructure([ 'total', @@ -38,7 +39,8 @@ public function testAssetApiIndexReturnsDisplayUpcomingAuditsDue() $this->actingAsForApi(User::factory()->superuser()->create()) ->getJson( - route('api.assets.list-upcoming', ['action' => 'audits', 'upcoming_status' => 'due'])) + route('api.assets.list-upcoming', ['action' => 'audits', 'upcoming_status' => 'due']) + ) ->assertOk() ->assertJsonStructure([ 'total', @@ -50,10 +52,11 @@ public function testAssetApiIndexReturnsDisplayUpcomingAuditsDue() public function testAssetApiIndexReturnsOverdueForAudit() { Asset::factory()->count(3)->create(['next_audit_date' => Carbon::now()->subDays(1)->format('Y-m-d')]); - + $this->actingAsForApi(User::factory()->superuser()->create()) ->getJson( - route('api.assets.list-upcoming', ['action' => 'audits', 'upcoming_status' => 'overdue'])) + route('api.assets.list-upcoming', ['action' => 'audits', 'upcoming_status' => 'overdue']) + ) ->assertOk() ->assertJsonStructure([ 'total', @@ -67,10 +70,11 @@ public function testAssetApiIndexReturnsDueOrOverdueForAudit() { Asset::factory()->count(3)->create(['next_audit_date' => Carbon::now()->format('Y-m-d')]); Asset::factory()->count(2)->create(['next_audit_date' => Carbon::now()->subDays(1)->format('Y-m-d')]); - + $this->actingAsForApi(User::factory()->superuser()->create()) ->getJson( - route('api.assets.list-upcoming', ['action' => 'audits', 'upcoming_status' => 'due-or-overdue'])) + route('api.assets.list-upcoming', ['action' => 'audits', 'upcoming_status' => 'due-or-overdue']) + ) ->assertOk() ->assertJsonStructure([ 'total', @@ -84,7 +88,7 @@ public function testAssetApiIndexReturnsDueOrOverdueForAudit() public function testAssetApiIndexReturnsDueForExpectedCheckin() { Asset::factory()->count(3)->create(['assigned_to' => '1', 'expected_checkin' => Carbon::now()->format('Y-m-d')]); - + $this->actingAsForApi(User::factory()->superuser()->create()) ->getJson( route('api.assets.list-upcoming', ['action' => 'checkins', 'upcoming_status' => 'due']) @@ -100,7 +104,7 @@ public function testAssetApiIndexReturnsDueForExpectedCheckin() public function testAssetApiIndexReturnsOverdueForExpectedCheckin() { Asset::factory()->count(3)->create(['assigned_to' => '1', 'expected_checkin' => Carbon::now()->subDays(1)->format('Y-m-d')]); - + $this->actingAsForApi(User::factory()->superuser()->create()) ->getJson(route('api.assets.list-upcoming', ['action' => 'checkins', 'upcoming_status' => 'overdue'])) ->assertOk() @@ -115,7 +119,7 @@ public function testAssetApiIndexReturnsDueOrOverdueForExpectedCheckin() { Asset::factory()->count(3)->create(['assigned_to' => '1', 'expected_checkin' => Carbon::now()->subDays(1)->format('Y-m-d')]); Asset::factory()->count(2)->create(['assigned_to' => '1', 'expected_checkin' => Carbon::now()->format('Y-m-d')]); - + $this->actingAsForApi(User::factory()->superuser()->create()) ->getJson(route('api.assets.list-upcoming', ['action' => 'checkins', 'upcoming_status' => 'due-or-overdue'])) ->assertOk() diff --git a/tests/Feature/Assets/Api/AuditAssetTest.php b/tests/Feature/Assets/Api/AuditAssetTest.php index f93a65ae6d84..c874445af364 100644 --- a/tests/Feature/Assets/Api/AuditAssetTest.php +++ b/tests/Feature/Assets/Api/AuditAssetTest.php @@ -41,15 +41,15 @@ public function testLegacyAssetAuditIsSaved() ->assertStatusMessageIs('success') ->assertJson( [ - 'messages' =>trans('admin/hardware/message.audit.success'), + 'messages' => trans('admin/hardware/message.audit.success'), 'payload' => [ 'id' => $asset->id, 'asset_tag' => $asset->asset_tag, 'note' => 'test' ], - ]) + ] + ) ->assertStatus(200); - } @@ -63,16 +63,14 @@ public function testAssetAuditIsSaved() ->assertStatusMessageIs('success') ->assertJson( [ - 'messages' =>trans('admin/hardware/message.audit.success'), + 'messages' => trans('admin/hardware/message.audit.success'), 'payload' => [ 'id' => $asset->id, 'asset_tag' => $asset->asset_tag, 'note' => 'test' ], - ]) + ] + ) ->assertStatus(200); - } - - } diff --git a/tests/Feature/Assets/Api/StoreAssetTest.php b/tests/Feature/Assets/Api/StoreAssetTest.php index ea5cfb617820..2be78094a0ae 100644 --- a/tests/Feature/Assets/Api/StoreAssetTest.php +++ b/tests/Feature/Assets/Api/StoreAssetTest.php @@ -469,7 +469,7 @@ public function testAssetTagsCanBeDuplicatedIfDeleted() ->assertStatusMessageIs('success') ->json(); - Asset::find($response['payload']['id'])->delete(); + Asset::find($response['payload']['id'])->delete(); $this->actingAsForApi(User::factory()->superuser()->create()) ->postJson(route('api.assets.store'), [ diff --git a/tests/Feature/Assets/Api/UpdateAssetTest.php b/tests/Feature/Assets/Api/UpdateAssetTest.php index df4448a2db5c..27e3315788d9 100644 --- a/tests/Feature/Assets/Api/UpdateAssetTest.php +++ b/tests/Feature/Assets/Api/UpdateAssetTest.php @@ -32,7 +32,6 @@ public function testRequiresPermissionToUpdateAsset() } public function testGivenPermissionUpdateAssetIsAllowed() - { $asset = Asset::factory()->create(); @@ -459,7 +458,6 @@ public function testCheckoutToLocationOnAssetUpdate() $asset->refresh(); $this->assertEquals($assigned_location->id, $asset->assigned_to); $this->assertEquals($asset->assigned_type, 'App\Models\Location'); - } public function testCheckoutToDeletedLocationFailsOnAssetUpdate() @@ -499,7 +497,6 @@ public function testCheckoutAssetOnAssetUpdate() $asset->refresh(); $this->assertEquals($assigned_asset->id, $asset->assigned_to); $this->assertEquals($asset->assigned_type, 'App\Models\Asset'); - } public function testCheckoutToDeletedAssetFailsOnAssetUpdate() diff --git a/tests/Feature/Assets/Ui/AssetLabelTest.php b/tests/Feature/Assets/Ui/AssetLabelTest.php index ddf57828bf8b..6f4392bfb803 100644 --- a/tests/Feature/Assets/Ui/AssetLabelTest.php +++ b/tests/Feature/Assets/Ui/AssetLabelTest.php @@ -30,7 +30,6 @@ public function testRedirectOfNoAssetsSelected() 'ids' => $id_array, 'bulk_actions' => 'Labels', ])->assertStatus(302) - ->assertRedirect(route('hardware.index')); + ->assertRedirect(route('hardware.index')); } - } diff --git a/tests/Feature/Assets/Ui/BulkDeleteAssetsTest.php b/tests/Feature/Assets/Ui/BulkDeleteAssetsTest.php index 38c69f3b994b..3ac4cc62a5b8 100644 --- a/tests/Feature/Assets/Ui/BulkDeleteAssetsTest.php +++ b/tests/Feature/Assets/Ui/BulkDeleteAssetsTest.php @@ -49,7 +49,7 @@ public function testPageRedirectFromInterstitialIfNoAssetsSelectedToDelete() ->assertStatus(302) ->assertRedirect(route('hardware.index')); - $this->followRedirects($response)->assertSee('alert-danger'); + $this->followRedirects($response)->assertSee('alert-danger'); } public function testPageRedirectFromInterstitialIfNoAssetsSelectedToRestore() @@ -82,7 +82,7 @@ public function testBulkDeleteSelectedAssetsFromInterstitial() 'bulk_actions' => 'delete', ])->assertStatus(302); - Asset::findMany($id_array)->each(function (Asset $asset) { + Asset::findMany($id_array)->each(function (Asset $asset) { $this->assertNotNull($asset->deleted_at); }); @@ -98,7 +98,7 @@ public function testBulkRestoreSelectedAssetsFromInterstitial() $id_array = $asset->pluck('id')->toArray(); // Check that the assets are deleted - Asset::findMany($id_array)->each(function (Asset $asset) { + Asset::findMany($id_array)->each(function (Asset $asset) { $this->assertNull($asset->deleted_at); }); @@ -110,7 +110,7 @@ public function testBulkRestoreSelectedAssetsFromInterstitial() $this->followRedirects($response)->assertSee('alert-success'); - Asset::findMany($id_array)->each(function (Asset $asset) { + Asset::findMany($id_array)->each(function (Asset $asset) { $this->assertNull($asset->deleted_at); }); } @@ -128,7 +128,8 @@ public function testActionLogCreatedUponBulkDelete() 'bulk_actions' => 'delete', ]); - $this->assertDatabaseHas('action_logs', + $this->assertDatabaseHas( + 'action_logs', [ 'action_type' => 'delete', 'target_id' => null, @@ -151,7 +152,8 @@ public function testActionLogCreatedUponBulkRestore() 'bulk_actions' => 'restore', ]); - $this->assertDatabaseHas('action_logs', + $this->assertDatabaseHas( + 'action_logs', [ 'action_type' => 'restore', 'target_id' => null, @@ -162,28 +164,28 @@ public function testActionLogCreatedUponBulkRestore() ); } - public function testBulkDeleteAssignedAssetTriggersError(){ + public function testBulkDeleteAssignedAssetTriggersError() + { $user = User::factory()->viewAssets()->deleteAssets()->editAssets()->create(); $asset = Asset::factory()->create([ - 'id' => 5, - 'assigned_to' => $user->id, - 'asset_tag' => '12345', + 'id' => 5, + 'assigned_to' => $user->id, + 'asset_tag' => '12345', ]); $response = $this->actingAs($user) - ->from(route('hardware/bulkedit')) - ->post('/hardware/bulkdelete', [ - 'ids' => [$asset->id], - 'bulk_actions' => 'delete', - ]); + ->from(route('hardware/bulkedit')) + ->post('/hardware/bulkdelete', [ + 'ids' => [$asset->id], + 'bulk_actions' => 'delete', + ]); $this->assertEquals(302, $response->getStatusCode()); $this->assertEquals(route('hardware.index'), $response->headers->get('Location')); $errorMessage = session('error'); - $expectedMessage = trans_choice('admin/hardware/message.delete.assigned_to_error',1, ['asset_tag' => $asset->asset_tag]); + $expectedMessage = trans_choice('admin/hardware/message.delete.assigned_to_error', 1, ['asset_tag' => $asset->asset_tag]); $this->assertEquals($expectedMessage, $errorMessage); - } - + } } diff --git a/tests/Feature/Assets/Ui/CloneAssetTest.php b/tests/Feature/Assets/Ui/CloneAssetTest.php index 7989d008b54a..0fa329a42799 100644 --- a/tests/Feature/Assets/Ui/CloneAssetTest.php +++ b/tests/Feature/Assets/Ui/CloneAssetTest.php @@ -26,7 +26,7 @@ public function testPageCanBeAccessed(): void public function testAssetCanBeCloned() { - $asset_to_clone = Asset::factory()->create(['name'=>'Asset to clone']); + $asset_to_clone = Asset::factory()->create(['name' => 'Asset to clone']); $this->actingAs(User::factory()->createAssets()->create()) ->get(route('clone/hardware', $asset_to_clone)) ->assertOk() diff --git a/tests/Feature/Authentication/LoginTest.php b/tests/Feature/Authentication/LoginTest.php index 2f688a59d8eb..c9689a9a3225 100644 --- a/tests/Feature/Authentication/LoginTest.php +++ b/tests/Feature/Authentication/LoginTest.php @@ -32,10 +32,10 @@ public function testLogsFailedLoginAttempt() public function testLoginThrottleConfigIsRespected() { - User::factory()->create(['username' => 'username_here']); + User::factory()->create(['username' => 'username_here']); - config(['auth.passwords.users.throttle.max_attempts' => 1]); - config(['auth.passwords.users.throttle.lockout_duration' => 1]); + config(['auth.passwords.users.throttle.max_attempts' => 1]); + config(['auth.passwords.users.throttle.lockout_duration' => 1]); for ($i = 0; $i < 2; ++$i) { $this->from('/login') diff --git a/tests/Feature/Categories/Api/CreateCategoriesTest.php b/tests/Feature/Categories/Api/CreateCategoriesTest.php index 2a4a0661a6eb..8181797f0fff 100644 --- a/tests/Feature/Categories/Api/CreateCategoriesTest.php +++ b/tests/Feature/Categories/Api/CreateCategoriesTest.php @@ -11,8 +11,6 @@ class CreateCategoriesTest extends TestCase { - - public function testRequiresPermissionToCreateCategory() { $this->actingAsForApi(User::factory()->create()) @@ -58,7 +56,6 @@ public function testCannotCreateCategoryWithoutCategoryType() ], ]); $this->assertFalse(Category::where('name', 'Test Category')->exists()); - } public function testCannotCreateCategoryWithInvalidCategoryType() @@ -77,9 +74,7 @@ public function testCannotCreateCategoryWithInvalidCategoryType() 'category_type' => ['The selected category type is invalid.'], ], ]); - - $this->assertFalse(Category::where('name', 'Test Category')->exists()); + $this->assertFalse(Category::where('name', 'Test Category')->exists()); } - } diff --git a/tests/Feature/Categories/Api/IndexCategoriesTest.php b/tests/Feature/Categories/Api/IndexCategoriesTest.php index d27bfbb06807..8b6471057e64 100644 --- a/tests/Feature/Categories/Api/IndexCategoriesTest.php +++ b/tests/Feature/Categories/Api/IndexCategoriesTest.php @@ -9,7 +9,6 @@ class IndexCategoriesTest extends TestCase { - public function testViewingCategoryIndexRequiresPermission() { $this->actingAsForApi(User::factory()->create()) @@ -30,7 +29,8 @@ public function testCategoryIndexReturnsExpectedSearchResults() 'order' => 'asc', 'offset' => '0', 'limit' => '20', - ])) + ]) + ) ->assertOk() ->assertJsonStructure([ 'total', @@ -39,7 +39,6 @@ public function testCategoryIndexReturnsExpectedSearchResults() ->assertJson([ 'total' => 1, ]); - } @@ -55,7 +54,8 @@ public function testCategoryIndexReturnsExpectedCategories() 'order' => 'asc', 'offset' => '0', 'limit' => '20', - ])) + ]) + ) ->assertOk() ->assertJsonStructure([ 'total', @@ -64,7 +64,5 @@ public function testCategoryIndexReturnsExpectedCategories() ->assertJson([ 'total' => 3, ]); - } - } diff --git a/tests/Feature/Categories/Api/UpdateCategoriesTest.php b/tests/Feature/Categories/Api/UpdateCategoriesTest.php index 6d6bc8da10eb..2b4e9c6e6433 100644 --- a/tests/Feature/Categories/Api/UpdateCategoriesTest.php +++ b/tests/Feature/Categories/Api/UpdateCategoriesTest.php @@ -8,7 +8,6 @@ class UpdateCategoriesTest extends TestCase { - public function testCanUpdateCategoryViaPatchWithoutCategoryType() { $category = Category::factory()->create(); @@ -29,7 +28,6 @@ public function testCanUpdateCategoryViaPatchWithoutCategoryType() $this->assertEquals('Test Category', $category->name, 'Name was not updated'); $this->assertEquals('Test EULA', $category->eula_text, 'EULA was not updated'); $this->assertEquals('Test Note', $category->notes, 'Note was not updated'); - } public function testCannotUpdateCategoryViaPatchWithCategoryType() @@ -47,13 +45,11 @@ public function testCannotUpdateCategoryViaPatchWithCategoryType() ->assertStatusMessageIs('error') ->assertStatus(200) ->json(); - + $category->refresh(); $this->assertNotEquals('Test Category', $category->name, 'Name was not updated'); $this->assertNotEquals('Test EULA', $category->eula_text, 'EULA was not updated'); $this->assertNotEquals('Test Note', $category->notes, 'Note was not updated'); $this->assertNotEquals('accessory', $category->category_type, 'EULA was not updated'); - } - } diff --git a/tests/Feature/Categories/Ui/CreateCategoriesTest.php b/tests/Feature/Categories/Ui/CreateCategoriesTest.php index 694b61c613b1..4e4bf3755502 100644 --- a/tests/Feature/Categories/Ui/CreateCategoriesTest.php +++ b/tests/Feature/Categories/Ui/CreateCategoriesTest.php @@ -55,5 +55,4 @@ public function testUserCannotCreateCategoriesWithInvalidType() $this->assertFalse(Category::where('name', 'Test Category')->exists()); } - } diff --git a/tests/Feature/Categories/Ui/UpdateCategoriesTest.php b/tests/Feature/Categories/Ui/UpdateCategoriesTest.php index ea5cc633886a..56b9b0ce5cb0 100644 --- a/tests/Feature/Categories/Ui/UpdateCategoriesTest.php +++ b/tests/Feature/Categories/Ui/UpdateCategoriesTest.php @@ -57,7 +57,6 @@ public function testUserCanEditAssetCategory() $this->followRedirects($response)->assertSee('Success'); $this->assertTrue(Category::where('name', 'Test Category Edited')->where('notes', 'Test Note Edited')->exists()); - } public function testUserCanChangeCategoryTypeIfNoAssetsAssociated() @@ -78,7 +77,6 @@ public function testUserCanChangeCategoryTypeIfNoAssetsAssociated() $this->followRedirects($response)->assertSee('Success'); $this->assertTrue(Category::where('name', 'Test Category Edited')->where('notes', 'Test Note Edited')->exists()); - } public function testUserCannotChangeCategoryTypeIfAssetsAreAssociated() @@ -100,7 +98,5 @@ public function testUserCannotChangeCategoryTypeIfAssetsAreAssociated() $this->followRedirects($response)->assertSee(trans('general.error')); $this->assertFalse(Category::where('name', 'Test Category Edited')->where('notes', 'Test Note Edited')->exists()); - } - } diff --git a/tests/Feature/Checkins/Api/LicenseCheckInTest.php b/tests/Feature/Checkins/Api/LicenseCheckInTest.php index 385933655c52..2b62a804d706 100644 --- a/tests/Feature/Checkins/Api/LicenseCheckInTest.php +++ b/tests/Feature/Checkins/Api/LicenseCheckInTest.php @@ -1,4 +1,5 @@ superuser()->create(); @@ -28,7 +30,8 @@ public function testLicenseCheckin() $response = $this->patchJson( route('api.licenses.seats.update', [$license->id, $licenseSeat->id]), - $payload); + $payload + ); $response->assertStatus(200) ->assertJsonFragment([ @@ -42,4 +45,4 @@ public function testLicenseCheckin() $this->assertEquals('Checking in the seat', $licenseSeat->notes); } -} \ No newline at end of file +} diff --git a/tests/Feature/Checkins/Ui/AccessoryCheckinTest.php b/tests/Feature/Checkins/Ui/AccessoryCheckinTest.php index a8572c6186a1..31fe3c3e2182 100644 --- a/tests/Feature/Checkins/Ui/AccessoryCheckinTest.php +++ b/tests/Feature/Checkins/Ui/AccessoryCheckinTest.php @@ -64,9 +64,8 @@ public function testEmailSentToUserIfSettingEnabled() User::factory()->checkinAccessories()->create(), '', )); - Mail::assertSent(CheckinAccessoryMail::class, function (CheckinAccessoryMail $mail) use ( $accessory, $user) { + Mail::assertSent(CheckinAccessoryMail::class, function (CheckinAccessoryMail $mail) use ($accessory, $user) { return $mail->hasTo($user->email); - }); } diff --git a/tests/Feature/Checkins/Ui/AssetCheckinTest.php b/tests/Feature/Checkins/Ui/AssetCheckinTest.php index 4f1c62cf2ce3..b6e3e20fd1a1 100644 --- a/tests/Feature/Checkins/Ui/AssetCheckinTest.php +++ b/tests/Feature/Checkins/Ui/AssetCheckinTest.php @@ -163,7 +163,8 @@ public function testCheckinTimeAndActionLogNoteCanBeSet() $this->actingAs(User::factory()->checkinAssets()->create()) ->post(route( - 'hardware.checkin.store', [Asset::factory()->assignedToUser()->create()] + 'hardware.checkin.store', + [Asset::factory()->assignedToUser()->create()] ), [ 'checkin_at' => '2023-01-02', 'note' => 'hello' diff --git a/tests/Feature/Checkins/Ui/LicenseCheckinTest.php b/tests/Feature/Checkins/Ui/LicenseCheckinTest.php index 7a6553d8ba61..4020a73f9e46 100644 --- a/tests/Feature/Checkins/Ui/LicenseCheckinTest.php +++ b/tests/Feature/Checkins/Ui/LicenseCheckinTest.php @@ -118,14 +118,12 @@ public function testCanCheckInLicenseAssignedToUser() && $event->checkedInBy->is($actor) && $event->note === 'my note'; }); - } - + public function testPageRenders() { $this->actingAs(User::factory()->superuser()->create()) ->get(route('licenses.checkin', LicenseSeat::factory()->assignedToUser()->create()->id)) ->assertOk(); - } } diff --git a/tests/Feature/CheckoutAcceptances/Ui/AssetAcceptanceTest.php b/tests/Feature/CheckoutAcceptances/Ui/AssetAcceptanceTest.php index 4a3ee4001a10..40db4a841783 100644 --- a/tests/Feature/CheckoutAcceptances/Ui/AssetAcceptanceTest.php +++ b/tests/Feature/CheckoutAcceptances/Ui/AssetAcceptanceTest.php @@ -133,8 +133,7 @@ public function testActionLoggedWhenAcceptingAsset() 'item_id' => $checkoutAcceptance->checkoutable->id, ]) ->whereNotNull('action_date') - ->exists() - ); + ->exists()); } public function testActionLoggedWhenDecliningAsset() @@ -157,7 +156,6 @@ public function testActionLoggedWhenDecliningAsset() 'item_id' => $checkoutAcceptance->checkoutable->id, ]) ->whereNotNull('action_date') - ->exists() - ); + ->exists()); } } diff --git a/tests/Feature/Checkouts/Api/AccessoryCheckoutTest.php b/tests/Feature/Checkouts/Api/AccessoryCheckoutTest.php index 7adab09c039b..38f6f016576a 100644 --- a/tests/Feature/Checkouts/Api/AccessoryCheckoutTest.php +++ b/tests/Feature/Checkouts/Api/AccessoryCheckoutTest.php @@ -46,17 +46,21 @@ public function testAccessoryMustBeAvailableWhenCheckingOut() [ 'checkout_qty' => [ - trans_choice('admin/accessories/message.checkout.checkout_qty.lte', 0, + trans_choice( + 'admin/accessories/message.checkout.checkout_qty.lte', + 0, [ 'number_currently_remaining' => 0, 'checkout_qty' => 1, 'number_remaining_after_checkout' => 0 - ]) + ] + ) ], ], 'payload' => null, - ]) + ] + ) ->assertStatus(200) ->json(); } @@ -89,7 +93,8 @@ public function testAccessoryCanBeCheckedOutWithoutQty() 'item_id' => $accessory->id, 'item_type' => Accessory::class, 'created_by' => $admin->id, - ])->count(),'Log entry either does not exist or there are more than expected' + ])->count(), + 'Log entry either does not exist or there are more than expected' ); } diff --git a/tests/Feature/Checkouts/Api/AssetCheckoutTest.php b/tests/Feature/Checkouts/Api/AssetCheckoutTest.php index e83ad7d30d7f..f5fc63177579 100644 --- a/tests/Feature/Checkouts/Api/AssetCheckoutTest.php +++ b/tests/Feature/Checkouts/Api/AssetCheckoutTest.php @@ -36,7 +36,6 @@ public function testCheckoutRequest() $this->actingAsForApi(User::factory()->create()) ->post(route('api.assets.requests.store', $nonRequestable->id)) ->assertStatusMessageIs('error'); - } public function testCheckingOutAssetRequiresCorrectPermission() @@ -179,7 +178,7 @@ public function testAssetCanBeCheckedOut($data) $this->actingAsForApi($admin) ->postJson(route('api.asset.checkout', $asset), [ 'checkout_to_type' => $type, - 'assigned_'.$type => $target->id, + 'assigned_' . $type => $target->id, 'status_id' => $newStatus->id, 'checkout_at' => '2024-04-01', 'expected_checkin' => '2024-04-08', diff --git a/tests/Feature/Checkouts/Api/ConsumableCheckoutTest.php b/tests/Feature/Checkouts/Api/ConsumableCheckoutTest.php index fba2c50df377..db2375258db7 100644 --- a/tests/Feature/Checkouts/Api/ConsumableCheckoutTest.php +++ b/tests/Feature/Checkouts/Api/ConsumableCheckoutTest.php @@ -70,7 +70,8 @@ public function testUserSentNotificationUponCheckout() } public function testActionLogCreatedUponCheckout() - {$consumable = Consumable::factory()->create(); + { + $consumable = Consumable::factory()->create(); $actor = User::factory()->checkoutConsumables()->create(); $user = User::factory()->create(); diff --git a/tests/Feature/Checkouts/Api/LicenseCheckOutTest.php b/tests/Feature/Checkouts/Api/LicenseCheckOutTest.php index 7a069b7d28ec..a66802a15035 100644 --- a/tests/Feature/Checkouts/Api/LicenseCheckOutTest.php +++ b/tests/Feature/Checkouts/Api/LicenseCheckOutTest.php @@ -1,4 +1,5 @@ superuser()->create(); @@ -26,7 +28,8 @@ public function testLicenseCheckout() $response = $this->patchJson( route('api.licenses.seats.update', [$license->id, $licenseSeat->id]), - $payload); + $payload + ); $response->assertStatus(200) ->assertJsonFragment([ @@ -38,4 +41,4 @@ public function testLicenseCheckout() $this->assertEquals($targetUser->id, $licenseSeat->assigned_to); $this->assertEquals('Checking out the seat to a user', $licenseSeat->notes); } -} \ No newline at end of file +} diff --git a/tests/Feature/Checkouts/Ui/AccessoryCheckoutTest.php b/tests/Feature/Checkouts/Ui/AccessoryCheckoutTest.php index 19b0d1ce7264..067be255deb2 100644 --- a/tests/Feature/Checkouts/Ui/AccessoryCheckoutTest.php +++ b/tests/Feature/Checkouts/Ui/AccessoryCheckoutTest.php @@ -87,7 +87,7 @@ public function testAccessoryCanBeCheckedOutWithoutQuantity() public function testAccessoryCanBeCheckedOutWithQuantity() { - $accessory = Accessory::factory()->create(['qty'=>5]); + $accessory = Accessory::factory()->create(['qty' => 5]); $user = User::factory()->create(); $this->actingAs(User::factory()->checkoutAccessories()->create()) @@ -113,7 +113,7 @@ public function testAccessoryCanBeCheckedOutWithQuantity() public function testAccessoryCanBeCheckedOutToLocationWithQuantity() { - $accessory = Accessory::factory()->create(['qty'=>5]); + $accessory = Accessory::factory()->create(['qty' => 5]); $location = Location::factory()->create(); $this->actingAs(User::factory()->checkoutAccessories()->create()) @@ -139,7 +139,7 @@ public function testAccessoryCanBeCheckedOutToLocationWithQuantity() public function testAccessoryCanBeCheckedOutToAssetWithQuantity() { - $accessory = Accessory::factory()->create(['qty'=>5]); + $accessory = Accessory::factory()->create(['qty' => 5]); $asset = Asset::factory()->create(); $this->actingAs(User::factory()->checkoutAccessories()->create()) @@ -233,7 +233,7 @@ public function testAccessoryCheckoutPagePostIsRedirectedIfRedirectSelectionIsIt $this->actingAs(User::factory()->admin()->create()) ->from(route('accessories.index')) - ->post(route('accessories.checkout.store' , $accessory), [ + ->post(route('accessories.checkout.store', $accessory), [ 'assigned_user' => User::factory()->create()->id, 'checkout_to_type' => 'user', 'redirect_option' => 'item', @@ -251,7 +251,7 @@ public function testAccessoryCheckoutPagePostIsRedirectedIfRedirectSelectionIsTa $this->actingAs(User::factory()->admin()->create()) ->from(route('accessories.index')) - ->post(route('accessories.checkout.store' , $accessory), [ + ->post(route('accessories.checkout.store', $accessory), [ 'assigned_user' => $user->id, 'checkout_to_type' => 'user', 'redirect_option' => 'target', diff --git a/tests/Feature/Checkouts/Ui/AssetCheckoutTest.php b/tests/Feature/Checkouts/Ui/AssetCheckoutTest.php index 00197917522e..5dc0775acd1e 100644 --- a/tests/Feature/Checkouts/Ui/AssetCheckoutTest.php +++ b/tests/Feature/Checkouts/Ui/AssetCheckoutTest.php @@ -287,7 +287,7 @@ public function testAssetCheckoutPagePostIsRedirectedIfRedirectSelectionIsItem() $this->actingAs(User::factory()->admin()->create()) ->from(route('hardware.checkout.create', $asset)) - ->post(route('hardware.checkout.store' , $asset), [ + ->post(route('hardware.checkout.store', $asset), [ 'checkout_to_type' => 'user', 'assigned_user' => User::factory()->create()->id, 'redirect_option' => 'item', @@ -304,7 +304,7 @@ public function testAssetCheckoutPagePostIsRedirectedIfRedirectSelectionIsUserTa $this->actingAs(User::factory()->admin()->create()) ->from(route('hardware.checkout.create', $asset)) - ->post(route('hardware.checkout.store' , $asset), [ + ->post(route('hardware.checkout.store', $asset), [ 'checkout_to_type' => 'user', 'assigned_user' => $user->id, 'redirect_option' => 'target', @@ -321,7 +321,7 @@ public function testAssetCheckoutPagePostIsRedirectedIfRedirectSelectionIsAssetT $this->actingAs(User::factory()->admin()->create()) ->from(route('hardware.checkout.create', $asset)) - ->post(route('hardware.checkout.store' , $asset), [ + ->post(route('hardware.checkout.store', $asset), [ 'checkout_to_type' => 'asset', 'assigned_asset' => $target->id, 'redirect_option' => 'target', @@ -338,7 +338,7 @@ public function testAssetCheckoutPagePostIsRedirectedIfRedirectSelectionIsLocati $this->actingAs(User::factory()->admin()->create()) ->from(route('hardware.checkout.create', $asset)) - ->post(route('hardware.checkout.store' , $asset), [ + ->post(route('hardware.checkout.store', $asset), [ 'checkout_to_type' => 'location', 'assigned_location' => $target->id, 'redirect_option' => 'target', diff --git a/tests/Feature/Checkouts/Ui/ComponentsCheckoutTest.php b/tests/Feature/Checkouts/Ui/ComponentsCheckoutTest.php index 18568d19858a..e9218d6251b3 100644 --- a/tests/Feature/Checkouts/Ui/ComponentsCheckoutTest.php +++ b/tests/Feature/Checkouts/Ui/ComponentsCheckoutTest.php @@ -70,7 +70,7 @@ public function testComponentCheckoutPagePostIsRedirectedIfRedirectSelectionIsIt $this->actingAs(User::factory()->admin()->create()) ->from(route('components.index')) - ->post(route('components.checkout.store' , $component), [ + ->post(route('components.checkout.store', $component), [ 'asset_id' => Asset::factory()->create()->id, 'redirect_option' => 'item', 'assigned_qty' => 1, @@ -86,7 +86,7 @@ public function testComponentCheckoutPagePostIsRedirectedIfRedirectSelectionIsTa $this->actingAs(User::factory()->admin()->create()) ->from(route('components.index')) - ->post(route('components.checkout.store' , $component), [ + ->post(route('components.checkout.store', $component), [ 'asset_id' => $asset->id, 'redirect_option' => 'target', 'assigned_qty' => 1, diff --git a/tests/Feature/Checkouts/Ui/ConsumableCheckoutTest.php b/tests/Feature/Checkouts/Ui/ConsumableCheckoutTest.php index 2c74e4d0cb23..0312087d8ee0 100644 --- a/tests/Feature/Checkouts/Ui/ConsumableCheckoutTest.php +++ b/tests/Feature/Checkouts/Ui/ConsumableCheckoutTest.php @@ -124,7 +124,7 @@ public function testConsumableCheckoutPagePostIsRedirectedIfRedirectSelectionIsI $this->actingAs(User::factory()->admin()->create()) ->from(route('consumables.index')) - ->post(route('consumables.checkout.store' , $consumable), [ + ->post(route('consumables.checkout.store', $consumable), [ 'assigned_to' => User::factory()->create()->id, 'redirect_option' => 'item', 'assigned_qty' => 1, @@ -140,7 +140,7 @@ public function testConsumableCheckoutPagePostIsRedirectedIfRedirectSelectionIsT $this->actingAs(User::factory()->admin()->create()) ->from(route('components.index')) - ->post(route('consumables.checkout.store' , $consumable), [ + ->post(route('consumables.checkout.store', $consumable), [ 'assigned_to' => $user->id, 'redirect_option' => 'target', 'assigned_qty' => 1, @@ -148,5 +148,4 @@ public function testConsumableCheckoutPagePostIsRedirectedIfRedirectSelectionIsT ->assertStatus(302) ->assertRedirect(route('users.show', $user)); } - } diff --git a/tests/Feature/Checkouts/Ui/LicenseCheckoutTest.php b/tests/Feature/Checkouts/Ui/LicenseCheckoutTest.php index 1750b7564783..90d3efa66254 100644 --- a/tests/Feature/Checkouts/Ui/LicenseCheckoutTest.php +++ b/tests/Feature/Checkouts/Ui/LicenseCheckoutTest.php @@ -100,7 +100,7 @@ public function testLicenseCheckoutPagePostIsRedirectedIfRedirectSelectionIsUser $this->actingAs(User::factory()->admin()->create()) ->from(route('licenses.checkout', $license)) - ->post(route('licenses.checkout' , $license), [ + ->post(route('licenses.checkout', $license), [ 'assigned_to' => $user->id, 'redirect_option' => 'target', ]) @@ -114,7 +114,7 @@ public function testLicenseCheckoutPagePostIsRedirectedIfRedirectSelectionIsAsse $this->actingAs(User::factory()->admin()->create()) ->from(route('licenses.checkout', $license)) - ->post(route('licenses.checkout' , $license), [ + ->post(route('licenses.checkout', $license), [ 'asset_id' => $asset->id, 'redirect_option' => 'target', ]) diff --git a/tests/Feature/Console/FixupAssignedToAssignedTypeTest.php b/tests/Feature/Console/FixupAssignedToAssignedTypeTest.php index 2b5f9b415d0e..261338db47ef 100644 --- a/tests/Feature/Console/FixupAssignedToAssignedTypeTest.php +++ b/tests/Feature/Console/FixupAssignedToAssignedTypeTest.php @@ -15,7 +15,7 @@ public function testEmptyAssignedType() $admin = User::factory()->admin()->create(); $asset->checkOut($user, $admin); - $asset->assigned_type=null; //blank out the assigned type + $asset->assigned_type = null; //blank out the assigned type $asset->save(); $this->artisan('snipeit:assigned-to-fixup --debug')->assertExitCode(0); @@ -31,11 +31,11 @@ public function testInvalidAssignedTo() $admin = User::factory()->admin()->create(); $asset->checkOut($user, $admin); - $asset->assigned_type=null; - $asset->assigned_to=null; + $asset->assigned_type = null; + $asset->assigned_to = null; $asset->saveOrFail(); //*should* generate a 'checkin'? - $asset->assigned_to=$user->id; //incorrectly mark asset as partially checked-out + $asset->assigned_to = $user->id; //incorrectly mark asset as partially checked-out $asset->saveOrFail(); $this->artisan('snipeit:assigned-to-fixup --debug')->assertExitCode(0); diff --git a/tests/Feature/Console/MergeUsersTest.php b/tests/Feature/Console/MergeUsersTest.php index 4c43e6293d3e..91df04004d0a 100644 --- a/tests/Feature/Console/MergeUsersTest.php +++ b/tests/Feature/Console/MergeUsersTest.php @@ -10,7 +10,6 @@ use App\Models\Actionlog; use Tests\TestCase; - class MergeUsersTest extends TestCase { public function testAssetsAreTransferredOnUserMerge() @@ -25,7 +24,6 @@ public function testAssetsAreTransferredOnUserMerge() $this->assertEquals(6, $user_to_merge_into->refresh()->assets->count()); $this->assertEquals(0, $user1->refresh()->assets->count()); - } public function testLicensesAreTransferredOnUserMerge(): void @@ -42,7 +40,6 @@ public function testLicensesAreTransferredOnUserMerge(): void $this->assertEquals(6, $user_to_merge_into->refresh()->licenses->count()); $this->assertEquals(0, $user1->refresh()->licenses->count()); - } public function testAccessoriesTransferredOnUserMerge(): void @@ -59,7 +56,6 @@ public function testAccessoriesTransferredOnUserMerge(): void $this->assertEquals(6, $user_to_merge_into->refresh()->accessories->count()); $this->assertEquals(0, $user1->refresh()->accessories->count()); - } public function testConsumablesTransferredOnUserMerge(): void @@ -76,7 +72,6 @@ public function testConsumablesTransferredOnUserMerge(): void $this->assertEquals(6, $user_to_merge_into->refresh()->consumables->count()); $this->assertEquals(0, $user1->refresh()->consumables->count()); - } public function testFilesAreTransferredOnUserMerge(): void @@ -93,7 +88,6 @@ public function testFilesAreTransferredOnUserMerge(): void $this->assertEquals(6, $user_to_merge_into->refresh()->uploads->count()); $this->assertEquals(0, $user1->refresh()->uploads->count()); - } public function testAcceptancesAreTransferredOnUserMerge(): void @@ -110,7 +104,6 @@ public function testAcceptancesAreTransferredOnUserMerge(): void $this->assertEquals(6, $user_to_merge_into->refresh()->acceptances->count()); $this->assertEquals(0, $user1->refresh()->acceptances->count()); - } public function testUserUpdateHistoryIsTransferredOnUserMerge(): void @@ -128,8 +121,5 @@ public function testUserUpdateHistoryIsTransferredOnUserMerge(): void // This needs to be more than the otherwise expected because the merge action itself is logged for the two merging users $this->assertEquals(7, $user_to_merge_into->refresh()->userlog->count()); $this->assertEquals(1, $user1->refresh()->userlog->count()); - } - - } diff --git a/tests/Feature/Console/SendAcceptanceReminderTest.php b/tests/Feature/Console/SendAcceptanceReminderTest.php index ee28e093557a..883170b9e744 100644 --- a/tests/Feature/Console/SendAcceptanceReminderTest.php +++ b/tests/Feature/Console/SendAcceptanceReminderTest.php @@ -7,17 +7,18 @@ use App\Models\User; use Illuminate\Support\Facades\Mail; use Tests\TestCase; + class SendAcceptanceReminderTest extends TestCase { public function testAcceptanceReminderCommand() { Mail::fake(); - $userA = User::factory()->create(['email' => 'userA@test.com']); - $userB = User::factory()->create(['email' => 'userB@test.com']); + $userA = User::factory()->create(['email' => 'userA@test.com']); + $userB = User::factory()->create(['email' => 'userB@test.com']); - CheckoutAcceptance::factory()->pending()->count(2)->create([ + CheckoutAcceptance::factory()->pending()->count(2)->create([ 'assigned_to_id' => $userA->id, - ]); + ]); CheckoutAcceptance::factory()->pending()->create([ 'assigned_to_id' => $userB->id, ]); @@ -32,7 +33,7 @@ public function testAcceptanceReminderCommand() return $mail->hasTo('userB@test.com'); }); - Mail::assertSent(UnacceptedAssetReminderMail::class,2); + Mail::assertSent(UnacceptedAssetReminderMail::class, 2); } public function testAcceptanceReminderCommandHandlesUserWithoutEmail() diff --git a/tests/Feature/Consumables/Api/ConsumableIndexTest.php b/tests/Feature/Consumables/Api/ConsumableIndexTest.php index f1d3ad7f0b0e..ee95b67bbf73 100644 --- a/tests/Feature/Consumables/Api/ConsumableIndexTest.php +++ b/tests/Feature/Consumables/Api/ConsumableIndexTest.php @@ -68,7 +68,8 @@ public function testConsumableIndexReturnsExpectedSearchResults() 'order' => 'asc', 'offset' => '0', 'limit' => '20', - ])) + ]) + ) ->assertOk() ->assertJsonStructure([ 'total', @@ -77,6 +78,5 @@ public function testConsumableIndexReturnsExpectedSearchResults() ->assertJson([ 'total' => 1, ]); - } } diff --git a/tests/Feature/Consumables/Api/ConsumableUpdateTest.php b/tests/Feature/Consumables/Api/ConsumableUpdateTest.php index 1c1e05d4d43b..1aadd4868aa9 100644 --- a/tests/Feature/Consumables/Api/ConsumableUpdateTest.php +++ b/tests/Feature/Consumables/Api/ConsumableUpdateTest.php @@ -9,7 +9,6 @@ class ConsumableUpdateTest extends TestCase { - public function testCanUpdateConsumableViaPatchWithoutCategoryType() { $consumable = Consumable::factory()->create(); @@ -25,7 +24,6 @@ public function testCanUpdateConsumableViaPatchWithoutCategoryType() $consumable->refresh(); $this->assertEquals('Test Consumable', $consumable->name, 'Name was not updated'); - } public function testCannotUpdateConsumableViaPatchWithInvalidCategoryType() @@ -46,7 +44,5 @@ public function testCannotUpdateConsumableViaPatchWithInvalidCategoryType() $category->refresh(); $this->assertNotEquals('Test Consumable', $consumable->name, 'Name was not updated'); $this->assertNotEquals('consumable', $consumable->category_id, 'Category was not updated'); - } - } diff --git a/tests/Feature/Consumables/Ui/CreateConsumableTest.php b/tests/Feature/Consumables/Ui/CreateConsumableTest.php index 83f0c89552c4..9b8950e19fd3 100644 --- a/tests/Feature/Consumables/Ui/CreateConsumableTest.php +++ b/tests/Feature/Consumables/Ui/CreateConsumableTest.php @@ -62,6 +62,5 @@ public function testPageRenders() $this->actingAs(User::factory()->superuser()->create()) ->get(route('consumables.create')) ->assertOk(); - } } diff --git a/tests/Feature/Consumables/Ui/UpdateConsumableTest.php b/tests/Feature/Consumables/Ui/UpdateConsumableTest.php index dbb13b9ce736..14de33d455de 100644 --- a/tests/Feature/Consumables/Ui/UpdateConsumableTest.php +++ b/tests/Feature/Consumables/Ui/UpdateConsumableTest.php @@ -74,7 +74,6 @@ public function testCannotSetQuantityToAmountLowerThanWhatIsCheckedOut() 'category_type' => 'consumable', ]) ->assertSessionHasErrors('qty'); - } public function testCanUpdateConsumable() diff --git a/tests/Feature/Departments/Api/CreateDepartmentsTest.php b/tests/Feature/Departments/Api/CreateDepartmentsTest.php index e0f975dd7f41..0134ead649ba 100644 --- a/tests/Feature/Departments/Api/CreateDepartmentsTest.php +++ b/tests/Feature/Departments/Api/CreateDepartmentsTest.php @@ -11,8 +11,6 @@ class CreateDepartmentsTest extends TestCase { - - public function testRequiresPermissionToCreateDepartment() { $this->actingAsForApi(User::factory()->create()) @@ -38,5 +36,4 @@ public function testCanCreateDepartment() $this->assertEquals('Test Department', $department->name); $this->assertEquals('Test Note', $department->notes); } - } diff --git a/tests/Feature/Departments/Api/DepartmentsIndexTest.php b/tests/Feature/Departments/Api/DepartmentsIndexTest.php index e3616e249166..63063e0d7a91 100644 --- a/tests/Feature/Departments/Api/DepartmentsIndexTest.php +++ b/tests/Feature/Departments/Api/DepartmentsIndexTest.php @@ -33,7 +33,8 @@ public function testDepartmentIndexReturnsExpectedDepartments() 'order' => 'asc', 'offset' => '0', 'limit' => '20', - ])) + ]) + ) ->assertOk() ->assertJsonStructure([ 'total', diff --git a/tests/Feature/Departments/Api/UpdateDepartmentsTest.php b/tests/Feature/Departments/Api/UpdateDepartmentsTest.php index b4eb38301a88..b34b9b9083c3 100644 --- a/tests/Feature/Departments/Api/UpdateDepartmentsTest.php +++ b/tests/Feature/Departments/Api/UpdateDepartmentsTest.php @@ -9,7 +9,6 @@ class UpdateDepartmentsTest extends TestCase { - public function testRequiresPermissionToEditDepartment() { $department = Department::factory()->create(); @@ -35,9 +34,5 @@ public function testCanUpdateDepartmentViaPatch() $department->refresh(); $this->assertEquals('Test Department', $department->name, 'Name was not updated'); $this->assertEquals('Test Note', $department->notes, 'Note was not updated'); - } - - - } diff --git a/tests/Feature/Departments/Ui/CreateDepartmentsTest.php b/tests/Feature/Departments/Ui/CreateDepartmentsTest.php index f20a2c7b6ac1..02df5d63774d 100644 --- a/tests/Feature/Departments/Ui/CreateDepartmentsTest.php +++ b/tests/Feature/Departments/Ui/CreateDepartmentsTest.php @@ -41,6 +41,4 @@ public function testUserCanCreateDepartments() $this->assertTrue(Department::where('name', 'Test Department')->where('notes', 'Test Note')->exists()); } - - } diff --git a/tests/Feature/Departments/Ui/UpdateDepartmentsTest.php b/tests/Feature/Departments/Ui/UpdateDepartmentsTest.php index 83e52bf7c0d1..fd9c86a49d95 100644 --- a/tests/Feature/Departments/Ui/UpdateDepartmentsTest.php +++ b/tests/Feature/Departments/Ui/UpdateDepartmentsTest.php @@ -42,9 +42,5 @@ public function testUserCanEditDepartments() $this->followRedirects($response)->assertSee('Success'); $this->assertTrue(Department::where('name', 'Test Department Edited')->where('notes', 'Test Note Edited')->exists()); - } - - - } diff --git a/tests/Feature/Depreciations/Api/DepreciationsIndexTest.php b/tests/Feature/Depreciations/Api/DepreciationsIndexTest.php index 29583001ab3b..3828f8c60b5f 100644 --- a/tests/Feature/Depreciations/Api/DepreciationsIndexTest.php +++ b/tests/Feature/Depreciations/Api/DepreciationsIndexTest.php @@ -13,5 +13,4 @@ public function testViewingDepreciationIndexRequiresPermission() ->getJson(route('api.departments.index')) ->assertForbidden(); } - } diff --git a/tests/Feature/Groups/Api/StoreGroupTest.php b/tests/Feature/Groups/Api/StoreGroupTest.php index 484c921a6ca7..21313f7890fe 100644 --- a/tests/Feature/Groups/Api/StoreGroupTest.php +++ b/tests/Feature/Groups/Api/StoreGroupTest.php @@ -58,7 +58,7 @@ public function testStoringGroupWithoutPermissionPassed() ); $this->actingAsForApi($superuser) - ->getJson(route('api.groups.show', ['group' => $group])) + ->getJson(route('api.groups.show', ['group' => $group])) ->assertOk(); } @@ -78,6 +78,5 @@ public function testStoringGroupWithInvalidPermissionDropsBadPermission() $this->assertNotNull($group); $this->assertEquals('1', $group->decodePermissions()['admin']); $this->assertNotContains('snipe_is_awesome', $group->decodePermissions()); - } } diff --git a/tests/Feature/Importing/Api/ImportAssetModelsTest.php b/tests/Feature/Importing/Api/ImportAssetModelsTest.php index f1af2ad34a55..64f7da5fc4b2 100644 --- a/tests/Feature/Importing/Api/ImportAssetModelsTest.php +++ b/tests/Feature/Importing/Api/ImportAssetModelsTest.php @@ -36,7 +36,7 @@ public function testRequiresPermission() $this->importFileResponse(['import' => 44])->assertForbidden(); } - + #[Test] public function importAssetModels(): void { @@ -60,7 +60,6 @@ public function importAssetModels(): void $this->assertEquals($row['name'], $newAssetModel->name); $this->assertEquals($row['model_number'], $newAssetModel->model_number); - } #[Test] @@ -136,5 +135,4 @@ public function updateAssetModelFromImport(): void Arr::except($updatedAssetmodel->attributesToArray(), $updatedAttributes), ); } - } diff --git a/tests/Feature/Importing/Api/ImportAssetsTest.php b/tests/Feature/Importing/Api/ImportAssetsTest.php index 0f54b22e92d7..2ba3958b8c36 100644 --- a/tests/Feature/Importing/Api/ImportAssetsTest.php +++ b/tests/Feature/Importing/Api/ImportAssetsTest.php @@ -138,7 +138,6 @@ public function importAsset(): void //Notes is never read. // $this->assertEquals($row['notes'], $newAsset->notes); - } #[Test] diff --git a/tests/Feature/Licenses/Ui/CreateLicenseTest.php b/tests/Feature/Licenses/Ui/CreateLicenseTest.php index 33f825bf952a..4a959778b3ac 100644 --- a/tests/Feature/Licenses/Ui/CreateLicenseTest.php +++ b/tests/Feature/Licenses/Ui/CreateLicenseTest.php @@ -42,6 +42,5 @@ public function testLicenseWithoutPurchaseDateFailsValidation() $response->assertSessionHasErrors(['purchase_date']); $this->followRedirects($response)->assertSee(trans('general.error')); $this->assertFalse(AssetModel::where('name', 'Test Invalid License')->exists()); - } } diff --git a/tests/Feature/Licenses/Ui/LicenseViewTest.php b/tests/Feature/Licenses/Ui/LicenseViewTest.php index 8bf5bf77fa9e..741170cd8fb6 100644 --- a/tests/Feature/Licenses/Ui/LicenseViewTest.php +++ b/tests/Feature/Licenses/Ui/LicenseViewTest.php @@ -23,7 +23,7 @@ public function testPageRenders() ->get(route('licenses.show', License::factory()->create()->id)) ->assertOk(); } - + public function testLicenseWithPurchaseDateDepreciatesCorrectly() { $depreciation = Depreciation::factory()->create(['months' => 12]); diff --git a/tests/Feature/Locations/Api/CreateLocationsTest.php b/tests/Feature/Locations/Api/CreateLocationsTest.php index 0a75517f31dd..b9e8faa557e2 100644 --- a/tests/Feature/Locations/Api/CreateLocationsTest.php +++ b/tests/Feature/Locations/Api/CreateLocationsTest.php @@ -8,7 +8,6 @@ class CreateLocationsTest extends TestCase { - public function testRequiresPermissionToCreateLocation() { $this->actingAsForApi(User::factory()->create()) @@ -23,6 +22,8 @@ public function testCanCreateLocation() ->postJson(route('api.locations.store'), [ 'name' => 'Test Location', 'notes' => 'Test Note', + 'latitude' => '38.7532', + 'longitude' => '-77.1969' ]) ->assertOk() ->assertStatusMessageIs('success') @@ -31,9 +32,11 @@ public function testCanCreateLocation() $this->assertTrue(Location::where('name', 'Test Location')->exists()); - $department = Location::find($response['payload']['id']); - $this->assertEquals('Test Location', $department->name); - $this->assertEquals('Test Note', $department->notes); + $location = Location::find($response['payload']['id']); + $this->assertEquals('Test Location', $location->name); + $this->assertEquals('Test Note', $location->notes); + $this->assertEquals(38.7532, $location->latitude); + $this->assertEquals(-77.1969, $location->longitude); } public function testCannotCreateNewLocationsWithTheSameName() @@ -49,8 +52,6 @@ public function testCannotCreateNewLocationsWithTheSameName() ->assertStatusMessageIs('error') ->assertStatus(200) ->json(); - - } public function testUserCannotCreateLocationsThatAreTheirOwnParent() @@ -69,8 +70,5 @@ public function testUserCannotCreateLocationsThatAreTheirOwnParent() ], ]) ->json(); - - } - } diff --git a/tests/Feature/Locations/Api/IndexLocationsTest.php b/tests/Feature/Locations/Api/IndexLocationsTest.php index 7b3b104638e6..25c179e34516 100644 --- a/tests/Feature/Locations/Api/IndexLocationsTest.php +++ b/tests/Feature/Locations/Api/IndexLocationsTest.php @@ -33,7 +33,8 @@ public function testLocationIndexReturnsExpectedLocations() 'order' => 'asc', 'offset' => '0', 'limit' => '20', - ])) + ]) + ) ->assertOk() ->assertJsonStructure([ 'total', @@ -41,5 +42,4 @@ public function testLocationIndexReturnsExpectedLocations() ]) ->assertJson(fn(AssertableJson $json) => $json->has('rows', 3)->etc()); } - } diff --git a/tests/Feature/Locations/Api/UpdateLocationsTest.php b/tests/Feature/Locations/Api/UpdateLocationsTest.php index a169ba87bfa9..332f7cf6162a 100644 --- a/tests/Feature/Locations/Api/UpdateLocationsTest.php +++ b/tests/Feature/Locations/Api/UpdateLocationsTest.php @@ -8,7 +8,6 @@ class UpdateLocationsTest extends TestCase { - public function testRequiresPermissionToEditLocation() { $this->actingAsForApi(User::factory()->create()) @@ -24,6 +23,8 @@ public function testCanUpdateLocationViaPatch() ->patchJson(route('api.locations.update', $location), [ 'name' => 'Test Updated Location', 'notes' => 'Test Updated Note', + 'latitude' => '38.7532', + 'longitude' => '-77.1969' ]) ->assertOk() ->assertStatusMessageIs('success') @@ -33,8 +34,7 @@ public function testCanUpdateLocationViaPatch() $location->refresh(); $this->assertEquals('Test Updated Location', $location->name, 'Name was not updated'); $this->assertEquals('Test Updated Note', $location->notes, 'Note was not updated'); - + $this->assertEquals(38.7532, $location->latitude, 'Latitude was not updated'); + $this->assertEquals(-77.1969, $location->longitude, 'Longitude was not updated'); } - - } diff --git a/tests/Feature/Locations/Ui/CreateLocationsTest.php b/tests/Feature/Locations/Ui/CreateLocationsTest.php index 794ee06c67e9..b1025e33fece 100644 --- a/tests/Feature/Locations/Ui/CreateLocationsTest.php +++ b/tests/Feature/Locations/Ui/CreateLocationsTest.php @@ -54,5 +54,4 @@ public function testUserCannotCreateLocationsWithInvalidParent() $this->assertFalse(Location::where('name', 'Test Location')->exists()); } - } diff --git a/tests/Feature/Locations/Ui/UpdateLocationsTest.php b/tests/Feature/Locations/Ui/UpdateLocationsTest.php index 22d9ce577007..4b5e19496427 100644 --- a/tests/Feature/Locations/Ui/UpdateLocationsTest.php +++ b/tests/Feature/Locations/Ui/UpdateLocationsTest.php @@ -34,13 +34,21 @@ public function testUserCanEditLocations() ->put(route('locations.update', ['location' => $location]), [ 'name' => 'Test Location Edited', 'notes' => 'Test Note Edited', + 'latitude' => '38.7532', + 'longitude' => '-77.1969' ]) ->assertStatus(302) ->assertSessionHasNoErrors() ->assertRedirect(route('locations.index')); $this->followRedirects($response)->assertSee('Success'); - $this->assertTrue(Location::where('name', 'Test Location Edited')->where('notes', 'Test Note Edited')->exists()); + $this->assertTrue( + Location::where('name', 'Test Location Edited') + ->where('notes', 'Test Note Edited') + // ->where('latitude', 38.7532) + // ->where('longitude', -77.1969) + ->exists() + ); } public function testUserCannotEditLocationsToMakeThemTheirOwnParent() @@ -73,7 +81,4 @@ public function testUserCannotEditLocationsWithInvalidParent() $this->followRedirects($response)->assertSee(trans('general.error')); $this->assertFalse(Location::where('name', 'Test Location')->exists()); } - - - } diff --git a/tests/Feature/Manufacturers/Api/CreateManufacturersTest.php b/tests/Feature/Manufacturers/Api/CreateManufacturersTest.php index 9dc953148e4f..81c88c0a8fad 100644 --- a/tests/Feature/Manufacturers/Api/CreateManufacturersTest.php +++ b/tests/Feature/Manufacturers/Api/CreateManufacturersTest.php @@ -8,8 +8,6 @@ class CreateManufacturersTest extends TestCase { - - public function testRequiresPermissionToCreateDepartment() { $this->actingAsForApi(User::factory()->create()) @@ -35,5 +33,4 @@ public function testCanCreateManufacturer() $this->assertEquals('Test Manufacturer', $manufacturer->name); $this->assertEquals('Test Note', $manufacturer->notes); } - } diff --git a/tests/Feature/Manufacturers/Api/UpdateManufacturersTest.php b/tests/Feature/Manufacturers/Api/UpdateManufacturersTest.php index f40052f2b295..c09945d7a3ce 100644 --- a/tests/Feature/Manufacturers/Api/UpdateManufacturersTest.php +++ b/tests/Feature/Manufacturers/Api/UpdateManufacturersTest.php @@ -42,9 +42,5 @@ public function testUserCanEditManufacturers() $this->followRedirects($response)->assertSee('Success'); $this->assertTrue(Manufacturer::where('name', 'Test Manufacturer Edited')->where('notes', 'Test Note Edited')->exists()); - } - - - } diff --git a/tests/Feature/Manufacturers/Ui/CreateManufacturerTest.php b/tests/Feature/Manufacturers/Ui/CreateManufacturerTest.php index 4eb9d4fb7ec8..6d0dd6fd4a21 100644 --- a/tests/Feature/Manufacturers/Ui/CreateManufacturerTest.php +++ b/tests/Feature/Manufacturers/Ui/CreateManufacturerTest.php @@ -28,5 +28,4 @@ public function testUserCanCreateManufacturer() $this->assertTrue(Manufacturer::where('name', 'Test Manufacturer')->where('notes', 'Test Note')->exists()); } - } diff --git a/tests/Feature/Manufacturers/Ui/UpdateManufacturerTest.php b/tests/Feature/Manufacturers/Ui/UpdateManufacturerTest.php index 9d5861300f83..71fb30145b18 100644 --- a/tests/Feature/Manufacturers/Ui/UpdateManufacturerTest.php +++ b/tests/Feature/Manufacturers/Ui/UpdateManufacturerTest.php @@ -32,5 +32,4 @@ public function testUserCanEditManufacturers() $this->followRedirects($response)->assertSee('Success'); $this->assertTrue(Manufacturer::where('name', 'Test Manufacturer Edited')->where('notes', 'Test Note Edited')->exists()); } - } diff --git a/tests/Feature/Modals/Ui/ShowModalsTest.php b/tests/Feature/Modals/Ui/ShowModalsTest.php index 6da781d319c5..2f5766870b20 100644 --- a/tests/Feature/Modals/Ui/ShowModalsTest.php +++ b/tests/Feature/Modals/Ui/ShowModalsTest.php @@ -61,6 +61,4 @@ public function testSupplierModalRenders() ->get('modals/supplier') ->assertOk(); } - - } diff --git a/tests/Feature/Notifications/Email/EmailNotificationsUponCheckinTest.php b/tests/Feature/Notifications/Email/EmailNotificationsUponCheckinTest.php index 9579f4c2e3d3..83920ab6d6ab 100644 --- a/tests/Feature/Notifications/Email/EmailNotificationsUponCheckinTest.php +++ b/tests/Feature/Notifications/Email/EmailNotificationsUponCheckinTest.php @@ -36,10 +36,9 @@ public function testCheckInEmailSentToUserIfSettingEnabled() $this->fireCheckInEvent($asset, $user); - Mail::assertSent(CheckinAssetMail::class, function($mail) use ($user) { + Mail::assertSent(CheckinAssetMail::class, function ($mail) use ($user) { return $mail->hasTo($user->email); }); - } public function testCheckInEmailNotSentToUserIfSettingDisabled() @@ -56,7 +55,6 @@ public function testCheckInEmailNotSentToUserIfSettingDisabled() ]); foreach ($checkoutables as $checkoutable) { - if ($checkoutable instanceof Asset) { $checkoutable->model->category->update([ 'checkin_email' => false, diff --git a/tests/Feature/Notifications/Email/ExpiringAlertsNotificationTest.php b/tests/Feature/Notifications/Email/ExpiringAlertsNotificationTest.php index 1d91cf25570f..e36e2516618f 100644 --- a/tests/Feature/Notifications/Email/ExpiringAlertsNotificationTest.php +++ b/tests/Feature/Notifications/Email/ExpiringAlertsNotificationTest.php @@ -12,116 +12,115 @@ use Illuminate\Support\Facades\Mail; use Tests\TestCase; - class ExpiringAlertsNotificationTest extends TestCase { - public function testExpiringAssetsEmailNotification() - { - $this->markIncompleteIfSqlite(); - Mail::fake(); - - $this->settings->enableAlertEmail('admin@example.com'); - $this->settings->setAlertInterval(30); - - $alert_email = Setting::first()->alert_email; - - $expiringAsset = Asset::factory()->create([ - 'purchase_date' => now()->subDays(350)->format('Y-m-d'), - 'warranty_months' => 12, - 'archived' => 0, - 'deleted_at' => null, - ]); - - $expiredAsset = Asset::factory()->create([ - 'purchase_date' => now()->subDays(370)->format('Y-m-d'), - 'warranty_months' => 12, - 'archived' => 0, - 'deleted_at' => null, - ]); - - $notExpiringAsset = Asset::factory()->create([ - 'purchase_date' => now()->subDays(330)->format('Y-m-d'), - 'warranty_months' => 12, - 'archived' => 0, - 'deleted_at' => null, - ]); - - $this->artisan('snipeit:expiring-alerts')->assertExitCode(0); - - Mail::assertSent(ExpiringAssetsMail::class, function($mail) use ($alert_email, $expiringAsset) { - return $mail->hasTo($alert_email) && $mail->assets->contains($expiringAsset); - }); - - Mail::assertNotSent(ExpiringAssetsMail::class, function($mail) use ($expiredAsset, $notExpiringAsset) { - return $mail->assets->contains($expiredAsset) || $mail->assets->contains($notExpiringAsset); - }); - } - - public function testExpiringLicensesEmailNotification() - { - $this->markIncompleteIfSqlite(); - Mail::fake(); - $this->settings->enableAlertEmail('admin@example.com'); - $this->settings->setAlertInterval(60); - - $alert_email = Setting::first()->alert_email; - - $expiringLicense = License::factory()->create([ - 'expiration_date' => now()->addDays(30)->format('Y-m-d'), - 'deleted_at' => null, - ]); - - $expiredLicense = License::factory()->create([ - 'expiration_date' => now()->subDays(10)->format('Y-m-d'), - 'deleted_at' => null, - ]); - $notExpiringLicense = License::factory()->create([ - 'expiration_date' => now()->addMonths(3)->format('Y-m-d'), - 'deleted_at' => null, - ]); - - $this->artisan('snipeit:expiring-alerts')->assertExitCode(0); - - Mail::assertSent(ExpiringLicenseMail::class, function($mail) use ($alert_email, $expiringLicense) { - return $mail->hasTo($alert_email) && $mail->licenses->contains($expiringLicense); - }); - - Mail::assertNotSent(ExpiringLicenseMail::class, function($mail) use ($expiredLicense, $notExpiringLicense) { - return $mail->licenses->contains($expiredLicense) || $mail->licenses->contains($notExpiringLicense); - }); - } - - public function testAuditWarningThresholdEmailNotification() - { - $this->markIncompleteIfSqlite(); - Mail::fake(); - $this->settings->enableAlertEmail('admin@example.com'); - $this->settings->setAuditWarningDays(15); - - $alert_email = Setting::first()->alert_email; - - $upcomingAuditableAsset = Asset::factory()->create([ - 'next_audit_date' => now()->addDays(14)->format('Y-m-d'), - 'deleted_at' => null, - ]); - - $overDueForAuditableAsset = Asset::factory()->create([ - 'next_audit_date' => now()->subDays(1)->format('Y-m-d'), - 'deleted_at' => null, - ]); - - $notAuditableAsset = Asset::factory()->create([ - 'next_audit_date' => now()->addDays(30)->format('Y-m-d'), - 'deleted_at' => null, - ]); - - $this->artisan('snipeit:upcoming-audits')->assertExitCode(0); - - Mail::assertSent(SendUpcomingAuditMail::class, function($mail) use ($alert_email, $upcomingAuditableAsset, $overDueForAuditableAsset) { - return $mail->hasTo($alert_email) && ($mail->assets->contains($upcomingAuditableAsset) && $mail->assets->contains($overDueForAuditableAsset)); - }); - Mail::assertNotSent(SendUpcomingAuditMail::class, function($mail) use ($alert_email, $notAuditableAsset) { - return $mail->hasTo($alert_email) && $mail->assets->contains($notAuditableAsset); - }); - } -} \ No newline at end of file + public function testExpiringAssetsEmailNotification() + { + $this->markIncompleteIfSqlite(); + Mail::fake(); + + $this->settings->enableAlertEmail('admin@example.com'); + $this->settings->setAlertInterval(30); + + $alert_email = Setting::first()->alert_email; + + $expiringAsset = Asset::factory()->create([ + 'purchase_date' => now()->subDays(350)->format('Y-m-d'), + 'warranty_months' => 12, + 'archived' => 0, + 'deleted_at' => null, + ]); + + $expiredAsset = Asset::factory()->create([ + 'purchase_date' => now()->subDays(370)->format('Y-m-d'), + 'warranty_months' => 12, + 'archived' => 0, + 'deleted_at' => null, + ]); + + $notExpiringAsset = Asset::factory()->create([ + 'purchase_date' => now()->subDays(330)->format('Y-m-d'), + 'warranty_months' => 12, + 'archived' => 0, + 'deleted_at' => null, + ]); + + $this->artisan('snipeit:expiring-alerts')->assertExitCode(0); + + Mail::assertSent(ExpiringAssetsMail::class, function ($mail) use ($alert_email, $expiringAsset) { + return $mail->hasTo($alert_email) && $mail->assets->contains($expiringAsset); + }); + + Mail::assertNotSent(ExpiringAssetsMail::class, function ($mail) use ($expiredAsset, $notExpiringAsset) { + return $mail->assets->contains($expiredAsset) || $mail->assets->contains($notExpiringAsset); + }); + } + + public function testExpiringLicensesEmailNotification() + { + $this->markIncompleteIfSqlite(); + Mail::fake(); + $this->settings->enableAlertEmail('admin@example.com'); + $this->settings->setAlertInterval(60); + + $alert_email = Setting::first()->alert_email; + + $expiringLicense = License::factory()->create([ + 'expiration_date' => now()->addDays(30)->format('Y-m-d'), + 'deleted_at' => null, + ]); + + $expiredLicense = License::factory()->create([ + 'expiration_date' => now()->subDays(10)->format('Y-m-d'), + 'deleted_at' => null, + ]); + $notExpiringLicense = License::factory()->create([ + 'expiration_date' => now()->addMonths(3)->format('Y-m-d'), + 'deleted_at' => null, + ]); + + $this->artisan('snipeit:expiring-alerts')->assertExitCode(0); + + Mail::assertSent(ExpiringLicenseMail::class, function ($mail) use ($alert_email, $expiringLicense) { + return $mail->hasTo($alert_email) && $mail->licenses->contains($expiringLicense); + }); + + Mail::assertNotSent(ExpiringLicenseMail::class, function ($mail) use ($expiredLicense, $notExpiringLicense) { + return $mail->licenses->contains($expiredLicense) || $mail->licenses->contains($notExpiringLicense); + }); + } + + public function testAuditWarningThresholdEmailNotification() + { + $this->markIncompleteIfSqlite(); + Mail::fake(); + $this->settings->enableAlertEmail('admin@example.com'); + $this->settings->setAuditWarningDays(15); + + $alert_email = Setting::first()->alert_email; + + $upcomingAuditableAsset = Asset::factory()->create([ + 'next_audit_date' => now()->addDays(14)->format('Y-m-d'), + 'deleted_at' => null, + ]); + + $overDueForAuditableAsset = Asset::factory()->create([ + 'next_audit_date' => now()->subDays(1)->format('Y-m-d'), + 'deleted_at' => null, + ]); + + $notAuditableAsset = Asset::factory()->create([ + 'next_audit_date' => now()->addDays(30)->format('Y-m-d'), + 'deleted_at' => null, + ]); + + $this->artisan('snipeit:upcoming-audits')->assertExitCode(0); + + Mail::assertSent(SendUpcomingAuditMail::class, function ($mail) use ($alert_email, $upcomingAuditableAsset, $overDueForAuditableAsset) { + return $mail->hasTo($alert_email) && ($mail->assets->contains($upcomingAuditableAsset) && $mail->assets->contains($overDueForAuditableAsset)); + }); + Mail::assertNotSent(SendUpcomingAuditMail::class, function ($mail) use ($alert_email, $notAuditableAsset) { + return $mail->hasTo($alert_email) && $mail->assets->contains($notAuditableAsset); + }); + } +} diff --git a/tests/Feature/Reporting/ActivityReportTest.php b/tests/Feature/Reporting/ActivityReportTest.php index e094f86b6ebd..eb9857fde65c 100644 --- a/tests/Feature/Reporting/ActivityReportTest.php +++ b/tests/Feature/Reporting/ActivityReportTest.php @@ -65,17 +65,12 @@ public function testRecordsAreScopedToCompanyWhenMultipleCompanySupportEnabled() $this->actingAsForApi($userInCompanyB) ->getJson( - route('api.activity.index')) + route('api.activity.index') + ) ->assertOk() ->assertJsonStructure([ 'rows', ]) ->assertJson(fn(AssertableJson $json) => $json->has('rows', 7)->etc()); - - - - - } - } diff --git a/tests/Feature/Reporting/UnacceptedAssetReportTest.php b/tests/Feature/Reporting/UnacceptedAssetReportTest.php index b3ec0b2e0bf1..44586b474e4d 100644 --- a/tests/Feature/Reporting/UnacceptedAssetReportTest.php +++ b/tests/Feature/Reporting/UnacceptedAssetReportTest.php @@ -57,5 +57,4 @@ public function testUserCanListUnacceptedAssets() ->get(route('reports/unaccepted_assets')) ->assertOk(); } - } diff --git a/tests/Feature/Settings/AlertsSettingTest.php b/tests/Feature/Settings/AlertsSettingTest.php index d79bd1cf21a4..038ff588fecd 100644 --- a/tests/Feature/Settings/AlertsSettingTest.php +++ b/tests/Feature/Settings/AlertsSettingTest.php @@ -5,7 +5,6 @@ use Tests\TestCase; use App\Models\User; - class AlertsSettingTest extends TestCase { public function testPermissionRequiredToViewAlertSettings() @@ -25,5 +24,4 @@ public function testAdminCCEmailArrayCanBeSaved() ->assertSessionHasNoErrors(); $this->followRedirects($response)->assertSee('alert-success'); } - } diff --git a/tests/Feature/Settings/BrandingSettingsTest.php b/tests/Feature/Settings/BrandingSettingsTest.php index d751a1ab47a5..5312ecad830a 100644 --- a/tests/Feature/Settings/BrandingSettingsTest.php +++ b/tests/Feature/Settings/BrandingSettingsTest.php @@ -8,7 +8,6 @@ use App\Models\User; use App\Models\Setting; - class BrandingSettingsTest extends TestCase { public function testSiteNameIsRequired() @@ -43,7 +42,8 @@ public function testLogoCanBeUploaded() $setting = Setting::factory()->create(['logo' => null]); $response = $this->actingAs(User::factory()->superuser()->create()) - ->post(route('settings.branding.save', + ->post(route( + 'settings.branding.save', ['logo' => UploadedFile::fake()->image('test_logo.png')->storeAs('', 'test_logo.png', 'public')] )) ->assertValid('logo') @@ -69,7 +69,8 @@ public function testLogoCanBeDeleted() $response = $this->actingAs(User::factory()->superuser()->create()) ->from(route('settings.branding.index')) - ->post(route('settings.branding.save', + ->post(route( + 'settings.branding.save', ['clear_logo' => '1'] )) ->assertValid('logo') @@ -92,7 +93,8 @@ public function testEmailLogoCanBeUploaded() $response = $this->actingAs(User::factory()->superuser()->create()) ->from(route('settings.branding.index')) - ->post(route('settings.branding.save', + ->post(route( + 'settings.branding.save', [ 'email_logo' => UploadedFile::fake()->image('new_test_email_logo.png')->storeAs('', 'new_test_email_logo.png', 'public') ] @@ -119,7 +121,8 @@ public function testEmailLogoCanBeDeleted() $response = $this->actingAs(User::factory()->superuser()->create()) ->from(route('settings.branding.index')) - ->post(route('settings.branding.save', + ->post(route( + 'settings.branding.save', ['clear_email_logo' => '1'] )) ->assertValid('email_logo') @@ -130,7 +133,6 @@ public function testEmailLogoCanBeDeleted() $this->assertDatabaseHas('settings', ['email_logo' => null]); //Storage::disk('public')->assertMissing('new_test_email_logo.png'); - } @@ -146,7 +148,8 @@ public function testLabelLogoCanBeUploaded() $response = $this->actingAs(User::factory()->superuser()->create()) ->from(route('settings.branding.index')) - ->post(route('settings.branding.save', + ->post(route( + 'settings.branding.save', [ 'label_logo' => UploadedFile::fake()->image('new_test_label_logo.png')->storeAs('', 'new_test_label_logo.png', 'public') ] @@ -159,8 +162,6 @@ public function testLabelLogoCanBeUploaded() Storage::disk('public')->assertExists('new_test_label_logo.png'); // Storage::disk('public')->assertMissing($original_file); - - } public function testLabelLogoCanBeDeleted() @@ -176,7 +177,8 @@ public function testLabelLogoCanBeDeleted() $response = $this->actingAs(User::factory()->superuser()->create()) ->from(route('settings.branding.index')) - ->post(route('settings.branding.save', + ->post(route( + 'settings.branding.save', ['label_logo' => '1'] )) ->assertValid('label_logo') @@ -187,7 +189,6 @@ public function testLabelLogoCanBeDeleted() $this->followRedirects($response)->assertSee(trans('alert-success')); // $this->assertNull($setting->refresh()->logo); // Storage::disk('public')->assertMissing($original_file); - } public function testDefaultAvatarCanBeUploaded() @@ -196,7 +197,8 @@ public function testDefaultAvatarCanBeUploaded() $response = $this->actingAs(User::factory()->superuser()->create()) ->from(route('settings.branding.index')) - ->post(route('settings.branding.save', + ->post(route( + 'settings.branding.save', [ 'default_avatar' => UploadedFile::fake()->image('default_avatar.png')->storeAs('', 'default_avatar.png', 'public') ] @@ -224,7 +226,8 @@ public function testDefaultAvatarCanBeDeleted() $response = $this->actingAs(User::factory()->superuser()->create()) ->from(route('settings.branding.index')) - ->post(route('settings.branding.save', + ->post(route( + 'settings.branding.save', ['clear_default_avatar' => '1'] )) ->assertValid('default_avatar') @@ -244,7 +247,8 @@ public function testSnipeDefaultAvatarCanBeDeleted() Storage::fake('public'); $this->actingAs(User::factory()->superuser()->create()) - ->post(route('settings.branding.save', + ->post(route( + 'settings.branding.save', ['default_avatar' => UploadedFile::fake()->image('default.png')->storeAs('avatars', 'default.png', 'public')] )); @@ -252,14 +256,14 @@ public function testSnipeDefaultAvatarCanBeDeleted() $this->actingAs(User::factory()->superuser()->create()) - ->post(route('settings.branding.save', + ->post(route( + 'settings.branding.save', ['clear_default_avatar' => '1'] )); $this->assertNull($setting->refresh()->default_avatar); $this->assertDatabaseHas('settings', ['default_avatar' => null]); Storage::disk('public')->assertExists('avatars/default.png'); - } public function testFaviconCanBeUploaded() @@ -269,9 +273,10 @@ public function testFaviconCanBeUploaded() $response = $this->actingAs(User::factory()->superuser()->create()) ->from(route('settings.branding.index')) - ->post(route('settings.branding.save', + ->post(route( + 'settings.branding.save', [ - 'favicon' =>UploadedFile::fake()->image('favicon.svg')->storeAs('', 'favicon.svg', 'public') + 'favicon' => UploadedFile::fake()->image('favicon.svg')->storeAs('', 'favicon.svg', 'public') ] )) ->assertValid('favicon') @@ -296,7 +301,8 @@ public function testFaviconCanBeDeleted() $response = $this->actingAs(User::factory()->superuser()->create()) ->from(route('settings.branding.index')) - ->post(route('settings.branding.save', + ->post(route( + 'settings.branding.save', ['clear_favicon' => '1'] )) ->assertValid('favicon') @@ -309,7 +315,4 @@ public function testFaviconCanBeDeleted() // This fails for some reason - the file is not being deleted, or at least the test doesn't think it is // Storage::disk('public')->assertMissing('favicon.png'); } - - - } diff --git a/tests/Feature/Settings/LabelSettingTest.php b/tests/Feature/Settings/LabelSettingTest.php index e96c684a892d..90eb826daba4 100644 --- a/tests/Feature/Settings/LabelSettingTest.php +++ b/tests/Feature/Settings/LabelSettingTest.php @@ -5,7 +5,6 @@ use Tests\TestCase; use App\Models\User; - class LabelSettingTest extends TestCase { public function testPermissionRequiredToViewLabelSettings() @@ -14,5 +13,4 @@ public function testPermissionRequiredToViewLabelSettings() ->get(route('settings.labels.index')) ->assertForbidden(); } - } diff --git a/tests/Feature/Settings/LdapSettingsTest.php b/tests/Feature/Settings/LdapSettingsTest.php index 6d690fd89b0e..1a1aeb5ecd1c 100644 --- a/tests/Feature/Settings/LdapSettingsTest.php +++ b/tests/Feature/Settings/LdapSettingsTest.php @@ -5,7 +5,6 @@ use Tests\TestCase; use App\Models\User; - class LdapSettingsTest extends TestCase { public function testPermissionRequiredToViewLdapSettings() @@ -57,5 +56,4 @@ public function testLdapSettingsAreValidatedCorrectly() ]); $this->followRedirects($response)->assertSee('alert-danger'); } - } diff --git a/tests/Feature/Settings/SecuritySettingTest.php b/tests/Feature/Settings/SecuritySettingTest.php index 6edeee673b54..0b70d2f987bf 100644 --- a/tests/Feature/Settings/SecuritySettingTest.php +++ b/tests/Feature/Settings/SecuritySettingTest.php @@ -5,7 +5,6 @@ use Tests\TestCase; use App\Models\User; - class SecuritySettingTest extends TestCase { public function testPermissionRequiredToViewSecuritySettings() @@ -14,5 +13,4 @@ public function testPermissionRequiredToViewSecuritySettings() ->get(route('settings.security.index')) ->assertForbidden(); } - } diff --git a/tests/Feature/Settings/ShowSetUpPageTest.php b/tests/Feature/Settings/ShowSetUpPageTest.php index fe071491e843..0e543ae7c08a 100644 --- a/tests/Feature/Settings/ShowSetUpPageTest.php +++ b/tests/Feature/Settings/ShowSetUpPageTest.php @@ -21,7 +21,6 @@ class ShowSetUpPageTest extends TestCase { - static ?TestResponse $latestResponse; /** * We do not want to make actual http request on every test to check .env file @@ -293,7 +292,7 @@ protected function assertSeeDirectoryPermissionError(bool $shouldSee = true): vo return; } - self::$latestResponse->assertSee($successMessage, false)->assertDontSee($errorMessage,false); + self::$latestResponse->assertSee($successMessage, false)->assertDontSee($errorMessage, false); } public function testWillNotSeeDirectoryPermissionErrorWhenStoragePathIsWritable(): void diff --git a/tests/Feature/Suppliers/Ui/UpdateSupplierTest.php b/tests/Feature/Suppliers/Ui/UpdateSupplierTest.php index f3be726319a7..6bab1e835b53 100644 --- a/tests/Feature/Suppliers/Ui/UpdateSupplierTest.php +++ b/tests/Feature/Suppliers/Ui/UpdateSupplierTest.php @@ -14,4 +14,30 @@ public function testPageRenders() ->get(route('suppliers.edit', Supplier::factory()->create()->id)) ->assertOk(); } + + public function testUserCanEditSuppliers() + { + $supplier = Supplier::factory()->create(['name' => 'Test Supplier']); + $this->assertTrue(Supplier::where('name', 'Test Supplier')->exists()); + + $response = $this->actingAs(User::factory()->superuser()->create()) + ->put(route('suppliers.update', ['supplier' => $supplier]), [ + 'name' => 'Test Supplier Edited', + 'notes' => 'Test Note Edited', + 'latitude' => '38.7532', + 'longitude' => '-77.1969' + ]) + ->assertStatus(302) + ->assertSessionHasNoErrors() + ->assertRedirect(route('suppliers.index')); + + $this->followRedirects($response)->assertSee('Success'); + $this->assertTrue( + Supplier::where('name', 'Test Supplier Edited') + ->where('notes', 'Test Note Edited') + // ->where('latitude', 38.7532) + // ->where('longitude', -77.1969) + ->exists() + ); + } } diff --git a/tests/Feature/Users/Api/DeleteUsersTest.php b/tests/Feature/Users/Api/DeleteUsersTest.php index a2e43f04bcb3..07947290c530 100644 --- a/tests/Feature/Users/Api/DeleteUsersTest.php +++ b/tests/Feature/Users/Api/DeleteUsersTest.php @@ -97,7 +97,6 @@ public function testUsersCannotDeleteThemselves() ->assertStatus(200) ->assertStatusMessageIs('error') ->json(); - } public function testAdheresToFullMultipleCompaniesSupportScoping() @@ -111,7 +110,7 @@ public function testAdheresToFullMultipleCompaniesSupportScoping() $userFromB = User::factory()->deleteUsers()->for($companyB)->create(); $this->actingAsForApi($userFromA) - ->deleteJson(route('api.users.destroy', $userFromB)) + ->deleteJson(route('api.users.destroy', $userFromB)) ->assertOk() ->assertStatus(200) ->assertStatusMessageIs('error') diff --git a/tests/Feature/Users/Api/RestoreUserTest.php b/tests/Feature/Users/Api/RestoreUserTest.php index 0ffac8f07e32..8bb6f41380ec 100644 --- a/tests/Feature/Users/Api/RestoreUserTest.php +++ b/tests/Feature/Users/Api/RestoreUserTest.php @@ -10,8 +10,6 @@ class RestoreUserTest extends TestCase { - - public function testErrorReturnedViaApiIfUserDoesNotExist() { $this->actingAsForApi(User::factory()->deleteUsers()->create()) @@ -96,10 +94,5 @@ public function testPermissionsForRestoringIfNotInSameCompanyAndNotSuperadmin() $userFromA->refresh(); $this->assertNull($userFromA->deleted_at); - } - - - - } diff --git a/tests/Feature/Users/Api/UpdateUserTest.php b/tests/Feature/Users/Api/UpdateUserTest.php index e70471770fa0..c941564d70e4 100644 --- a/tests/Feature/Users/Api/UpdateUserTest.php +++ b/tests/Feature/Users/Api/UpdateUserTest.php @@ -216,8 +216,8 @@ public function testUsersScopedToCompanyDuringUpdateWhenMultipleFullCompanySuppo { $this->settings->enableMultipleFullCompanySupport(); - $companyA = Company::factory()->create(['name'=>'Company A']); - $companyB = Company::factory()->create(['name'=>'Company B']); + $companyA = Company::factory()->create(['name' => 'Company A']); + $companyB = Company::factory()->create(['name' => 'Company B']); $adminA = User::factory(['company_id' => $companyA->id])->admin()->create(); $adminB = User::factory(['company_id' => $companyB->id])->admin()->create(); @@ -321,7 +321,8 @@ public function testUserGroupsAreOnlyUpdatedIfAuthenticatedUserIsSuperUser() 'groups' => [$groupToJoin->id], ]); - $this->assertFalse($userToUpdateByUserWhoCanEditUsers->refresh()->groups->contains($groupToJoin), + $this->assertFalse( + $userToUpdateByUserWhoCanEditUsers->refresh()->groups->contains($groupToJoin), 'Non-super-user was able to modify user group' ); @@ -364,10 +365,10 @@ public function testNonSuperuserCannotUpdateOwnGroups() 'groups' => [$groupToJoin->id], ]); - $this->assertFalse($user->refresh()->groups->contains($groupToJoin), + $this->assertFalse( + $user->refresh()->groups->contains($groupToJoin), 'Non-super-user was able to modify user group' ); - } public function testNonSuperuserCannotUpdateGroups() @@ -383,12 +384,12 @@ public function testNonSuperuserCannotUpdateGroups() ]); - $this->assertFalse($user->refresh()->groups->contains($newGroupToJoin), + $this->assertFalse( + $user->refresh()->groups->contains($newGroupToJoin), 'Non-super-user was able to modify user group membership' ); $this->assertTrue($user->refresh()->groups->contains($group)); - } public function testUsersGroupsAreNotClearedIfNoGroupPassedBySuperUser() @@ -410,8 +411,8 @@ public function testMultipleGroupsUpdateBySuperUser() $user = User::factory()->create(); $superUser = User::factory()->superuser()->create(); - $groupA = Group::factory()->create(['name'=>'Group A']); - $groupB = Group::factory()->create(['name'=>'Group B']); + $groupA = Group::factory()->create(['name' => 'Group A']); + $groupB = Group::factory()->create(['name' => 'Group B']); $this->actingAsForApi($superUser) ->patchJson(route('api.users.update', $user), [ @@ -511,5 +512,4 @@ public function testMultiCompanyUserCanBeUpdatedIfHasAssetInSameCompany() 'company_id' => $companyB->id, ])->assertStatusMessageIs('error'); } - } diff --git a/tests/Feature/Users/Api/ViewUserTest.php b/tests/Feature/Users/Api/ViewUserTest.php index 07346dbbb881..b5656ccd43b7 100644 --- a/tests/Feature/Users/Api/ViewUserTest.php +++ b/tests/Feature/Users/Api/ViewUserTest.php @@ -10,7 +10,6 @@ class ViewUserTest extends TestCase { - public function testCanReturnUser() { $user = User::factory()->create(); @@ -19,5 +18,4 @@ public function testCanReturnUser() ->getJson(route('api.users.show', $user)) ->assertOk(); } - } diff --git a/tests/Feature/Users/Ui/CloneUserTest.php b/tests/Feature/Users/Ui/CloneUserTest.php index 97b4babd7be5..8dfb3c9a909f 100644 --- a/tests/Feature/Users/Ui/CloneUserTest.php +++ b/tests/Feature/Users/Ui/CloneUserTest.php @@ -13,6 +13,4 @@ public function testPageRenders() ->get(route('users.clone.show', User::factory()->create())) ->assertOk(); } - - } diff --git a/tests/Feature/Users/Ui/CreateUserTest.php b/tests/Feature/Users/Ui/CreateUserTest.php index d63dc40f9ebe..b72dd5e8e8e2 100644 --- a/tests/Feature/Users/Ui/CreateUserTest.php +++ b/tests/Feature/Users/Ui/CreateUserTest.php @@ -7,7 +7,6 @@ class CreateUserTest extends TestCase { - public function testPermissionRequiredToCreateUser() { $this->actingAs(User::factory()->create()) @@ -20,7 +19,6 @@ public function testPageRenders() $this->actingAs(User::factory()->createUsers()->create()) ->get(route('users.create')) ->assertOk(); - } public function testCanCreateUser() @@ -39,6 +37,5 @@ public function testCanCreateUser() ->assertRedirect(route('users.index')); $this->followRedirects($response)->assertSee('Success'); - } } diff --git a/tests/Feature/Users/Ui/DeleteUserTest.php b/tests/Feature/Users/Ui/DeleteUserTest.php index 6d687ed0f89e..79b4916ea4a6 100644 --- a/tests/Feature/Users/Ui/DeleteUserTest.php +++ b/tests/Feature/Users/Ui/DeleteUserTest.php @@ -8,12 +8,10 @@ use App\Models\Accessory; use App\Models\User; use App\Models\Company; - use App\Models\Asset; class DeleteUserTest extends TestCase { - public function testUserCanDeleteAnotherUser() { $user = User::factory()->deleteUsers()->viewUsers()->create(); @@ -94,7 +92,6 @@ public function testFmcsPermissionsToDeleteUser() $userFromA->refresh(); $this->assertNotNull($userFromA->deleted_at); - } @@ -170,7 +167,6 @@ public function testAllowUserDeletionIfNotManagingLocations() ->assertRedirect(route('users.index')); $this->followRedirects($response)->assertSee('Success'); - } public function testDisallowUserDeletionIfNoDeletePermissions() @@ -215,6 +211,4 @@ public function testUsersCannotDeleteThemselves() $this->followRedirects($response)->assertSee('Error'); } - - } diff --git a/tests/Feature/Users/Ui/EmailAssignedToUserTest.php b/tests/Feature/Users/Ui/EmailAssignedToUserTest.php index a6403679c001..b0838ebab8a4 100644 --- a/tests/Feature/Users/Ui/EmailAssignedToUserTest.php +++ b/tests/Feature/Users/Ui/EmailAssignedToUserTest.php @@ -34,7 +34,8 @@ public function testUserWithoutCompanyPermissionsCannotSendInventory() ->assertStatus(302); Notification::assertSentTo( - [$user], CurrentInventory::class + [$user], + CurrentInventory::class ); } } diff --git a/tests/Feature/Users/Ui/MergeUsersTest.php b/tests/Feature/Users/Ui/MergeUsersTest.php index a9ae11171bf7..0b1d380b0748 100644 --- a/tests/Feature/Users/Ui/MergeUsersTest.php +++ b/tests/Feature/Users/Ui/MergeUsersTest.php @@ -10,7 +10,6 @@ use App\Models\Actionlog; use Tests\TestCase; - class MergeUsersTest extends TestCase { public function testAssetsAreTransferredOnUserMerge() @@ -24,11 +23,13 @@ public function testAssetsAreTransferredOnUserMerge() Asset::factory()->count(3)->assignedToUser($user_to_merge_into)->create(); $response = $this->actingAs(User::factory()->editUsers()->viewUsers()->create()) - ->post(route('users.merge.save', $user1->id), + ->post( + route('users.merge.save', $user1->id), [ 'ids_to_merge' => [$user1->id, $user2->id], 'merge_into_id' => $user_to_merge_into->id - ]) + ] + ) ->assertStatus(302) ->assertRedirect(route('users.index')); @@ -36,7 +37,6 @@ public function testAssetsAreTransferredOnUserMerge() $this->assertEquals(9, $user_to_merge_into->refresh()->assets->count()); $this->assertEquals(0, $user1->refresh()->assets->count()); $this->assertEquals(0, $user2->refresh()->assets->count()); - } public function testLicensesAreTransferredOnUserMerge() @@ -52,11 +52,13 @@ public function testLicensesAreTransferredOnUserMerge() $this->assertEquals(3, $user_to_merge_into->refresh()->licenses->count()); $response = $this->actingAs(User::factory()->editUsers()->viewUsers()->create()) - ->post(route('users.merge.save', $user1->id), + ->post( + route('users.merge.save', $user1->id), [ 'ids_to_merge' => [$user1->id, $user2->id], 'merge_into_id' => $user_to_merge_into->id - ]) + ] + ) ->assertStatus(302) ->assertRedirect(route('users.index')); @@ -64,7 +66,6 @@ public function testLicensesAreTransferredOnUserMerge() $this->assertEquals(9, $user_to_merge_into->refresh()->licenses->count()); $this->assertEquals(0, $user1->refresh()->licenses->count()); $this->assertEquals(0, $user2->refresh()->licenses->count()); - } public function testAccessoriesTransferredOnUserMerge() @@ -80,11 +81,13 @@ public function testAccessoriesTransferredOnUserMerge() $this->assertEquals(3, $user_to_merge_into->refresh()->accessories->count()); $response = $this->actingAs(User::factory()->editUsers()->viewUsers()->create()) - ->post(route('users.merge.save', $user1->id), + ->post( + route('users.merge.save', $user1->id), [ 'ids_to_merge' => [$user1->id, $user2->id], 'merge_into_id' => $user_to_merge_into->id - ]) + ] + ) ->assertStatus(302) ->assertRedirect(route('users.index')); @@ -92,7 +95,6 @@ public function testAccessoriesTransferredOnUserMerge() $this->assertEquals(9, $user_to_merge_into->refresh()->accessories->count()); $this->assertEquals(0, $user1->refresh()->accessories->count()); $this->assertEquals(0, $user2->refresh()->accessories->count()); - } public function testConsumablesTransferredOnUserMerge() @@ -108,11 +110,13 @@ public function testConsumablesTransferredOnUserMerge() $this->assertEquals(3, $user_to_merge_into->refresh()->consumables->count()); $response = $this->actingAs(User::factory()->editUsers()->viewUsers()->create()) - ->post(route('users.merge.save', $user1->id), + ->post( + route('users.merge.save', $user1->id), [ 'ids_to_merge' => [$user1->id, $user2->id], 'merge_into_id' => $user_to_merge_into->id - ]) + ] + ) ->assertStatus(302) ->assertRedirect(route('users.index')); @@ -120,7 +124,6 @@ public function testConsumablesTransferredOnUserMerge() $this->assertEquals(9, $user_to_merge_into->refresh()->consumables->count()); $this->assertEquals(0, $user1->refresh()->consumables->count()); $this->assertEquals(0, $user2->refresh()->consumables->count()); - } public function testFilesAreTransferredOnUserMerge() @@ -136,11 +139,13 @@ public function testFilesAreTransferredOnUserMerge() $this->assertEquals(3, $user_to_merge_into->refresh()->uploads->count()); $response = $this->actingAs(User::factory()->editUsers()->viewUsers()->create()) - ->post(route('users.merge.save', $user1->id), + ->post( + route('users.merge.save', $user1->id), [ 'ids_to_merge' => [$user1->id, $user2->id], 'merge_into_id' => $user_to_merge_into->id - ]) + ] + ) ->assertStatus(302) ->assertRedirect(route('users.index')); @@ -148,7 +153,6 @@ public function testFilesAreTransferredOnUserMerge() $this->assertEquals(9, $user_to_merge_into->refresh()->uploads->count()); $this->assertEquals(0, $user1->refresh()->uploads->count()); $this->assertEquals(0, $user2->refresh()->uploads->count()); - } public function testAcceptancesAreTransferredOnUserMerge() @@ -164,11 +168,13 @@ public function testAcceptancesAreTransferredOnUserMerge() $this->assertEquals(3, $user_to_merge_into->refresh()->acceptances->count()); $response = $this->actingAs(User::factory()->editUsers()->viewUsers()->create()) - ->post(route('users.merge.save', $user1->id), + ->post( + route('users.merge.save', $user1->id), [ 'ids_to_merge' => [$user1->id, $user2->id], 'merge_into_id' => $user_to_merge_into->id - ]) + ] + ) ->assertStatus(302) ->assertRedirect(route('users.index')); @@ -176,7 +182,6 @@ public function testAcceptancesAreTransferredOnUserMerge() $this->assertEquals(9, $user_to_merge_into->refresh()->acceptances->count()); $this->assertEquals(0, $user1->refresh()->acceptances->count()); $this->assertEquals(0, $user2->refresh()->acceptances->count()); - } public function testUserUpdateHistoryIsTransferredOnUserMerge() @@ -192,11 +197,13 @@ public function testUserUpdateHistoryIsTransferredOnUserMerge() $this->assertEquals(3, $user_to_merge_into->refresh()->userlog->count()); $response = $this->actingAs(User::factory()->editUsers()->viewUsers()->create()) - ->post(route('users.merge.save', $user1->id), + ->post( + route('users.merge.save', $user1->id), [ 'ids_to_merge' => [$user1->id, $user2->id], 'merge_into_id' => $user_to_merge_into->id - ]) + ] + ) ->assertStatus(302) ->assertRedirect(route('users.index')); @@ -206,8 +213,5 @@ public function testUserUpdateHistoryIsTransferredOnUserMerge() $this->assertEquals(11, $user_to_merge_into->refresh()->userlog->count()); $this->assertEquals(2, $user1->refresh()->userlog->count()); $this->assertEquals(2, $user2->refresh()->userlog->count()); - } - - } diff --git a/tests/Support/AssertsAgainstSlackNotifications.php b/tests/Support/AssertsAgainstSlackNotifications.php index 11e6beea2de9..7d9d363f5fc6 100644 --- a/tests/Support/AssertsAgainstSlackNotifications.php +++ b/tests/Support/AssertsAgainstSlackNotifications.php @@ -11,7 +11,7 @@ trait AssertsAgainstSlackNotifications public function assertSlackNotificationSent(string $notificationClass) { Notification::assertSentTo( - new AnonymousNotifiable, + new AnonymousNotifiable(), $notificationClass, function ($notification, $channels, $notifiable) { return $notifiable->routes['slack'] === Setting::getSettings()->webhook_endpoint; @@ -21,6 +21,6 @@ function ($notification, $channels, $notifiable) { public function assertNoSlackNotificationSent(string $notificationClass) { - Notification::assertNotSentTo(new AnonymousNotifiable, $notificationClass); + Notification::assertNotSentTo(new AnonymousNotifiable(), $notificationClass); } } diff --git a/tests/Support/Importing/FileBuilder.php b/tests/Support/Importing/FileBuilder.php index bf08dc96d102..c8a04e83decb 100644 --- a/tests/Support/Importing/FileBuilder.php +++ b/tests/Support/Importing/FileBuilder.php @@ -45,7 +45,7 @@ public function __construct(array $rows = []) */ public static function new(array $attributes = []) { - $instance = new static; + $instance = new static(); return $instance->push($instance->definition())->replace($attributes); } @@ -57,7 +57,7 @@ public static function new(array $attributes = []) */ public static function fromFile(string $filepath) { - $instance = new static; + $instance = new static(); $reader = Reader::createFromPath($filepath); $importFileHeaders = $reader->first(); @@ -92,7 +92,7 @@ public static function fromFile(string $filepath) */ public static function times(int $amountOfRows = 1) { - $instance = new static; + $instance = new static(); for ($i = 1; $i <= $amountOfRows; $i++) { $instance->push($instance->definition()); diff --git a/tests/Unit/AccessoryTest.php b/tests/Unit/AccessoryTest.php index ec931fad6ebc..54bbb87a1d38 100644 --- a/tests/Unit/AccessoryTest.php +++ b/tests/Unit/AccessoryTest.php @@ -1,4 +1,5 @@ create( - [ - 'company_id' => - Company::factory()->create()->id]); + ['company_id' => Company::factory()->create()->id] + ); $this->assertInstanceOf(Company::class, $accessory->company); } @@ -26,7 +26,8 @@ public function testAnAccessoryHasALocation() ->create( [ 'location_id' => Location::factory()->create()->id - ]); + ] + ); $this->assertInstanceOf(Location::class, $accessory->location); } @@ -35,12 +36,13 @@ public function testAnAccessoryBelongsToACategory() $accessory = Accessory::factory()->appleBtKeyboard() ->create( [ - 'category_id' => + 'category_id' => Category::factory()->create( [ 'category_type' => 'accessory' ] - )->id]); + )->id] + ); $this->assertInstanceOf(Category::class, $accessory->category); $this->assertEquals('accessory', $accessory->category->category_type); } @@ -51,7 +53,8 @@ public function testAnAccessoryHasAManufacturer() [ 'category_id' => Category::factory()->create(), 'manufacturer_id' => Manufacturer::factory()->apple()->create() - ]); + ] + ); $this->assertInstanceOf(Manufacturer::class, $accessory->manufacturer); } } diff --git a/tests/Unit/AssetMaintenanceTest.php b/tests/Unit/AssetMaintenanceTest.php index 46a0efdd7c96..add8b6835995 100644 --- a/tests/Unit/AssetMaintenanceTest.php +++ b/tests/Unit/AssetMaintenanceTest.php @@ -1,4 +1,5 @@ is_warranty = ''; $this->assertTrue($c->is_warranty === 0); $c->is_warranty = '4'; @@ -28,7 +29,7 @@ public function testSetsCostsAppropriately() public function testNullsOutNotesIfBlank() { - $c = new AssetMaintenance; + $c = new AssetMaintenance(); $c->notes = ''; $this->assertTrue($c->notes === null); $c->notes = 'This is a long note'; @@ -37,7 +38,7 @@ public function testNullsOutNotesIfBlank() public function testNullsOutCompletionDateIfBlankOrInvalid() { - $c = new AssetMaintenance; + $c = new AssetMaintenance(); $c->completion_date = ''; $this->assertTrue($c->completion_date === null); $c->completion_date = '0000-00-00'; diff --git a/tests/Unit/AssetModelTest.php b/tests/Unit/AssetModelTest.php index 4cc62e20a011..d35b356c4757 100644 --- a/tests/Unit/AssetModelTest.php +++ b/tests/Unit/AssetModelTest.php @@ -1,4 +1,5 @@ create([ 'category_id' => $category->id, ]); - + $asset = Asset::factory()->create([ 'model_id' => $model->id ]); diff --git a/tests/Unit/AssetTest.php b/tests/Unit/AssetTest.php index d0f3af623373..130def3a606b 100644 --- a/tests/Unit/AssetTest.php +++ b/tests/Unit/AssetTest.php @@ -1,4 +1,5 @@ assertModelExists($a); $this->assertModelExists($b); - } public function testAutoIncrementCollision() @@ -179,14 +179,14 @@ public function testWarrantyExpiresAttribute() [ 'category_id' => Category::factory()->assetLaptopCategory()->create()->id ] - )->id, + )->id, 'warranty_months' => 24, - 'purchase_date' => Carbon::createFromDate(2017, 1, 1)->hour(0)->minute(0)->second(0) - ]); + 'purchase_date' => Carbon::createFromDate(2017, 1, 1)->hour(0)->minute(0)->second(0) + ] + ); + - $this->assertEquals(Carbon::createFromDate(2017, 1, 1)->format('Y-m-d'), $asset->purchase_date->format('Y-m-d')); $this->assertEquals(Carbon::createFromDate(2019, 1, 1)->format('Y-m-d'), $asset->warranty_expires->format('Y-m-d')); - } } diff --git a/tests/Unit/CategoryTest.php b/tests/Unit/CategoryTest.php index 8b1b16ee9f4a..bfe032e5444f 100644 --- a/tests/Unit/CategoryTest.php +++ b/tests/Unit/CategoryTest.php @@ -1,4 +1,5 @@ assetDesktopCategory()->create(); + $category = Category::factory()->assetDesktopCategory()->create(); // Generate 5 models via factory - $models = AssetModel::factory() + $models = AssetModel::factory() ->count(5) ->create( [ 'category_id' => $category->id ] - ); + ); + - // Loop through the models and create 2 assets in each model - $models->each(function ($model) { + $models->each(function ($model) { //dd($model); $asset = Asset::factory() ->count(2) diff --git a/tests/Unit/ComponentTest.php b/tests/Unit/ComponentTest.php index 6abbffd82d91..91b006f7d567 100644 --- a/tests/Unit/ComponentTest.php +++ b/tests/Unit/ComponentTest.php @@ -1,4 +1,5 @@ create( - [ + [ 'company_id' => Company::factory()->create()->id ] - ); + ); $this->assertInstanceOf(Company::class, $component->company); } @@ -34,12 +35,13 @@ public function testAComponentBelongsToACategory() $component = Component::factory()->ramCrucial4() ->create( [ - 'category_id' => + 'category_id' => Category::factory()->create( [ 'category_type' => 'component' ] - )->id]); + )->id] + ); $this->assertInstanceOf(Category::class, $component->category); $this->assertEquals('component', $component->category->category_type); } diff --git a/tests/Unit/CustomFieldTest.php b/tests/Unit/CustomFieldTest.php index d5704d8aa318..953db9f819dd 100644 --- a/tests/Unit/CustomFieldTest.php +++ b/tests/Unit/CustomFieldTest.php @@ -1,4 +1,5 @@ create( [ 'category_id' => Category::factory()->assetLaptopCategory()->create(), - 'depreciation_id' => $depreciation->id - ]); - + 'depreciation_id' => $depreciation->id + ] + ); + $this->assertEquals(5, $depreciation->models->count()); } public function testDepreciationAmount() @@ -31,7 +33,7 @@ public function testDepreciationAmount() $depreciation = Depreciation::factory()->create([ 'depreciation_type' => 'amount', 'depreciation_min' => 1000, - 'months'=> 36, + 'months' => 36, ]); $asset = Asset::factory() @@ -41,7 +43,8 @@ public function testDepreciationAmount() 'category_id' => Category::factory()->assetLaptopCategory()->create(), 'purchase_date' => now()->subDecade(), 'purchase_cost' => 4000, - ]); + ] + ); $asset->model->update([ 'depreciation_id' => $depreciation->id, ]); @@ -55,7 +58,7 @@ public function testDepreciationPercentage() $depreciation = Depreciation::factory()->create([ 'depreciation_type' => 'percent', 'depreciation_min' => 50, - 'months'=> 36, + 'months' => 36, ]); $asset = Asset::factory() @@ -65,7 +68,8 @@ public function testDepreciationPercentage() 'category_id' => Category::factory()->assetLaptopCategory()->create(), 'purchase_date' => now()->subDecade(), 'purchase_cost' => 4000, - ]); + ] + ); $asset->model->update([ 'depreciation_id' => $depreciation->id, ]); @@ -85,8 +89,9 @@ public function testADepreciationHasLicenses() ->create( [ 'category_id' => Category::factory()->licenseGraphicsCategory()->create(), - 'depreciation_id' => $depreciation->id - ]); + 'depreciation_id' => $depreciation->id + ] + ); $this->assertEquals(5, $depreciation->licenses()->count()); } diff --git a/tests/Unit/Helpers/HelperTest.php b/tests/Unit/Helpers/HelperTest.php index 2fb1c58e26f5..182306c6dc4b 100644 --- a/tests/Unit/Helpers/HelperTest.php +++ b/tests/Unit/Helpers/HelperTest.php @@ -32,7 +32,7 @@ public function testGetRedirectOptionMethod() { $test_data = [ 'Option target: redirect for user assigned to ' => [ - 'request' =>(object) ['assigned_user' => 22], + 'request' => (object) ['assigned_user' => 22], 'id' => 1, 'checkout_to_type' => 'user', 'redirect_option' => 'target', @@ -40,7 +40,7 @@ public function testGetRedirectOptionMethod() 'route' => route('users.show', 22), ], 'Option target: redirect location assigned to ' => [ - 'request' =>(object) ['assigned_location' => 10], + 'request' => (object) ['assigned_location' => 10], 'id' => 2, 'checkout_to_type' => 'location', 'redirect_option' => 'target', @@ -48,7 +48,7 @@ public function testGetRedirectOptionMethod() 'route' => route('locations.show', 10), ], 'Option target: redirect back to asset assigned to ' => [ - 'request' =>(object) ['assigned_asset' => 101], + 'request' => (object) ['assigned_asset' => 101], 'id' => 3, 'checkout_to_type' => 'asset', 'redirect_option' => 'target', @@ -56,7 +56,7 @@ public function testGetRedirectOptionMethod() 'route' => route('hardware.show', 101), ], 'Option item: redirect back to asset ' => [ - 'request' =>(object) ['assigned_asset' => null], + 'request' => (object) ['assigned_asset' => null], 'id' => 999, 'checkout_to_type' => null, 'redirect_option' => 'item', @@ -64,7 +64,7 @@ public function testGetRedirectOptionMethod() 'route' => route('hardware.show', 999), ], 'Option index: redirect back to asset index ' => [ - 'request' =>(object) ['assigned_asset' => null], + 'request' => (object) ['assigned_asset' => null], 'id' => null, 'checkout_to_type' => null, 'redirect_option' => 'index', @@ -73,7 +73,7 @@ public function testGetRedirectOptionMethod() ], 'Option item: redirect back to user ' => [ - 'request' =>(object) ['assigned_asset' => null], + 'request' => (object) ['assigned_asset' => null], 'id' => 999, 'checkout_to_type' => null, 'redirect_option' => 'item', @@ -82,7 +82,7 @@ public function testGetRedirectOptionMethod() ], 'Option index: redirect back to user index ' => [ - 'request' =>(object) ['assigned_asset' => null], + 'request' => (object) ['assigned_asset' => null], 'id' => null, 'checkout_to_type' => null, 'redirect_option' => 'index', @@ -91,7 +91,7 @@ public function testGetRedirectOptionMethod() ], 'Option item: redirect back to license ' => [ - 'request' =>(object) ['assigned_asset' => null], + 'request' => (object) ['assigned_asset' => null], 'id' => 999, 'checkout_to_type' => null, 'redirect_option' => 'item', @@ -100,7 +100,7 @@ public function testGetRedirectOptionMethod() ], 'Option index: redirect back to license index ' => [ - 'request' =>(object) ['assigned_asset' => null], + 'request' => (object) ['assigned_asset' => null], 'id' => null, 'checkout_to_type' => null, 'redirect_option' => 'index', @@ -109,7 +109,7 @@ public function testGetRedirectOptionMethod() ], 'Option item: redirect back to accessory list ' => [ - 'request' =>(object) ['assigned_asset' => null], + 'request' => (object) ['assigned_asset' => null], 'id' => 999, 'checkout_to_type' => null, 'redirect_option' => 'item', @@ -118,7 +118,7 @@ public function testGetRedirectOptionMethod() ], 'Option index: redirect back to accessory index ' => [ - 'request' =>(object) ['assigned_asset' => null], + 'request' => (object) ['assigned_asset' => null], 'id' => null, 'checkout_to_type' => null, 'redirect_option' => 'index', @@ -126,7 +126,7 @@ public function testGetRedirectOptionMethod() 'route' => route('accessories.index'), ], 'Option item: redirect back to consumable ' => [ - 'request' =>(object) ['assigned_asset' => null], + 'request' => (object) ['assigned_asset' => null], 'id' => 999, 'checkout_to_type' => null, 'redirect_option' => 'item', @@ -135,7 +135,7 @@ public function testGetRedirectOptionMethod() ], 'Option index: redirect back to consumables index ' => [ - 'request' =>(object) ['assigned_asset' => null], + 'request' => (object) ['assigned_asset' => null], 'id' => null, 'checkout_to_type' => null, 'redirect_option' => 'index', @@ -144,7 +144,7 @@ public function testGetRedirectOptionMethod() ], 'Option item: redirect back to component ' => [ - 'request' =>(object) ['assigned_asset' => null], + 'request' => (object) ['assigned_asset' => null], 'id' => 999, 'checkout_to_type' => null, 'redirect_option' => 'item', @@ -153,7 +153,7 @@ public function testGetRedirectOptionMethod() ], 'Option index: redirect back to component index ' => [ - 'request' =>(object) ['assigned_asset' => null], + 'request' => (object) ['assigned_asset' => null], 'id' => null, 'checkout_to_type' => null, 'redirect_option' => 'index', @@ -162,15 +162,14 @@ public function testGetRedirectOptionMethod() ], ]; - foreach ($test_data as $scenario => $data ) { - + foreach ($test_data as $scenario => $data) { Session::put('redirect_option', $data['redirect_option']); Session::put('checkout_to_type', $data['checkout_to_type']); - $redirect = redirect()->to(Helper::getRedirectOption($data['request'],$data['id'], $data['table'])); + $redirect = redirect()->to(Helper::getRedirectOption($data['request'], $data['id'], $data['table'])); $this->assertInstanceOf(RedirectResponse::class, $redirect); - $this->assertEquals($data['route'], $redirect->getTargetUrl(), $scenario.'failed.'); + $this->assertEquals($data['route'], $redirect->getTargetUrl(), $scenario . 'failed.'); } } } diff --git a/tests/Unit/Importer/AssetImportTest.php b/tests/Unit/Importer/AssetImportTest.php index 09e594c1beaf..d7123659b942 100644 --- a/tests/Unit/Importer/AssetImportTest.php +++ b/tests/Unit/Importer/AssetImportTest.php @@ -5,6 +5,7 @@ use App\Importer\AssetImporter; use App\Models\Statuslabel; use Tests\TestCase; + use function Livewire\invade; class AssetImportTest extends TestCase diff --git a/tests/Unit/LdapTest.php b/tests/Unit/LdapTest.php index a492b1efbce8..cf5a31cc8ad7 100644 --- a/tests/Unit/LdapTest.php +++ b/tests/Unit/LdapTest.php @@ -24,7 +24,7 @@ public function testConnect() $blah = Ldap::connectToLdap(); - $this->assertEquals('hello',$blah,"LDAP_connect should return 'hello'"); + $this->assertEquals('hello', $blah, "LDAP_connect should return 'hello'"); } // other test cases - with/without client-side certs? @@ -43,7 +43,7 @@ public function testBindBad() { $this->settings->enableLdap(); $this->getFunctionMock("App\\Models", "ldap_bind")->expects($this->once())->willReturn(false); - $this->getFunctionMock("App\\Models","ldap_error")->expects($this->once())->willReturn("exception"); + $this->getFunctionMock("App\\Models", "ldap_error")->expects($this->once())->willReturn("exception"); $this->expectExceptionMessage("Could not bind to LDAP:"); $this->assertNull(Ldap::bindAdminToLdap("dummy")); @@ -62,7 +62,7 @@ public function testBadAnonymousBind() { $this->settings->enableAnonymousLdap(); $this->getFunctionMock("App\\Models", "ldap_bind")->expects($this->once())->willReturn(false); - $this->getFunctionMock("App\\Models","ldap_error")->expects($this->once())->willReturn("exception"); + $this->getFunctionMock("App\\Models", "ldap_error")->expects($this->once())->willReturn("exception"); $this->expectExceptionMessage("Could not bind to LDAP:"); $this->assertNull(Ldap::bindAdminToLdap("dummy")); @@ -102,8 +102,8 @@ public function testFindAndBind() ] ); - $results = Ldap::findAndBindUserLdap("username","password"); - $this->assertEqualsCanonicalizing(["count" =>1,0 =>['sn' => 'Surname','firstname' => 'FirstName']],$results); + $results = Ldap::findAndBindUserLdap("username", "password"); + $this->assertEqualsCanonicalizing(["count" => 1,0 => ['sn' => 'Surname','firstname' => 'FirstName']], $results); } public function testFindAndBindBadPassword() @@ -123,7 +123,7 @@ public function testFindAndBindBadPassword() // $this->expectExceptionMessage("exception"); - $results = Ldap::findAndBindUserLdap("username","password"); + $results = Ldap::findAndBindUserLdap("username", "password"); $this->assertFalse($results); } @@ -142,7 +142,7 @@ public function testFindAndBindCannotFindSelf() $this->getFunctionMock("App\\Models", "ldap_search")->expects($this->once())->willReturn(false); $this->expectExceptionMessage("Could not search LDAP:"); - $results = Ldap::findAndBindUserLdap("username","password"); + $results = Ldap::findAndBindUserLdap("username", "password"); $this->assertFalse($results); } @@ -186,9 +186,9 @@ public function testFindLdapUsersPaginated() $this->getFunctionMock("App\\Models", "ldap_search")->expects($this->exactly(2))->willReturn(["stuff"]); $this->getFunctionMock("App\\Models", "ldap_parse_result")->expects($this->exactly(2))->willReturnCallback( - function ($ldapconn, $search_results, $errcode , $matcheddn , $errmsg , $referrals, &$controls) { + function ($ldapconn, $search_results, $errcode, $matcheddn, $errmsg, $referrals, &$controls) { static $count = 0; - if($count == 0) { + if ($count == 0) { $count++; $controls[LDAP_CONTROL_PAGEDRESULTS]['value']['cookie'] = "cookie"; return ["count" => 1]; @@ -196,7 +196,6 @@ function ($ldapconn, $search_results, $errcode , $matcheddn , $errmsg , $referra $controls = []; return ["count" => 1]; } - } ); @@ -232,5 +231,4 @@ public function testFreshTLSFile() $possibly_recached_cert_file = Setting::get_client_side_cert_path(); //this should *NOT* re-cache from the Settings $this->assertStringEqualsFile($possibly_recached_cert_file, 'WEIRDLY UPDATED CERT FILE'); } - } diff --git a/tests/Unit/Listeners/LogListenerTest.php b/tests/Unit/Listeners/LogListenerTest.php index 64dd2a3d673b..dae8b08619d1 100644 --- a/tests/Unit/Listeners/LogListenerTest.php +++ b/tests/Unit/Listeners/LogListenerTest.php @@ -36,5 +36,4 @@ public function testLogsEntryOnCheckoutableCheckedOut() 'note' => 'A simple note...', ]); } - } diff --git a/tests/Unit/LocationTest.php b/tests/Unit/LocationTest.php index 3fded9e568dd..ed5b9abb663b 100644 --- a/tests/Unit/LocationTest.php +++ b/tests/Unit/LocationTest.php @@ -1,4 +1,5 @@ create( [ - 'company_id'=> $company->id + 'company_id' => $company->id ] - ); + ); $this->assertCount(1, $company->users); } diff --git a/tests/Unit/Models/ReportTemplates/ReportTemplateParsingValuesTest.php b/tests/Unit/Models/ReportTemplates/ReportTemplateParsingValuesTest.php index 91bd8979d0f3..098a1b1c20f5 100644 --- a/tests/Unit/Models/ReportTemplates/ReportTemplateParsingValuesTest.php +++ b/tests/Unit/Models/ReportTemplates/ReportTemplateParsingValuesTest.php @@ -13,7 +13,7 @@ class ReportTemplateParsingValuesTest extends TestCase { public function testParsingValuesOnNonExistentReportTemplate() { - $unsavedTemplate = new ReportTemplate; + $unsavedTemplate = new ReportTemplate(); // checkmarkValue() should be "checked" (1) by default $this->assertEquals('1', $unsavedTemplate->checkmarkValue('is_a_checkbox_field')); @@ -49,7 +49,7 @@ public function testParsingCheckmarkValue() $this->assertEquals('1', $template->checkmarkValue('is_a_checkbox_field')); $this->assertEquals('0', $template->checkmarkValue('non_existent_key')); $this->assertEquals('0', $template->checkmarkValue('is_checkbox_field_with_zero')); - $this->assertEquals('0', (new ReportTemplate)->checkmarkValue('non_existent_key_that_is_overwritten_to_default_to_zero', '0')); + $this->assertEquals('0', (new ReportTemplate())->checkmarkValue('non_existent_key_that_is_overwritten_to_default_to_zero', '0')); } public function testParsingTextValue() @@ -63,8 +63,8 @@ public function testParsingTextValue() $this->assertEquals('some text', $template->textValue('is_a_text_field')); $this->assertEquals('', $template->textValue('non_existent_key')); - $this->assertEquals('', (new ReportTemplate)->textValue('is_a_text_field')); - $this->assertEquals('my fallback', (new ReportTemplate)->textValue('non_existent_key', 'my fallback')); + $this->assertEquals('', (new ReportTemplate())->textValue('is_a_text_field')); + $this->assertEquals('my fallback', (new ReportTemplate())->textValue('non_existent_key', 'my fallback')); } public function testParsingRadioValue() @@ -137,7 +137,7 @@ public function testSelectValueDoesNotIncludeDeletedOrNonExistentModels() $this->assertNull($templateWithDeletedId->selectValue('single_value', Location::class)); $this->assertNull($templateWithInvalidId->selectValue('single_value', Location::class)); - $this->assertNull((new ReportTemplate)->selectValue('value_on_unsaved_template', Location::class)); + $this->assertNull((new ReportTemplate())->selectValue('value_on_unsaved_template', Location::class)); } public function testSelectValuesDoNotIncludeDeletedOrNonExistentModels() diff --git a/tests/Unit/NotificationTest.php b/tests/Unit/NotificationTest.php index 5b420a675385..0a5c8cc8d7dc 100644 --- a/tests/Unit/NotificationTest.php +++ b/tests/Unit/NotificationTest.php @@ -1,4 +1,5 @@ Category::factory()->assetLaptopCategory()->create()->id ] - )->id, + )->id, 'warranty_months' => 24, 'purchase_date' => Carbon::createFromDate(2017, 1, 1)->hour(0)->minute(0)->second(0)->format('Y-m-d') - ]); + ] + ); Mail::fake(); $asset->checkOut($user, $admin->id); diff --git a/tests/Unit/SnipeModelTest.php b/tests/Unit/SnipeModelTest.php index 2bc81da61b7a..d64bece7418c 100644 --- a/tests/Unit/SnipeModelTest.php +++ b/tests/Unit/SnipeModelTest.php @@ -1,4 +1,5 @@ purchase_date = ''; $this->assertTrue($c->purchase_date === null); $c->purchase_date = '2016-03-25 12:35:50'; @@ -17,7 +18,7 @@ public function testSetsPurchaseDatesAppropriately() public function testSetsPurchaseCostsAppropriately() { - $c = new SnipeModel; + $c = new SnipeModel(); $c->purchase_cost = '0.00'; $this->assertTrue($c->purchase_cost === null); $c->purchase_cost = '9.54'; @@ -28,7 +29,7 @@ public function testSetsPurchaseCostsAppropriately() public function testNullsBlankLocationIdsButNotOthers() { - $c = new SnipeModel; + $c = new SnipeModel(); $c->location_id = ''; $this->assertTrue($c->location_id === null); $c->location_id = '5'; @@ -37,7 +38,7 @@ public function testNullsBlankLocationIdsButNotOthers() public function testNullsBlankCategoriesButNotOthers() { - $c = new SnipeModel; + $c = new SnipeModel(); $c->category_id = ''; $this->assertTrue($c->category_id === null); $c->category_id = '1'; @@ -46,7 +47,7 @@ public function testNullsBlankCategoriesButNotOthers() public function testNullsBlankSuppliersButNotOthers() { - $c = new SnipeModel; + $c = new SnipeModel(); $c->supplier_id = ''; $this->assertTrue($c->supplier_id === null); $c->supplier_id = '4'; @@ -55,7 +56,7 @@ public function testNullsBlankSuppliersButNotOthers() public function testNullsBlankDepreciationsButNotOthers() { - $c = new SnipeModel; + $c = new SnipeModel(); $c->depreciation_id = ''; $this->assertTrue($c->depreciation_id === null); $c->depreciation_id = '4'; @@ -64,7 +65,7 @@ public function testNullsBlankDepreciationsButNotOthers() public function testNullsBlankManufacturersButNotOthers() { - $c = new SnipeModel; + $c = new SnipeModel(); $c->manufacturer_id = ''; $this->assertTrue($c->manufacturer_id === null); $c->manufacturer_id = '4'; diff --git a/tests/Unit/SnipeTranslatorTest.php b/tests/Unit/SnipeTranslatorTest.php index d374bf913475..a32c669c4067 100644 --- a/tests/Unit/SnipeTranslatorTest.php +++ b/tests/Unit/SnipeTranslatorTest.php @@ -13,19 +13,19 @@ class SnipeTranslatorTest extends TestCase public function testBasic() { - $this->assertEquals('This user has admin privileges',trans('general.admin_tooltip',[],'en-US')); + $this->assertEquals('This user has admin privileges', trans('general.admin_tooltip', [], 'en-US')); } public function testPortuguese() { - $this->assertEquals('Acessório',trans('general.accessory',[],'pt-PT')); + $this->assertEquals('Acessório', trans('general.accessory', [], 'pt-PT')); } public function testFallback() { $this->assertEquals( 'This user has admin privileges', - trans('general.admin_tooltip',[],'xx-ZZ'), + trans('general.admin_tooltip', [], 'xx-ZZ'), "Nonexistent locale should fall-back to en-US" ); } @@ -34,7 +34,7 @@ public function testBackupString() { $this->assertEquals( 'Ingen sikkerhetskopier ble gjort ennå', - trans('backup::notifications.no_backups_info',[],'nb-NO'), + trans('backup::notifications.no_backups_info', [], 'nb-NO'), "Norwegian 'no backups info' message should be here" ); } @@ -43,17 +43,16 @@ public function testBackupFallback() { $this->assertEquals( 'No backups were made yet', - trans('backup::notifications.no_backups_info',[],'xx-ZZ'), + trans('backup::notifications.no_backups_info', [], 'xx-ZZ'), "'no backups info' string should fallback to 'en'" ); - } public function testTransChoiceSingular() { $this->assertEquals( '1 Consumível', - trans_choice('general.countable.consumables',1,[],'pt-PT') + trans_choice('general.countable.consumables', 1, [], 'pt-PT') ); } @@ -61,7 +60,7 @@ public function testTransChoicePlural() { $this->assertEquals( '2 Consumíveis', - trans_choice('general.countable.consumables',2,[],'pt-PT') + trans_choice('general.countable.consumables', 2, [], 'pt-PT') ); } @@ -69,24 +68,26 @@ public function testTotallyBogusKey() { $this->assertEquals( 'bogus_key', - trans('bogus_key',[],'pt-PT'), + trans('bogus_key', [], 'pt-PT'), "Translating a completely bogus key should at least just return back that key" ); } - public function testReplacements() { + public function testReplacements() + { $this->assertEquals( 'Artigos alocados a Some Name Here', - trans('admin/users/general.assets_user',['name' => 'Some Name Here'],'pt-PT'), + trans('admin/users/general.assets_user', ['name' => 'Some Name Here'], 'pt-PT'), "Text should get replaced in translations when given" ); } - public function testNonlegacyBackupLocale() { + public function testNonlegacyBackupLocale() + { //Spatie backup *usually* uses two-character locales, but pt-BR is an exception $this->assertEquals( 'Mensagem de exceção: MESSAGE', - trans('backup::notifications.exception_message',['message' => 'MESSAGE'],'pt-BR') + trans('backup::notifications.exception_message', ['message' => 'MESSAGE'], 'pt-BR') ); } } diff --git a/tests/Unit/StatuslabelTest.php b/tests/Unit/StatuslabelTest.php index fe5f3cacc067..511d92fa44b7 100644 --- a/tests/Unit/StatuslabelTest.php +++ b/tests/Unit/StatuslabelTest.php @@ -1,4 +1,5 @@ create(['months' => 0]); $asset->model->depreciation()->associate($depreciation); - $transformer = new DepreciationReportTransformer; + $transformer = new DepreciationReportTransformer(); $result = $transformer->transformAsset($asset); diff --git a/upgrade.php b/upgrade.php index b98162ed96e0..fcdd45717aa9 100644 --- a/upgrade.php +++ b/upgrade.php @@ -415,7 +415,7 @@ function url_get_contents ($Url) { // Print out a useful error message if ($dirs_not_writable!='') { echo "\e[91m--------------------------------------------------------\n"; - echo "\eThe following directories/files do not seem writable: \n"; + echo "\eThe following directories/files do not seem writable: \n"; // codespell:ignore echo "\e--------------------------------------------------------\e[39m\n"; echo $dirs_not_writable;