Skip to content

Instantly share code, notes, and snippets.

@dannewns
Created December 1, 2014 10:33

Revisions

  1. dannewns created this gist Dec 1, 2014.
    78 changes: 78 additions & 0 deletions gistfile1.php
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,78 @@
    /**
    * Mutators
    */
    public function setEmailAttribute($value)
    {
    $value = \Import::splitMultipleFieldsData($value);

    $this->setEmailAddressesAttribute($value);
    }

    public function setEmailAddressesAttribute(array $array)
    {
    // Need to save the student to ensure it has an ID to relate to
    $this->save();

    // Collect E-Mail Addresses, so we can remove any that aren't here.
    $emailAddresses = array();

    // Order E-Mail Addresses
    $order = 1;

    foreach ($array as $emailAddress) {
    if ( ! is_array($emailAddress)) {
    // To match the data from the Student Create/Edit form
    $emailAddress = array(
    'email' => $emailAddress
    );
    }

    $emailAddress['email'] = trim($emailAddress['email']);

    if ( ! strlen($emailAddress['email'])) {
    // E-Mail Address is empty, but that is ok because empty fields will be ignored.
    continue;
    }

    if (filter_var($emailAddress['email'], FILTER_VALIDATE_EMAIL) === false) {
    throw new \Exception(sprintf('"%s" does not appear to be a valid e-mail address.', $emailAddress['email']));
    }

    $emailAddress['email'] = strtolower($emailAddress['email']);

    // Used after the loop to remove any e-mail addresses that aren't here afterwards.
    $emailAddresses[] = $emailAddress['email'];

    // Check if Student already has this e-mail address
    $studentEmailAddress = StudentEmailAddress::where('student_id', $this->id)
    ->where('email', $emailAddress['email'])
    ->first();

    if (is_null($studentEmailAddress)) {
    $studentEmailAddress = new StudentEmailAddress();
    $studentEmailAddress->student_id = $this->id;
    $studentEmailAddress->email = $emailAddress['email'];
    }

    if (isset($emailAddress['unsubscribed'])) {
    $studentEmailAddress->unsubscribed = (bool) $emailAddress['unsubscribed'];
    } else {
    $studentEmailAddress->unsubscribed = false;
    }

    $studentEmailAddress->order = $order++;
    $studentEmailAddress->save();
    }

    if (count($emailAddresses)) {
    // Remove E-Mail addresses that aren't in the input.
    StudentEmailAddress::where('student_id', $this->id)
    ->whereNotIn('email', $emailAddresses)
    ->delete();
    } else {
    // No E-Mail Addreses were found in the input.
    // Remove All E-Mail Addresses for Student.
    StudentEmailAddress::where('student_id', $this->id)
    ->delete();
    }
    }