Convert PHP script to be compatible with magento 2 - php

PHP script used:
$product=Mage::getModel('core/store');
$product->load($order->getStoreId());
$value=$product->getWebsiteId();
return $value;
if (strpos($value, '1') !== false) {
return "34501";
}
else if (strpos($value, '3') !== false) {
return "34502";
}
else if (strpos($value, '2') !== false) {
return "34503";
}
Example of expected result:
34501
I tried many times but I did't found anything can you help me out this is my first task

You need to optimize your code. Please check below if it could be helpful for you. And also, check the conditions you have used; it might be the case the product could not be found with the passing id you have used. Could you handle this try-and-catch statement?
Better to use a switch case statement.
$product=Mage::getModel('core/store');
$product->load($order->getStoreId());
$value=$product->getWebsiteId();
try {
if (strpos($value, '1') !== false) {
return "34501";
}
else if (strpos($value, '3') !== false) {
return "34502";
}
else if (strpos($value, '2') !== false) {
return "34503";
}
else {
throw new Exception('Value Not Found');
}
}
catch(Exception $e) {
echo $e->getMessage(), "\n";
}
OR
$product=Mage::getModel('core/store');
$product->load($order->getStoreId());
$value=$product->getWebsiteId();
if (strpos($value, '1') !== false) {
return "34501";
}
else if (strpos($value, '3') !== false) {
return "34502";
}
else if (strpos($value, '2') !== false) {
return "34503";
}
else {
return 'Value not found';
}
Thanks

Related

Trying to access array offset on value of type int { DefaultValueBinder.php line 82 }

I have an export to excel button which downloads excel file.
However when i click it shows me error as Trying to access array offset on value of type int
My code is this:
public static function dataTypeForValue($pValue = null)
{
// Match the value against a few data types
if ($pValue === null) {
return PHPExcel_Cell_DataType::TYPE_NULL;
} elseif ($pValue === '') {
return PHPExcel_Cell_DataType::TYPE_STRING;
} elseif ($pValue instanceof PHPExcel_RichText) {
return PHPExcel_Cell_DataType::TYPE_INLINE;
} elseif ($pValue[0] === '=' && strlen($pValue) > 1) { //error comes in this line
return PHPExcel_Cell_DataType::TYPE_FORMULA;
} elseif (is_bool($pValue)) {
return PHPExcel_Cell_DataType::TYPE_BOOL;
} elseif (is_float($pValue) || is_int($pValue)) {
return PHPExcel_Cell_DataType::TYPE_NUMERIC;
} elseif (preg_match('/^[\+\-]?([0-9]+\\.?[0-9]*|[0-9]*\\.?[0-9]+)([Ee][\-\+]?[0-2]?\d{1,3})?$/', $pValue)) {
$tValue = ltrim($pValue, '+-');
if (is_string($pValue) && $tValue[0] === '0' && strlen($tValue) > 1 && $tValue[1] !== '.') {
return PHPExcel_Cell_DataType::TYPE_STRING;
} elseif ((strpos($pValue, '.') === false) && ($pValue > PHP_INT_MAX)) {
return PHPExcel_Cell_DataType::TYPE_STRING;
}
return PHPExcel_Cell_DataType::TYPE_NUMERIC;
} elseif (is_string($pValue) && array_key_exists($pValue, PHPExcel_Cell_DataType::getErrorCodes())) {
return PHPExcel_Cell_DataType::TYPE_ERROR;
}
return PHPExcel_Cell_DataType::TYPE_STRING;
}
}
what can be the solution for this..?
In the PHPExcel file "DefaultValueBinder.php", replace this line 82:
} elseif ($pValue[0] === '=' && strlen($pValue) > 1) {
with the following:
} elseif (0 === strpos($pValue, '=') && strlen($pValue) > 1) {
(!is_int($pValue) && $pValue[0] === '=' && strlen($pValue) > 1) should work. $pValue[0] will not work with integers so check if it is an int or not before continuing.
I update some files in library and It's work fine for me at php 7.4
Please check updated code library :
Google Drive LInk

Why is strpos working the first time, but not the second?

I´m using strpos two timer. In the first if/else it works well but in the second it doesn´t work. This is my code:
if (strpos($word, "mono") == true) {
$type = "Monobloc";
} else {
$type = "Articulated";
}
if ($word, "galva") == true) {
$coating = "Galvanized Rod";
} elseif (strpos($word, "epoxi") == true) {
$coating = "EPOXI 100%";
} elseif ($word, "electro") == true) {
$coating = "Electrozinced";
}
Example:
If the variable word has the value "galva-mono" $type should be "Monobloc" and $coating should be "Galvanized Rod". The problem is that it is assigning well the $type but in the coating it doen´t enter in the if clause.
As stated in the official documentation:
Warning
This function may return Boolean FALSE, but may also return a
non-Boolean value which evaluates to FALSE. Please read the section on
Booleans for more information. Use the === operator for testing the
return value of this function.
You are checking the result with == true instead of !== false.
So, try this code:
if (strpos($word, "mono") !== false) {
$type = "Monobloc";
} else {
$type = "Articulated";
}
if (strpos($word, "galva") !== false) {
$coating = "Galvanized Rod";
} elseif (strpos($word, "epoxi") !== false) {
$coating = "EPOXI 100%";
} elseif (strpos($word, "electro") !== false) {
$coating = "Electrozinced";
}

Put foreach data into a varible and add the varible to a database

I've been searching and I've tried multiple ways with no luck, What's happening in my code looks for a link. It will then determine what type of link it is and adjust it to suit my needs. Once adjusted I need it to go into an Array with the end goal of adding that Array to my database. print_r($items) will be where ill be adding the array to the Database if you know how do do this also I will not say no to the help :D I am guessing it the same as adding a variable to the database.
Here is my code so far :)
//Lets look for links
$urlcomp = array();
$items = array();
foreach($html->find('a') as $element){
if( strpos( $element->href, "http" ) !== false) {
$urlcomp[] = $element->href;
// Look for gov websites
if ((strpos($urlcomp, 'gov') !== false) || (strpos($urlcomp, 'police') !== false) || (strpos($urlcomp, 'nhs') !== false) || (strpos($urlcomp, 'org') !== false) || (strpos($urlcomp, 'council') !== false)){
} else {
if (in_array($urlcomp, $websiteurlall)) {
}else{
echo "First Batch - " . $urlcomp;
$items[] = array($urlcomp);
echo "</br>";
}
}
}else{
$urlcomp = $websiteurlcomp.$element->href;
// Look for gov websites
if ((strpos($urlcomp, 'gov') !== false) || (strpos($urlcomp, 'police') !== false) || (strpos($urlcomp, 'nhs') !== false) || (strpos($urlcomp, 'org') !== false) || (strpos($urlcomp, 'council') !== false)){
} else {
if (in_array($urlcomp, $websiteurlall)) {
}else{
echo "Second Batch - " . $urlcomp;
$items[] = array($urlcomp);
echo "</br>";
}
}
}
}
print_r($items);
$urlcomp[] = $element->href; should have been $urlcomp = $element->href; that was the only issue :S

Error in PHP Generator

What is the best way to inform who use my generator function if something errors occurs, instead of writing weird return or raising exception like this piece of code
function csv_file_generator($csvFilename, $delimiter = ";", $enclousure = '"') {
if(($csvHandler = fopen($csvFilename, 'rb')) === false) {
return;
}
while (($row = fgetcsv($csvHandler, 0, $delimiter, $enclousure)) !== false) {
yield $row;
}
if (feof($csvHandler) === false) {
return;
}
if (fclose($csvHandler) === false) {
return;
}
return; /* Exit Generator */
}
<?php
class CsvFileGenerator {
protected $fp;
protected $delimiter;
protected $enclousure;
public function __construct($filename, $delimiter = ";", $enclousure = '"'){
$this->delimiter=$delimiter;
$this->enclousure=$enclousure;
if(!file_exists($filename)){
throw new Exception("file [$filename] dont exists");
}
if(!is_readable($filename)){
throw new Exception("file [$filename] is not readable");
}
$this->fp = fopen($filename, 'rb');
if($this->fp === false){
throw new Exception("cant open [$filename]");
}
}
public function getGenerator(){
while (($row = fgetcsv($this->fp, 0, $this->delimiter, $this->enclousure)) !== false) {
yield $row;
}
}
public function __destruct() {
if($this->fp){
fclose($this->fp);
}
}
}
foreach( (new CsvFileGenerator('mycsvfile.csv'))->getGenerator() as $line){
#do some
}
One way to rome. :-)
How about callbacks?
function gen($i, $on_close = null, $on_error = null) {
while ($i--) {
yield $i;
if ($i === 5 && is_callable($on_close)) {
$on_close();
}
}
}
$closed = false;
$gen = gen(10, function () use (&$closed) {
$closed = true;
});
foreach ($gen as $x) {
if ($closed) {
break;
}
echo $x, PHP_EOL;
}
I'll admit its not pretty. Another options could be to return instances of special classes to let your main code know something is wrong.

How to delete all files under a specified directory with PHP?

I think the title is clear.
$dir = '/some/path/to/delete/';//note the trailing slashes
$dh = opendir($dir);
while($file = readdir($dh))
{
if(!is_dir($file))
{
#unlink($dir.$file);
}
}
closedir($dh);
function Delete($path)
{
if (is_dir($path) === true)
{
$files = array_diff(scandir($path), array('.', '..'));
foreach ($files as $file)
{
Delete(realpath($path) . '/' . $file);
}
return rmdir($path);
}
else if (is_file($path) === true)
{
return unlink($path);
}
return false;
}
http://us.php.net/manual/en/function.unlink.php.
You will find many functions in the comments that does what you need
One example:
function unlinkRecursive($dir, $deleteRootToo)
{
if(!$dh = #opendir($dir))
{
return;
}
while (false !== ($obj = readdir($dh)))
{
if($obj == '.' || $obj == '..')
{
continue;
}
if (!#unlink($dir . '/' . $obj))
{
unlinkRecursive($dir.'/'.$obj, true);
}
}
closedir($dh);
if ($deleteRootToo)
{
#rmdir($dir);
}
return;
}
This function will remove recursively (like rm -r). Be careful!
function rm_recursive($filepath)
{
if (is_dir($filepath) && !is_link($filepath))
{
if ($dh = opendir($filepath))
{
while (($sf = readdir($dh)) !== false)
{
if ($sf == '.' || $sf == '..')
{
continue;
}
if (!rm_recursive($filepath.'/'.$sf))
{
throw new Exception($filepath.'/'.$sf.' could not be deleted.');
}
}
closedir($dh);
}
return rmdir($filepath);
}
return unlink($filepath);
}

Categories