2024-03-07 06:40:52 -08:00
< ? php
namespace App\Console\Commands ;
use App\Models\Asset ;
use App\Models\CustomField ;
use Illuminate\Console\Command ;
2024-03-07 07:04:08 -08:00
use Illuminate\Support\Facades\DB ;
2024-03-07 06:40:52 -08:00
class ToggleCustomfieldEncryption extends Command
{
/**
* The name and signature of the console command .
*
* @ var string
*/
protected $signature = ' snipeit : customfield - encryption
{ fieldname : the db_column_name of the field } ' ;
/**
* The console command description .
*
* @ var string
*/
2024-03-07 06:43:06 -08:00
protected $description = 'This command should be used to convert an unencrypted custom field into a custom field and encrypt the associated data in the assets table for that column.' ;
2024-03-07 06:40:52 -08:00
/**
* Create a new command instance .
*
* @ return void
*/
public function __construct ()
{
parent :: __construct ();
}
/**
* Execute the console command .
*
* @ return int
*/
public function handle ()
{
$fieldname = $this -> argument ( 'fieldname' );
if ( $field = CustomField :: where ( 'db_column' , $fieldname ) -> first ()) {
2024-03-07 06:43:06 -08:00
2024-03-07 06:40:52 -08:00
// If the field is not encrypted, make it encrypted and encrypt the data in the assets table for the
// corresponding field.
2024-03-07 07:04:08 -08:00
DB :: transaction ( function () use ( $field ) {
2024-03-07 06:40:52 -08:00
2024-03-07 07:04:08 -08:00
if ( $field -> field_encrypted == 0 ) {
$assets = Asset :: whereNotNull ( $field -> db_column ) -> get ();
foreach ( $assets as $asset ) {
$asset -> { $field -> db_column } = encrypt ( $asset -> { $field -> db_column });
$asset -> save ();
}
2024-03-07 06:40:52 -08:00
2024-03-07 07:04:08 -08:00
$field -> field_encrypted = 1 ;
$field -> save ();
2024-03-07 06:40:52 -08:00
2024-03-07 07:04:08 -08:00
// This field is already encrypted. Do nothing.
} else {
$this -> error ( 'The custom field ' . $field -> db_column . ' is already encrypted. No action was taken.' );
}
});
2024-03-07 06:40:52 -08:00
2024-03-07 07:04:08 -08:00
// No matching column name found
2024-03-07 06:40:52 -08:00
} else {
$this -> error ( 'No matching results for unencrypted custom fields with db_column name: ' . $fieldname . '. Please check the fieldname.' );
}
}
}