Connect Subscriptions
@param  string               $customerUUID
@param  array                $data
@param  ClientInterface|null $client
@return bool
183427
public static function connectSubscriptions($customerUUID, array $data = [], ClientInterface $client = null)
    {
        (new static([], $client))
            ->getClient()
            ->setResourcekey(static::class)
            ->send('/v1/customers/'.$customerUUID.'/connect_subscriptions', 'POST', $data);
        return true;
    }
874373
public function subscribe( $channels, Closure $callback, $connection = null, $method = 'subscribe' )
	{
		$loop = $this->connection( $connection )->pubSubLoop();

		call_user_func_array( [$loop, $method], (array) $channels );

		foreach ( $loop as $message )
		{
			if ( $message->kind === 'message' || $message->kind === 'pmessage' )
			{
				call_user_func( $callback, $message->payload, $message->channel );
			}
		}

		unset( $loop );
	}
763052
public function create($data, $subscriptionId = null)
    {
        if (isset($subscriptionId)) {
            return $this->client()->put($data, 'subscriptions/{subscriptionId}', ['subscriptionId' => $subscriptionId]);
        }

        return $this->client()->post($data, 'subscriptions');
    }
1031233
protected function notifyClients(array $identifiers, array $data)
    {
        foreach ($identifiers as $identifier) {
            $client_name = strpos($identifier, ':') !== false
                ? substr($identifier, 0, strpos($identifier, ':'))
                : $identifier
                ;

            $client = $this
                ->getSession()
                ->getClient($this->getPoolerType(), $client_name)
                ;

            if ($client !== null) {
                $client->notify($identifier, $data);
            }
        }

        return $this;
    }
1312293
protected function createAuthCodeClient(ClientRepository $clients)
    {
        $userId = $this->ask(
            'Which user ID should the client be assigned to?'
        );

        $name = $this->option('name') ?: $this->ask(
            'What should we name the client?'
        );

        $redirect = $this->ask(
            'Where should we redirect the request after authorization?',
            url('/auth/callback')
        );

        $client = $clients->create(
            $userId, $name, $redirect
        );

        $this->info('New client created successfully.');
        $this->line('<comment>Client ID:</comment> '.$client->_id);
        $this->line('<comment>Client secret:</comment> '.$client->secret);
    }
979965
public function get(int $id, CustomerRequest $customerRequest = null): Customer
    {
        $customerResource = $this->restClient->getResource(
            Customer::class,
            sprintf('/v2/customers/%d', $id)
        );

        return $this->hydrateCustomerWithSubEntities(
            $customerResource,
            $customerRequest ?: new CustomerRequest()
        );
    }
883739
public function reactivate($customerId, $subscriptionId, array $attributes = [])
    {
        if (! isset($attributes['plan'])) {
            $subscription = $this->find($customerId, $subscriptionId);

            $attributes['plan'] = $subscription['plan']['id'];
        }

        return $this->update($customerId, $subscriptionId, $attributes);
    }
735437
protected function createPersonalClient(ClientRepository $clients)
    {
        $name = $this->option('name') ?: $this->ask(
            'What should we name the personal access client?',
            config('app.name').' Personal Access Client'
        );

        $client = $clients->createPersonalAccessClient(
            null, $name, 'http://localhost'
        );

        $this->info('Personal access client created successfully.');

        $this->outputClientDetails($client);
    }
1049906
public function create(ClientInterface $client): ClientInterface
    {
        try {
            $now    = $this->ignoreException(function (): DateTimeImmutable {
                return new DateTimeImmutable();
            });
            $schema = $this->getDatabaseSchema();
            $values = [
                $schema->getClientsIdentityColumn()               => $client->getIdentifier(),
                $schema->getClientsNameColumn()                   => $client->getName(),
                $schema->getClientsDescriptionColumn()            => $client->getDescription(),
                $schema->getClientsCredentialsColumn()            => $client->getCredentials(),
                $schema->getClientsIsConfidentialColumn()         => $client->isConfidential(),
                $schema->getClientsIsScopeExcessAllowedColumn()   => $client->isScopeExcessAllowed(),
                $schema->getClientsIsUseDefaultScopeColumn()      => $client->isUseDefaultScopesOnEmptyRequest(),
                $schema->getClientsIsCodeGrantEnabledColumn()     => $client->isCodeGrantEnabled(),
                $schema->getClientsIsImplicitGrantEnabledColumn() => $client->isImplicitGrantEnabled(),
                $schema->getClientsIsPasswordGrantEnabledColumn() => $client->isPasswordGrantEnabled(),
                $schema->getClientsIsClientGrantEnabledColumn()   => $client->isClientGrantEnabled(),
                $schema->getClientsIsRefreshGrantEnabledColumn()  => $client->isRefreshGrantEnabled(),
                $schema->getClientsCreatedAtColumn()              => $now,
            ];

            $identifier = $client->getIdentifier();
            if (empty($scopeIdentifiers = $client->getScopeIdentifiers()) === true) {
                $this->createResource($values);
            } else {
                $this->inTransaction(function () use ($identifier, $values, $scopeIdentifiers) {
                    $this->createResource($values);
                    $this->bindScopeIdentifiers($identifier, $scopeIdentifiers);
                });
            }
            $client->setCreatedAt($now);

            return $client;
        } catch (RepositoryException $exception) {
            $message = 'Client creation failed.';
            throw new RepositoryException($message, 0, $exception);
        }
    }
367788
public function customer($customerFid = null, $visitorId = null)
  {
    if($visitorId === null)
    {
      $visitorId = $this->getVisitorIdCookie();
    }

    return Customer::newInstance($this)
      ->setVisitorId($visitorId)
      ->setCustomerFid($customerFid);
  }
251637
public function joinClub($id)
    {
        try {
            return $this->service->joinClub($id);
        } catch (ServiceException $e) {
            throw new ClientException('[SERVICE] ' . $e->getMessage());
        }
    }
563435
public function updateFromEmbeddedApiResponse(array $data): CustomerInterface
    {
        // we cast to int because for some reason Dandomain can (sometimes) have customers where the id is not set
        // and instead of setting the id to 0, Dandomain sets it to ''
        $id = (int) $data['id'];

        $customer = $this->customerRepository->findOneByExternalId($id);
        if (!$customer) {
            $customer = new Customer();
            $customer->setExternalId($id);
        }

        $customer
            ->setAddress($data['address'])
            ->setAddress2($data['address2'])
            ->setAttention($data['attention'])
            ->setCity($data['city'])
            ->setCountry($data['country'])
            ->setCountryId($data['countryId'])
            ->setEan($data['ean'])
            ->setEmail($data['email'])
            ->setFax($data['fax'])
            ->setName($data['name'])
            ->setPhone($data['phone'])
            ->setState($data['state'])
            ->setZipCode($data['zipCode'])
        ;

        return $customer;
    }
506857
public function create($data, $userId = null)
    {
        if (isset($userId)) {
            return $this->client()->put($data, 'users/{userId}', ['userId' => $userId]);
        }

        return $this->client()->post($data, 'users');
    }
704189
private function handlePublishEntity(ConnectionInterface $from, $data) {
    $this->logger->notice(
        "Received an entity publish! ".
          "({$data['guid']}, {$data['event']}, {$from->resourceId})"
    );

    $etype = $data['etype'];

    if (!key_exists($etype, $this->querySubs)) {
      return;
    }

    foreach ($this->querySubs[$etype] as $curQuery => $curClients) {
      $updatedClients = new \SplObjectStorage();

      if ($data['event'] === 'delete' || $data['event'] === 'update') {
        // Check if it is in any client's currents.
        foreach ($curClients as $curClient) {
          $curData = $curClients[$curClient];
          if (in_array($data['guid'], $curData['current'])) {
            // Update currents list.
            $queryArgs = unserialize($curQuery);
            $this->prepareSelectors($queryArgs);
            $queryArgs[0]['source'] = 'client';
            $queryArgs[] = ['&', 'guid' => $data['guid']];
            $token = null;
            if ($this->sessions->contains($curClient)) {
              $token = $this->sessions[$curClient];
            }
            if (class_exists('\Tilmeld\Tilmeld') && isset($token)) {
              $user = \Tilmeld\Tilmeld::extractToken($token);
              if ($user) {
                // Log in the user for access controls.
                \Tilmeld\Tilmeld::fillSession($user);
              }
            }
            $current = call_user_func_array(
                "\Nymph\Nymph::getEntity",
                $queryArgs
            );

            if (isset($current)) {
              // Notify subscriber.
              $this->logger->notice(
                  "Notifying client of update! ".
                    "({$curClient->resourceId})"
              );
              if (is_callable([$current, 'updateDataProtection'])) {
                $current->updateDataProtection();
              }
              $curClient->send(json_encode([
                'query' => $curData['query'],
                'updated' => $data['guid'],
                'data' => $current
              ]));
            } else {
              $curData['current'] = array_diff(
                  $curData['current'],
                  [$data['guid']]
              );
              $curClients[$curClient] = $curData;

              // Notify subscriber.
              $this->logger->notice(
                  "Notifying client of removal! ".
                    "({$curClient->resourceId})"
              );
              $curClient->send(json_encode([
                'query' => $curData['query'],
                'removed' => $data['guid']
              ]));
            }

            if (class_exists('\Tilmeld\Tilmeld') && isset($token)) {
              // Clear the user that was temporarily logged in.
              \Tilmeld\Tilmeld::clearSession();
            }

            $updatedClients->attach($curClient);
          }
        }
      }

      if ($data['event'] === 'create' || $data['event'] === 'update') {
        // Check if it matches the query.
        $selectors = unserialize($curQuery);
        $this->prepareSelectors($selectors);
        $options = $selectors[0];
        unset($selectors[0]);
        $entityData = $data['entity']['data'];
        $entityData['cdate'] = $data['entity']['cdate'];
        $entityData['mdate'] = $data['entity']['mdate'];
        $entitySData = [];

        if (class_exists($options['class'])
            && class_exists($data['entity']['class'])
            && $options['class']::ETYPE === $data['entity']['class']::ETYPE
            && \Nymph\Nymph::checkData(
                $entityData,
                $entitySData,
                $selectors,
                $data['guid'],
                $data['entity']['tags']
            )
          ) {
          // It does match the query.
          foreach ($curClients as $curClient) {
            if ($updatedClients->contains($curClient)) {
              // The user was already notified. (Of an update.)
              continue;
            }

            // Check that the user can access the entity.
            $queryArgs = unserialize($curQuery);
            $this->prepareSelectors($queryArgs);
            $queryArgs[0]['source'] = 'client';
            $queryArgs[] = ['&', 'guid' => $data['guid']];
            $token = null;
            if ($this->sessions->contains($curClient)) {
              $token = $this->sessions[$curClient];
            }
            if (class_exists('\Tilmeld\Tilmeld') && isset($token)) {
              $user = \Tilmeld\Tilmeld::extractToken($token);
              if ($user) {
                // Log in the user for access controls.
                \Tilmeld\Tilmeld::fillSession($user);
              }
            }
            $current = call_user_func_array(
                "\Nymph\Nymph::getEntity",
                $queryArgs
            );

            if (isset($current)) {
              // Update the currents list.
              $curData = $curClients[$curClient];
              $curData['current'][] = $data['guid'];
              $curClients[$curClient] = $curData;

              // Notify client.
              $this->logger->notice(
                  "Notifying client of new match! ".
                    "({$curClient->resourceId})"
              );
              if (is_callable([$current, 'updateDataProtection'])) {
                $current->updateDataProtection();
              }
              $curClient->send(json_encode([
                'query' => $curData['query'],
                'added' => $data['guid'],
                'data' => $current
              ]));
            }

            if (class_exists('\Tilmeld\Tilmeld') && isset($token)) {
              // Clear the user that was temporarily logged in.
              \Tilmeld\Tilmeld::clearSession();
            }
          }
        }
      }
    }
  }
917259
public function sendInvite($customerId, CustomerInvite $invite = null)
    {
        $data = is_null($invite) ? array() : $invite->exportData();
        $endpoint = '/admin/customers/'.$customerId.'/send_invite.json';
        $response = $this->request(
            $endpoint, 'POST', array(
            'custom_invite' => $data
            )
        );
        return $response['customer_invite'];
    }
492561
public function add($userId, array $data=null, $getOrCreate=null)
    {
        $endpoint = 'user/';
        $payload = [
            'id' => $userId,
        ];
        if( $data !== null ){
            $payload['data'] = $data;
        }
        if($getOrCreate){
            $endpoint .= '?get_or_create=true';
        }
        $response = $this->doRequest('POST', $endpoint, $payload);
        $body = $response->getBody()->getContents();
        return json_decode($body, true);
    }
968176
public function authenticate(ClientInterface $client) {
    $account = Account::find()->byClient($client)->one();

    if (!$this->module->enableRegistration && ($account === null || $account->user === null)) {
      Yii::$app->session->setFlash('danger', Yii::t('users', 'Registration on this website is disabled'));
      $this->action->successUrl = Url::to(['/users/security/login']);
      return;
    }

    if ($account === null) {
      /** @var Account $account */
      $accountObj = Yii::createObject(Account::className());
      $account = $accountObj::create($client);
    }

    $event = $this->getAuthEvent($account, $client);

    $this->trigger(self::EVENT_BEFORE_AUTHENTICATE, $event);

    if ($account->user instanceof User) {
      if ($account->user->isBlocked) {
        Yii::$app->session->setFlash('danger', Yii::t('users', 'Your account has been blocked.'));
        $this->action->successUrl = Url::to(['/users/security/login']);
      } else {
        Yii::$app->user->login($account->user, $this->module->rememberFor);
        $this->action->successUrl = Yii::$app->getUser()->getReturnUrl();
      }
    } else {
      $this->action->successUrl = $account->getConnectUrl();
    }

    $this->trigger(self::EVENT_AFTER_AUTHENTICATE, $event);
  }