Completed
Push — master ( b1cd7c...5705a3 )
by mw
34:39
created

StringValueFormatter::getAbbreviatedText()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 16
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
dl 0
loc 16
rs 9.4285
c 1
b 0
f 1
cc 3
eloc 10
nc 2
nop 3
1
<?php
2
3
namespace SMW\DataValues\ValueFormatters;
4
5
use SMWDataValue as DataValue;
6
use SMWStringValue as StringValue;
7
use RuntimeException;
8
use SMW\Highlighter;
9
10
/**
11
 * @license GNU GPL v2+
12
 * @since 2.4
13
 *
14
 * @author mwjames
15
 */
16
class StringValueFormatter extends DataValueFormatter {
17
18
	/**
19
	 * @since 2.4
20
	 *
21
	 * {@inheritDoc}
22
	 */
23
	public function isFormatterFor( DataValue $dataValue ) {
24
		return $dataValue instanceOf StringValue;
25
	}
26
27
	/**
28
	 * @since 2.4
29
	 *
30
	 * {@inheritDoc}
31
	 */
32
	public function format( $type, $linker = null ) {
33
34
		if ( !$this->dataValue instanceOf StringValue ) {
35
			throw new RuntimeException( "The formatter is missing a valid StringValue object" );
36
		}
37
38
		if ( $type === self::VALUE ) {
39
			return $this->dataValue->isValid() ? $this->dataValue->getDataItem()->getString() : 'error';
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class SMWDataItem as the method getString() does only exist in the following sub-classes of SMWDataItem: SMWDIBlob, SMWDIError, SMWDIString. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

abstract class User
{
    /** @return string */
    abstract public function getPassword();
}

class MyUser extends User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different sub-classes of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
40
		}
41
42
		if ( $this->dataValue->getCaption() !== false && $type === self::WIKI_SHORT ) {
43
			return $this->dataValue->getCaption();
44
		}
45
46
		if ( $this->dataValue->getCaption() !== false && $type === self::HTML_SHORT ) {
47
			return smwfXMLContentEncode( $this->dataValue->getCaption() );
48
		}
49
50
		if ( !$this->dataValue->isValid() ) {
51
			return '';
52
		}
53
54
		return $this->doFormatFinalOutputFor( $type, $linker );
55
	}
56
57
	protected function doFormatFinalOutputFor( $type, $linker ) {
58
59
		// Make a possibly shortened printout string for displaying the value.
60
		// The result is only escaped to be HTML-safe if this is requested
61
		// explicitly. The result will contain mark-up that must not be escaped
62
		// again.
63
		$abbreviate = $type === self::WIKI_LONG || $type === self::HTML_LONG;
64
		$text = $this->dataValue->getDataItem()->getString() ;
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class SMWDataItem as the method getString() does only exist in the following sub-classes of SMWDataItem: SMWDIBlob, SMWDIError, SMWDIString. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

abstract class User
{
    /** @return string */
    abstract public function getPassword();
}

class MyUser extends User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different sub-classes of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
65
66
		if ( $type === self::HTML_SHORT || $type === self::HTML_LONG ) {
67
			$text = smwfXMLContentEncode( $text );
68
		}
69
70
		$length = mb_strlen( $text );
71
72
		return $abbreviate && $length > 255 ? $this->getAbbreviatedText( $text, $length, $linker ) : $text;
73
	}
74
75
	private function getAbbreviatedText( $text, $length, $linker ) {
76
77
		if ( $linker === false || $linker === null ) {
78
			$ellipsis = ' <span class="smwwarning">…</span> ';
79
		} else {
80
			$highlighter = Highlighter::factory( Highlighter::TYPE_TEXT );
81
			$highlighter->setContent( array (
82
				'caption' => ' … ',
83
				'content' => $text
84
			) );
85
86
			$ellipsis = $highlighter->getHtml();
87
		}
88
89
		return mb_substr( $text, 0, 42 ) . $ellipsis . mb_substr( $text, $length - 42 );
90
	}
91
92
}
93