<?php
class BrokenSignException extends \Exception {}
class ExportableData
{
protected static function getCost()
{
return 13;
}
private $data;
private $filename;
/**
* Constructor from data
* @param mixed $data Data to save
*/
public function __construct($data)
{
$this->data = $data;
}
/**
* Exports data to specified file
* @param string $filename Filename
*/
public function export($filename)
{
$this->filename = $filename;
$this->save($this->exportToString());
}
/**
* Export data to string
* @return string Exported data
*/
public function exportToString()
{
return serialize($this->sign());
}
/**
* Import signed data from string
* @param string $data Signed data
* @return ExportableData Instance of @a ExportableData
* @throws BrokenSignException If sign verification failed
*/
public static function importFromString($data)
{
$me = new static(null);
$me->verify(unserialize($data));
return $me;
}
/**
* Data getter
* @return mixed User data
*/
public function getData()
{
return $this->data;
}
/**
* Import signed data from specified file
* @param string $filename Filename
* @return ExportableData Instance of @a ExportableData with data from file
* @throws BrokenSignException If sign verification failed
*/
public static function import($filename)
{
$me = new static(null);
$me->filename = $filename;
$me->verify($me->load());
return $me;
}
protected load()
{
return unserialize(file_get_contents($this->filename));
}
protected function verify(array $rawData)
{
if (!password_verify($rawData[0], $rawData[1])) {
throw new BrokenSignException();
}
$this->data = unserialize(base64_decode($rawData[1]));
}
protected function sign()
{
$serialized = base64_encode(serialize($this->data));
$sign = password_hash($serialized, PASSWORD_BCRYPT, ['cost' => static::getCost()]);
return [$serialized, $sign];
}
protected function save($rawData)
{
file_put_contents($this->filename, $rawData);
}
}
// Example
// Saving
/** @var mixed $product */
$exportable = new ExportableData($product);
$exportable->export('somefile.sav');
// Or if you want to get file as string
$exportable->exportToString();
// Loading
$data = null;
try {
// if you got file as string
$data = ExportableData::importFromString($stringData);
// if you got file
$data = ExportableData::import($filename);
} catch (BrokenSignException $e) {
die('Data is broken!');
}
$product = $data->getData();
Что вы понимаете под "химичили" и куда в дальнейшем направляется файл?