1: <?php
2:
3: 4: 5: 6: 7: 8:
9:
10: namespace rsanchez\Deep\Model;
11:
12: use Illuminate\Database\Eloquent\Model;
13: use Illuminate\Database\Eloquent\Builder;
14: use rsanchez\Deep\Collection\EntryCollection;
15: use rsanchez\Deep\Collection\FileCollection;
16: use rsanchez\Deep\Model\UploadPref;
17: use Carbon\Carbon;
18:
19: 20: 21:
22: class File extends Model implements FileInterface
23: {
24: 25: 26:
27: protected $table = 'files';
28:
29: 30: 31:
32: protected $primaryKey = 'file_id';
33:
34: 35: 36:
37: protected $hidden = array('site_id', 'upload_location_id', 'rel_path', 'uploaded_by_member_id', 'modified_by_member_id', 'uploadPref');
38:
39: 40: 41:
42: protected $appends = array('url');
43:
44: 45: 46: 47:
48: protected $uploadPref;
49:
50: 51: 52: 53: 54:
55: public function setUploadPref(UploadPref $uploadPref)
56: {
57: $this->uploadPref = $uploadPref;
58: }
59:
60: 61: 62:
63: public function getUrlAttribute()
64: {
65: return $this->uploadPref->url.$this->file_name;
66: }
67:
68: 69: 70:
71: public function getServerPathAttribute()
72: {
73: return $this->uploadPref->server_path.$this->file_name;
74: }
75:
76: 77: 78: 79: 80: 81:
82: public function getUploadDateAttribute($value)
83: {
84: return Carbon::createFromFormat('U', $value);
85: }
86:
87: 88: 89: 90: 91: 92:
93: public function getModifiedDateAttribute($value)
94: {
95: return Carbon::createFromFormat('U', $value);
96: }
97:
98: 99: 100:
101: public function __toString()
102: {
103: return $this->getUrlAttribute();
104: }
105:
106: 107: 108: 109: 110: 111:
112: public function newCollection(array $models = array())
113: {
114: return new FileCollection($models);
115: }
116:
117: 118: 119: 120: 121: 122: 123: 124: 125: 126:
127: public function scopeFromEntryCollection(Builder $query, EntryCollection $collection)
128: {
129: foreach ($collection as $entry) {
130:
131: foreach ($entry->channel->fieldsByType('file') as $field) {
132:
133: $value = $entry->getAttribute('field_id_'.$field->field_id);
134:
135: if (! preg_match('#^{filedir_(\d+)}(.*)$#', $value, $match)) {
136: return;
137: }
138:
139: $filedir = $match[1];
140: $filename = $match[2];
141:
142: $query->orWhere(function ($query) use ($filedir, $filename) {
143: return $query->where('file_name', $filename)
144: ->where('upload_location_id', $filedir);
145: });
146: }
147:
148: }
149:
150: return $query;
151: }
152:
153: 154: 155:
156: public function attributesToArray()
157: {
158: $attributes = parent::attributesToArray();
159:
160: foreach (array('upload_date', 'modified_date') as $key) {
161: if (isset($attributes[$key]) && $attributes[$key] instanceof Carbon) {
162: $attributes[$key] = (string) $attributes[$key];
163: }
164: }
165:
166: return $attributes;
167: }
168: }
169: