本文整理汇总了PHP中Magento\Customer\Api\CustomerRepositoryInterface类的典型用法代码示例。如果您正苦于以下问题:PHP CustomerRepositoryInterface类的具体用法?PHP CustomerRepositoryInterface怎么用?PHP CustomerRepositoryInterface使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了CustomerRepositoryInterface类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: 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;
}
示例2: testExecute
/**
* @return void
*/
public function testExecute()
{
$formId = 'user_login';
$login = 'login';
$loginParams = ['username' => $login];
$customerId = 7;
$redirectUrl = 'http://magento.com/customer/account/login/';
$captchaValue = 'some-value';
$captcha = $this->getMock('Magento\\Captcha\\Model\\DefaultModel', [], [], '', false);
$captcha->expects($this->once())->method('isRequired')->with($login)->willReturn(true);
$captcha->expects($this->once())->method('isCorrect')->with($captchaValue)->willReturn(false);
$captcha->expects($this->once())->method('logAttempt')->with($login);
$this->helperMock->expects($this->once())->method('getCaptcha')->with($formId)->willReturn($captcha);
$response = $this->getMock('Magento\\Framework\\App\\Response\\Http', [], [], '', false);
$response->expects($this->once())->method('setRedirect')->with($redirectUrl);
$request = $this->getMock('Magento\\Framework\\App\\Request\\Http', [], [], '', false);
$request->expects($this->any())->method('getPost')->with('login')->willReturn($loginParams);
$controller = $this->getMock('Magento\\Framework\\App\\Action\\Action', [], [], '', false);
$controller->expects($this->any())->method('getRequest')->will($this->returnValue($request));
$controller->expects($this->any())->method('getResponse')->will($this->returnValue($response));
$this->captchaStringResolverMock->expects($this->once())->method('resolve')->with($request, $formId)->willReturn($captchaValue);
$customerDataMock = $this->getMock('\\Magento\\Customer\\Model\\Data\\Customer', ['getId'], [], '', false);
$customerDataMock->expects($this->once())->method('getId')->willReturn($customerId);
$this->customerRepositoryMock->expects($this->once())->method('get')->with($login)->willReturn($customerDataMock);
$this->authenticationMock->expects($this->once())->method('processAuthenticationFailure')->with($customerId);
$this->messageManagerMock->expects($this->once())->method('addError')->with(__('Incorrect CAPTCHA'));
$this->actionFlagMock->expects($this->once())->method('set')->with('', \Magento\Framework\App\Action\Action::FLAG_NO_DISPATCH, true);
$this->customerSessionMock->expects($this->once())->method('setUsername')->with($login);
$this->customerSessionMock->expects($this->once())->method('getBeforeAuthUrl')->willReturn(false);
$this->customerUrlMock->expects($this->once())->method('getLoginUrl')->willReturn($redirectUrl);
$this->observer->execute(new \Magento\Framework\Event\Observer(['controller_action' => $controller]));
}
示例3: 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);
}
示例4: tearDown
/**
* Ensure that fixture customer and his addresses are deleted.
*/
protected function tearDown()
{
/** @var \Magento\Framework\Registry $registry */
$registry = Bootstrap::getObjectManager()->get('Magento\\Framework\\Registry');
$registry->unregister('isSecureArea');
$registry->register('isSecureArea', true);
try {
$fixtureFirstAddressId = 1;
$this->addressRepository->deleteById($fixtureFirstAddressId);
} catch (\Magento\Framework\Exception\NoSuchEntityException $e) {
/** First address fixture was not used */
}
try {
$fixtureSecondAddressId = 2;
$this->addressRepository->deleteById($fixtureSecondAddressId);
} catch (\Magento\Framework\Exception\NoSuchEntityException $e) {
/** Second address fixture was not used */
}
try {
$fixtureCustomerId = 1;
$this->customerRepository->deleteById($fixtureCustomerId);
} catch (\Magento\Framework\Exception\NoSuchEntityException $e) {
/** Customer fixture was not used */
}
$registry->unregister('isSecureArea');
$registry->register('isSecureArea', false);
parent::tearDown();
}
示例5: 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;
}
}
示例6: 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;
}
示例7: install
/**
* {@inheritdoc}
*/
public function install(array $fixtures)
{
foreach ($fixtures as $file) {
$fileName = $this->fixtureManager->getFixture($file);
if (!file_exists($fileName)) {
continue;
}
$rows = $this->csvReader->getData($fileName);
$header = array_shift($rows);
$isFirst = true;
foreach ($rows as $row) {
$data = [];
foreach ($row as $key => $value) {
$data[$header[$key]] = $value;
}
$row = $data;
if ($isFirst) {
$customer = $this->customerRepository->get($row['customer_email']);
if (!$customer->getId()) {
continue;
}
/** @var \Magento\Sales\Model\ResourceModel\Collection $orderCollection */
$orderCollection = $this->orderCollectionFactory->create();
$orderCollection->addFilter('customer_id', $customer->getId());
if ($orderCollection->count() > 0) {
break;
}
}
$isFirst = false;
$orderData = $this->converter->convertRow($row);
$this->orderProcessor->createOrder($orderData);
}
}
}
示例8: 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;
}
示例9: 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;
}
示例10: 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/');
}
示例11: execute
protected function execute(\Symfony\Component\Console\Input\InputInterface $input, \Symfony\Component\Console\Output\OutputInterface $output)
{
$def = $this->manTrans->begin();
try {
foreach ($this->DEFAULT_DWNL_TREE as $custId => $parentId) {
$first = 'User' . $custId;
$last = 'Last';
$email = "customer_{$custId}@test.com";
if ($custId != $parentId) {
/* save parent ID to registry */
$referralCode = $this->mapCustomerMageIdByIndex[$parentId];
$this->toolReferral->replaceCodeInRegistry($referralCode);
}
/** @var \Magento\Customer\Api\Data\CustomerInterface $customer */
$customer = $this->_manObj->create(\Magento\Customer\Api\Data\CustomerInterface::class);
$customer->setEmail($email);
$customer->setFirstname($first);
$customer->setLastname($last);
/* MOBI-427: change group ID for retail customers */
if (in_array($custId, $this->GROUP_RETAIL)) {
$customer->setGroupId(BusinessCodesManager::M_CUST_GROUP_RETAIL);
}
/** @var \Magento\Customer\Api\Data\CustomerInterface $saved */
$saved = $this->repoCustomer->save($customer, $this->DEFAULT_PASSWORD_HASH);
$this->mapCustomerMageIdByIndex[$custId] = $saved->getId();
$this->mapCustomerIndexByMageId[$saved->getId()] = $custId;
}
/* MOBI-426 : rename customer groups according to Generic App scheme. */
$this->subCustomerGroups->renameGroups();
$this->manTrans->commit($def);
} finally {
// transaction will be rolled back if commit is not done (otherwise - do nothing)
$this->manTrans->end($def);
}
}
示例12: run
/**
* {@inheritdoc}
*/
public function run()
{
$this->logger->log('Installing orders:');
foreach ($this->fixtures as $file) {
$fileName = $this->fixtureHelper->getPath($file);
$csvReader = $this->csvReaderFactory->create(['fileName' => $fileName, 'mode' => 'r']);
$isFirst = true;
foreach ($csvReader as $row) {
if ($isFirst) {
$customer = $this->customerRepository->get($row['customer_email']);
if (!$customer->getId()) {
continue;
}
/** @var \Magento\Sales\Model\Resource\Collection $orderCollection */
$orderCollection = $this->orderCollectionFactory->create();
$orderCollection->addFilter('customer_id', $customer->getId());
if ($orderCollection->count() > 0) {
break;
}
}
$isFirst = false;
$orderData = $this->converter->convertRow($row);
$this->orderProcessor->createOrder($orderData);
$this->logger->logInline('.');
}
}
}
示例13: 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;
}
示例14: testSubscribe
public function testSubscribe()
{
$email = 'subscriber_email@magento.com';
$this->resource->expects($this->any())->method('loadByEmail')->willReturn(['subscriber_status' => 3, 'subscriber_email' => $email, 'name' => 'subscriber_name']);
$this->resource->expects($this->any())->method('getIdFieldName')->willReturn('id_field');
$this->scopeConfig->expects($this->any())->method('getValue')->willReturn(true);
$this->customerSession->expects($this->any())->method('isLoggedIn')->willReturn(true);
$customerDataModel = $this->getMock('\\Magento\\Customer\\Api\\Data\\CustomerInterface');
$this->customerSession->expects($this->any())->method('getCustomerDataObject')->willReturn($customerDataModel);
$this->customerSession->expects($this->any())->method('getCustomerId')->willReturn(1);
$customerDataModel->expects($this->any())->method('getEmail')->willReturn($email);
$this->customerRepository->expects($this->any())->method('getById')->willReturn($customerDataModel);
$customerDataModel->expects($this->any())->method('getStoreId')->willReturn(1);
$customerDataModel->expects($this->any())->method('getId')->willReturn(1);
$this->transportBuilder->expects($this->any())->method('setTemplateIdentifier')->willReturnSelf();
$this->transportBuilder->expects($this->any())->method('setTemplateOptions')->willReturnSelf();
$this->transportBuilder->expects($this->any())->method('setTemplateVars')->willReturnSelf();
$this->transportBuilder->expects($this->any())->method('setFrom')->willReturnSelf();
$this->transportBuilder->expects($this->any())->method('addTo')->willReturnSelf();
$storeModel = $this->getMock('\\Magento\\Store\\Model\\Store', ['getId'], [], '', false);
$this->scopeConfig->expects($this->any())->method('getValue')->willReturn('owner_email@magento.com');
$this->storeManager->expects($this->any())->method('getStore')->willReturn($storeModel);
$storeModel->expects($this->any())->method('getId')->willReturn(1);
$transport = $this->getMock('\\Magento\\Framework\\Mail\\TransportInterface');
$this->transportBuilder->expects($this->any())->method('getTransport')->willReturn($transport);
$transport->expects($this->any())->method('sendMessage')->willReturnSelf();
$inlineTranslation = $this->getMock('Magento\\Framework\\Translate\\Inline\\StateInterface');
$inlineTranslation->expects($this->any())->method('resume')->willReturnSelf();
$this->resource->expects($this->atLeastOnce())->method('save')->willReturnSelf();
$this->assertEquals(1, $this->subscriber->subscribe($email));
}
示例15: load
/**
* Load search results
*
* @return $this
*/
public function load()
{
$result = [];
if (!$this->hasStart() || !$this->hasLimit() || !$this->hasQuery()) {
$this->setResults($result);
return $this;
}
$this->searchCriteriaBuilder->setCurrentPage($this->getStart());
$this->searchCriteriaBuilder->setPageSize($this->getLimit());
$searchFields = ['firstname', 'lastname', 'company'];
$filters = [];
foreach ($searchFields as $field) {
$filters[] = $this->filterBuilder->setField($field)->setConditionType('like')->setValue($this->getQuery() . '%')->create();
}
$this->searchCriteriaBuilder->addFilters($filters);
$searchCriteria = $this->searchCriteriaBuilder->create();
$searchResults = $this->customerRepository->getList($searchCriteria);
foreach ($searchResults->getItems() as $customer) {
$customerAddresses = $customer->getAddresses();
/** Look for a company name defined in default billing address */
$company = null;
foreach ($customerAddresses as $customerAddress) {
if ($customerAddress->getId() == $customer->getDefaultBilling()) {
$company = $customerAddress->getCompany();
break;
}
}
$result[] = ['id' => 'customer/1/' . $customer->getId(), 'type' => __('Customer'), 'name' => $this->_customerViewHelper->getCustomerName($customer), 'description' => $company, 'url' => $this->_adminhtmlData->getUrl('customer/index/edit', ['id' => $customer->getId()])];
}
$this->setResults($result);
return $this;
}