本文整理匯總了PHP中Magento\Customer\Api\CustomerRepositoryInterface::getById方法的典型用法代碼示例。如果您正苦於以下問題:PHP CustomerRepositoryInterface::getById方法的具體用法?PHP CustomerRepositoryInterface::getById怎麽用?PHP CustomerRepositoryInterface::getById使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類Magento\Customer\Api\CustomerRepositoryInterface
的用法示例。
在下文中一共展示了CustomerRepositoryInterface::getById方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的PHP代碼示例。
示例1: testEmulateWelcomeBlock
/**
* @magentoConfigFixture current_store persistent/options/enabled 1
* @magentoConfigFixture current_store persistent/options/remember_enabled 1
* @magentoConfigFixture current_store persistent/options/remember_default 1
* @magentoAppArea frontend
* @magentoAppIsolation enabled
*/
public function testEmulateWelcomeBlock()
{
$this->_customerSession->loginById(1);
$httpContext = new \Magento\Framework\App\Http\Context();
$httpContext->setValue(Context::CONTEXT_AUTH, 1, 1);
$block = $this->_objectManager->create('Magento\\Sales\\Block\\Reorder\\Sidebar', ['httpContext' => $httpContext]);
$this->_observer->emulateWelcomeBlock($block);
$customerName = $this->_escaper->escapeHtml($this->_customerViewHelper->getCustomerName($this->customerRepository->getById($this->_persistentSessionHelper->getSession()->getCustomerId())));
$translation = __('Welcome, %1!', $customerName);
$this->assertStringMatchesFormat('%A' . $translation . '%A', $block->getWelcome());
$this->_customerSession->logout();
}
示例2: execute
/**
* Set persistent data to customer session
*
* @param \Magento\Framework\Event\Observer $observer
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
*
* @return $this
*/
public function execute(\Magento\Framework\Event\Observer $observer)
{
if (!$this->_persistentData->canProcess($observer) || !$this->_persistentData->isShoppingCartPersist()) {
return $this;
}
if ($this->_persistentSession->isPersistent() && !$this->_customerSession->isLoggedIn()) {
/** @var \Magento\Customer\Api\Data\CustomerInterface $customer */
$customer = $this->customerRepository->getById($this->_persistentSession->getSession()->getCustomerId());
if ($defaultShipping = $customer->getDefaultShipping()) {
/** @var \Magento\Customer\Model\Data\Address $address */
$address = $this->addressRepository->getById($defaultShipping);
if ($address) {
$this->_customerSession->setDefaultTaxShippingAddress(['country_id' => $address->getCountryId(), 'region_id' => $address->getRegion() ? $address->getRegionId() : null, 'postcode' => $address->getPostcode()]);
}
}
if ($defaultBilling = $customer->getDefaultBilling()) {
$address = $this->addressRepository->getById($defaultBilling);
if ($address) {
$this->_customerSession->setDefaultTaxBillingAddress(['country_id' => $address->getCountryId(), 'region_id' => $address->getRegion() ? $address->getRegionId() : null, 'postcode' => $address->getPostcode()]);
}
}
$this->_customerSession->setCustomerId($customer->getId())->setCustomerGroupId($customer->getGroupId());
}
return $this;
}
示例3: execute
/**
* Confirm customer account by id and confirmation key
*
* @return \Magento\Framework\Controller\Result\Redirect
*/
public function execute()
{
/** @var \Magento\Framework\Controller\Result\Redirect $resultRedirect */
$resultRedirect = $this->resultRedirectFactory->create();
if ($this->_getSession()->isLoggedIn()) {
$resultRedirect->setPath('*/*/');
return $resultRedirect;
}
try {
$customerId = $this->getRequest()->getParam('id', false);
$key = $this->getRequest()->getParam('key', false);
if (empty($customerId) || empty($key)) {
throw new \Exception(__('Bad request.'));
}
// log in and send greeting email
$customerEmail = $this->customerRepository->getById($customerId)->getEmail();
$customer = $this->customerAccountManagement->activate($customerEmail, $key);
$this->_getSession()->setCustomerDataAsLoggedIn($customer);
$this->messageManager->addSuccess($this->getSuccessMessage());
$resultRedirect->setUrl($this->getSuccessRedirect());
return $resultRedirect;
} catch (StateException $e) {
$this->messageManager->addException($e, __('This confirmation key is invalid or has expired.'));
} catch (\Exception $e) {
$this->messageManager->addException($e, __('There was an error confirming the account'));
}
// die unhappy
$url = $this->urlModel->getUrl('*/*/index', ['_secure' => true]);
$resultRedirect->setUrl($this->_redirect->error($url));
return $resultRedirect;
}
示例4: executeInternal
/**
* Save newsletter subscription preference action
*
* @return void|null
*/
public function executeInternal()
{
if (!$this->formKeyValidator->validate($this->getRequest())) {
return $this->_redirect('customer/account/');
}
$customerId = $this->_customerSession->getCustomerId();
if ($customerId === null) {
$this->messageManager->addError(__('Something went wrong while saving your subscription.'));
} else {
try {
$customer = $this->customerRepository->getById($customerId);
$storeId = $this->storeManager->getStore()->getId();
$customer->setStoreId($storeId);
$this->customerRepository->save($customer);
if ((bool) $this->getRequest()->getParam('is_subscribed', false)) {
$this->subscriberFactory->create()->subscribeCustomerById($customerId);
$this->messageManager->addSuccess(__('We saved the subscription.'));
} else {
$this->subscriberFactory->create()->unsubscribeCustomerById($customerId);
$this->messageManager->addSuccess(__('We removed the subscription.'));
}
} catch (\Exception $e) {
$this->messageManager->addError(__('Something went wrong while saving your subscription.'));
}
}
$this->_redirect('customer/account/');
}
示例5: capture
/**
* @param InfoInterface $payment
* @param float $amount
* @return $this
* @throws LocalizedException
*/
public function capture(InfoInterface $payment, $amount)
{
parent::capture($payment, $amount);
$customerId = $payment->getOrder()->getCustomerId();
$customer = $this->customerRepository->getById($customerId);
$openpayCustomerId = $customer->getCustomAttribute('openpay_customer_id')->getValue();
$cardId = $payment->getAdditionalInformation('customer_card_id');
$deviceSessionId = $payment->getAdditionalInformation('device_session_id');
$order = $payment->getOrder();
$currency = $order->getOrderCurrencyCode();
$useOrderId = $this->getConfigData('useOrderId');
$paymentLeyend = $this->getConfigData('paymentLeyend');
$orderId = $order->getIncrementId();
$params = ['source_id' => $cardId, 'method' => self::OPENPAY_PAYMENT_METHOD_CARD, 'amount' => $amount, 'currency' => $currency, 'description' => __($paymentLeyend)->getText(), 'order_id' => $useOrderId ? $orderId : null, 'device_session_id' => $deviceSessionId];
try {
$transaction = $this->chargeAdapter->chargeCustomerCard($openpayCustomerId, $params);
$payment->setTransactionId($transaction->getId())->setIsTransactionClosed(0);
$this->openpayCustomerRepository->clearCustomerCache($openpayCustomerId);
} catch (OpenpayException $e) {
$this->debugData(['request' => $params, 'exception' => $e->getMessage()]);
$this->_logger->error(__('Payment capturing error.'));
throw new LocalizedException(new Phrase('[' . $e->getErrorCode() . ']' . $e->getMessage()));
}
return $this;
}
示例6: execute
/**
* Reset forgotten password
*
* Used to handle data received from reset forgotten password form
*
* @return \Magento\Framework\Controller\Result\Redirect
*/
public function execute()
{
/** @var \Magento\Framework\Controller\Result\Redirect $resultRedirect */
$resultRedirect = $this->resultRedirectFactory->create();
$resetPasswordToken = (string) $this->getRequest()->getQuery('token');
$customerId = (int) $this->getRequest()->getQuery('id');
$password = (string) $this->getRequest()->getPost('password');
$passwordConfirmation = (string) $this->getRequest()->getPost('password_confirmation');
if ($password !== $passwordConfirmation) {
$this->messageManager->addError(__("New Password and Confirm New Password values didn't match."));
$resultRedirect->setPath('*/*/createPassword', ['id' => $customerId, 'token' => $resetPasswordToken]);
return $resultRedirect;
}
if (iconv_strlen($password) <= 0) {
$this->messageManager->addError(__('New password field cannot be empty.'));
$resultRedirect->setPath('*/*/createPassword', ['id' => $customerId, 'token' => $resetPasswordToken]);
return $resultRedirect;
}
try {
$customerEmail = $this->customerRepository->getById($customerId)->getEmail();
$this->accountManagement->resetPassword($customerEmail, $resetPasswordToken, $password);
$this->messageManager->addSuccess(__('Your password has been updated.'));
$resultRedirect->setPath('*/*/login');
return $resultRedirect;
} catch (\Exception $exception) {
$this->messageManager->addError(__('There was an error saving the new password.'));
$resultRedirect->setPath('*/*/createPassword', ['id' => $customerId, 'token' => $resetPasswordToken]);
return $resultRedirect;
}
}
示例7: validate
/**
* Validates the fields in a specified address data object.
*
* @param \Magento\Quote\Api\Data\AddressInterface $addressData The address data object.
* @return bool
* @throws \Magento\Framework\Exception\InputException The specified address belongs to another customer.
* @throws \Magento\Framework\Exception\NoSuchEntityException The specified customer ID or address ID is not valid.
*/
public function validate(\Magento\Quote\Api\Data\AddressInterface $addressData)
{
//validate customer id
if ($addressData->getCustomerId()) {
$customer = $this->customerRepository->getById($addressData->getCustomerId());
if (!$customer->getId()) {
throw new \Magento\Framework\Exception\NoSuchEntityException(__('Invalid customer id %1', $addressData->getCustomerId()));
}
}
if ($addressData->getCustomerAddressId()) {
try {
$this->addressRepository->getById($addressData->getCustomerAddressId());
} catch (NoSuchEntityException $e) {
throw new \Magento\Framework\Exception\NoSuchEntityException(__('Invalid address id %1', $addressData->getId()));
}
$applicableAddressIds = array_map(function ($address) {
/** @var \Magento\Customer\Api\Data\AddressInterface $address */
return $address->getId();
}, $this->customerRepository->getById($addressData->getCustomerId())->getAddresses());
if (!in_array($addressData->getCustomerAddressId(), $applicableAddressIds)) {
throw new \Magento\Framework\Exception\NoSuchEntityException(__('Invalid address id %1', $addressData->getCustomerAddressId()));
}
}
return true;
}
示例8: getWishlistCustomer
/**
* Retrieve Shared Wishlist Customer instance
*
* @return \Magento\Customer\Api\Data\CustomerInterface
*/
public function getWishlistCustomer()
{
if ($this->_customer === null) {
$this->_customer = $this->customerRepository->getById($this->_getWishlist()->getCustomerId());
}
return $this->_customer;
}
示例9: testGetCustomerAttributeMetadata
/**
* @magentoDataFixture Magento/Customer/_files/customer.php
*/
public function testGetCustomerAttributeMetadata()
{
// Expect these attributes to exist but do not check the value
$expectAttrsWOutVals = ['created_at', 'updated_at'];
// Expect these attributes to exist and check the value - values come from _files/customer.php
$expectAttrsWithVals = ['id' => 1, 'website_id' => 1, 'store_id' => 1, 'group_id' => 1, 'prefix' => 'Mr.', 'firstname' => 'John', 'middlename' => 'A', 'lastname' => 'Smith', 'suffix' => 'Esq.', 'email' => 'customer@example.com', 'default_billing' => '1', 'default_shipping' => '1', 'disable_auto_group_change' => 0, 'taxvat' => '12', 'gender' => 0];
$customer = $this->customerRepository->getById(1);
$this->assertNotNull($customer);
$attributes = $this->_extensibleDataObjectConverter->toFlatArray($customer, [], '\\Magento\\Customer\\Api\\Data\\CustomerInterface');
$this->assertNotEmpty($attributes);
foreach ($attributes as $attributeCode => $attributeValue) {
$this->assertNotNull($attributeCode);
$this->assertNotNull($attributeValue);
$attributeMetadata = $this->_service->getAttributeMetadata($attributeCode);
$attrMetadataCode = $attributeMetadata->getAttributeCode();
$this->assertSame($attributeCode, $attrMetadataCode);
if (($key = array_search($attrMetadataCode, $expectAttrsWOutVals)) !== false) {
unset($expectAttrsWOutVals[$key]);
} else {
$this->assertArrayHasKey($attrMetadataCode, $expectAttrsWithVals);
$this->assertSame($expectAttrsWithVals[$attrMetadataCode], $attributeValue, "Failed for {$attrMetadataCode}");
unset($expectAttrsWithVals[$attrMetadataCode]);
}
}
$this->assertEmpty($expectAttrsWOutVals);
$this->assertEmpty($expectAttrsWithVals);
}
示例10: emulateWelcomeBlock
/**
* Emulate 'welcome' block with persistent data
*
* @param \Magento\Framework\View\Element\AbstractBlock $block
* @return $this
*/
public function emulateWelcomeBlock($block)
{
$escapedName = $this->_escaper->escapeHtml($this->_customerViewHelper->getCustomerName($this->customerRepository->getById($this->_persistentSession->getSession()->getCustomerId())), null);
$this->_applyAccountLinksPersistentData();
$welcomeMessage = __('Welcome, %1!', $escapedName) . ' ' . $this->_layout->getBlock('header.additional')->toHtml();
$block->setWelcome($welcomeMessage);
return $this;
}
示例11: execute
/**
* Unlock customer on success login attempt.
* @param \Magento\Framework\Event\Observer $observer
* @return $this
*/
public function execute(\Magento\Framework\Event\Observer $observer)
{
/** @var \Magento\Customer\Model\Customer $model */
$customerModel = $observer->getEvent()->getData('model');
$customer = $this->customerRepository->getById($customerModel->getId());
$this->accountManagementHelper->processUnlockData($customer->getId());
$this->customerRepository->save($customer);
return $this;
}
示例12: getCustomerName
/**
* Return the full name of the customer currently logged in
*
* @return string|null
*/
public function getCustomerName()
{
try {
$customer = $this->customerRepository->getById($this->currentCustomer->getCustomerId());
return $this->escapeHtml($this->_viewHelper->getCustomerName($customer));
} catch (\Magento\Framework\Exception\NoSuchEntityException $e) {
return null;
}
}
示例13: execute
/**
* Change customer password action
*
* @return \Magento\Framework\Controller\Result\Redirect
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
*/
public function execute()
{
/** @var \Magento\Framework\Controller\Result\Redirect $resultRedirect */
$resultRedirect = $this->resultRedirectFactory->create();
if (!$this->formKeyValidator->validate($this->getRequest())) {
$resultRedirect->setPath('*/*/edit');
return $resultRedirect;
}
if ($this->getRequest()->isPost()) {
$customerId = $this->_getSession()->getCustomerId();
$customer = $this->customerExtractor->extract('customer_account_edit', $this->_request);
$customer->setId($customerId);
if ($customer->getAddresses() == null) {
$customer->setAddresses($this->customerRepository->getById($customerId)->getAddresses());
}
if ($this->getRequest()->getParam('change_password')) {
$currPass = $this->getRequest()->getPost('current_password');
$newPass = $this->getRequest()->getPost('password');
$confPass = $this->getRequest()->getPost('password_confirmation');
if (strlen($newPass)) {
if ($newPass == $confPass) {
try {
$customerEmail = $this->customerRepository->getById($customerId)->getEmail();
$this->customerAccountManagement->changePassword($customerEmail, $currPass, $newPass);
} catch (AuthenticationException $e) {
$this->messageManager->addError($e->getMessage());
} catch (\Exception $e) {
$this->messageManager->addException($e, __('Something went wrong while changing the password.'));
}
} else {
$this->messageManager->addError(__('Confirm your new password.'));
}
} else {
$this->messageManager->addError(__('Please enter new password.'));
}
}
try {
$this->customerRepository->save($customer);
} catch (AuthenticationException $e) {
$this->messageManager->addError($e->getMessage());
} catch (InputException $e) {
$this->messageManager->addException($e, __('Invalid input'));
} catch (\Exception $e) {
$this->messageManager->addException($e, __('We can\'t save the customer.') . $e->getMessage() . '<pre>' . $e->getTraceAsString() . '</pre>');
}
if ($this->messageManager->getMessages()->getCount() > 0) {
$this->_getSession()->setCustomerFormData($this->getRequest()->getPostValue());
$resultRedirect->setPath('*/*/edit');
return $resultRedirect;
}
$this->messageManager->addSuccess(__('You saved the account information.'));
$resultRedirect->setPath('customer/account');
return $resultRedirect;
}
$resultRedirect->setPath('*/*/edit');
return $resultRedirect;
}
示例14: loadSource
/**
* @return \Magento\Customer\Api\Data\CustomerInterface
*/
protected function loadSource()
{
if ($this->isBackendOrder()) {
// For backend orders
$customerId = $this->objectManager->get('Magento\\Backend\\Model\\Session\\Quote')->getQuote()->getCustomerId();
} else {
$customerId = $this->objectManager->get('Magento\\Customer\\Model\\Session')->getCustomerId();
}
return $this->customerRepository->getById($customerId);
}
示例15: beforeDispatch
/**
* @param AbstractAction $subject
* @param RequestInterface $request
* @return void
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function beforeDispatch(AbstractAction $subject, RequestInterface $request)
{
if ($this->state->getAreaCode() == Area::AREA_FRONTEND && $request->isPost() && $this->notificationStorage->isExists(NotificationStorage::UPDATE_CUSTOMER_SESSION, $this->session->getCustomerId())) {
$customer = $this->customerRepository->getById($this->session->getCustomerId());
$this->session->setCustomerData($customer);
$this->session->setCustomerGroupId($customer->getGroupId());
$this->session->regenerateId();
$this->notificationStorage->remove(NotificationStorage::UPDATE_CUSTOMER_SESSION, $customer->getId());
}
}