我正在开发一个网络应用程序,试图控制PHPstan的建议。
我对这种方法有些困难:
/**
* AJAX: deletes a work file
*
* @return \Cake\Http\Response|false
*/
public function delete()
{
$this->autoRender = false;
$this->viewBuilder()->setLayout('ajax');
$this->request->allowMethod(['post', 'delete']);
$data = $this->request->getData();
$data = is_array($data) ? $data : [$data];
$workFile = $this->WorkFiles->find('all')
->where(['WorkFiles.id' => $data['id']])
->contain(['Works'])
->first();
$res = [
'status' => 'error',
'message' => __('The file could not be deleted. Please, try again.'),
'class' => 'alert-error',
];
if ($workFile->work->anagraphic_id == $this->authAnagraphics['id']) { // error #1
if ($this->WorkFiles->delete($workFile)) { // error #2
$res = [
'status' => 'success',
'message' => __('File successfully deleted.'),
'class' => 'alert-success',
];
}
}
return $this->response->withStringBody((string)json_encode($res));
}代码本身可以工作,但我有两个phpstan错误:
[phpstan] Cannot access property $work on array|Cake\Datasource\EntityInterface|null.[phpstan] Parameter #1 $entity of method Cake\ORM\Table::delete() expects Cake\Datasource\EntityInterface, array|Cake\Datasource\EntityInterface|null given.我做错了什么吗?
发布于 2022-10-19 10:00:42
始终使用内联注释,然后在这里:
/** @var \App\Model\Entity\WorkFile|null $workFile */
$workFile = $this->WorkFiles->find('all')
->where(['WorkFiles.id' => $data['id']])
->contain(['Works'])
->first();但是注释是正确的,您在事后盲目地使用一个可能的空值,因为您的代码没有正确地编写。
用这个代替:
/** @var \App\Model\Entity\WorkFile $workFile */
$workFile = $this->WorkFiles->find('all')
->where(['WorkFiles.id' => $data['id']])
->contain(['Works'])
->firstOrFail();https://stackoverflow.com/questions/74114683
复制相似问题