Block.php
1 month ago
BlockFinder.php
1 year ago
DynamicData.php
3 weeks ago
HasOneRelationship.php
1 year ago
Integration.php
1 year ago
Utility.php
3 weeks ago
HasOneRelationship.php
76 lines
| 1 | <?php |
| 2 | |
| 3 | namespace PrestoPlayer\Support; |
| 4 | |
| 5 | class HasOneRelationship { |
| 6 | |
| 7 | protected $classname, $parent_model, $parent_field; |
| 8 | |
| 9 | /** |
| 10 | * Construct |
| 11 | * |
| 12 | * @param string $classname |
| 13 | * @param \PrestoPlayer\Models\Model $parent_model |
| 14 | */ |
| 15 | public function __construct( $classname, $parent_model, $parent_field ) { |
| 16 | $this->classname = $classname; |
| 17 | $this->parent_model = $parent_model; |
| 18 | $this->parent_field = $parent_field; |
| 19 | } |
| 20 | |
| 21 | public function getRelationshipClass() { |
| 22 | return $this->classname; |
| 23 | } |
| 24 | |
| 25 | public function getParentField() { |
| 26 | return $this->parent_field; |
| 27 | } |
| 28 | |
| 29 | public function getRelationshipTable() { |
| 30 | return ( new $this->classname() )->getTableName(); |
| 31 | } |
| 32 | |
| 33 | /** |
| 34 | * Save the model with the relationship |
| 35 | * |
| 36 | * @param array $arguments |
| 37 | * @return \PrestoPlayer\Models\Model |
| 38 | */ |
| 39 | public function save( $arguments ) { |
| 40 | // create the item and save as |
| 41 | $saved_id = ( new $this->classname() )->create( $arguments ); |
| 42 | |
| 43 | // update or create parent model |
| 44 | if ( $this->parent_model->id ) { |
| 45 | return $this->parent_model->update( |
| 46 | array( |
| 47 | $this->parent_field => (int) $saved_id, |
| 48 | ) |
| 49 | ); |
| 50 | } |
| 51 | |
| 52 | return new \WP_Error( 'unsaved', 'Please save the model before adding the relationship.' ); |
| 53 | } |
| 54 | |
| 55 | public function update( $arguments ) { |
| 56 | if ( ! $this->parent_field ) { |
| 57 | return new \WP_Error( 'unsaved', 'Please create the relationship before updating it.' ); |
| 58 | } |
| 59 | |
| 60 | $item_class = ( new $this->classname() ); |
| 61 | $item = $this->parent_model->{$this->parent_field}; |
| 62 | |
| 63 | if ( is_int( $item ) ) { |
| 64 | $item = $item_class->get( $item ); |
| 65 | } elseif ( is_object( $item ) ) { |
| 66 | $item = $item_class->set( $item ); |
| 67 | } |
| 68 | |
| 69 | if ( empty( $item ) ) { |
| 70 | return new \WP_Error( 'unsaved', 'Please create the relationship before updating it.' ); |
| 71 | } |
| 72 | |
| 73 | return $item->update( $arguments ); |
| 74 | } |
| 75 | } |
| 76 |