1+ <?php
2+ namespace Grimzy \LaravelSpatial \Eloquent ;
3+
4+ use Grimzy \LaravelSpatial \Exceptions \SpatialFieldsNotDefinedException ;
5+ use Grimzy \LaravelSpatial \Types \Geometry ;
6+ use Grimzy \LaravelSpatial \Types \GeometryInterface ;
7+ use Illuminate \Database \Eloquent \Builder as EloquentBuilder ;
8+
9+ trait SpatialTrait
10+ {
11+ /*
12+ * The attributes that are spatial representations.
13+ * To use this Trait, add the following array to the model class
14+ *
15+ * @var array
16+ *
17+ * protected $spatialFields = [];
18+ */
19+
20+ public $ geometries = [];
21+
22+ /**
23+ * Create a new Eloquent query builder for the model.
24+ *
25+ * @param \Illuminate\Database\Query\Builder $query
26+ *
27+ * @return \Grimzy\LaravelSpatial\Eloquent\Builder
28+ */
29+ public function newEloquentBuilder ($ query )
30+ {
31+ return new Builder ($ query );
32+ }
33+
34+ protected function performInsert (EloquentBuilder $ query , array $ options = [])
35+ {
36+ foreach ($ this ->attributes as $ key => $ value ) {
37+ if ($ value instanceof GeometryInterface) {
38+ $ this ->geometries [$ key ] = $ value ; //Preserve the geometry objects prior to the insert
39+ $ this ->attributes [$ key ] = $ this ->getConnection ()->raw (sprintf ("ST_GeomFromText('%s') " , $ value ->toWKT ()));
40+ }
41+ }
42+
43+ $ insert = parent ::performInsert ($ query , $ options );
44+
45+ foreach ($ this ->geometries as $ key => $ value ) {
46+ $ this ->attributes [$ key ] = $ value ; //Retrieve the geometry objects so they can be used in the model
47+ }
48+
49+ return $ insert ; //Return the result of the parent insert
50+ }
51+
52+ public function setRawAttributes (array $ attributes , $ sync = false )
53+ {
54+ $ spatial_fields = $ this ->getSpatialFields ();
55+
56+ foreach ($ attributes as $ attribute => &$ value ) {
57+ if (in_array ($ attribute , $ spatial_fields ) && is_string ($ value ) && strlen ($ value ) >= 15 ) {
58+ $ value = Geometry::fromWKB ($ value );
59+ }
60+ }
61+
62+ parent ::setRawAttributes ($ attributes , $ sync );
63+ }
64+
65+ public function getSpatialFields ()
66+ {
67+ if (property_exists ($ this , 'spatialFields ' )) {
68+ return $ this ->spatialFields ;
69+ } else {
70+ throw new SpatialFieldsNotDefinedException (__CLASS__ . ' has to define $spatialFields ' );
71+ }
72+
73+ }
74+ }
0 commit comments