44
55use Illuminate \Support \Facades \Cache ;
66use Statamic \Assets \Asset as FileAsset ;
7+ use Statamic \Assets \AssetUploader as Uploader ;
78use Statamic \Facades \Blink ;
9+ use Statamic \Facades \Path ;
810use Statamic \Support \Arr ;
11+ use Statamic \Support \Str ;
912
1013class Asset extends FileAsset
1114{
15+ protected $ removedData = [];
16+
1217 public function meta ($ key = null )
1318 {
1419 if (func_num_args () === 1 ) {
@@ -20,7 +25,14 @@ public function meta($key = null)
2025 }
2126
2227 if ($ this ->meta ) {
23- return array_merge ($ this ->meta , ['data ' => $ this ->data ->all ()]);
28+ $ meta = $ this ->meta ;
29+
30+ $ meta ['data ' ] = collect (Arr::get ($ meta , 'data ' , []))
31+ ->merge ($ this ->data ->all ())
32+ ->except ($ this ->removedData )
33+ ->all ();
34+
35+ return $ meta ;
2436 }
2537
2638 return $ this ->meta = Cache::rememberForever ($ this ->metaCacheKey (), function () {
@@ -56,11 +68,7 @@ private function metaValue($key)
5668 return $ value ;
5769 }
5870
59- Cache::forget ($ this ->metaCacheKey ());
60-
61- $ this ->writeMeta ($ meta = $ this ->generateMeta ());
62-
63- return Arr::get ($ meta , $ key );
71+ return Arr::get ($ this ->generateMeta (), $ key );
6472 }
6573
6674 public function writeMeta ($ meta )
@@ -79,4 +87,35 @@ public function writeMeta($meta)
7987
8088 $ model ->save ();
8189 }
90+
91+ /**
92+ * Move the asset to a different location.
93+ *
94+ * @param string $folder The folder relative to the container.
95+ * @param string|null $filename The new filename, if renaming.
96+ * @return $this
97+ */
98+ public function move ($ folder , $ filename = null )
99+ {
100+ $ filename = Uploader::getSafeFilename ($ filename ?: $ this ->filename ());
101+ $ oldPath = $ this ->path ();
102+ $ oldMetaPath = $ this ->metaPath ();
103+ $ newPath = Str::removeLeft (Path::tidy ($ folder .'/ ' .$ filename .'. ' .pathinfo ($ oldPath , PATHINFO_EXTENSION )), '/ ' );
104+
105+ $ this ->hydrate ();
106+ $ this ->disk ()->rename ($ oldPath , $ newPath );
107+ $ this ->path ($ newPath );
108+ $ this ->save ();
109+
110+ if ($ oldMetaPath != $ this ->metaPath ()) {
111+ $ oldMetaModel = app ('statamic.eloquent.assets.model ' )::whereHandle ($ this ->container ()->handle ().':: ' .$ oldMetaPath )->first ();
112+
113+ if ($ oldMetaModel ) {
114+ $ oldMetaModel ->delete ();
115+ $ this ->writeMeta ($ oldMetaModel ->data );
116+ }
117+ }
118+
119+ return $ this ;
120+ }
82121}
0 commit comments