/**
  * Reports Modules and module changes to the database reporting_module_status table
  *
  * @return \Magento\NewRelicReporting\Model\Cron\ReportModulesInfo
  */
 public function report()
 {
     if ($this->config->isNewRelicEnabled()) {
         $moduleData = $this->collect->getModuleData();
         if (count($moduleData['changes']) > 0) {
             foreach ($moduleData['changes'] as $change) {
                 switch ($change['type']) {
                     case Config::ENABLED:
                         $modelData = ['type' => Config::MODULE_ENABLED, 'action' => $this->jsonEncoder->encode($change), 'updated_at' => $this->dateTime->formatDate(true)];
                         break;
                     case Config::DISABLED:
                         $modelData = ['type' => Config::MODULE_DISABLED, 'action' => $this->jsonEncoder->encode($change), 'updated_at' => $this->dateTime->formatDate(true)];
                         break;
                     case Config::INSTALLED:
                         $modelData = ['type' => Config::MODULE_INSTALLED, 'action' => $this->jsonEncoder->encode($change), 'updated_at' => $this->dateTime->formatDate(true)];
                         break;
                     case Config::UNINSTALLED:
                         $modelData = ['type' => Config::MODULE_UNINSTALLED, 'action' => $this->jsonEncoder->encode($change), 'updated_at' => $this->dateTime->formatDate(true)];
                         break;
                 }
                 /** @var \Magento\NewRelicReporting\Model\System $systemModel */
                 $systemModel = $this->systemFactory->create();
                 $systemModel->setData($modelData);
                 $systemModel->save();
             }
         }
     }
     return $this;
 }
Example #2
0
 public function getAlists($json = false)
 {
     //       return [1];
     $id = $this->getRequest()->getParam('id');
     $collection = $this->_testFactory->create()->setId($id);
     $listso = $this->_objectManager->create('Sugarcode\\Test\\Model\\Test')->load($id);
     $collection = unserialize($listso->getInListsGrid());
     if (sizeof($collection) > 0) {
         if ($json) {
             $jsonLists = [];
             foreach ($collection as $usrid) {
                 $jsonLists[$usrid] = 0;
             }
             return $this->_jsonEncoder->encode((object) $jsonLists);
         } else {
             return array_values($collection);
         }
     } else {
         if ($json) {
             return '{}';
         } else {
             return [];
         }
     }
 }
Example #3
0
 /**
  * {@inheritdoc}
  */
 public function install(SchemaSetupInterface $setup, ModuleContextInterface $context)
 {
     /** @var State[] $stateIndexers */
     $stateIndexers = [];
     $states = $this->statesFactory->create();
     foreach ($states->getItems() as $state) {
         /** @var State $state */
         $stateIndexers[$state->getIndexerId()] = $state;
     }
     foreach ($this->config->getIndexers() as $indexerId => $indexerConfig) {
         $expectedHashConfig = $this->encryptor->hash($this->encoder->encode($indexerConfig), Encryptor::HASH_VERSION_MD5);
         if (isset($stateIndexers[$indexerId])) {
             if ($stateIndexers[$indexerId]->getHashConfig() != $expectedHashConfig) {
                 $stateIndexers[$indexerId]->setStatus(StateInterface::STATUS_INVALID);
                 $stateIndexers[$indexerId]->setHashConfig($expectedHashConfig);
                 $stateIndexers[$indexerId]->save();
             }
         } else {
             /** @var State $state */
             $state = $this->stateFactory->create();
             $state->loadByIndexer($indexerId);
             $state->setHashConfig($expectedHashConfig);
             $state->setStatus(StateInterface::STATUS_INVALID);
             $state->save();
         }
     }
 }
Example #4
0
 /**
  * Forms script response
  *
  * @return string
  */
 public function _toHtml()
 {
     $updateResult = $this->_coreRegistry->registry('composite_update_result');
     $resultJson = $this->_jsonEncoder->encode($updateResult);
     $jsVarname = $updateResult->getJsVarName();
     return $this->_jsHelper->getScript(sprintf('var %s = %s', $jsVarname, $resultJson));
 }
Example #5
0
 /**
  * @return string
  */
 public function getProductsJson()
 {
     $products = $this->getCategory()->getProductsPosition();
     if (!empty($products)) {
         return $this->jsonEncoder->encode($products);
     }
     return '{}';
 }
Example #6
0
 /**
  * Render single action as dropdown option html
  *
  * @param array $action
  * @param \Magento\Framework\DataObject $row
  * @return string
  */
 protected function _toOptionHtml($action, \Magento\Framework\DataObject $row)
 {
     $actionAttributes = new \Magento\Framework\DataObject();
     $actionCaption = '';
     $this->_transformActionData($action, $actionCaption, $row);
     $htmlAttibutes = ['value' => $this->escapeHtml($this->_jsonEncoder->encode($action))];
     $actionAttributes->setData($htmlAttibutes);
     return '<option ' . $actionAttributes->serialize() . '>' . $actionCaption . '</option>';
 }
Example #7
0
 public function testAfterGetOptions()
 {
     $resultJson = '[]';
     $this->jsonDecoder->expects($this->once())->method('decode')->with('[]')->willReturn([]);
     $expected = ['configurable_attribute_1' => [['mediaType' => 'type', 'videoUrl' => 'url', 'isBase' => true]]];
     $this->jsonEncoder->expects($this->any())->method('encode')->with($expected)->willReturn(json_encode($expected));
     $blockMock = $this->getMockBuilder('\\Magento\\ProductVideo\\Block\\Product\\View\\Gallery')->disableOriginalConstructor()->getMock();
     $result = $this->plugin->afterGetOptionsMediaGalleryDataJson($blockMock, $resultJson);
     $this->assertEquals(json_encode($expected), $result);
 }
Example #8
0
 /**
  * Render block HTML
  *
  * @return string
  */
 protected function _toHtml()
 {
     $localeCode = $this->_localeResolver->getLocaleCode();
     // get days names
     $days = \Zend_Locale_Data::getList($localeCode, 'days');
     $this->assign('days', array('wide' => $this->encoder->encode(array_values($days['format']['wide'])), 'abbreviated' => $this->encoder->encode(array_values($days['format']['abbreviated']))));
     // get months names
     $months = \Zend_Locale_Data::getList($localeCode, 'months');
     $this->assign('months', array('wide' => $this->encoder->encode(array_values($months['format']['wide'])), 'abbreviated' => $this->encoder->encode(array_values($months['format']['abbreviated']))));
     // get "today" and "week" words
     $this->assign('today', $this->encoder->encode(\Zend_Locale_Data::getContent($localeCode, 'relative', 0)));
     $this->assign('week', $this->encoder->encode(\Zend_Locale_Data::getContent($localeCode, 'field', 'week')));
     // get "am" & "pm" words
     $this->assign('am', $this->encoder->encode(\Zend_Locale_Data::getContent($localeCode, 'am')));
     $this->assign('pm', $this->encoder->encode(\Zend_Locale_Data::getContent($localeCode, 'pm')));
     // get first day of week and weekend days
     $this->assign('firstDay', (int) $this->_scopeConfig->getValue('general/locale/firstday', \Magento\Store\Model\ScopeInterface::SCOPE_STORE));
     $this->assign('weekendDays', $this->encoder->encode((string) $this->_scopeConfig->getValue('general/locale/weekend', \Magento\Store\Model\ScopeInterface::SCOPE_STORE)));
     // define default format and tooltip format
     $this->assign('defaultFormat', $this->encoder->encode($this->_localeDate->getDateFormat(TimezoneInterface::FORMAT_TYPE_MEDIUM)));
     $this->assign('toolTipFormat', $this->encoder->encode($this->_localeDate->getDateFormat(TimezoneInterface::FORMAT_TYPE_LONG)));
     // get days and months for en_US locale - calendar will parse exactly in this locale
     $days = \Zend_Locale_Data::getList('en_US', 'days');
     $months = \Zend_Locale_Data::getList('en_US', 'months');
     $enUS = new \stdClass();
     $enUS->m = new \stdClass();
     $enUS->m->wide = array_values($months['format']['wide']);
     $enUS->m->abbr = array_values($months['format']['abbreviated']);
     $this->assign('enUS', $this->encoder->encode($enUS));
     return parent::_toHtml();
 }
 /**
  * Setup
  *
  * @return void
  */
 public function setUp()
 {
     $this->config = $this->getMockBuilder('Magento\\NewRelicReporting\\Model\\Config')->disableOriginalConstructor()->setMethods(['isNewRelicEnabled'])->getMock();
     $this->collectMock = $this->getMockBuilder('Magento\\NewRelicReporting\\Model\\Module\\Collect')->disableOriginalConstructor()->setMethods(['getModuleData'])->getMock();
     $this->systemFactoryMock = $this->getMockBuilder('Magento\\NewRelicReporting\\Model\\SystemFactory')->disableOriginalConstructor()->setMethods(['create'])->getMock();
     $this->systemModelMock = $this->getMockBuilder('Magento\\NewRelicReporting\\Model\\System')->disableOriginalConstructor()->getMock();
     $this->jsonEncoderMock = $this->getMockBuilder('Magento\\Framework\\Json\\EncoderInterface')->getMock();
     $this->systemFactoryMock->expects($this->any())->method('create')->willReturn($this->systemModelMock);
     $this->jsonEncoderMock->expects($this->any())->method('encode')->willReturn('json_string');
     $this->model = new ReportModulesInfo($this->config, $this->collectMock, $this->systemFactoryMock, $this->jsonEncoderMock);
 }
 /**
  * Reports a system cache flush to the database reporting_system_updates table
  *
  * @param Observer $observer
  * @return void
  * @SuppressWarnings(PHPMD.UnusedFormalParameter)
  */
 public function execute(Observer $observer)
 {
     if ($this->config->isNewRelicEnabled()) {
         $jsonData = ['status' => 'updated'];
         $modelData = ['type' => Config::FLUSH_CACHE, 'action' => $this->jsonEncoder->encode($jsonData)];
         /** @var \Magento\NewRelicReporting\Model\System $systemModel */
         $systemModel = $this->systemFactory->create();
         $systemModel->setData($modelData);
         $systemModel->save();
     }
 }
Example #11
0
 public function testGetWidgetOptions()
 {
     $rand = rand();
     $this->mathRandom->expects($this->any())->method('getUniqueHash')->with('id_')->willReturn('id_' . $rand);
     $saveVideoUrl = 'http://host/index.php/admin/catalog/product_gallery/upload/key/';
     $saveRemoteVideoUrl = 'http://host/index.php/admin/product_video/product_gallery/retrieveImage/';
     $this->urlBuilder->expects($this->exactly(2))->method('getUrl')->willReturnOnConsecutiveCalls($saveVideoUrl, $saveRemoteVideoUrl);
     $value = ['saveVideoUrl' => $saveVideoUrl, 'saveRemoteVideoUrl' => $saveRemoteVideoUrl, 'htmlId' => 'id_' . $rand];
     $this->jsonEncoderMock->expects($this->once())->method('encode')->with($value)->willReturn(json_encode($value));
     $this->block->getWidgetOptions();
 }
Example #12
0
 /**
  * Get object data as JSON
  *
  * @return string
  */
 public function getDataAsJSON()
 {
     $result = [];
     $inputNames = $this->getInputNames();
     if ($serializeData = $this->getSerializeData()) {
         $result = $serializeData;
     } elseif (!empty($inputNames)) {
         return '{}';
     }
     return $this->_jsonEncoder->encode($result);
 }
 /**
  * Test case when module is enabled in config
  *
  * @return void
  */
 public function testReportSystemCacheFlush()
 {
     $testType = 'systemCacheFlush';
     $testAction = 'JSON string';
     /** @var \Magento\Framework\Event\Observer|\PHPUnit_Framework_MockObject_MockObject $eventObserver */
     $eventObserver = $this->getMockBuilder('Magento\\Framework\\Event\\Observer')->disableOriginalConstructor()->getMock();
     $this->config->expects($this->once())->method('isNewRelicEnabled')->willReturn(true);
     $this->jsonEncoder->expects($this->once())->method('encode')->willReturn($testAction);
     $this->systemModel->expects($this->once())->method('setData')->with(['type' => $testType, 'action' => $testAction])->willReturnSelf();
     $this->systemModel->expects($this->once())->method('save');
     $this->model->execute($eventObserver);
 }
 /**
  * Reports any products deleted to the database reporting_system_updates table
  *
  * @param Observer $observer
  * @return void
  */
 public function execute(Observer $observer)
 {
     if ($this->config->isNewRelicEnabled()) {
         /** @var \Magento\Catalog\Model\Product $product */
         $product = $observer->getEvent()->getProduct();
         $jsonData = ['id' => $product->getId(), 'status' => 'deleted'];
         $modelData = ['type' => Config::PRODUCT_CHANGE, 'action' => $this->jsonEncoder->encode($jsonData), 'updated_at' => $this->dateTime->formatDate(true)];
         /** @var \Magento\NewRelicReporting\Model\System $systemModel */
         $systemModel = $this->systemFactory->create();
         $systemModel->setData($modelData);
         $systemModel->save();
     }
 }
 /**
  * Setup
  *
  * @return void
  */
 public function setUp()
 {
     $this->config = $this->getMockBuilder('Magento\\NewRelicReporting\\Model\\Config')->disableOriginalConstructor()->setMethods(['isNewRelicEnabled'])->getMock();
     $this->collect = $this->getMockBuilder('Magento\\NewRelicReporting\\Model\\Module\\Collect')->disableOriginalConstructor()->setMethods(['getModuleData'])->getMock();
     $this->systemFactory = $this->getMockBuilder('Magento\\NewRelicReporting\\Model\\SystemFactory')->disableOriginalConstructor()->setMethods(['create'])->getMock();
     $this->systemModel = $this->getMockBuilder('Magento\\NewRelicReporting\\Model\\System')->disableOriginalConstructor()->getMock();
     $this->jsonEncoder = $this->getMockBuilder('Magento\\Framework\\Json\\EncoderInterface')->getMock();
     $this->dateTime = $this->getMockBuilder('Magento\\Framework\\Stdlib\\DateTime')->disableOriginalConstructor()->setMethods(['formatDate'])->getMock();
     $this->systemFactory->expects($this->any())->method('create')->willReturn($this->systemModel);
     $this->jsonEncoder->expects($this->any())->method('encode')->willReturn('json_string');
     $this->dateTime->expects($this->any())->method('formatDate')->willReturn('1970-01-01 00:00:00');
     $this->model = new ReportModulesInfo($this->config, $this->collect, $this->systemFactory, $this->jsonEncoder, $this->dateTime);
 }
 /**
  * Reports concurrent admins to the database reporting_users table
  *
  * @param Observer $observer
  * @return void
  * @SuppressWarnings(PHPMD.UnusedFormalParameter)
  */
 public function execute(Observer $observer)
 {
     if ($this->config->isNewRelicEnabled()) {
         if ($this->backendAuthSession->isLoggedIn()) {
             $user = $this->backendAuthSession->getUser();
             $jsonData = ['id' => $user->getId(), 'username' => $user->getUsername(), 'name' => $user->getFirstname() . ' ' . $user->getLastname()];
             $modelData = ['type' => 'admin_activity', 'action' => $this->jsonEncoder->encode($jsonData)];
             /** @var \Magento\NewRelicReporting\Model\Users $usersModel */
             $usersModel = $this->usersFactory->create();
             $usersModel->setData($modelData);
             $usersModel->save();
         }
     }
 }
 /**
  * Reports concurrent users to the database reporting_users table
  *
  * @param Observer $observer
  * @return void
  * @SuppressWarnings(PHPMD.UnusedFormalParameter)
  */
 public function execute(Observer $observer)
 {
     if ($this->config->isNewRelicEnabled()) {
         if ($this->customerSession->isLoggedIn()) {
             $customer = $this->customerRepository->getById($this->customerSession->getCustomerId());
             $jsonData = ['id' => $customer->getId(), 'name' => $customer->getFirstname() . ' ' . $customer->getLastname(), 'store' => $this->storeManager->getStore()->getName(), 'website' => $this->storeManager->getWebsite()->getName()];
             $modelData = ['type' => 'user_action', 'action' => $this->jsonEncoder->encode($jsonData), 'updated_at' => $this->dateTime->formatDate(true)];
             /** @var \Magento\NewRelicReporting\Model\Users $usersModel */
             $usersModel = $this->usersFactory->create();
             $usersModel->setData($modelData);
             $usersModel->save();
         }
     }
 }
 public function testGetUsersPositiveNumberOfRolesAndJsonTrue()
 {
     $roleId = 1;
     $roles = ['role1', 'role2', 'role3'];
     /** @var \Magento\Authorization\Model\Role|\PHPUnit_Framework_MockObject_MockObject */
     $roleModelMock = $this->getMockBuilder('Magento\\Authorization\\Model\\Role')->disableOriginalConstructor()->setMethods([])->getMock();
     $this->requestInterfaceMock->expects($this->at(0))->method('getParam')->willReturn("");
     $this->requestInterfaceMock->expects($this->at(1))->method('getParam')->willReturn($roleId);
     $this->requestInterfaceMock->expects($this->at(2))->method('getParam')->willReturn($roleId);
     $this->registryMock->expects($this->once())->method('registry')->with(\Magento\User\Controller\Adminhtml\User\Role\SaveRole::IN_ROLE_USER_FORM_DATA_SESSION_KEY)->willReturn('role1=value1&role2=value2&role3=value3');
     $this->roleFactoryMock->expects($this->never())->method('create')->willReturn($roleModelMock);
     $this->jsonEncoderMock->expects($this->once())->method('encode')->willReturn($roles);
     $this->assertEquals($roles, $this->model->getUsers(true));
 }
Example #19
0
 /**
  * Render block HTML
  *
  * @return string
  */
 protected function _toHtml()
 {
     $result = [];
     $layout = $this->getLayout();
     foreach ($this->getChildNames() as $name) {
         $result[$name] = $layout->renderElement($name);
     }
     $resultJson = $this->_jsonEncoder->encode($result);
     $jsVarname = $this->getRequest()->getParam('as_js_varname');
     if ($jsVarname) {
         return $this->_jsHelper->getScript(sprintf('var %s = %s', $jsVarname, $resultJson));
     } else {
         return $resultJson;
     }
 }
 public function testGetUsersPositiveNumberOfRolesAndJsonTrue()
 {
     $roleId = 1;
     $roles = ['role1', 'role2', 'role3'];
     /** @var \Magento\Authorization\Model\Role|\PHPUnit_Framework_MockObject_MockObject */
     $roleModelMock = $this->getMockBuilder('Magento\\Authorization\\Model\\Role')->disableOriginalConstructor()->setMethods([])->getMock();
     $this->requestInterfaceMock->expects($this->at(0))->method('getParam')->willReturn("");
     $this->requestInterfaceMock->expects($this->at(1))->method('getParam')->willReturn($roleId);
     $this->requestInterfaceMock->expects($this->at(2))->method('getParam')->willReturn($roleId);
     $this->roleFactoryMock->expects($this->once())->method('create')->willReturn($roleModelMock);
     $roleModelMock->expects($this->once())->method('setId')->willReturnSelf();
     $roleModelMock->expects($this->once())->method('getRoleUsers')->willReturn($roles);
     $this->jsonEncoderMock->expects($this->once())->method('encode')->willReturn($roles);
     $this->assertEquals($roles, $this->model->getUsers(true));
 }
Example #21
0
 public function testGetImagesJson()
 {
     $url = [['file_1.jpg', 'url_to_the_image/image_1.jpg'], ['file_2.jpg', 'url_to_the_image/image_2.jpg']];
     $mediaPath = [['file_1.jpg', 'catalog/product/image_1.jpg'], ['file_2.jpg', 'catalog/product/image_2.jpg']];
     $sizeMap = [['catalog/product/image_1.jpg', ['size' => 399659]], ['catalog/product/image_2.jpg', ['size' => 879394]]];
     $imagesResult = [['value_id' => '2', 'file' => 'file_2.jpg', 'media_type' => 'image', 'position' => '0', 'url' => 'url_to_the_image/image_2.jpg', 'size' => 879394], ['value_id' => '1', 'file' => 'file_1.jpg', 'media_type' => 'image', 'position' => '1', 'url' => 'url_to_the_image/image_1.jpg', 'size' => 399659]];
     $images = ['images' => [['value_id' => '1', 'file' => 'file_1.jpg', 'media_type' => 'image', 'position' => '1'], ['value_id' => '2', 'file' => 'file_2.jpg', 'media_type' => 'image', 'position' => '0']]];
     $this->content->setElement($this->galleryMock);
     $this->galleryMock->expects($this->once())->method('getImages')->willReturn($images);
     $this->fileSystemMock->expects($this->once())->method('getDirectoryRead')->willReturn($this->readMock);
     $this->mediaConfigMock->expects($this->any())->method('getMediaUrl')->willReturnMap($url);
     $this->mediaConfigMock->expects($this->any())->method('getMediaPath')->willReturnMap($mediaPath);
     $this->readMock->expects($this->any())->method('stat')->willReturnMap($sizeMap);
     $this->jsonEncoderMock->expects($this->once())->method('encode')->willReturnCallback('json_encode');
     $this->assertSame(json_encode($imagesResult), $this->content->getImagesJson());
 }
Example #22
0
 /**
  * Retrieve validate button block
  *
  * @return \Magento\Backend\Block\Widget\Button
  */
 public function getValidateButton()
 {
     if ($this->_validateButton === null) {
         /** @var $form \Magento\Framework\Data\Form */
         $form = $this->_element->getForm();
         $vatElementId = $this->_element->getHtmlId();
         $countryElementId = $form->getElement('country_id')->getHtmlId();
         $validateUrl = $this->_urlBuilder->getUrl('customer/system_config_validatevat/validateAdvanced');
         $groupMessage = __('The customer is currently assigned to Customer Group %s.') . ' ' . __('Would you like to change the Customer Group for this order?');
         $vatValidateOptions = $this->_jsonEncoder->encode(['vatElementId' => $vatElementId, 'countryElementId' => $countryElementId, 'groupIdHtmlId' => 'group_id', 'validateUrl' => $validateUrl, 'vatValidMessage' => __('The VAT ID is valid.'), 'vatInvalidMessage' => __('The VAT ID entered (%s) is not a valid VAT ID.'), 'vatValidAndGroupValidMessage' => __('The VAT ID is valid. The current Customer Group will be used.'), 'vatValidAndGroupInvalidMessage' => __('The VAT ID is valid but no Customer Group is assigned for it.'), 'vatValidAndGroupChangeMessage' => __('Based on the VAT ID, the customer would belong to the Customer Group %s.') . "\n" . $groupMessage, 'vatValidationFailedMessage' => __('There was an error validating the VAT ID. '), 'vatCustomerGroupMessage' => __('The customer would belong to Customer Group %s.'), 'vatGroupErrorMessage' => __('There was an error detecting Customer Group.')]);
         $optionsVarName = $this->getJsVariablePrefix() . 'VatParameters';
         $beforeHtml = '<script>var ' . $optionsVarName . ' = ' . $vatValidateOptions . ';</script>';
         $this->_validateButton = $this->getLayout()->createBlock('Magento\\Backend\\Block\\Widget\\Button')->setData(['label' => __('Validate VAT Number'), 'before_html' => $beforeHtml, 'onclick' => 'order.validateVat(' . $optionsVarName . ')']);
     }
     return $this->_validateButton;
 }
Example #23
0
 /**
  * @param \Magento\Catalog\Api\Data\ProductInterface $product
  * @param LinkInterface $link
  * @param bool $isGlobalScopeContent
  * @return int
  */
 protected function saveLink(\Magento\Catalog\Api\Data\ProductInterface $product, LinkInterface $link, $isGlobalScopeContent)
 {
     $linkData = ['link_id' => $link->getid() === null ? 0 : $link->getid(), 'is_delete' => 0, 'type' => $link->getLinkType(), 'sort_order' => $link->getSortOrder(), 'title' => $link->getTitle(), 'price' => $link->getPrice(), 'number_of_downloads' => $link->getNumberOfDownloads(), 'is_shareable' => $link->getIsShareable()];
     if ($link->getLinkType() == 'file' && $link->getLinkFile() === null) {
         $linkData['file'] = $this->jsonEncoder->encode([$this->fileContentUploader->upload($link->getLinkFileContent(), 'link_file')]);
     } elseif ($link->getLinkType() === 'url') {
         $linkData['link_url'] = $link->getLinkUrl();
     } else {
         //existing link file
         $linkData['file'] = $this->jsonEncoder->encode([['file' => $link->getLinkFile(), 'status' => 'old']]);
     }
     if ($link->getSampleType() == 'file' && $link->getSampleFile() === null) {
         $linkData['sample']['type'] = 'file';
         $linkData['sample']['file'] = $this->jsonEncoder->encode([$this->fileContentUploader->upload($link->getSampleFileContent(), 'link_sample_file')]);
     } elseif ($link->getSampleType() == 'url') {
         $linkData['sample']['type'] = 'url';
         $linkData['sample']['url'] = $link->getSampleUrl();
     }
     $downloadableData = ['link' => [$linkData]];
     $product->setDownloadableData($downloadableData);
     if ($isGlobalScopeContent) {
         $product->setStoreId(0);
     }
     $this->downloadableType->save($product);
     return $product->getLastAddedLinkId();
 }
 /**
  * Test case when module is enabled in config
  *
  * @return void
  */
 public function testReportProductDeleted()
 {
     $testType = 'adminProductChange';
     $testAction = 'JSON string';
     /** @var \Magento\Framework\Event\Observer|\PHPUnit_Framework_MockObject_MockObject $eventObserver */
     $eventObserver = $this->getMockBuilder('Magento\\Framework\\Event\\Observer')->disableOriginalConstructor()->getMock();
     $this->config->expects($this->once())->method('isNewRelicEnabled')->willReturn(true);
     $event = $this->getMockBuilder('Magento\\Framework\\Event')->setMethods(['getProduct'])->disableOriginalConstructor()->getMock();
     $eventObserver->expects($this->once())->method('getEvent')->willReturn($event);
     $product = $this->getMockBuilder('Magento\\Catalog\\Model\\Product')->setMethods(['getId'])->disableOriginalConstructor()->getMock();
     $event->expects($this->once())->method('getProduct')->willReturn($product);
     $this->jsonEncoder->expects($this->once())->method('encode')->willReturn($testAction);
     $this->systemModel->expects($this->once())->method('setData')->with(['type' => $testType, 'action' => $testAction])->willReturnSelf();
     $this->systemModel->expects($this->once())->method('save');
     $this->model->execute($eventObserver);
 }
 /**
  * Tests client request with Bad status
  *
  * @return void
  */
 public function testSendRequestStatusBad()
 {
     $json = '{"eventType":"Cron","appName":"app_name","appId":"app_id"}';
     $statusBad = '401';
     $uri = 'https://example.com/listener';
     $method = ZendClient::POST;
     $headers = ['X-Insert-Key' => 'insert_key_value', 'Content-Type' => 'application/json'];
     $accId = 'acc_id';
     $appId = 'app_id';
     $appName = 'app_name';
     $insightApiKey = 'insert_key_value';
     $this->zendClientMock->expects($this->once())->method('setUri')->with($uri)->willReturnSelf();
     $this->zendClientMock->expects($this->once())->method('setMethod')->with($method)->willReturnSelf();
     $this->zendClientMock->expects($this->once())->method('setHeaders')->with($headers)->willReturnSelf();
     $this->zendClientMock->expects($this->once())->method('setRawData')->with($json)->willReturnSelf();
     $this->configMock->expects($this->once())->method('getNewRelicAccountId')->willReturn($accId);
     $this->configMock->expects($this->once())->method('getInsightsApiUrl')->willReturn($uri);
     $this->configMock->expects($this->once())->method('getInsightsInsertKey')->willReturn($insightApiKey);
     $this->configMock->expects($this->once())->method('getNewRelicAppName')->willReturn($appName);
     $this->configMock->expects($this->once())->method('getNewRelicAppId')->willReturn($appId);
     $this->jsonEncoderMock->expects($this->once())->method('encode')->willReturn($json);
     $zendHttpResponseMock = $this->getMockBuilder('Zend_Http_Response')->disableOriginalConstructor()->getMock();
     $zendHttpResponseMock->expects($this->any())->method('getStatus')->willReturn($statusBad);
     $this->zendClientMock->expects($this->once())->method('request')->willReturn($zendHttpResponseMock);
     $this->zendClientFactoryMock->expects($this->once())->method('create')->willReturn($this->zendClientMock);
     $this->assertInternalType('bool', $this->model->sendRequest());
 }
Example #26
0
 /**
  * {@inheritdoc}
  */
 public function create($productSku, DownloadableSampleContent $sampleContent, $isGlobalScopeContent = false)
 {
     $product = $this->productRepository->get($productSku, true);
     if ($product->getTypeId() !== \Magento\Downloadable\Model\Product\Type::TYPE_DOWNLOADABLE) {
         throw new InputException('Product type of the product must be \'downloadable\'.');
     }
     if (!$this->contentValidator->isValid($sampleContent)) {
         throw new InputException('Provided sample information is invalid.');
     }
     if (!in_array($sampleContent->getSampleType(), array('url', 'file'))) {
         throw new InputException('Invalid sample type.');
     }
     $title = $sampleContent->getTitle();
     if (empty($title)) {
         throw new InputException('Sample title cannot be empty.');
     }
     $sampleData = array('sample_id' => 0, 'is_delete' => 0, 'type' => $sampleContent->getSampleType(), 'sort_order' => $sampleContent->getSortOrder(), 'title' => $sampleContent->getTitle());
     if ($sampleContent->getSampleType() == 'file') {
         $sampleData['file'] = $this->jsonEncoder->encode(array($this->fileContentUploader->upload($sampleContent->getSampleFile(), 'sample')));
     } else {
         $sampleData['sample_url'] = $sampleContent->getSampleUrl();
     }
     $downloadableData = array('sample' => array($sampleData));
     $product->setDownloadableData($downloadableData);
     if ($isGlobalScopeContent) {
         $product->setStoreId(0);
     }
     $product->save();
     return $product->getLastAddedSampleId();
 }
Example #27
0
 /**
  * Get JSON encoded configuration array which can be used for JS dynamic
  * price calculation depending on product options
  *
  * @return string
  */
 public function getJsonConfig()
 {
     $config = array();
     if (!$this->hasOptions()) {
         return $this->_jsonEncoder->encode($config);
     }
     $customerId = $this->getCustomerId();
     /* @var $product \Magento\Catalog\Model\Product */
     $product = $this->getProduct();
     $defaultTax = $this->taxCalculationService->getDefaultCalculatedRate($product->getTaxClassId(), $customerId);
     $currentTax = $this->taxCalculationService->getCalculatedRate($product->getTaxClassId(), $customerId);
     $tierPrices = array();
     $tierPricesList = $product->getPriceInfo()->getPrice('tier_price')->getTierPriceList();
     foreach ($tierPricesList as $tierPrice) {
         $tierPrices[] = $this->_coreData->currency($tierPrice['price']->getValue(), false, false);
     }
     $config = array('productId' => $product->getId(), 'priceFormat' => $this->_localeFormat->getPriceFormat(), 'includeTax' => $this->_taxData->priceIncludesTax() ? 'true' : 'false', 'showIncludeTax' => $this->_taxData->displayPriceIncludingTax(), 'showBothPrices' => $this->_taxData->displayBothPrices(), 'productPrice' => $this->_coreData->currency($product->getPriceInfo()->getPrice('final_price')->getValue(), false, false), 'productOldPrice' => $this->_coreData->currency($product->getPriceInfo()->getPrice('regular_price')->getAmount()->getValue(), false, false), 'inclTaxPrice' => $this->_coreData->currency($product->getPriceInfo()->getPrice('final_price')->getAmount()->getValue(), false, false), 'exclTaxPrice' => $this->_coreData->currency($product->getPriceInfo()->getPrice('final_price')->getAmount()->getBaseAmount(), false, false), 'defaultTax' => $defaultTax, 'currentTax' => $currentTax, 'idSuffix' => '_clone', 'oldPlusDisposition' => 0, 'plusDisposition' => 0, 'plusDispositionTax' => 0, 'oldMinusDisposition' => 0, 'minusDisposition' => 0, 'tierPrices' => $tierPrices);
     $responseObject = new \Magento\Framework\Object();
     $this->_eventManager->dispatch('catalog_product_view_config', array('response_object' => $responseObject));
     if (is_array($responseObject->getAdditionalOptions())) {
         foreach ($responseObject->getAdditionalOptions() as $option => $value) {
             $config[$option] = $value;
         }
     }
     return $this->_jsonEncoder->encode($config);
 }
Example #28
0
 /**
  * @param bool $json
  * @return string|array
  */
 public function getUsers($json = false)
 {
     if ($this->getRequest()->getParam('in_role_user') != "") {
         return $this->getRequest()->getParam('in_role_user');
     }
     $roleId = $this->getRequest()->getParam('rid') > 0 ? $this->getRequest()->getParam('rid') : $this->_coreRegistry->registry('RID');
     $users = $this->_roleFactory->create()->setId($roleId)->getRoleUsers();
     if (sizeof($users) > 0) {
         if ($json) {
             $jsonUsers = [];
             foreach ($users as $usrid) {
                 $jsonUsers[$usrid] = 0;
             }
             return $this->_jsonEncoder->encode((object) $jsonUsers);
         } else {
             return array_values($users);
         }
     } else {
         if ($json) {
             return '{}';
         } else {
             return [];
         }
     }
 }
Example #29
0
 /**
  * Get json representation of
  *
  * @return string
  */
 public function getJsonConfig()
 {
     $config = [];
     foreach ($this->getOptions() as $option) {
         /* @var $option \Magento\Catalog\Model\Product\Option */
         $priceValue = 0;
         if ($option->getGroupByType() == \Magento\Catalog\Model\Product\Option::OPTION_GROUP_SELECT) {
             $tmpPriceValues = [];
             foreach ($option->getValues() as $value) {
                 /* @var $value \Magento\Catalog\Model\Product\Option\Value */
                 $id = $value->getId();
                 $tmpPriceValues[$id] = $this->_getPriceConfiguration($value);
             }
             $priceValue = $tmpPriceValues;
         } else {
             $priceValue = $this->_getPriceConfiguration($option);
         }
         $config[$option->getId()] = $priceValue;
     }
     $configObj = new \Magento\Framework\DataObject(['config' => $config]);
     //pass the return array encapsulated in an object for the other modules to be able to alter it eg: weee
     $this->_eventManager->dispatch('catalog_product_option_price_configuration_after', ['configObj' => $configObj]);
     $config = $configObj->getConfig();
     return $this->_jsonEncoder->encode($config);
 }
Example #30
0
 /**
  * Get categories tree as recursive array
  *
  * @param int $parentId
  * @param bool $asJson
  * @param int $recursionLevel
  * @return array
  */
 public function getTreeArray($parentId = null, $asJson = false, $recursionLevel = 3)
 {
     $productId = $this->_request->getParam('product');
     if ($productId) {
         $product = $this->_productFactory->create()->setId($productId);
         $this->_allowedCategoryIds = $product->getCategoryIds();
         unset($product);
     }
     $result = [];
     if ($parentId) {
         try {
             $category = $this->categoryRepository->get($parentId);
         } catch (NoSuchEntityException $e) {
             $category = null;
         }
         if ($category) {
             $tree = $this->_getNodesArray($this->getNode($category, $recursionLevel));
             if (!empty($tree) && !empty($tree['children'])) {
                 $result = $tree['children'];
             }
         }
     } else {
         $result = $this->_getNodesArray($this->getRoot(null, $recursionLevel));
     }
     if ($asJson) {
         return $this->_jsonEncoder->encode($result);
     }
     $this->_allowedCategoryIds = [];
     return $result;
 }