Creates MemberInvitation

@param string $email
@param string $memberId
@return MemberInvitation
190728
protected function createMemberInvitation($email, $memberId)
    {
        $memberInvitation = new MemberInvitation();
        $memberInvitation->email = $email;
        $memberInvitation->member_id = $memberId;
        $memberInvitation->inviter_id = $this->userContext()->id;
        $memberInvitation->token = str_random(32);
        $memberInvitation->save();
        return $memberInvitation;
    }
180801
protected function buildMessage(EmailEntity $email)
    {
        // Create attachments array
        $attachments = json_decode($email->getAttachments(), true);

        $recipientEmail = $email->getRecipientEmail();

        $to = [
            [
                'email' => $this->filterThroughWhitelist($recipientEmail),
                'name'  => $email->getRecipientName(),
                'type'  => 'to'
            ]
        ];

        $message = [
            'html'                => $email->getMessage(),
            'subject'             => $email->getSubject(),
            'from_email'          => $email->getSenderEmail(),
            'from_name'           => $email->getSenderName(),
            'to'                  => $to,
            'attachments'         => $attachments,
            'headers'             => json_decode($email->getHeaders(), true),
            'important'           => false,
            'track_opens'         => true,
            'track_clicks'        => true,
            'auto_text'           => true,
            'auto_html'           => false,
            'inline_css'          => true,
            'url_strip_qs'        => null,
            'preserve_recipients' => false,
            'bcc_address'         => $email->getBcc(),
            'merge'               => true,
        ];

        return $message;
    }
1370947
public function signupNewUser(string $email = null, string $password = null): ResponseInterface
    {
        return $this->createUser(
            Request\CreateUser::new()
                ->withUnverifiedEmail($email)
                ->withClearTextPassword($password)
        );
    }
580524
public function fromEmail(Email $emailEntity)
    {
        $message = (new \Swift_Message())
            ->setSubject($emailEntity->getSubject())
            ->setTo([$emailEntity->getTargetMail()])
            ->setFrom($emailEntity->getFrom())
            ->setBody($emailEntity->getBodyHtml(), 'text/html')
            ->addPart($emailEntity->getBodyText(), 'text/plain');

        foreach ($emailEntity->getAttachments() as $name => $attachment) {
            $message->attach(AttachmentManager::buildSwift($attachment, $name));
        }

        return $message;
    }
861611
public function status(string $listId, string $email): string
    {
        $this->checkListExists($listId);
        $memberId = md5(strtolower($email));
        try {
            $member = $this->api->getMember($listId, $memberId);
        } catch (Throwable $e) {
            if ($this->api->responseCodeNotFound()) {
                return 'not found';
            }
            throw $e;
        }
        if (!$this->memberStatusIsValid($member)) {
            throw new MailchimpException('Unknown error, status value not found: ' . var_export($member, true));
        }
        return $member['status'];
    }
567979
public function toMail(Member $notifiable)
    {
        $teamName = $notifiable->team->name;
        $data = [
            'inviterName' => $this->invitation->inviter->user->name,
            'teamName' => $teamName,
            'token' => $this->invitation->token,
        ];
        return (new MailMessage)
            ->subject("Invitation to Join {$teamName}")
            ->markdown('combine::mail.member.invited', $data);
    }
733053
public function convertInviteEmails($email, $user_id)
	{
		// @FIXME: Should wrap this up in a nice transaction to handle partial failures and
		// race conditions.

		if (empty($email) || empty($user_id))
		{
			return false;
		}

		$db = \App::get('db');

		$sql = 'SELECT gidNumber FROM `#__xgroups_inviteemails` WHERE email=' . $db->quote($email) . ';';

		$db->setQuery($sql);

		$result = $db->loadColumn();

		if ($result === false)
		{
			return false;
		}

		if (empty($result))
		{
			return true;
		}

		foreach ($result as $r)
		{
			$values .= "($r,$user_id),";
			$gids   .= "$r,";
		}

		$values = rtrim($values, ',');
		$gids = rtrim($gids, ',');

		$sql = 'INSERT INTO `#__xgroups_invitees` (gidNumber,uidNumber) VALUES ' . $values . ';';

		$db->setQuery($sql);

		$result = $db->query();

		if (!$result)
		{
			return false;
		}

		$sql = 'DELETE FROM `#__xgroups_inviteemails` WHERE email=' . $db->quote($email) . ' AND gidNumber IN (' . $gids . ');';

		$db->setQuery($sql);

		$result = $db->query();

		if (!$result)
		{
			return false;
		}

		return true;
	}
668007
private function createCustomerWithUserAccount(
        $email,
        $password,
        $enabled = true,
        $firstName = null,
        $lastName = null,
        $role = null
    ) {
        /** @var ShopUserInterface $user */
        $user = $this->userFactory->createNew();

        /** @var CustomerInterface $customer */
        $customer = $this->customerFactory->createNew();

        $customer->setFirstName($firstName);
        $customer->setLastName($lastName);
        $customer->setEmail($email);

        $user->setUsername($email);
        $user->setPlainPassword($password);
        $user->setEnabled($enabled);
        if (null !== $role) {
            $user->addRole($role);
        }

        $customer->setUser($user);

        $this->sharedStorage->set('customer', $customer);

        return $customer;
    }
185392
public function property(string $memberExpression) : ColumnMappingDefiner
    {
        $this->memberParser->parse($this->class, $memberExpression);

        return new ColumnMappingDefiner(
            function (IColumn $column) use ($memberExpression) {
                $this->column($column);
                $this->propertyComponentIdMap[$memberExpression] = $column->getComponentId();
            },
            function ($componentId) use ($memberExpression) {
                $this->propertyComponentIdMap[$memberExpression] = $componentId;
            }
        );
    }
806820
public function getFkMemberElement($memberFK, $objectFK, $fkClass, $fkTable) {
		$element = "";
		$_fkClass = str_replace ( "\\", ".", $fkClass );
		if (is_array ( $objectFK ) || $objectFK instanceof \Traversable) {
			$element = $this->getFkList ( $memberFK, $objectFK );
			foreach ( $objectFK as $oItem ) {
				if (method_exists ( $oItem, "__toString" )) {
					$id = (CRUDHelper::getIdentifierFunction ( $fkClass )) ( 0, $oItem );
					$item = $element->addItem ( $oItem . "" );
					$item->setProperty ( "data-ajax", $_fkClass . "||" . $id );
					$item->addClass ( "showTable" );
					$this->displayFkElementList ( $item, $memberFK, $fkClass, $oItem );
				}
			}
		} else {
			if (method_exists ( $objectFK, "__toString" )) {
				$id = (CRUDHelper::getIdentifierFunction ( $fkClass )) ( 0, $objectFK );
				$element = $this->getFkElement ( $memberFK, $fkClass, $objectFK );
				$element->setProperty ( "data-ajax", $_fkClass . "||" . $id )->addClass ( "showTable" );
			}
		}
		return $element;
	}
314152
public function createUserAndMembership($roles = [Membership::ROLE_READ], $organization = '')
    {
        if (\is_string($roles)) {
            $roles = [$roles];
        }
        $roles = array_map(function ($role) {
            return strtolower($role);
        }, $roles);
        $contents = $this
            ->call('POST',
                implode('/', [self::ORGANIZATION_RESOURCE, $this->getOrganizationName($organization), 'memberships']),
                ['json' => [
                    'roles' => $roles,
            ]])
            ->getBody()
            ->getContents();

        return $this->getSingleMemberShipFromJsonResponse($contents);
    }
1116963
public function index($memberId)
    {
        $member = Member::findOrFail($memberId);
        $this->authorize('view', $member);
        /** @noinspection PhpUndefinedMethodInspection */
        $member->load('member_tags');
        return fractal($member->member_tags, new MemberTagTransformer())
            ->withResourceName('memberMemberTag')
            ->respond();
    }
805793
public function getUserByEmail($email, $baseDn = null, $scope = Ldap::SEARCH_SCOPE_SUB, $attributes = [])
    {
        return $this->search(
            sprintf('(&(objectClass=user)(mail=%s))', AbstractFilter::escapeValue($email)),
            $baseDn,
            $scope,
            $attributes
        );
    }
51170
public static function loadMemberFromCRMData($membershipID) {
    /** @var $client \Drupal\openy_campaign\CRMClientInterface */
    $client = \Drupal::getContainer()->get('openy_campaign.client_factory')->getClient();

    $resultsCRM = $client->getMemberInformation($membershipID);
    if (!$resultsCRM->Success) {
      \Drupal::logger('openy_campaign')
        ->error('Failed getting information from CRM for card ID @membershipID', ['@membershipID' => $membershipID]);

      return FALSE;
    }

    // Get info from CRM.
    $email = openy_campaign_clean_personify_email($resultsCRM->PrimaryEmail);
    if (!empty($resultsCRM->BirthDate)) {
      $birthdate = new \DateTime($resultsCRM->BirthDate);
      $birthdate = $birthdate->format('Y-m-d');
    }

    // Find branch from Mapping entity. It connects Branch ID from CRM and Branch node on the site.
    $branch = Mapping::getBranchByPersonifyId($resultsCRM->BranchId);

    // Transform ProductCode into MemberUnitType.
    // Trying to find type as a part of the product code among allowed field's values.
    $productCode = '';
    $productCodeFull = strtolower($resultsCRM->ProductCode);
    $allowedValues = [];
    $membershipUnitTypesSettings = [];
    foreach (\Drupal::getContainer()->get('entity.manager')->getFieldDefinitions('node', 'campaign') as $field_name => $field_definition) {
      if ($field_name == 'field_campaign_membership_u_t') {
        /** var \Drupal\Core\Field\FieldDefinitionInterface $field_definition */
        $membershipUnitTypesSettings = $field_definition->getSettings();
        $allowedValues = array_map(
          function ($v) {
            return strtolower($v);
          },
          array_keys($membershipUnitTypesSettings['allowed_values'])
        );
        break;
      }
    }

    if (!empty($membershipUnitTypesSettings)) {
      foreach ($allowedValues as $allowedValue) {
        if (strpos($productCodeFull, $allowedValue) !== FALSE) {
          $productCode = $allowedValue;
          break;
        }
      }
    }

    // Create Member entity.
    $memberValues = [
      'membership_id' => $membershipID,
      'personify_id' => $resultsCRM->MasterCustomerId,
      'mail' => $email,
      'personify_email' => $email,
      'first_name' => $resultsCRM->FirstName,
      'last_name' => $resultsCRM->LastName,
      'is_employee' => !empty($resultsCRM->ProductCode) && strpos($resultsCRM->ProductCode, 'STAFF'),
      'birth_date' => (isset($birthdate)) ? $birthdate : NULL,
      // Add these fields to CRM API.
      'branch' => !empty($branch) ? $branch : '',
      'order_number' => $resultsCRM->OrderNumber,
      'payment_type' => '',
      'member_unit_type' => $productCode,
      'is_non_y_member' => FALSE,
    ];

    // Load Member by unique Membership ID.
    $query = \Drupal::entityQuery('openy_campaign_member')
      ->condition('membership_id', $membershipID);
    $result = $query->execute();
    if (!empty($result)) {
      $memberID = reset($result);
      $member = self::load($memberID);

      // Update Member entity with values from CRM.
      foreach ($memberValues as $field => $value) {
        $member->set($field, $value);
      }

      return $member;
    }

    /** @var Member $member Otherwise create temporary Member object. Will be saved later. */
    $member = \Drupal::entityTypeManager()
      ->getStorage('openy_campaign_member')
      ->create($memberValues);

    return $member;
  }
945612
public PrimaryBackupSession createSession(long sessionId, MemberId memberId) {
    PrimaryBackupSession session = new PrimaryBackupSession(SessionId.from(sessionId), memberId, service.serializer(), this);
    if (sessions.putIfAbsent(sessionId, session) == null) {
      service.register(session);
    }
    return session;
  }
577401
public static function findMemberCampaign($membershipID, $campaignID) {
    $connection = \Drupal::service('database');
    /** @var \Drupal\Core\Database\Query\Select $query */
    $query = $connection->select('openy_campaign_member', 'm');
    $query->condition('m.membership_id', $membershipID);
    $query->join('openy_campaign_member_campaign', 'mc', 'm.id = mc.member');
    $query->condition('mc.campaign', $campaignID);
    $query->fields('mc', ['id']);
    $memberCampaignRes = $query->execute()->fetchField();

    return (!empty($memberCampaignRes)) ? $memberCampaignRes : FALSE;
  }
957542
public function createAdmin($username, $password, $email)
    {
        return $this->createAccount($username, $password, $email, [], 'ACCOUNT_ADMIN', Admin::class);
    }