2017-01-27 141 views
1

我有一個if語句時<img>標籤缺失尺寸(width/height),其驗證,或者如果他們是空的(width=""/height=""),例如:這個「if」語句可以簡化嗎?

<img src="https://placehold.it/100x50" alt="Blank width/height" width="" height=""> 
<img src="https://placehold.it/100x50" alt="Blank width" width=""> 
<img src="https://placehold.it/100x50" alt="Blank height" height=""> 
<img src="https://placehold.it/100x50" alt="No width/height"> 

if聲明以下爲我工作。但是,我想知道是否可以簡化我在下面使用的邏輯。 Here's the link to the full source code

if (
    # There is no width 
    ! in_array('width', $img[1]) || 
    # There is no height 
    ! in_array('height', $img[1]) || 
    # The width is blank (width="") 
    (in_array('width', $img[1]) && in_array('""', $img[2])) || 
    # The height is blank (height="") 
    (in_array('height', $img[1]) && in_array('""', $img[2])) 
) { 
# Code here... 
} 
+1

是不是有可能' $ img [2]'包含沒有對應於寬度或高度的''「''? (例如''「'alt?) – apokryfos

+2

應該移動到http://codereview.stackexchange.com/ – zurfyx

+0

@apokryfos剛剛更新我的問題,我嘗試了它,是最好的邏輯,但? –

回答

0

我能夠通過執行以下操作來簡化邏輯:

if (! in_array('width|height', $img[1]) || in_array('""', $img[2])) { 
    # Code here... 
} 
0
$search = ['width','height']; 
foreach ($search as $value) { 
    if(!in_array($value, $img[1]) || (in_array($value, $img[1]) && in_array('""', $img[2])) { 
     // code away 
    } 
} 

或者你總是可以使用jQuery來檢查您的定義的元素的屬性,甚至可以定義在CSS的寬度和高度,而不是使用內嵌樣式。

+0

更新了我在這個問題中簡化它的嘗試,您怎麼看? –

0

是的,導出一個函數中的所有檢查,在該函數中檢查每個單個條件並返回相應的值。俗話說:

失敗年初,快速失敗

if(illegalImage($img)) { 
// Code here ... 
} 

private function illegalImage(array $imgData) { 
    // check the array since we're in a validation function, so be thorough 
    if (count($imgData) < 3) { // or whatever check makes sense here 
     return true; 
    } 
    if (!in_array('width', $imgData[1])) { 
     return true; 
    } 
    if (!in_array('height', $imgData[1])) { 
     return true; 
    } 
    /* you'd have failed earlier if 'width' or 'height' was missing 
    * so no need of complicated boolean expressions here 
    */ 
    if (in_array('""', $img[2])) { 
     return true; 
    } 

    return false; 
} 
+0

是不是因爲我爲它創建了一個全新的功能而變得更大? –

+0

它更具可讀性,易於維護和擴展 - 在我的書中有很大的優勢。考慮在幾個月內重新訪問它,或者不得不添加另一個條件。 – Havelock