_id
stringlengths
2
7
title
stringlengths
3
151
partition
stringclasses
3 values
text
stringlengths
83
13k
language
stringclasses
1 value
meta_information
dict
q244100
Sheep_Debug_Block_View_Sidebar.getHttpMethodsSelect
validation
public function getHttpMethodsSelect() { $options = $this->getHttpMethodOptions(); array_unshift($options, array('value' => '', 'label' => 'Any')); /** @var Mage_Core_Block_Html_Select $select */ $select = $this->getLayout()->createBlock('core/html_select'); $select->setName('method') ->setId('method') ->setValue($this->getRequest()->getParam('method')) ->setOptions($options); return $select->getHtml(); }
php
{ "resource": "" }
q244101
Sheep_Debug_Block_View_Sidebar.getLimitOptionsSelect
validation
public function getLimitOptionsSelect() { /** @var Sheep_Debug_Helper_Filter $filterHelper */ $filterHelper = Mage::helper('sheep_debug/filter'); /** @var Mage_Core_Block_Html_Select $select */ $select = $this->getLayout()->createBlock('core/html_select'); $select->setName('limit') ->setId('limit') ->setValue($this->getRequest()->getParam('limit', $filterHelper->getLimitDefaultValue())) ->setOptions($this->getOptionArray($filterHelper->getLimitValues())); return $select->getHtml(); }
php
{ "resource": "" }
q244102
Sheep_Debug_Model_Logging.getRange
validation
public function getRange($logFile) { if (!array_key_exists($logFile, $this->ranges)) { throw new Exception('Invalid log file'); } return $this->ranges[$logFile]; }
php
{ "resource": "" }
q244103
Sheep_Debug_Model_Logging.startRequest
validation
public function startRequest() { foreach ($this->files as $logFile) { $logFilePath = $this->getLogFilePath($logFile); $this->ranges[$logFile] = array( 'start' => $this->getLastFilePosition($logFilePath), 'end' => 0 ); } }
php
{ "resource": "" }
q244104
Sheep_Debug_Model_Logging.getLogging
validation
public function getLogging() { $logging = array(); foreach ($this->files as $logFile) { $logging[$logFile] = $this->getLoggedContent($logFile); } return $logging; }
php
{ "resource": "" }
q244105
Sheep_Debug_Model_Logging.getLastFilePosition
validation
public function getLastFilePosition($filePath) { if (!file_exists($filePath)) { return 0; } $f = fopen($filePath, 'r'); fseek($f, -1, SEEK_END); return ftell($f); }
php
{ "resource": "" }
q244106
Sheep_Debug_Model_Logging.getLoggedContent
validation
public function getLoggedContent($logFile) { if (!array_key_exists($logFile, $this->ranges)) { throw new Exception('Invalid log file'); } return $this->getContent( $this->getLogFilePath($logFile), $this->ranges[$logFile]['start'], $this->ranges[$logFile]['end'] ); }
php
{ "resource": "" }
q244107
Sheep_Debug_Model_Logging.getTotalLineCount
validation
public function getTotalLineCount() { if ($this->logLineCount === null) { $this->logLineCount = 0; foreach ($this->getFiles() as $log) { $this->logLineCount += $this->getLineCount($log); } } return $this->logLineCount; }
php
{ "resource": "" }
q244108
Sheep_Debug_Model_Logging.getContent
validation
public function getContent($filePath, $startPosition, $endPosition) { if (!file_exists($filePath)) { return ''; } // End position not saved yet if (!$endPosition) { return trim(file_get_contents($filePath, null, null, $startPosition)); } // End position exists but is less then start position if ($endPosition <= $startPosition) { return ''; } return trim(file_get_contents($filePath, null, null, $startPosition, $endPosition - $startPosition)); }
php
{ "resource": "" }
q244109
Sheep_Debug_Controller_Front_Action.preDispatch
validation
public function preDispatch() { parent::preDispatch(); if (!Mage::helper('sheep_debug')->isAllowed()) { $this->setFlag('', 'no-dispatch', true); $this->getResponse()->setHttpResponseCode(404); } }
php
{ "resource": "" }
q244110
Sheep_Debug_Controller_Front_Action.renderArray
validation
public function renderArray(array $data, $noDataLabel = 'No Data', $header = null) { /** @var Sheep_Debug_Block_View $block */ $block = $this->getLayout()->createBlock('sheep_debug/view'); $html = $block->renderArray($data, $noDataLabel, $header); $this->getResponse()->setHttpResponseCode(200)->setBody($html); }
php
{ "resource": "" }
q244111
Sheep_Debug_Helper_Config.getExtensionStatus
validation
public function getExtensionStatus() { $status = array(); $extensions = $this->getExtensionRequirements(); foreach ($extensions as $extension) { $status [$extension] = extension_loaded($extension); } return $status; }
php
{ "resource": "" }
q244112
Sheep_Debug_Helper_Config.getModules
validation
public function getModules() { $items = array(); $items[] = array( 'module' => 'Magento', 'codePool' => 'core', 'active' => true, 'version' => $this->getMagentoVersion() ); $modulesConfig = Mage::getConfig()->getModuleConfig(); foreach ($modulesConfig as $node) { foreach ($node as $module => $data) { $items[] = array( 'module' => $module, 'codePool' => (string)$data->codePool, 'active' => $data->active == 'true', 'version' => (string)$data->version ); } } return $items; }
php
{ "resource": "" }
q244113
Sheep_Debug_Model_Model.init
validation
public function init(Mage_Core_Model_Abstract $model) { $this->class = get_class($model); $this->resource = $model->getResourceName(); $this->count = 0; }
php
{ "resource": "" }
q244114
Sheep_Debug_Helper_Filter.getRequestFilters
validation
public function getRequestFilters(Mage_Core_Controller_Request_Http $request) { if (!$this->requestFilterValues) { $filters = $this->getFilterParams(); $this->requestFilterValues = array(); foreach ($filters as $filter) { $param = $request->getParam($filter, null); if ($param !== null) { $this->requestFilterValues[$filter] = $param; } } } return $this->requestFilterValues; }
php
{ "resource": "" }
q244115
Sheep_Debug_ModuleController.enableAction
validation
public function enableAction() { $moduleName = (string)$this->getRequest()->getParam('module'); try { $this->getService()->setModuleStatus($moduleName, true); $this->getService()->flushCache(); Mage::getSingleton('core/session')->addSuccess('Module was enabled.'); } catch (Exception $e) { Mage::getSingleton('core/session')->addError('Unable to enable module: ' . $e->getMessage()); } $this->_redirectReferer(); }
php
{ "resource": "" }
q244116
Sheep_Debug_Helper_Performance.getCategory
validation
public function getCategory($timerName) { $category = self::CORE_CATEGORY; if (strpos($timerName, 'mage::dispatch') === 0 || strpos($timerName, 'column.phtml') > 0) { $category = self::SECTION; } else if (strpos($timerName, 'Model_Resource') > 0) { $category = self::DB_CATEGORY; } else if (strpos($timerName, 'EAV') === 0 || strpos($timerName, '_LOAD_ATTRIBUTE_') === 0 || strpos($timerName, '__EAV_') === 0) { $category = self::EAV_CATEGORY; } else if (strpos($timerName, 'CORE::create_object_of') === 0) { $category = self::CORE_CATEGORY; } else if (strpos($timerName, 'OBSERVER') === 0 || strpos($timerName, 'DISPATCH EVENT') === 0) { $category = self::EVENT_CATEGORY; } else if (strpos($timerName, 'BLOCK') === 0) { $category = self::LAYOUT_CATEGORY; } else if (strpos($timerName, 'init_config') === 0) { $category = self::CONFIG_CATEGORY; } else if (strpos($timerName, 'layout/') === 0 || strpos($timerName, 'layout_') > 0) { $category = self::LAYOUT_CATEGORY; } else if (strpos($timerName, 'Mage_Core_Model_Design') === 0) { $category = self::LAYOUT_CATEGORY; } else if (strpos($timerName, '.phtml') > 0) { $category = self::LAYOUT_CATEGORY; } return $category; }
php
{ "resource": "" }
q244117
Sheep_Debug_Helper_Performance.convertTimers
validation
public function convertTimers(Sheep_Debug_Model_RequestInfo $request) { if (!$request->getTimers()) { return array(); } $requestData = array(); $requestData['id'] = $request->getToken(); $requestData['left'] = 0; $requestData['events'] = array(); $currentTime = 0; /** timer is an array defined by @see Varien_Profiler */ foreach ($request->getTimers() as $name => $timer) { if (!$timer['sum']) { continue; } // convert seconds into microseconds $timer['sum'] *= 1000; $category = $this->getCategory($name); // we don't have start time, end time or multiple periods // so built an estimation of how this event might look assuming that we have only one // occurrence (period) and that it followed immediately after last event $requestData['events'][] = array( 'name' => $name, 'category' => $category, 'origin' => 0, 'starttime' => $currentTime, 'endtime' => $currentTime + $timer['sum'], 'duration' => $timer['sum'], 'memory' => round($timer['realmem'] / pow(2014, 2), 2), 'periods' => array( array('start' => $currentTime, 'end' => $currentTime + $timer['sum']) ) ); // we assume certain events contain the other events (most of the time it makes sense) if ($category != self::SECTION) { $currentTime += $timer['sum']; } } $data = array(); $data['max'] = $currentTime; $data['requests'] = array($requestData); return $data; }
php
{ "resource": "" }
q244118
Sheep_Debug_UtilController.searchGroupClassAction
validation
public function searchGroupClassAction() { if (!$this->getRequest()->isPost()) { $this->getResponse()->setHttpResponseCode(405); return; } $uri = (string)$this->getRequest()->getPost('uri'); $groupType = $this->getRequest()->getPost('group'); $groupTypes = array($groupType); if ($groupType == 'all') { $groupTypes = array('model', 'block', 'helper'); } $items = array(); if ($uri) { foreach ($groupTypes as $type) { $items[$type]['class'] = Mage::getConfig()->getGroupedClassName($type, $uri); $items[$type]['filepath'] = mageFindClassFile($items[$type]['class']); } $block = $this->getLayout()->createBlock('sheep_debug/array'); $block->setTemplate('sheep_debug/grouped_class_search.phtml'); $block->assign('items', $items); $this->getResponse()->setBody($block->toHtml()); } else { $this->getResponse()->setBody($this->__('Please fill in a search query')); } }
php
{ "resource": "" }
q244119
Sheep_Debug_UtilController.enableFPCDebugAction
validation
public function enableFPCDebugAction() { try { $this->getService()->setFPCDebug(1); $this->getService()->flushCache(); $message = $this->__('FPC debug was enabled'); $this->getSession()->addSuccess($message); } catch (Exception $e) { $message = $this->__('FPC debug cannot be enabled: %s', $e->getMessage()); $this->getSession()->addError($message); } $this->_redirectReferer(); }
php
{ "resource": "" }
q244120
Sheep_Debug_UtilController.enableTemplateHintsAction
validation
public function enableTemplateHintsAction() { try { $this->getService()->setTemplateHints(1); $this->getService()->flushCache(); // no need to notify customer - it's obvious if they were enabled } catch (Exception $e) { $message = $this->__('Template hints cannot be enabled: %s', $e->getMessage()); $this->getSession()->addError($message); } $this->_redirectReferer(); }
php
{ "resource": "" }
q244121
Sheep_Debug_UtilController.disableTranslateAction
validation
public function disableTranslateAction() { try { $this->getService()->setTranslateInline(0); $this->getService()->flushCache(); } catch (Exception $e) { $message = $this->__('Translate inline cannot be disabled: %s', $e->getMessage()); $this->getSession()->addError($message); } $this->_redirectReferer(); }
php
{ "resource": "" }
q244122
Sheep_Debug_EmailController.getBodyAction
validation
public function getBodyAction() { if ($email = $this->_initEmail()) { $this->getResponse()->setHeader('Content-Type', $email->getIsPlain() ? 'text/plain' : 'text/html'); $this->getResponse()->setBody($email->getBody()); } }
php
{ "resource": "" }
q244123
Sheep_Debug_EmailController._initEmail
validation
protected function _initEmail() { $token = $this->getRequest()->getParam('token'); $index = $this->getRequest()->getParam('index'); if ($token === null || $index === null) { $this->getResponse()->setHttpResponseCode(400)->setBody('Invalid parameters'); return null; } /** @var Sheep_Debug_Model_RequestInfo $requestProfile */ $requestProfile = Mage::getModel('sheep_debug/requestInfo')->load($token, 'token'); if (!$requestProfile->getId()) { $this->getResponse()->setHttpResponseCode(404)->setBody('Request profile not found'); return null; } $emails = $requestProfile->getEmails(); if (!$emails || !($index < count($emails))) { $this->getResponse()->setHttpResponseCode(404)->setBody('E-mail not found'); return null; } return $emails[(int)$index]; }
php
{ "resource": "" }
q244124
Sheep_Debug_Model_Observer.getRequestInfo
validation
public function getRequestInfo() { if ($this->requestInfo === null) { $this->requestInfo = Mage::getModel('sheep_debug/requestInfo'); } return $this->requestInfo; }
php
{ "resource": "" }
q244125
Sheep_Debug_Model_Observer.startProfiling
validation
public function startProfiling() { // Magento configuration is now available and we can init $this->canCapture = Mage::helper('sheep_debug')->canCapture(); // Are we still allowed to collect if (!$this->canCapture) { return; } $requestInfo = $this->getRequestInfo(); $requestInfo->setIsStarted(true); // Register shutdown function $this->registerShutdown(); // Init profile $requestInfo->setStoreId($this->getCurrentStore()->getId()); $requestInfo->setDate(date('Y-m-d H:i:s')); $requestInfo->initController(); $requestInfo->initLogging(); if (Mage::helper('sheep_debug')->canEnableVarienProfiler()) { Varien_Profiler::enable(); } // use customer Zend Db Profiler that also records stack traces $stackTraceProfiler = Mage::getModel('sheep_debug/db_profiler'); $stackTraceProfiler->setCaptureStacktraces(Mage::helper('sheep_debug')->canEnableSqlStacktrace()); $stackTraceProfiler->replaceProfiler(); }
php
{ "resource": "" }
q244126
Sheep_Debug_Model_Observer.saveProfiling
validation
public function saveProfiling() { if (!$this->canCollect() || !Mage::helper('sheep_debug')->canPersist()) { return; } if (Mage::helper('sheep_debug')->hasDisablePersistenceCookie()) { return; } if (!$this->getRequestInfo()->getIsStarted()) { return; } $this->getRequestInfo()->save(); }
php
{ "resource": "" }
q244127
Sheep_Debug_Model_Observer.onActionPreDispatch
validation
public function onActionPreDispatch(Varien_Event_Observer $observer) { if (!$this->canCollect()) { return; } $action = $observer->getData('controller_action'); // Record action that handled current request $this->getRequestInfo()->initController($action); }
php
{ "resource": "" }
q244128
Sheep_Debug_Model_Observer.onLayoutGenerate
validation
public function onLayoutGenerate(Varien_Event_Observer $observer) { if (!$this->canCollect()) { return; } /** @var Mage_Core_Model_Layout $layout */ $layout = $observer->getData('layout'); $requestInfo = $this->getRequestInfo(); // Adds block description for all blocks generated by layout $layoutBlocks = $layout->getAllBlocks(); foreach ($layoutBlocks as $block) { if (!$this->canCaptureBlock($block)) { continue; } $requestInfo->addBlock($block); } // Update design information /** @var Mage_Core_Model_Design_Package $design */ $design = Mage::getSingleton('core/design_package'); $requestInfo->addLayout($layout, $design); // Save profiler information to get a generated token before rendering toolbar $this->saveProfiling(); }
php
{ "resource": "" }
q244129
Sheep_Debug_Model_Observer.onBlockToHtml
validation
public function onBlockToHtml(Varien_Event_Observer $observer) { if (!$this->canCollect()) { return; } /* @var $block Mage_Core_Block_Abstract */ $block = $observer->getData('block'); // Last chance before rendering toolbar to fetch updates (queries triggered from blocks) if ($block->getNameInLayout() == 'debug_panels') { $this->updateProfiling(); } if (!$this->canCaptureBlock($block)) { return; } $blockName = Mage::helper('sheep_debug')->getBlockName($block); $requestInfo = $this->getRequestInfo(); try { $blockInfo = $requestInfo->getBlock($blockName); } catch (Exception $e) { // block was not found - lets add it now $blockInfo = $requestInfo->addBlock($block); } $blockInfo->startRendering($block); }
php
{ "resource": "" }
q244130
Sheep_Debug_Model_Observer.onCollectionLoad
validation
public function onCollectionLoad(Varien_Event_Observer $observer) { if (!$this->canCollect()) { return; } /** @var Mage_Core_Model_Resource_Db_Collection_Abstract */ $collection = $observer->getData('collection'); $this->getRequestInfo()->addCollection($collection); }
php
{ "resource": "" }
q244131
Sheep_Debug_Model_Observer.onModelLoad
validation
public function onModelLoad(Varien_Event_Observer $observer) { if (!$this->canCollect()) { return; } $model = $observer->getData('object'); $this->getRequestInfo()->addModel($model); }
php
{ "resource": "" }
q244132
Sheep_Debug_Model_Observer.onControllerFrontSendResponseAfter
validation
public function onControllerFrontSendResponseAfter(Varien_Event_Observer $observer) { if (!$this->canCollect()) { return; } /** @var Mage_Core_Controller_Varien_Front $front */ $front = $observer->getData('front'); $this->updateProfiling(); $this->getRequestInfo()->getController()->addResponseInfo($front->getResponse()); }
php
{ "resource": "" }
q244133
Sheep_Debug_Model_Observer.onWebsiteRestriction
validation
public function onWebsiteRestriction(Varien_Event_Observer $observer) { /** @var Mage_Core_Controller_Front_Action $controller */ $controller = $observer->getController(); /** @var Varien_Object $result */ $result = $observer->getResult(); $helper = Mage::helper('sheep_debug'); if ($helper->canShowToolbar() && $controller instanceof Sheep_Debug_Controller_Front_Action) { $result->setShouldProceed(false); } }
php
{ "resource": "" }
q244134
Sheep_Debug_Model_Observer.canCaptureBlock
validation
public function canCaptureBlock($block) { $blockClass = get_class($block); if (!$this->canCaptureCoreBlocks() && strpos($blockClass, 'Mage_') === 0) { return false; } // Don't capture debug blocks if (strpos($blockClass, 'Sheep_Debug_Block') > 0) { return false; } return true; }
php
{ "resource": "" }
q244135
Sheep_Debug_Model_Query.init
validation
public function init(Zend_Db_Profiler_Query $profilerQuery, $stacktrace = '') { $this->queryType = $profilerQuery->getQueryType(); $this->query = $profilerQuery->getQuery(); $this->queryParams = $profilerQuery->getQueryParams(); $this->elapsedSecs = $profilerQuery->getElapsedSecs(); $this->stacktrace = $stacktrace; }
php
{ "resource": "" }
q244136
Sheep_Debug_Model_Core_Email_Capture.send
validation
public function send() { try { $this->captureEmail(); } catch (Exception $e) { Mage::logException($e); } return $this->parentSend(); }
php
{ "resource": "" }
q244137
Sheep_Debug_Model_Core_Email_Capture.captureEmail
validation
public function captureEmail() { $email = Mage::getModel('sheep_debug/email'); $email->setFromEmail($this->getFromEmail()); $email->setFromName($this->getFromName()); $email->setToEmail($this->getToEmail()); $email->setToName($this->getToName()); $email->setSubject($this->getSubject()); $email->setIsPlain($this->getType() != 'html'); $email->setBody($this->getBody()); $email->setIsSmtpDisabled((bool)Mage::getStoreConfigFlag('system/smtp/disable')); $email->setIsAccepted(true); // Assume e-mail is accepted $requestInfo = Mage::getSingleton('sheep_debug/observer')->getRequestInfo(); $requestInfo->addEmail($email); }
php
{ "resource": "" }
q244138
Sheep_Debug_Model_Db_Profiler.replaceProfiler
validation
public function replaceProfiler() { /** @var Magento_Db_Adapter_Pdo_Mysql $connection */ $connection = Mage::getSingleton('core/resource')->getConnection('core_write'); $currentProfile = $connection->getProfiler(); if ($currentProfile) { // Copy queries $this->_queryProfiles = $currentProfile->_queryProfiles; } $this->setEnabled($currentProfile->getEnabled()); $connection->setProfiler($this); }
php
{ "resource": "" }
q244139
Sheep_Debug_Model_Db_Profiler.queryEnd
validation
public function queryEnd($queryId) { $result = $this->parentQueryEnd($queryId); if ($this->captureStacktraces) { $this->stackTraces[$queryId] = $this->getStackTrace(); } return $result; }
php
{ "resource": "" }
q244140
Sheep_Debug_Model_Db_Profiler.getQueryModels
validation
public function getQueryModels() { $queries = array(); foreach ($this->_queryProfiles as $queryId => $queryProfile) { $queryModel = Mage::getModel('sheep_debug/query'); $stacktrace = array_key_exists($queryId, $this->stackTraces) ? $this->stackTraces[$queryId] : ''; $queryModel->init($queryProfile, $stacktrace); $queries[] = $queryModel; } return $queries; }
php
{ "resource": "" }
q244141
Sheep_Debug_Model_Controller.initFromAction
validation
public function initFromAction($action) { if (!$action) { return; } /** @var Mage_Core_Controller_Request_Http $request */ $request = $action->getRequest(); $this->httpMethod = $request->getMethod(); $this->requestOriginalPath = $request->getOriginalPathInfo(); $this->requestPath = $request->getPathInfo(); $this->remoteIp = Mage::helper('core/http')->getRemoteAddr(); $this->routeName = $request->getRouteName(); $this->module = $request->getControllerModule(); $this->class = get_class($action); $this->action = $action->getActionMethodName($request->getActionName()); }
php
{ "resource": "" }
q244142
Sheep_Debug_Model_Controller.addResponseInfo
validation
public function addResponseInfo(Mage_Core_Controller_Response_Http $httpResponse) { $this->responseCode = $httpResponse->getHttpResponseCode(); $this->responseHeaders = array(); $headers = $httpResponse->getHeaders(); foreach ($headers as $header) { $this->responseHeaders[$header['name']] = $header['value']; } }
php
{ "resource": "" }
q244143
Sheep_Debug_ConfigController.downloadAction
validation
public function downloadAction() { $type = $this->getRequest()->getParam('type', 'xml'); /** @var Mage_Core_Model_Config_Element $configNode */ $configNode = Mage::app()->getConfig()->getNode(); switch ($type) { case 'txt'; $this->downloadAsText($configNode); break; case 'xml': default: $this->downloadAsXml($configNode); } }
php
{ "resource": "" }
q244144
Sheep_Debug_ConfigController.downloadAsText
validation
public function downloadAsText(Mage_Core_Model_Config_Element $configNode) { $items = array(); Mage::helper('sheep_debug')->xml2array($configNode, $items); $content = ''; foreach ($items as $key => $value) { $content .= "$key = $value\n"; } $this->_prepareDownloadResponse('config.txt', $content, 'text/plain'); }
php
{ "resource": "" }
q244145
Sheep_Debug_Model_Core_Email_Template_Capture.send
validation
public function send($email, $name = null, array $variables = array()) { // store a reference to mail object that get populate by parent send() $zendMail = $this->getMail(); $result = $this->parentSend($email, $name, $variables); try { $this->addEmailToProfile($email, $name, $variables, $result, $zendMail); } catch (Exception $e) { Mage::logException($e); } return $result; }
php
{ "resource": "" }
q244146
Sheep_Debug_Model_Core_Email_Template_Capture.addEmailToProfile
validation
public function addEmailToProfile($email, $name, $variables, $result, Zend_Mail $mail) { $emailCapture = Mage::getModel('sheep_debug/email'); $subject = $this->decodeSubject($mail->getSubject()); $body = $this->getContent($mail); $emailCapture->setFromName($this->getSenderName()); $emailCapture->setFromEmail($this->getSenderEmail()); $emailCapture->setToEmail($email); $emailCapture->setToName($name); $emailCapture->setSubject($subject); $emailCapture->setIsPlain($this->isPlain()); $emailCapture->setBody($body); $emailCapture->setIsAccepted($result); $emailCapture->setVariables($variables); $emailCapture->setIsSmtpDisabled((bool)Mage::getStoreConfigFlag('system/smtp/disable')); Mage::getSingleton('sheep_debug/observer')->getRequestInfo()->addEmail($emailCapture); }
php
{ "resource": "" }
q244147
Sheep_Debug_Model_Core_Email_Template_Capture.getContent
validation
public function getContent(Zend_Mail $mail) { $hasQueue = $this->hasQueue(); if ($hasQueue && $queue = $this->getQueue()) { return $queue->getMessageBody(); } /** @var Zend_Mime_Part $mimePart */ $mimePart = $this->isPlain() ? $mail->getBodyText() : $mail->getBodyHtml(); return $mimePart ? $this->getPartDecodedContent($mimePart) : ''; }
php
{ "resource": "" }
q244148
Sheep_Debug_Model_Core_Email_Template_Capture.getPartDecodedContent
validation
public function getPartDecodedContent(Zend_Mime_Part $mimePart) { // getRawContent is not available in Zend 1.11 (Magento CE 1.7) if (method_exists($mimePart, 'getRawContent')) { return $mimePart->getRawContent(); } $content = ''; if (method_exists($mimePart, 'getContent')) { $encoding = $mimePart->encoding; $mimePart->encoding = 'none'; $content = $mimePart->getContent(); $mimePart->encoding = $encoding; } return $content; }
php
{ "resource": "" }
q244149
Sheep_Debug_Model_Core_Email_Template_Capture.decodeSubject
validation
public function decodeSubject($subject) { if ($this->hasQueue() && $queue = $this->getQueue()) { return $queue->getMessageParameters('subject'); } return base64_decode(substr($subject, strlen('=?utf-8?B?'), -1 * strlen('?='))); }
php
{ "resource": "" }
q244150
Sheep_Debug_Helper_Data.getModuleVersion
validation
public function getModuleVersion() { /** @var Mage_Core_Model_Config_Element $moduleConfig */ $moduleConfig = $this->getConfig()->getModuleConfig($this->getModuleName()); return (string)$moduleConfig->version; }
php
{ "resource": "" }
q244151
Sheep_Debug_Helper_Data.runSql
validation
public function runSql($query, $queryParams = array()) { /** @var Magento_Db_Adapter_Pdo_Mysql $connection */ $connection = Mage::getSingleton('core/resource')->getConnection('core_write'); /** @var Varien_Db_Statement_Pdo_Mysql $statement */ $statement = $connection->query($query, $queryParams); return $statement->fetchAll(PDO::FETCH_ASSOC); }
php
{ "resource": "" }
q244152
Sheep_Debug_Helper_Data.xml2array
validation
public function xml2array($xml, array &$arr, $parentKey = '') { if (!$xml) { return; } if (count($xml->children()) == 0) { $arr[$parentKey] = (string)$xml; } else { foreach ($xml->children() as $key => $item) { $key = $parentKey ? $parentKey . DS . $key : $key; $this->xml2array($item, $arr, $key); } } return $arr; }
php
{ "resource": "" }
q244153
Sheep_Debug_Helper_Data.formatNumber
validation
public function formatNumber($number, $precision = 2) { $locale = Mage::app()->getLocale()->getLocale(); return Zend_Locale_Format::toNumber($number, array('locale' => $locale, 'precision' => $precision)); }
php
{ "resource": "" }
q244154
Sheep_Debug_Helper_Data.formatMemorySize
validation
public function formatMemorySize($size, $precision = 2) { $sizes = array(" Bytes", " KB", " MB", " GB", " TB", " PB", " EB", " ZB", " YB"); if ($size == 0) { return $this->__('n/a'); } else { $value = round($size / pow(1000, ($i = floor(log($size, 1000)))), $precision); $unitIndex = (int)$i; return $this->__('%s%s', $this->formatNumber($value, $precision), $sizes[$unitIndex]); } }
php
{ "resource": "" }
q244155
Sheep_Debug_Helper_Data.formatStacktrace
validation
public function formatStacktrace(array $trace, $stripFilepath = '', $trimPath = '') { $out = ''; foreach ($trace as $index => $row) { if ($stripFilepath && isset($row['file']) && strpos($row['file'], $stripFilepath) !== false) { continue; } if ($trimPath && isset($row['file'])) { $row['file'] = str_replace($trimPath, '', $row['file']); } if (isset($row['file'])) { $out .= "[$index] {$row['file']}:{$row['line']}\n"; } else { // sometimes there is undefined index 'file' $out .= "[$index] (?) {$row['class']}:{$row['function']}\n"; } } return $out; }
php
{ "resource": "" }
q244156
Sheep_Debug_Helper_Data.getLayoutUpdatesFiles
validation
public function getLayoutUpdatesFiles($storeId, $designArea) { $updatesRoot = $this->getConfig()->getNode($designArea . '/layout/updates'); // Find files with layout updates $updateFiles = array(); /** @var Mage_Core_Model_Config_Element $updateNode */ foreach ($updatesRoot->children() as $updateNode) { if ($updateNode->file) { $module = $updateNode->getAttribute('module'); if ($module && Mage::getStoreConfigFlag('advanced/modules_disable_output/' . $module, $storeId)) { continue; } $updateFiles[] = (string)$updateNode->file; } } // custom local layout updates file $updateFiles[] = 'local.xml'; return $updateFiles; }
php
{ "resource": "" }
q244157
DotenvGetKeysCommand.stringToType
validation
protected function stringToType($string) { if (is_string($string)) { switch (true) { case ($string == 'null' || $string == 'NULL'): $string = null; break; case ($string == 'true' || $string == 'TRUE'): $string = true; break; case ($string == 'false' || $string == 'FALSE'): $string = false; break; default: break; } } return $string; }
php
{ "resource": "" }
q244158
DotenvWriter.ensureFileIsWritable
validation
protected function ensureFileIsWritable($filePath) { if ((is_file($filePath) && !is_writable($filePath)) || (!is_file($filePath) && !is_writable(dirname($filePath)))) { throw new UnableWriteToFileException(sprintf('Unable to write to the file at %s.', $filePath)); } }
php
{ "resource": "" }
q244159
DotenvWriter.appendSetter
validation
public function appendSetter($key, $value = null, $comment = null, $export = false) { $line = $this->formatter->formatSetterLine($key, $value, $comment, $export); return $this->appendLine($line); }
php
{ "resource": "" }
q244160
DotenvWriter.updateSetter
validation
public function updateSetter($key, $value = null, $comment = null, $export = false) { $pattern = "/^(export\h)?\h*{$key}=.*/m"; $line = $this->formatter->formatSetterLine($key, $value, $comment, $export); $this->buffer = preg_replace($pattern, $line, $this->buffer); return $this; }
php
{ "resource": "" }
q244161
DotenvWriter.deleteSetter
validation
public function deleteSetter($key) { $pattern = "/^(export\h)?\h*{$key}=.*\n/m"; $this->buffer = preg_replace($pattern, null, $this->buffer); return $this; }
php
{ "resource": "" }
q244162
DotenvWriter.save
validation
public function save($filePath) { $this->ensureFileIsWritable($filePath); file_put_contents($filePath, $this->buffer); return $this; }
php
{ "resource": "" }
q244163
DotenvReader.ensureFileIsReadable
validation
protected function ensureFileIsReadable() { if (!is_readable($this->filePath) || !is_file($this->filePath)) { throw new UnableReadFileException(sprintf('Unable to read the file at %s.', $this->filePath)); } }
php
{ "resource": "" }
q244164
DotenvReader.lines
validation
public function lines() { $content = []; $lines = $this->readLinesFromFile(); foreach ($lines as $row => $line) { $data = [ 'line' => $row+1, 'raw_data' => $line, 'parsed_data' => $this->formatter->parseLine($line) ]; $content[] = $data; } return $content; }
php
{ "resource": "" }
q244165
DotenvFormatter.formatSetterLine
validation
public function formatSetterLine($key, $value = null, $comment = null, $export = false) { $forceQuotes = (strlen($comment) > 0 && strlen(trim($value)) == 0); $value = $this->formatValue($value, $forceQuotes); $key = $this->formatKey($key); $comment = $this->formatComment($comment); $export = $export ? 'export ' : ''; $line = "{$export}{$key}={$value}{$comment}"; return $line; }
php
{ "resource": "" }
q244166
DotenvFormatter.normaliseValue
validation
public function normaliseValue($value, $quote = '') { if (strlen($quote) == 0) { return trim($value); } $value = str_replace("\\$quote", $quote, $value); $value = str_replace('\\\\', '\\', $value); return $value; }
php
{ "resource": "" }
q244167
DotenvEditor.load
validation
public function load($filePath = null, $restoreIfNotFound = false, $restorePath = null) { $this->resetContent(); if (! is_null($filePath)) { $this->filePath = $filePath; } else { if (method_exists($this->app, 'environmentPath') && method_exists($this->app, 'environmentFile')) { $this->filePath = $this->app->environmentPath().'/'.$this->app->environmentFile(); } else { $this->filePath = __DIR__.'/../../../../../../.env'; } } $this->reader->load($this->filePath); if (file_exists($this->filePath)) { $this->writer->setBuffer($this->getContent()); return $this; } elseif ($restoreIfNotFound) { return $this->restore($restorePath); } else { return $this; } }
php
{ "resource": "" }
q244168
DotenvEditor.resetContent
validation
protected function resetContent() { $this->filePath = null; $this->reader->load(null); $this->writer->setBuffer(null); }
php
{ "resource": "" }
q244169
DotenvEditor.getKeys
validation
public function getKeys($keys = []) { $allKeys = $this->reader->keys(); return array_filter($allKeys, function ($key) use ($keys) { if (!empty($keys)) { return in_array($key, $keys); } return true; }, ARRAY_FILTER_USE_KEY); }
php
{ "resource": "" }
q244170
DotenvEditor.keyExists
validation
public function keyExists($key) { $allKeys = $this->getKeys(); if (array_key_exists($key, $allKeys)) { return true; } return false; }
php
{ "resource": "" }
q244171
DotenvEditor.getValue
validation
public function getValue($key) { $allKeys = $this->getKeys([$key]); if (array_key_exists($key, $allKeys)) { return $allKeys[$key]['value']; } throw new KeyNotFoundException('Requested key not found in your file.'); }
php
{ "resource": "" }
q244172
DotenvEditor.setKeys
validation
public function setKeys($data) { foreach ($data as $setter) { if (array_key_exists('key', $setter)) { $key = $this->formatter->formatKey($setter['key']); $value = array_key_exists('value', $setter) ? $setter['value'] : null; $comment = array_key_exists('comment', $setter) ? $setter['comment'] : null; $export = array_key_exists('export', $setter) ? $setter['export'] : false; if (!is_file($this->filePath) || !$this->keyExists($key)) { $this->writer->appendSetter($key, $value, $comment, $export); } else { $oldInfo = $this->getKeys([$key]); $comment = is_null($comment) ? $oldInfo[$key]['comment'] : $comment; $this->writer->updateSetter($key, $value, $comment, $export); } } } return $this; }
php
{ "resource": "" }
q244173
DotenvEditor.setKey
validation
public function setKey($key, $value = null, $comment = null, $export = false) { $data = [compact('key', 'value', 'comment', 'export')]; return $this->setKeys($data); }
php
{ "resource": "" }
q244174
DotenvEditor.deleteKeys
validation
public function deleteKeys($keys = []) { foreach ($keys as $key) { $this->writer->deleteSetter($key); } return $this; }
php
{ "resource": "" }
q244175
DotenvEditor.save
validation
public function save() { if (is_file($this->filePath) && $this->autoBackup) { $this->backup(); } $this->writer->save($this->filePath); return $this; }
php
{ "resource": "" }
q244176
DotenvEditor.backup
validation
public function backup() { if (!is_file($this->filePath)) { throw new FileNotFoundException("File does not exist at path {$this->filePath}"); return false; } copy( $this->filePath, $this->backupPath . self::BACKUP_FILENAME_PREFIX . date('Y_m_d_His') . self::BACKUP_FILENAME_SUFFIX ); return $this; }
php
{ "resource": "" }
q244177
DotenvEditor.getBackups
validation
public function getBackups() { $backups = array_diff(scandir($this->backupPath), array('..', '.')); $output = []; foreach ($backups as $backup) { $filenamePrefix = preg_quote(self::BACKUP_FILENAME_PREFIX, '/'); $filenameSuffix = preg_quote(self::BACKUP_FILENAME_SUFFIX, '/'); $filenameRegex = '/^' .$filenamePrefix. '(\d{4})_(\d{2})_(\d{2})_(\d{2})(\d{2})(\d{2})' .$filenameSuffix. '$/'; $datetime = preg_replace($filenameRegex, '$1-$2-$3 $4:$5:$6', $backup); $data = [ 'filename' => $backup, 'filepath' => $this->backupPath . $backup, 'created_at' => $datetime, ]; $output[] = $data; } return $output; }
php
{ "resource": "" }
q244178
DotenvEditor.restore
validation
public function restore($filePath = null) { if (is_null($filePath)) { $latestBackup = $this->getLatestBackup(); if (is_null($latestBackup)) { throw new NoBackupAvailableException("There are no available backups!"); } $filePath = $latestBackup['filepath']; } if (!is_file($filePath)) { throw new FileNotFoundException("File does not exist at path {$filePath}"); } copy($filePath, $this->filePath); $this->writer->setBuffer($this->getContent()); return $this; }
php
{ "resource": "" }
q244179
DotenvEditor.deleteBackups
validation
public function deleteBackups($filePaths = []) { if (empty($filePaths)) { $allBackups = $this->getBackups(); foreach ($allBackups as $backup) { $filePaths[] = $backup['filepath']; } } foreach ($filePaths as $filePath) { if (is_file($filePath)) { unlink($filePath); } } return $this; }
php
{ "resource": "" }
q244180
UnitOfMeasure.linearUnitFactory
validation
public static function linearUnitFactory($name, $toNativeUnitFactor) { return new static( $name, function ($valueInNativeUnit) use ($toNativeUnitFactor) { return $valueInNativeUnit / $toNativeUnitFactor; }, function ($valueInThisUnit) use ($toNativeUnitFactor) { return $valueInThisUnit * $toNativeUnitFactor; } ); }
php
{ "resource": "" }
q244181
AbstractPhysicalQuantity.addUnit
validation
public static function addUnit(UnitOfMeasureInterface $unit) { if (static::unitNameOrAliasesAlreadyRegistered($unit)) { throw new Exception\DuplicateUnitNameOrAlias([ ':labels' => implode(', ', array_merge([$unit->getName()], $unit->getAliases())) ]); } static::$unitDefinitions[] = $unit; }
php
{ "resource": "" }
q244182
AbstractPhysicalQuantity.getUnit
validation
public static function getUnit($unit) { // If this class hasn't been initialized yet, do so now if (!is_array(static::$unitDefinitions)) { static::$unitDefinitions = []; static::initialize(); } $key = static::buildUnitCacheKey($unit); if (isset(self::$unitCache[$key])) { return self::$unitCache[$key]; } foreach (static::$unitDefinitions as $unitOfMeasure) { if ($unit === $unitOfMeasure->getName() || $unitOfMeasure->isAliasOf($unit)) { return self::$unitCache[$key] = $unitOfMeasure; } } throw new Exception\UnknownUnitOfMeasure([':unit' => $unit]); }
php
{ "resource": "" }
q244183
AbstractPhysicalQuantity.unitNameOrAliasesAlreadyRegistered
validation
protected static function unitNameOrAliasesAlreadyRegistered(UnitOfMeasureInterface $unit) { // If this class hasn't been initialized yet, do so now if (!is_array(static::$unitDefinitions)) { static::$unitDefinitions = []; static::initialize(); } $currentUnitNamesAndAliases = []; foreach (static::$unitDefinitions as $unitOfMeasure) { $currentUnitNamesAndAliases[] = $unitOfMeasure->getName(); $currentUnitNamesAndAliases = array_merge($currentUnitNamesAndAliases, $unitOfMeasure->getAliases()); } $newUnitNamesAndAliases = array_merge([$unit->getName()], $unit->getAliases()); return count(array_intersect($currentUnitNamesAndAliases, $newUnitNamesAndAliases)) > 0; }
php
{ "resource": "" }
q244184
HasRoles.hasRoleWithPermission
validation
public function hasRoleWithPermission($permission) { return $this->roles->contains(function ($role) use ($permission) { return $role->getPermissions->contains('permission_slug', $permission); }); }
php
{ "resource": "" }
q244185
HasRoles.assignRole
validation
public function assignRole($role) { if (is_string($role)) { return $this->roles()->attach(Role::where('slug', $role)->first()); } return $this->roles()->attach($role); }
php
{ "resource": "" }
q244186
HasRoles.removeRole
validation
public function removeRole($role) { if (is_string($role)) { return $this->roles()->detach(Role::where('slug', $role)->first()); } return $this->roles()->detach($role); }
php
{ "resource": "" }
q244187
HasRoles.setRolesById
validation
public function setRolesById($roles) { $roles = is_array($roles)? $roles : [$roles]; return $this->roles()->sync($roles); }
php
{ "resource": "" }
q244188
Role.grant
validation
public function grant($permission) { if ($this->hasPermission($permission)) { return true; } if (!array_key_exists($permission, Gate::abilities())) { abort(403, 'Unknown permission'); } return Permission::create([ 'role_id' => $this->id, 'permission_slug' => $permission, ]); return false; }
php
{ "resource": "" }
q244189
RoboFile.release
validation
public function release($version) { $package = 'upyun/sdk'; $name = 'php-sdk'; $collection = $this->collectionBuilder(); $workingPath = __DIR__ . DIRECTORY_SEPARATOR . $collection->workDir("release"); $collection->taskExec("composer create-project {$package} {$name} {$version}") ->dir($workingPath) ->arg('--prefer-dist') ->arg('--no-dev') ->arg('-vvv') ->taskExec('composer dump-autoload --optimize') ->dir($workingPath . DIRECTORY_SEPARATOR . $name) ->arg('-vvv'); $collection->run(); $zipFile = "release/{$name}-{$version}.zip"; $this->_remove($zipFile); $this->taskPack($zipFile) ->addDir("php-sdk", __DIR__ . "/release/php-sdk") ->run(); $this->_deleteDir("release/$name"); }
php
{ "resource": "" }
q244190
DataLoader.dispatchQueue
validation
private function dispatchQueue() { // Take the current loader queue, replacing it with an empty queue. $queue = $this->queue; $this->queue = []; $queueLength = count($queue); // If a maxBatchSize was provided and the queue is longer, then segment the // queue into multiple batches, otherwise treat the queue as a single batch. $maxBatchSize = $this->options->getMaxBatchSize(); if ($maxBatchSize && $maxBatchSize > 0 && $maxBatchSize < $queueLength) { for ($i = 0; $i < $queueLength / $maxBatchSize; $i++) { $offset = $i * $maxBatchSize; $length = ($i + 1) * $maxBatchSize - $offset; $this->dispatchQueueBatch(array_slice($queue, $offset, $length)); } } else { $this->dispatchQueueBatch($queue); } }
php
{ "resource": "" }
q244191
DataLoader.failedDispatch
validation
private function failedDispatch($queue, \Exception $error) { foreach ($queue as $index => $data) { $this->clear($data['key']); $data['reject']($error); } }
php
{ "resource": "" }
q244192
TextParser.parseText
validation
public function parseText($text, $findMatchingTemplate = false) { $this->logger->info(sprintf('Parsing: %s', $text)); $text = $this->prepareText($text); $matchedTemplates = $this->getTemplates($text, $findMatchingTemplate); foreach ($matchedTemplates as $templatePath => $templateContent) { $this->logger->debug(sprintf('Parsing against template: %s', $templatePath)); $templatePattern = $this->prepareTemplate($templateContent); $extractedData = $this->extractData($text, $templatePattern); if ($extractedData) { $this->logger->info(sprintf('Data extracted: %s', json_encode($extractedData))); return $extractedData; } } return null; }
php
{ "resource": "" }
q244193
TextParser.prepareTemplate
validation
protected function prepareTemplate($templateTxt) { $patterns = [ '/\\\{%(.*)%\\\}/U', // 1 Replace all {%Var%}... '/\s+/', // 2 Replace all white-spaces... ]; $replacements = [ '(?<$1>.*)', // 1 ...with (?<Var>.*) ' ', // 2 ...with a single space ]; $templateTxt = preg_replace($patterns, $replacements, preg_quote($templateTxt, '/')); return trim($templateTxt); }
php
{ "resource": "" }
q244194
TextParser.extractData
validation
protected function extractData($text, $template) { //Extract the text based on the provided template using REGEX preg_match('/' . $template . '/s', $text, $matches); //Extract only the named parameters from the matched regex array $keys = array_filter(array_keys($matches), 'is_string'); $matches = array_intersect_key($matches, array_flip($keys)); if (!empty($matches)) { return $this->cleanExtractedData($matches); } return false; }
php
{ "resource": "" }
q244195
TextParser.findTemplate
validation
protected function findTemplate($text) { $matchedTemplate = []; $maxMatch = -1; foreach ($this->directoryIterator as $fileInfo) { $templateContent = file_get_contents($fileInfo->getPathname()); similar_text($text, $templateContent, $matchPercentage); //Compare template against text to decide on similarity percentage if ($matchPercentage > $maxMatch) { $this->logger->debug(sprintf('Template "%s" is a best match for now', $fileInfo->getPathname())); $maxMatch = $matchPercentage; $matchedTemplate = [$fileInfo->getPathname() => $templateContent]; } } return $matchedTemplate; }
php
{ "resource": "" }
q244196
PhpSerial.PhpSerial
validation
public function PhpSerial() { setlocale(LC_ALL, "en_US"); $sysName = php_uname(); if (substr($sysName, 0, 5) === "Linux") { $this->_os = "linux"; if ($this->_exec("stty") === 0) { register_shutdown_function(array($this, "deviceClose")); } else { trigger_error( "No stty availible, unable to run.", E_USER_ERROR ); } } elseif (substr($sysName, 0, 6) === "Darwin") { $this->_os = "osx"; register_shutdown_function(array($this, "deviceClose")); } elseif (substr($sysName, 0, 7) === "Windows") { $this->_os = "windows"; register_shutdown_function(array($this, "deviceClose")); } else { trigger_error("Host OS is neither osx, linux nor windows, unable " . "to run.", E_USER_ERROR); exit(); } }
php
{ "resource": "" }
q244197
PhpSerial.deviceClose
validation
public function deviceClose() { if ($this->_dState !== SERIAL_DEVICE_OPENED) { return true; } if (fclose($this->_dHandle)) { $this->_dHandle = null; $this->_dState = SERIAL_DEVICE_SET; return true; } trigger_error("Unable to close the device", E_USER_ERROR); return false; }
php
{ "resource": "" }
q244198
PhpSerial.confCharacterLength
validation
public function confCharacterLength($int) { if ($this->_dState !== SERIAL_DEVICE_SET) { trigger_error("Unable to set length of a character : the device " . "is either not set or opened", E_USER_WARNING); return false; } $int = (int) $int; if ($int < 5) { $int = 5; } elseif ($int > 8) { $int = 8; } if ($this->_os === "linux") { $ret = $this->_exec( "stty -F " . $this->_device . " cs" . $int, $out ); } elseif ($this->_os === "osx") { $ret = $this->_exec( "stty -f " . $this->_device . " cs" . $int, $out ); } else { $ret = $this->_exec( "mode " . $this->_winDevice . " DATA=" . $int, $out ); } if ($ret === 0) { return true; } trigger_error( "Unable to set character length : " .$out[1], E_USER_WARNING ); return false; }
php
{ "resource": "" }
q244199
PhpSerial.confStopBits
validation
public function confStopBits($length) { if ($this->_dState !== SERIAL_DEVICE_SET) { trigger_error("Unable to set the length of a stop bit : the " . "device is either not set or opened", E_USER_WARNING); return false; } if ($length != 1 and $length != 2 and $length != 1.5 and !($length == 1.5 and $this->_os === "linux") ) { trigger_error( "Specified stop bit length is invalid", E_USER_WARNING ); return false; } if ($this->_os === "linux") { $ret = $this->_exec( "stty -F " . $this->_device . " " . (($length == 1) ? "-" : "") . "cstopb", $out ); } elseif ($this->_os === "osx") { $ret = $this->_exec( "stty -f " . $this->_device . " " . (($length == 1) ? "-" : "") . "cstopb", $out ); } else { $ret = $this->_exec( "mode " . $this->_winDevice . " STOP=" . $length, $out ); } if ($ret === 0) { return true; } trigger_error( "Unable to set stop bit length : " . $out[1], E_USER_WARNING ); return false; }
php
{ "resource": "" }