3 namespace Drupal\file\FileUsage;
5 use Drupal\Core\Config\ConfigFactoryInterface;
6 use Drupal\Core\Database\Connection;
7 use Drupal\file\FileInterface;
10 * Defines the database file usage backend. This is the default Drupal backend.
12 class DatabaseFileUsageBackend extends FileUsageBase {
15 * The database connection used to store file usage information.
17 * @var \Drupal\Core\Database\Connection
19 protected $connection;
22 * The name of the SQL table used to store file usage information.
29 * Construct the DatabaseFileUsageBackend.
31 * @param \Drupal\Core\Database\Connection $connection
32 * The database connection which will be used to store the file usage
34 * @param string $table
35 * (optional) The table to store file usage info. Defaults to 'file_usage'.
36 * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
37 * (optional) The config factory.
39 public function __construct(Connection $connection, $table = 'file_usage', ConfigFactoryInterface $config_factory = NULL) {
40 parent::__construct($config_factory);
41 $this->connection = $connection;
43 $this->tableName = $table;
49 public function add(FileInterface $file, $module, $type, $id, $count = 1) {
50 $this->connection->merge($this->tableName)
57 ->fields(['count' => $count])
58 ->expression('count', 'count + :count', [':count' => $count])
61 parent::add($file, $module, $type, $id, $count);
67 public function delete(FileInterface $file, $module, $type = NULL, $id = NULL, $count = 1) {
68 // Delete rows that have a exact or less value to prevent empty rows.
69 $query = $this->connection->delete($this->tableName)
70 ->condition('module', $module)
71 ->condition('fid', $file->id());
74 ->condition('type', $type)
75 ->condition('id', $id);
78 $query->condition('count', $count, '<=');
80 $result = $query->execute();
82 // If the row has more than the specified count decrement it by that number.
83 if (!$result && $count > 0) {
84 $query = $this->connection->update($this->tableName)
85 ->condition('module', $module)
86 ->condition('fid', $file->id());
89 ->condition('type', $type)
90 ->condition('id', $id);
92 $query->expression('count', 'count - :count', [':count' => $count]);
96 parent::delete($file, $module, $type, $id, $count);
102 public function listUsage(FileInterface $file) {
103 $result = $this->connection->select($this->tableName, 'f')
104 ->fields('f', ['module', 'type', 'id', 'count'])
105 ->condition('fid', $file->id())
106 ->condition('count', 0, '>')
109 foreach ($result as $usage) {
110 $references[$usage->module][$usage->type][$usage->id] = $usage->count;