1: <?php
2:
3: /**
4: * Deep
5: *
6: * @package rsanchez\Deep
7: * @author Rob Sanchez <info@robsanchez.com>
8: */
9:
10: namespace rsanchez\Deep\Model;
11:
12: use Illuminate\Database\Eloquent\Model;
13: use Illuminate\Database\Eloquent\Builder;
14: use rsanchez\Deep\Repository\MemberFieldRepository;
15: use rsanchez\Deep\Model\JoinableTrait;
16:
17: /**
18: * Model for the members table
19: */
20: class Member extends Model
21: {
22: use JoinableTrait;
23:
24: /**
25: * {@inheritdoc}
26: *
27: * @var string
28: */
29: protected $table = 'members';
30:
31: /**
32: * {@inheritdoc}
33: *
34: * @var string
35: */
36: protected $primaryKey = 'member_id';
37:
38: /**
39: * Global Member Field Repository
40: * @var \rsanchez\Deep\Repository\MemberFieldRepository
41: */
42: protected static $memberFieldRepository;
43:
44: /**
45: * Set the global MemberFieldRepository
46: * @param \rsanchez\Deep\Repository\MemberFieldRepository $memberFieldRepository
47: * @return void
48: */
49: public static function setMemberFieldRepository(MemberFieldRepository $memberFieldRepository)
50: {
51: self::$memberFieldRepository = $memberFieldRepository;
52: }
53:
54: /**
55: * Join with member_data
56: *
57: * @param \Illuminate\Database\Eloquent\Builder $query;
58: * @return \Illuminate\Database\Eloquent\Builder
59: */
60: public function scopeWithFields(Builder $query)
61: {
62: return $this->requireTable($query, 'member_data');
63: }
64:
65: /**
66: * {@inheritdoc}
67: */
68: protected static function joinTables()
69: {
70: return array(
71: 'member_data' => function ($query) {
72: $query->join('member_data', 'member_data.member_id', '=', 'member_data.member_id');
73: },
74: );
75: }
76:
77: /**
78: * Alias custom field names
79: *
80: * {@inheritdoc}
81: */
82: public function getAttribute($name)
83: {
84: if (! isset($this->attributes[$name]) && self::$memberFieldRepository->hasField($name)) {
85: $name = 'm_field_id_'.self::$memberFieldRepository->getFieldId($name);
86: }
87:
88: return parent::getAttribute($name);
89: }
90:
91: /**
92: * {@inheritdoc}
93: */
94: public function attributesToArray()
95: {
96: $array = parent::attributesToArray();
97:
98: foreach ($array as $key => $value) {
99: if (strncmp($key, 'm_field_id_', 11) === 0) {
100: $id = substr($key, 11);
101:
102: if (self::$memberFieldRepository->hasFieldId($id)) {
103: $array[self::$memberFieldRepository->getFieldName($id)] = $value;
104: }
105:
106: unset($array[$key]);
107: }
108: }
109:
110: return $array;
111: }
112:
113: /**
114: * Return the screen_name when cast to string
115: *
116: * @var string
117: */
118: public function __toString()
119: {
120: return $this->screen_name;
121: }
122: }
123: