Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
Public Member Functions | Protected Member Functions | Protected Attributes
SendFriend Class Reference
Inheritance diagram for SendFriend:
AbstractModel DataObject

Public Member Functions

 __construct (\Magento\Framework\Model\Context $context, \Magento\Framework\Registry $registry, \Magento\Store\Model\StoreManagerInterface $storeManager, \Magento\Framework\Mail\Template\TransportBuilder $transportBuilder, \Magento\Catalog\Helper\Image $catalogImage, \Magento\SendFriend\Helper\Data $sendfriendData, \Magento\Framework\Escaper $escaper, \Magento\Framework\HTTP\PhpEnvironment\RemoteAddress $remoteAddress, \Magento\Framework\Stdlib\CookieManagerInterface $cookieManager, \Magento\Framework\Translate\Inline\StateInterface $inlineTranslation, \Magento\Framework\Model\ResourceModel\AbstractResource $resource=null, \Magento\Framework\Data\Collection\AbstractDb $resourceCollection=null, array $data=[])
 
 send ()
 
 validate ()
 
 setRecipients ($recipients)
 
 getRecipients ()
 
 setProduct ($product)
 
 getProduct ()
 
 setSender ($sender)
 
 getSender ()
 
 getMaxSendsToFriend ()
 
 getMaxRecipients ()
 
 canEmailToFriend ()
 
 isExceedLimit ()
 
 getSentCount ($useCache=true)
 
- Public Member Functions inherited from AbstractModel
 __construct (\Magento\Framework\Model\Context $context, \Magento\Framework\Registry $registry, \Magento\Framework\Model\ResourceModel\AbstractResource $resource=null, \Magento\Framework\Data\Collection\AbstractDb $resourceCollection=null, array $data=[])
 
 __sleep ()
 
 __wakeup ()
 
 setIdFieldName ($name)
 
 getIdFieldName ()
 
 getId ()
 
 setId ($value)
 
 isDeleted ($isDeleted=null)
 
 hasDataChanges ()
 
 setData ($key, $value=null)
 
 unsetData ($key=null)
 
 setDataChanges ($value)
 
 getOrigData ($key=null)
 
 setOrigData ($key=null, $data=null)
 
 dataHasChangedFor ($field)
 
 getResourceName ()
 
 getResourceCollection ()
 
 getCollection ()
 
 load ($modelId, $field=null)
 
 beforeLoad ($identifier, $field=null)
 
 afterLoad ()
 
 isSaveAllowed ()
 
 setHasDataChanges ($flag)
 
 save ()
 
 afterCommitCallback ()
 
 isObjectNew ($flag=null)
 
 beforeSave ()
 
 validateBeforeSave ()
 
 getCacheTags ()
 
 cleanModelCache ()
 
 afterSave ()
 
 delete ()
 
 beforeDelete ()
 
 afterDelete ()
 
 afterDeleteCommit ()
 
 getResource ()
 
 getEntityId ()
 
 setEntityId ($entityId)
 
 clearInstance ()
 
 getStoredData ()
 
 getEventPrefix ()
 
- Public Member Functions inherited from DataObject
 __construct (array $data=[])
 
 addData (array $arr)
 
 setData ($key, $value=null)
 
 unsetData ($key=null)
 
 getData ($key='', $index=null)
 
 getDataByPath ($path)
 
 getDataByKey ($key)
 
 setDataUsingMethod ($key, $args=[])
 
 getDataUsingMethod ($key, $args=null)
 
 hasData ($key='')
 
 toArray (array $keys=[])
 
 convertToArray (array $keys=[])
 
 toXml (array $keys=[], $rootName='item', $addOpenTag=false, $addCdata=true)
 
 convertToXml (array $arrAttributes=[], $rootName='item', $addOpenTag=false, $addCdata=true)
 
 toJson (array $keys=[])
 
 convertToJson (array $keys=[])
 
 toString ($format='')
 
 __call ($method, $args)
 
 isEmpty ()
 
 serialize ($keys=[], $valueSeparator='=', $fieldSeparator=' ', $quote='"')
 
 debug ($data=null, &$objects=[])
 
 offsetSet ($offset, $value)
 
 offsetExists ($offset)
 
 offsetUnset ($offset)
 
 offsetGet ($offset)
 

Protected Member Functions

 _construct ()
 
 _incrementSentCount ()
 
 _sentCountByCookies ($increment=false)
 
 _sentCountByIp ($increment=false)
 
- Protected Member Functions inherited from AbstractModel
 _construct ()
 
 _init ($resourceModel)
 
 _setResourceModel ($resourceName, $collectionName=null)
 
 _getResource ()
 
 _getEventData ()
 
 _beforeLoad ($modelId, $field=null)
 
 _afterLoad ()
 
 _hasModelChanged ()
 
 _getValidatorBeforeSave ()
 
 _createValidatorBeforeSave ()
 
 _getValidationRulesBeforeSave ()
 
 _clearReferences ()
 
 _clearData ()
 
- Protected Member Functions inherited from DataObject
 _getData ($key)
 
 _underscore ($name)
 

Protected Attributes

 $_names = []
 
 $_emails = []
 
 $_sender = []
 
 $_product
 
 $_sentCount
 
 $_lastCookieValue = []
 
 $_sendfriendData = null
 
 $_catalogImage = null
 
 $_transportBuilder
 
 $_storeManager
 
 $_escaper
 
 $inlineTranslation
 
 $cookieManager
 
 $remoteAddress
 
- Protected Attributes inherited from AbstractModel
 $_eventPrefix = 'core_abstract'
 
 $_eventObject = 'object'
 
 $_idFieldName = 'id'
 
 $_hasDataChanges = false
 
 $_origData
 
 $_isDeleted = false
 
 $_resource
 
 $_resourceCollection
 
 $_resourceName
 
 $_collectionName
 
 $_cacheTag = false
 
 $_dataSaveAllowed = true
 
 $_isObjectNew = null
 
 $_validatorBeforeSave = null
 
 $_eventManager
 
 $_cacheManager
 
 $_registry
 
 $_logger
 
 $_appState
 
 $_actionValidator
 
 $storedData = []
 
- Protected Attributes inherited from DataObject
 $_data = []
 

Additional Inherited Members

- Static Protected Attributes inherited from DataObject
static $_underscoreCache = []
 

Detailed Description

SendFriend Log

@method int getIp() @method \Magento\SendFriend\Model\SendFriend setIp(int $value) @method int getTime() @method \Magento\SendFriend\Model\SendFriend setTime(int $value)

Author
Magento Core Team core@.nosp@m.mage.nosp@m.ntoco.nosp@m.mmer.nosp@m.ce.co.nosp@m.m @SuppressWarnings(PHPMD.CouplingBetweenObjects)

@api

Since
100.0.2

Definition at line 24 of file SendFriend.php.

Constructor & Destructor Documentation

◆ __construct()

Parameters
\Magento\Framework\Model\Context$context
\Magento\Framework\Registry$registry
\Magento\Store\Model\StoreManagerInterface$storeManager
\Magento\Framework\Mail\Template\TransportBuilder$transportBuilder
\Magento\Catalog\Helper\Image$catalogImage
\Magento\SendFriend\Helper\Data$sendfriendData
\Magento\Framework\Escaper$escaper
\Magento\Framework\HTTP\PhpEnvironment\RemoteAddress$remoteAddress
\Magento\Framework\Stdlib\CookieManagerInterface$cookieManager
\Magento\Framework\Translate\Inline\StateInterface$inlineTranslation
\Magento\Framework\Model\ResourceModel\AbstractResource$resource
\Magento\Framework\Data\Collection\AbstractDb$resourceCollection
array$data@SuppressWarnings(PHPMD.ExcessiveParameterList)

Definition at line 128 of file SendFriend.php.

142  {
143  $this->_storeManager = $storeManager;
144  $this->_transportBuilder = $transportBuilder;
145  $this->_catalogImage = $catalogImage;
146  $this->_sendfriendData = $sendfriendData;
147  $this->_escaper = $escaper;
148  $this->remoteAddress = $remoteAddress;
149  $this->cookieManager = $cookieManager;
150  $this->inlineTranslation = $inlineTranslation;
151  parent::__construct($context, $registry, $resource, $resourceCollection, $data);
152  }
$storeManager
$resource
Definition: bulk.php:12

Member Function Documentation

◆ _construct()

_construct ( )
protected

Initialize resource model

Returns
void

Definition at line 159 of file SendFriend.php.

160  {
161  $this->_init(\Magento\SendFriend\Model\ResourceModel\SendFriend::class);
162  }

◆ _incrementSentCount()

_incrementSentCount ( )
protected

Increase count of sent

Returns
int

Definition at line 456 of file SendFriend.php.

457  {
458  switch ($this->_sendfriendData->getLimitBy()) {
459  case \Magento\SendFriend\Helper\Data::CHECK_COOKIE:
460  return $this->_sentCount = $this->_sentCountByCookies(true);
461  case \Magento\SendFriend\Helper\Data::CHECK_IP:
462  return $this->_sentCount = $this->_sentCountByIp(true);
463  default:
464  return 0;
465  }
466  }
_sentCountByCookies($increment=false)
Definition: SendFriend.php:474

◆ _sentCountByCookies()

_sentCountByCookies (   $increment = false)
protected

Return count of sent in last period by cookie

Parameters
bool$increment- flag, increase count before return value
Returns
int

Definition at line 474 of file SendFriend.php.

475  {
476  $cookieName = $this->_sendfriendData->getCookieName();
477  $time = time();
478  $newTimes = [];
479 
480  if (isset($this->_lastCookieValue[$cookieName])) {
481  $oldTimes = $this->_lastCookieValue[$cookieName];
482  } else {
483  $oldTimes = $this->cookieManager->getCookie($cookieName);
484  }
485 
486  if ($oldTimes) {
487  $oldTimes = explode(',', $oldTimes);
488  foreach ($oldTimes as $oldTime) {
489  $periodTime = $time - $this->_sendfriendData->getPeriod();
490  if (is_numeric($oldTime) and $oldTime >= $periodTime) {
491  $newTimes[] = $oldTime;
492  }
493  }
494  }
495 
496  if ($increment) {
497  $newTimes[] = $time;
498  $newValue = implode(',', $newTimes);
499  $this->cookieManager->setSensitiveCookie($cookieName, $newValue);
500  $this->_lastCookieValue[$cookieName] = $newValue;
501  }
502 
503  return count($newTimes);
504  }

◆ _sentCountByIp()

_sentCountByIp (   $increment = false)
protected

Return count of sent in last period by IP address

Parameters
bool$increment- flag, increase count before return value
Returns
int

Definition at line 512 of file SendFriend.php.

513  {
514  $time = time();
515  $period = $this->_sendfriendData->getPeriod();
516  $websiteId = $this->_storeManager->getStore()->getWebsiteId();
517 
518  if ($increment) {
519  // delete expired logs
520  $this->_getResource()->deleteLogsBefore($time - $period);
521  // add new item
522  $this->_getResource()->addSendItem($this->remoteAddress->getRemoteAddress(true), $time, $websiteId);
523  }
524 
525  return $this->_getResource()->getSendCount(
526  $this,
527  $this->remoteAddress->getRemoteAddress(true),
528  time() - $period,
529  $websiteId
530  );
531  }

◆ canEmailToFriend()

canEmailToFriend ( )

Check if user is allowed to email product to a friend

Returns
boolean

Definition at line 414 of file SendFriend.php.

415  {
416  return $this->_sendfriendData->isEnabled();
417  }

◆ getMaxRecipients()

getMaxRecipients ( )

Get max allowed recipients for "Send to a Friend" function

Returns
integer

Definition at line 404 of file SendFriend.php.

405  {
406  return $this->_sendfriendData->getMaxRecipients();
407  }

◆ getMaxSendsToFriend()

getMaxSendsToFriend ( )

Get max allowed uses of "Send to Friend" function per hour

Returns
integer

Definition at line 394 of file SendFriend.php.

395  {
396  return $this->_sendfriendData->getMaxEmailPerPeriod();
397  }

◆ getProduct()

getProduct ( )

Retrieve Product instance

Exceptions

Definition at line 348 of file SendFriend.php.

349  {
350  $product = $this->_getData('_product');
351  if (!$product instanceof \Magento\Catalog\Model\Product) {
352  throw new \Magento\Framework\Exception\LocalizedException(__('Please define a correct product instance.'));
353  }
354  return $product;
355  }
__()
Definition: __.php:13

◆ getRecipients()

getRecipients ( )

Retrieve Recipients object

Returns
\Magento\Framework\DataObject

Definition at line 321 of file SendFriend.php.

322  {
323  $recipients = $this->_getData('_recipients');
324  if (!$recipients instanceof \Magento\Framework\DataObject) {
325  $recipients = new \Magento\Framework\DataObject(['emails' => [], 'names' => []]);
326  $this->setData('_recipients', $recipients);
327  }
328  return $recipients;
329  }

◆ getSender()

getSender ( )

Retrieve Sender Information Object

Exceptions

Definition at line 378 of file SendFriend.php.

379  {
380  $sender = $this->_getData('_sender');
381  if (!$sender instanceof \Magento\Framework\DataObject) {
382  throw new \Magento\Framework\Exception\LocalizedException(
383  __('Please define the correct sender information.')
384  );
385  }
386  return $sender;
387  }
__()
Definition: __.php:13

◆ getSentCount()

getSentCount (   $useCache = true)

Return count of sent in last period

Parameters
bool$useCache- flag, is allow to use value of attribute of model if it is processed last time
Returns
int

Definition at line 435 of file SendFriend.php.

436  {
437  if ($useCache && $this->_sentCount !== null) {
438  return $this->_sentCount;
439  }
440 
441  switch ($this->_sendfriendData->getLimitBy()) {
442  case \Magento\SendFriend\Helper\Data::CHECK_COOKIE:
443  return $this->_sentCount = $this->_sentCountByCookies(false);
444  case \Magento\SendFriend\Helper\Data::CHECK_IP:
445  return $this->_sentCount = $this->_sentCountByIp(false);
446  default:
447  return 0;
448  }
449  }
_sentCountByCookies($increment=false)
Definition: SendFriend.php:474

◆ isExceedLimit()

isExceedLimit ( )

Check if user is exceed limit

Returns
boolean

Definition at line 424 of file SendFriend.php.

425  {
426  return $this->getSentCount() >= $this->getMaxSendsToFriend();
427  }

◆ send()

send ( )
Returns
$this
Exceptions
CoreException

Definition at line 168 of file SendFriend.php.

169  {
170  if ($this->isExceedLimit()) {
171  throw new \Magento\Framework\Exception\LocalizedException(
172  __('You\'ve met your limit of %1 sends in an hour.', $this->getMaxSendsToFriend())
173  );
174  }
175 
176  $this->inlineTranslation->suspend();
177 
178  $message = nl2br(htmlspecialchars($this->getSender()->getMessage()));
179  $sender = [
180  'name' => $this->_escaper->escapeHtml($this->getSender()->getName()),
181  'email' => $this->_escaper->escapeHtml($this->getSender()->getEmail()),
182  ];
183 
184  foreach ($this->getRecipients()->getEmails() as $k => $email) {
185  $name = $this->getRecipients()->getNames($k);
186  $this->_transportBuilder->setTemplateIdentifier(
187  $this->_sendfriendData->getEmailTemplate()
188  )->setTemplateOptions(
189  [
190  'area' => \Magento\Framework\App\Area::AREA_FRONTEND,
191  'store' => $this->_storeManager->getStore()->getId(),
192  ]
193  )->setFrom(
194  $sender
195  )->setTemplateVars(
196  [
197  'name' => $name,
198  'email' => $email,
199  'product_name' => $this->getProduct()->getName(),
200  'product_url' => $this->getProduct()->getUrlInStore(),
201  'message' => $message,
202  'sender_name' => $sender['name'],
203  'sender_email' => $sender['email'],
204  'product_image' => $this->_catalogImage->init($this->getProduct(), 'sendfriend_small_image')
205  ->getUrl(),
206  ]
207  )->addTo(
208  $email,
209  $name
210  );
211  $transport = $this->_transportBuilder->getTransport();
212  $transport->sendMessage();
213  }
214 
215  $this->inlineTranslation->resume();
216 
217  $this->_incrementSentCount();
218 
219  return $this;
220  }
$email
Definition: details.phtml:13
__()
Definition: __.php:13
$message
if(!isset($_GET['name'])) $name
Definition: log.php:14

◆ setProduct()

setProduct (   $product)

Set product instance

Parameters
\Magento\Catalog\Model\Product$product
Returns
$this

Definition at line 337 of file SendFriend.php.

338  {
339  return $this->setData('_product', $product);
340  }

◆ setRecipients()

setRecipients (   $recipients)

Set Recipients

Parameters
array$recipients
Returns
$this @SuppressWarnings(PHPMD.CyclomaticComplexity)

Definition at line 279 of file SendFriend.php.

280  {
281  // validate array
282  if (!is_array(
283  $recipients
284  ) or !isset(
285  $recipients['email']
286  ) or !isset(
287  $recipients['name']
288  ) or !is_array(
289  $recipients['email']
290  ) or !is_array(
291  $recipients['name']
292  )
293  ) {
294  return $this;
295  }
296 
297  $emails = [];
298  $names = [];
299  foreach ($recipients['email'] as $k => $email) {
300  if (!isset($emails[$email]) && isset($recipients['name'][$k])) {
301  $emails[$email] = true;
302  $names[] = $recipients['name'][$k];
303  }
304  }
305 
306  if ($emails) {
307  $emails = array_keys($emails);
308  }
309 
310  return $this->setData(
311  '_recipients',
312  new \Magento\Framework\DataObject(['emails' => $emails, 'names' => $names])
313  );
314  }
$email
Definition: details.phtml:13

◆ setSender()

setSender (   $sender)

Set Sender Information array

Parameters
array$sender
Returns
$this

Definition at line 363 of file SendFriend.php.

364  {
365  if (!is_array($sender)) {
366  __('Invalid Sender Information');
367  }
368 
369  return $this->setData('_sender', new \Magento\Framework\DataObject($sender));
370  }
__()
Definition: __.php:13

◆ validate()

validate ( )

Validate Form data

Returns
bool|string[] @SuppressWarnings(PHPMD.CyclomaticComplexity) @SuppressWarnings(PHPMD.NPathComplexity)

Definition at line 229 of file SendFriend.php.

230  {
231  $errors = [];
232 
233  $name = $this->getSender()->getName();
234  if (empty($name)) {
235  $errors[] = __('Please enter a sender name.');
236  }
237 
238  $email = $this->getSender()->getEmail();
239  if (empty($email) or !\Zend_Validate::is($email, \Magento\Framework\Validator\EmailAddress::class)) {
240  $errors[] = __('Invalid Sender Email');
241  }
242 
243  $message = $this->getSender()->getMessage();
244  if (empty($message)) {
245  $errors[] = __('Please enter a message.');
246  }
247 
248  if (!$this->getRecipients()->getEmails()) {
249  $errors[] = __('Please specify at least one recipient.');
250  }
251 
252  // validate recipients email addresses
253  foreach ($this->getRecipients()->getEmails() as $email) {
254  if (!\Zend_Validate::is($email, \Magento\Framework\Validator\EmailAddress::class)) {
255  $errors[] = __('Please enter a correct recipient email address.');
256  break;
257  }
258  }
259 
260  $maxRecipients = $this->getMaxRecipients();
261  if (count($this->getRecipients()->getEmails()) > $maxRecipients) {
262  $errors[] = __('No more than %1 emails can be sent at a time.', $this->getMaxRecipients());
263  }
264 
265  if (empty($errors)) {
266  return true;
267  }
268 
269  return $errors;
270  }
$email
Definition: details.phtml:13
__()
Definition: __.php:13
$message
static is($value, $classBaseName, array $args=array(), $namespaces=array())
Definition: Validate.php:195
$errors
Definition: overview.phtml:9
if(!isset($_GET['name'])) $name
Definition: log.php:14

Field Documentation

◆ $_catalogImage

$_catalogImage = null
protected

Definition at line 80 of file SendFriend.php.

◆ $_emails

$_emails = []
protected

Definition at line 38 of file SendFriend.php.

◆ $_escaper

$_escaper
protected

Definition at line 95 of file SendFriend.php.

◆ $_lastCookieValue

$_lastCookieValue = []
protected

Definition at line 66 of file SendFriend.php.

◆ $_names

$_names = []
protected

Definition at line 31 of file SendFriend.php.

◆ $_product

$_product
protected

Definition at line 52 of file SendFriend.php.

◆ $_sender

$_sender = []
protected

Definition at line 45 of file SendFriend.php.

◆ $_sendfriendData

$_sendfriendData = null
protected

Definition at line 73 of file SendFriend.php.

◆ $_sentCount

$_sentCount
protected

Definition at line 59 of file SendFriend.php.

◆ $_storeManager

$_storeManager
protected

Definition at line 90 of file SendFriend.php.

◆ $_transportBuilder

$_transportBuilder
protected

Definition at line 85 of file SendFriend.php.

◆ $cookieManager

$cookieManager
protected

Definition at line 105 of file SendFriend.php.

◆ $inlineTranslation

$inlineTranslation
protected

Definition at line 100 of file SendFriend.php.

◆ $remoteAddress

$remoteAddress
protected

Definition at line 110 of file SendFriend.php.


The documentation for this class was generated from the following file: