【发布时间】:2021-11-23 07:48:04
【问题描述】:
我正在使用 SonarQube 扫描我的 Laravel 应用程序,但它不喜欢以下代码:
class EligibilityImportJob implements ShouldQueue
{
use Dispatchable,
InteractsWithQueue,
Queueable,
SerializesModels;
/** @var string */
protected $file;
/** @var int */
protected $mode;
public function __construct(string $file, $mode)
{
$this->file = $file;
$this->mode = $mode;
}
public function handle(): void
{
$file = $this->file;
$mode = $this->mode;
new EligibilityImport($file, $mode); // Doesn't like this line
}
}
它给了我以下错误:Either remove this useless object instantiation of class "EligibilityImport" or use it。我怎样才能解决这个问题?下面是 EligibilityImport 类,它从数据库中导入或删除数据,来自 CSV 文件:
final class EligibilityImport
{
const MODE_APPEND = 1;
const MODE_PURGE = 2;
const MODES = [
self::MODE_APPEND => 'append',
self::MODE_PURGE => 'purge'
];
/** @var string */
protected $file;
/** @var int */
protected $mode;
/** @var array */
protected $cache = [];
public function __construct($file, $mode = self::MODE_APPEND)
{
$this->file = $file;
$this->mode = $mode;
$this->process();
}
protected function process()
{
$file = $this->file;
$mode = $this->mode;
$path = storage_path('app/imports/' . $file);
if (is_file($path)) {
$csv = Reader::createFromPath($path, 'r');
$csv->setHeaderOffset(0);
$records = $csv->getRecords();
foreach ($records as $record) {
$companyName = $record['company'] ?? null;
if ( ! empty($companyName)) {
$company = $this->cache['companies'][$companyName] ?? null;
if (empty($company)) {
$company = Company::where('name', $companyName)->first();
if ($company !== null) {
$this->cache['companies'][$companyName] = $company;
}
}
if ($company !== null) {
$eligibility = null;
$skip = false;
$firstName = $record['first_name'] ?? null;
$lastName = $record['last_name'] ?? null;
$email = $record['email'] ?? null;
$ein = $record['ein'] ?? null;
if ( ! empty($email)) {
$eligibility = $company
->eligibilities()
->where('email_hash', sha1($email))
->first();
if ($eligibility !== null) {
$skip = true;
if ($mode == self::MODE_PURGE) {
$eligibility->delete();
}
}
}
if ( ! empty($ein)) {
$eligibility = $company
->eligibilities()
->where('ein_hash', sha1($ein))
->first();
if ($eligibility !== null) {
$skip = true;
if ($mode == self::MODE_PURGE) {
$eligibility->delete();
}
}
}
if ($mode == self::MODE_APPEND && ! $skip) {
if ( ! empty($firstName) && ! empty($lastName) && ( ! empty($email) || ! empty($ein))) {
$eligibility = new Eligibility();
$eligibility->fill($record);
$company->eligibilities()->save($eligibility);
}
}
}
}
}
@unlink($path);
}
}
}
【问题讨论】:
-
你是对的。我最初输入了另一个错误的代码。我已经更新了原始问题并提供了更多代码供您查看。
-
谢谢。实际上,您现在已经发布了正确的代码。请看下面我的回答。 :-) 看看为什么以 MRE 的形式发布正确的代码会有所作为?
标签: laravel sonarqube sonarscanner