Fixed No clean way to manipulate the AttachmentData entity before the file is copied

Jake B.

Well-known member
Affected version
2.1.7
I'm making some changes to how attachments are stored for certain cases, but am not able to manipulate anything within the AttachmentData entity before it's saved, and the files have already been uploaded within \XF\Service\Attachment\Preparer::insertDataFromFile so I'm required to overwrite the entire method which doesn't seem very clean, and prone to issues if this method gets changed. What I propose is the following:

Remove the following from insertDataFromFile

PHP:
/** @var \XF\Entity\AttachmentData $data */
$data = $this->app->em()->create('XF:AttachmentData');
$data->user_id = $userId;
$data->set('filename', $file->getFileName(), ['forceConstraint' => true]);
$data->file_size = $file->getFileSize();
$data->file_hash = md5_file($sourceFile);
$data->file_path = $extra['file_path'];
$data->width = $width;
$data->height = $height;

if ($extra['upload_date'])
{
   $data->upload_date = $extra['upload_date'];
}

if (!$data->preSave())
{
   throw new \XF\PrintableException($data->getErrors());
}

and place it into a separate function:

PHP:
protected function initializeAttachmentDataFromFile(\XF\FileWrapper $file, $userId, array $extra = [])
   {
       $sourceFile = $file->getFilePath();
       $width = $file->getImageWidth();
       $height = $file->getImageHeight();
       
       /** @var \XF\Entity\AttachmentData $data */
       $data = $this->app->em()->create('XF:AttachmentData');
       $data->user_id = $userId;
       $data->set('filename', $file->getFileName(), ['forceConstraint' => true]);
       $data->file_size = $file->getFileSize();
       $data->file_hash = md5_file($sourceFile);
       $data->file_path = $extra['file_path'];
       $data->width = $width;
       $data->height = $height;

       if ($extra['upload_date'])
       {
           $data->upload_date = $extra['upload_date'];
       }

       if (!$data->preSave())
       {
           throw new \XF\PrintableException($data->getErrors());
       }
       
       return $data;
   }
 
Thank you for reporting this issue, it has now been resolved. We are aiming to include any changes that have been made in a future XF release (2.1.8).

Change log:
Allow attachment data manipulation before copying files
There may be a delay before changes are rolled out to the XenForo Community.
 
Back
Top Bottom